JAL-845 handling eXpand/Gather split frame views
[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 the specified panel and close up tabs appropriately.
1484    * 
1485    * @param panelToClose
1486    */
1487   public void closeView(AlignmentPanel panelToClose)
1488   {
1489     int index = tabbedPane.getSelectedIndex();
1490     int closedindex = tabbedPane.indexOfComponent(panelToClose);
1491     alignPanels.remove(panelToClose);
1492     panelToClose.closePanel();
1493     panelToClose = null;
1494
1495     tabbedPane.removeTabAt(closedindex);
1496     tabbedPane.validate();
1497
1498     if (index > closedindex || index == tabbedPane.getTabCount())
1499     {
1500       // modify currently selected tab index if necessary.
1501       index--;
1502     }
1503
1504     this.tabSelectionChanged(index);
1505   }
1506
1507   /**
1508    * DOCUMENT ME!
1509    */
1510   void updateEditMenuBar()
1511   {
1512
1513     if (viewport.getHistoryList().size() > 0)
1514     {
1515       undoMenuItem.setEnabled(true);
1516       CommandI command = viewport.getHistoryList().peek();
1517       undoMenuItem.setText(MessageManager.formatMessage(
1518               "label.undo_command", new Object[]
1519               { command.getDescription() }));
1520     }
1521     else
1522     {
1523       undoMenuItem.setEnabled(false);
1524       undoMenuItem.setText(MessageManager.getString("action.undo"));
1525     }
1526
1527     if (viewport.getRedoList().size() > 0)
1528     {
1529       redoMenuItem.setEnabled(true);
1530
1531       CommandI command = viewport.getRedoList().peek();
1532       redoMenuItem.setText(MessageManager.formatMessage(
1533               "label.redo_command", new Object[]
1534               { command.getDescription() }));
1535     }
1536     else
1537     {
1538       redoMenuItem.setEnabled(false);
1539       redoMenuItem.setText(MessageManager.getString("action.redo"));
1540     }
1541   }
1542
1543   public void addHistoryItem(CommandI command)
1544   {
1545     if (command.getSize() > 0)
1546     {
1547       viewport.addToHistoryList(command);
1548       viewport.clearRedoList();
1549       updateEditMenuBar();
1550       viewport.updateHiddenColumns();
1551       // viewport.hasHiddenColumns = (viewport.getColumnSelection() != null
1552       // && viewport.getColumnSelection().getHiddenColumns() != null &&
1553       // viewport.getColumnSelection()
1554       // .getHiddenColumns().size() > 0);
1555     }
1556   }
1557
1558   /**
1559    * 
1560    * @return alignment objects for all views
1561    */
1562   AlignmentI[] getViewAlignments()
1563   {
1564     if (alignPanels != null)
1565     {
1566       AlignmentI[] als = new AlignmentI[alignPanels.size()];
1567       int i = 0;
1568       for (AlignmentPanel ap : alignPanels)
1569       {
1570         als[i++] = ap.av.getAlignment();
1571       }
1572       return als;
1573     }
1574     if (viewport != null)
1575     {
1576       return new AlignmentI[]
1577       { viewport.getAlignment() };
1578     }
1579     return null;
1580   }
1581
1582   /**
1583    * DOCUMENT ME!
1584    * 
1585    * @param e
1586    *          DOCUMENT ME!
1587    */
1588   @Override
1589   protected void undoMenuItem_actionPerformed(ActionEvent e)
1590   {
1591     if (viewport.getHistoryList().isEmpty())
1592     {
1593       return;
1594     }
1595     CommandI command = viewport.getHistoryList().pop();
1596     viewport.addToRedoList(command);
1597     command.undoCommand(getViewAlignments());
1598
1599     AlignmentViewport originalSource = getOriginatingSource(command);
1600     updateEditMenuBar();
1601
1602     if (originalSource != null)
1603     {
1604       if (originalSource != viewport)
1605       {
1606         Cache.log
1607                 .warn("Implementation worry: mismatch of viewport origin for undo");
1608       }
1609       originalSource.updateHiddenColumns();
1610       // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1611       // null
1612       // && viewport.getColumnSelection().getHiddenColumns() != null &&
1613       // viewport.getColumnSelection()
1614       // .getHiddenColumns().size() > 0);
1615       originalSource.firePropertyChange("alignment", null, originalSource
1616               .getAlignment().getSequences());
1617     }
1618   }
1619
1620   /**
1621    * DOCUMENT ME!
1622    * 
1623    * @param e
1624    *          DOCUMENT ME!
1625    */
1626   @Override
1627   protected void redoMenuItem_actionPerformed(ActionEvent e)
1628   {
1629     if (viewport.getRedoList().size() < 1)
1630     {
1631       return;
1632     }
1633
1634     CommandI command = viewport.getRedoList().pop();
1635     viewport.addToHistoryList(command);
1636     command.doCommand(getViewAlignments());
1637
1638     AlignmentViewport originalSource = getOriginatingSource(command);
1639     updateEditMenuBar();
1640
1641     if (originalSource != null)
1642     {
1643
1644       if (originalSource != viewport)
1645       {
1646         Cache.log
1647                 .warn("Implementation worry: mismatch of viewport origin for redo");
1648       }
1649       originalSource.updateHiddenColumns();
1650       // originalSource.hasHiddenColumns = (viewport.getColumnSelection() !=
1651       // null
1652       // && viewport.getColumnSelection().getHiddenColumns() != null &&
1653       // viewport.getColumnSelection()
1654       // .getHiddenColumns().size() > 0);
1655       originalSource.firePropertyChange("alignment", null, originalSource
1656               .getAlignment().getSequences());
1657     }
1658   }
1659
1660   AlignmentViewport getOriginatingSource(CommandI command)
1661   {
1662     AlignmentViewport originalSource = null;
1663     // For sequence removal and addition, we need to fire
1664     // the property change event FROM the viewport where the
1665     // original alignment was altered
1666     AlignmentI al = null;
1667     if (command instanceof EditCommand)
1668     {
1669       EditCommand editCommand = (EditCommand) command;
1670       al = editCommand.getAlignment();
1671       List<Component> comps = PaintRefresher.components.get(viewport
1672               .getSequenceSetId());
1673
1674       for (Component comp : comps)
1675       {
1676         if (comp instanceof AlignmentPanel)
1677         {
1678           if (al == ((AlignmentPanel) comp).av.getAlignment())
1679           {
1680             originalSource = ((AlignmentPanel) comp).av;
1681             break;
1682           }
1683         }
1684       }
1685     }
1686
1687     if (originalSource == null)
1688     {
1689       // The original view is closed, we must validate
1690       // the current view against the closed view first
1691       if (al != null)
1692       {
1693         PaintRefresher.validateSequences(al, viewport.getAlignment());
1694       }
1695
1696       originalSource = viewport;
1697     }
1698
1699     return originalSource;
1700   }
1701
1702   /**
1703    * DOCUMENT ME!
1704    * 
1705    * @param up
1706    *          DOCUMENT ME!
1707    */
1708   public void moveSelectedSequences(boolean up)
1709   {
1710     SequenceGroup sg = viewport.getSelectionGroup();
1711
1712     if (sg == null)
1713     {
1714       return;
1715     }
1716     viewport.getAlignment().moveSelectedSequencesByOne(sg,
1717             viewport.getHiddenRepSequences(), up);
1718     alignPanel.paintAlignment(true);
1719   }
1720
1721   synchronized void slideSequences(boolean right, int size)
1722   {
1723     List<SequenceI> sg = new ArrayList<SequenceI>();
1724     if (viewport.cursorMode)
1725     {
1726       sg.add(viewport.getAlignment().getSequenceAt(
1727               alignPanel.getSeqPanel().seqCanvas.cursorY));
1728     }
1729     else if (viewport.getSelectionGroup() != null
1730             && viewport.getSelectionGroup().getSize() != viewport
1731                     .getAlignment().getHeight())
1732     {
1733       sg = viewport.getSelectionGroup().getSequences(
1734               viewport.getHiddenRepSequences());
1735     }
1736
1737     if (sg.size() < 1)
1738     {
1739       return;
1740     }
1741
1742     List<SequenceI> invertGroup = new ArrayList<SequenceI>();
1743
1744     for (SequenceI seq : viewport.getAlignment().getSequences())
1745     {
1746       if (!sg.contains(seq))
1747       {
1748         invertGroup.add(seq);
1749       }
1750     }
1751
1752     SequenceI[] seqs1 = sg.toArray(new SequenceI[0]);
1753
1754     SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
1755     for (int i = 0; i < invertGroup.size(); i++)
1756     {
1757       seqs2[i] = invertGroup.get(i);
1758     }
1759
1760     SlideSequencesCommand ssc;
1761     if (right)
1762     {
1763       ssc = new SlideSequencesCommand("Slide Sequences", seqs2, seqs1,
1764               size, viewport.getGapCharacter());
1765     }
1766     else
1767     {
1768       ssc = new SlideSequencesCommand("Slide Sequences", seqs1, seqs2,
1769               size, viewport.getGapCharacter());
1770     }
1771
1772     int groupAdjustment = 0;
1773     if (ssc.getGapsInsertedBegin() && right)
1774     {
1775       if (viewport.cursorMode)
1776       {
1777         alignPanel.getSeqPanel().moveCursor(size, 0);
1778       }
1779       else
1780       {
1781         groupAdjustment = size;
1782       }
1783     }
1784     else if (!ssc.getGapsInsertedBegin() && !right)
1785     {
1786       if (viewport.cursorMode)
1787       {
1788         alignPanel.getSeqPanel().moveCursor(-size, 0);
1789       }
1790       else
1791       {
1792         groupAdjustment = -size;
1793       }
1794     }
1795
1796     if (groupAdjustment != 0)
1797     {
1798       viewport.getSelectionGroup().setStartRes(
1799               viewport.getSelectionGroup().getStartRes() + groupAdjustment);
1800       viewport.getSelectionGroup().setEndRes(
1801               viewport.getSelectionGroup().getEndRes() + groupAdjustment);
1802     }
1803
1804     boolean appendHistoryItem = false;
1805     Deque<CommandI> historyList = viewport.getHistoryList();
1806     if (historyList != null
1807             && historyList.size() > 0
1808             && historyList.peek() instanceof SlideSequencesCommand)
1809     {
1810       appendHistoryItem = ssc
1811               .appendSlideCommand((SlideSequencesCommand) historyList
1812                       .peek());
1813     }
1814
1815     if (!appendHistoryItem)
1816     {
1817       addHistoryItem(ssc);
1818     }
1819
1820     repaint();
1821   }
1822
1823   /**
1824    * DOCUMENT ME!
1825    * 
1826    * @param e
1827    *          DOCUMENT ME!
1828    */
1829   @Override
1830   protected void copy_actionPerformed(ActionEvent e)
1831   {
1832     System.gc();
1833     if (viewport.getSelectionGroup() == null)
1834     {
1835       return;
1836     }
1837     // TODO: preserve the ordering of displayed alignment annotation in any
1838     // internal paste (particularly sequence associated annotation)
1839     SequenceI[] seqs = viewport.getSelectionAsNewSequence();
1840     String[] omitHidden = null;
1841
1842     if (viewport.hasHiddenColumns())
1843     {
1844       omitHidden = viewport.getViewAsString(true);
1845     }
1846
1847     String output = new FormatAdapter().formatSequences("Fasta", seqs,
1848             omitHidden);
1849
1850     StringSelection ss = new StringSelection(output);
1851
1852     try
1853     {
1854       jalview.gui.Desktop.internalCopy = true;
1855       // Its really worth setting the clipboard contents
1856       // to empty before setting the large StringSelection!!
1857       Toolkit.getDefaultToolkit().getSystemClipboard()
1858               .setContents(new StringSelection(""), null);
1859
1860       Toolkit.getDefaultToolkit().getSystemClipboard()
1861               .setContents(ss, Desktop.instance);
1862     } catch (OutOfMemoryError er)
1863     {
1864       new OOMWarning("copying region", er);
1865       return;
1866     }
1867
1868     ArrayList<int[]> hiddenColumns = null;
1869     if (viewport.hasHiddenColumns())
1870     {
1871       hiddenColumns = new ArrayList<int[]>();
1872       int hiddenOffset = viewport.getSelectionGroup().getStartRes(), hiddenCutoff = viewport
1873               .getSelectionGroup().getEndRes();
1874       for (int[] region : viewport.getColumnSelection().getHiddenColumns())
1875       {
1876         if (region[0] >= hiddenOffset && region[1] <= hiddenCutoff)
1877         {
1878           hiddenColumns.add(new int[]
1879           { region[0] - hiddenOffset, region[1] - hiddenOffset });
1880         }
1881       }
1882     }
1883
1884     Desktop.jalviewClipboard = new Object[]
1885     { seqs, viewport.getAlignment().getDataset(), hiddenColumns };
1886     statusBar.setText(MessageManager.formatMessage(
1887             "label.copied_sequences_to_clipboard", new Object[]
1888             { Integer.valueOf(seqs.length).toString() }));
1889   }
1890
1891   /**
1892    * DOCUMENT ME!
1893    * 
1894    * @param e
1895    *          DOCUMENT ME!
1896    */
1897   @Override
1898   protected void pasteNew_actionPerformed(ActionEvent e)
1899   {
1900     paste(true);
1901   }
1902
1903   /**
1904    * DOCUMENT ME!
1905    * 
1906    * @param e
1907    *          DOCUMENT ME!
1908    */
1909   @Override
1910   protected void pasteThis_actionPerformed(ActionEvent e)
1911   {
1912     paste(false);
1913   }
1914
1915   /**
1916    * Paste contents of Jalview clipboard
1917    * 
1918    * @param newAlignment
1919    *          true to paste to a new alignment, otherwise add to this.
1920    */
1921   void paste(boolean newAlignment)
1922   {
1923     boolean externalPaste = true;
1924     try
1925     {
1926       Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
1927       Transferable contents = c.getContents(this);
1928
1929       if (contents == null)
1930       {
1931         return;
1932       }
1933
1934       String str, format;
1935       try
1936       {
1937         str = (String) contents.getTransferData(DataFlavor.stringFlavor);
1938         if (str.length() < 1)
1939         {
1940           return;
1941         }
1942
1943         format = new IdentifyFile().Identify(str, "Paste");
1944
1945       } catch (OutOfMemoryError er)
1946       {
1947         new OOMWarning("Out of memory pasting sequences!!", er);
1948         return;
1949       }
1950
1951       SequenceI[] sequences;
1952       boolean annotationAdded = false;
1953       AlignmentI alignment = null;
1954
1955       if (Desktop.jalviewClipboard != null)
1956       {
1957         // The clipboard was filled from within Jalview, we must use the
1958         // sequences
1959         // And dataset from the copied alignment
1960         SequenceI[] newseq = (SequenceI[]) Desktop.jalviewClipboard[0];
1961         // be doubly sure that we create *new* sequence objects.
1962         sequences = new SequenceI[newseq.length];
1963         for (int i = 0; i < newseq.length; i++)
1964         {
1965           sequences[i] = new Sequence(newseq[i]);
1966         }
1967         alignment = new Alignment(sequences);
1968         externalPaste = false;
1969       }
1970       else
1971       {
1972         // parse the clipboard as an alignment.
1973         alignment = new FormatAdapter().readFile(str, "Paste", format);
1974         sequences = alignment.getSequencesArray();
1975       }
1976
1977       int alwidth = 0;
1978       ArrayList<Integer> newGraphGroups = new ArrayList<Integer>();
1979       int fgroup = -1;
1980
1981       if (newAlignment)
1982       {
1983
1984         if (Desktop.jalviewClipboard != null)
1985         {
1986           // dataset is inherited
1987           alignment.setDataset((Alignment) Desktop.jalviewClipboard[1]);
1988         }
1989         else
1990         {
1991           // new dataset is constructed
1992           alignment.setDataset(null);
1993         }
1994         alwidth = alignment.getWidth() + 1;
1995       }
1996       else
1997       {
1998         AlignmentI pastedal = alignment; // preserve pasted alignment object
1999         // Add pasted sequences and dataset into existing alignment.
2000         alignment = viewport.getAlignment();
2001         alwidth = alignment.getWidth() + 1;
2002         // decide if we need to import sequences from an existing dataset
2003         boolean importDs = Desktop.jalviewClipboard != null
2004                 && Desktop.jalviewClipboard[1] != alignment.getDataset();
2005         // importDs==true instructs us to copy over new dataset sequences from
2006         // an existing alignment
2007         Vector newDs = (importDs) ? new Vector() : null; // used to create
2008         // minimum dataset set
2009
2010         for (int i = 0; i < sequences.length; i++)
2011         {
2012           if (importDs)
2013           {
2014             newDs.addElement(null);
2015           }
2016           SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
2017           // paste
2018           if (importDs && ds != null)
2019           {
2020             if (!newDs.contains(ds))
2021             {
2022               newDs.setElementAt(ds, i);
2023               ds = new Sequence(ds);
2024               // update with new dataset sequence
2025               sequences[i].setDatasetSequence(ds);
2026             }
2027             else
2028             {
2029               ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
2030             }
2031           }
2032           else
2033           {
2034             // copy and derive new dataset sequence
2035             sequences[i] = sequences[i].deriveSequence();
2036             alignment.getDataset().addSequence(
2037                     sequences[i].getDatasetSequence());
2038             // TODO: avoid creation of duplicate dataset sequences with a
2039             // 'contains' method using SequenceI.equals()/SequenceI.contains()
2040           }
2041           alignment.addSequence(sequences[i]); // merges dataset
2042         }
2043         if (newDs != null)
2044         {
2045           newDs.clear(); // tidy up
2046         }
2047         if (alignment.getAlignmentAnnotation() != null)
2048         {
2049           for (AlignmentAnnotation alan : alignment
2050                   .getAlignmentAnnotation())
2051           {
2052             if (alan.graphGroup > fgroup)
2053             {
2054               fgroup = alan.graphGroup;
2055             }
2056           }
2057         }
2058         if (pastedal.getAlignmentAnnotation() != null)
2059         {
2060           // Add any annotation attached to alignment.
2061           AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
2062           for (int i = 0; i < alann.length; i++)
2063           {
2064             annotationAdded = true;
2065             if (alann[i].sequenceRef == null && !alann[i].autoCalculated)
2066             {
2067               AlignmentAnnotation newann = new AlignmentAnnotation(alann[i]);
2068               if (newann.graphGroup > -1)
2069               {
2070                 if (newGraphGroups.size() <= newann.graphGroup
2071                         || newGraphGroups.get(newann.graphGroup) == null)
2072                 {
2073                   for (int q = newGraphGroups.size(); q <= newann.graphGroup; q++)
2074                   {
2075                     newGraphGroups.add(q, null);
2076                   }
2077                   newGraphGroups.set(newann.graphGroup, new Integer(
2078                           ++fgroup));
2079                 }
2080                 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2081                         .intValue();
2082               }
2083
2084               newann.padAnnotation(alwidth);
2085               alignment.addAnnotation(newann);
2086             }
2087           }
2088         }
2089       }
2090       if (!newAlignment)
2091       {
2092         // /////
2093         // ADD HISTORY ITEM
2094         //
2095         addHistoryItem(new EditCommand(
2096                 MessageManager.getString("label.add_sequences"),
2097                 Action.PASTE,
2098                 sequences, 0, alignment.getWidth(), alignment));
2099       }
2100       // Add any annotations attached to sequences
2101       for (int i = 0; i < sequences.length; i++)
2102       {
2103         if (sequences[i].getAnnotation() != null)
2104         {
2105           AlignmentAnnotation newann;
2106           for (int a = 0; a < sequences[i].getAnnotation().length; a++)
2107           {
2108             annotationAdded = true;
2109             newann = sequences[i].getAnnotation()[a];
2110             newann.adjustForAlignment();
2111             newann.padAnnotation(alwidth);
2112             if (newann.graphGroup > -1)
2113             {
2114               if (newann.graphGroup > -1)
2115               {
2116                 if (newGraphGroups.size() <= newann.graphGroup
2117                         || newGraphGroups.get(newann.graphGroup) == null)
2118                 {
2119                   for (int q = newGraphGroups.size(); q <= newann.graphGroup; q++)
2120                   {
2121                     newGraphGroups.add(q, null);
2122                   }
2123                   newGraphGroups.set(newann.graphGroup, new Integer(
2124                           ++fgroup));
2125                 }
2126                 newann.graphGroup = newGraphGroups.get(newann.graphGroup)
2127                         .intValue();
2128               }
2129             }
2130             alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation
2131             // was
2132             // duplicated
2133             // earlier
2134             alignment
2135                     .setAnnotationIndex(sequences[i].getAnnotation()[a], a);
2136           }
2137         }
2138       }
2139       if (!newAlignment)
2140       {
2141
2142         // propagate alignment changed.
2143         viewport.setEndSeq(alignment.getHeight());
2144         if (annotationAdded)
2145         {
2146           // Duplicate sequence annotation in all views.
2147           AlignmentI[] alview = this.getViewAlignments();
2148           for (int i = 0; i < sequences.length; i++)
2149           {
2150             AlignmentAnnotation sann[] = sequences[i].getAnnotation();
2151             if (sann == null)
2152             {
2153               continue;
2154             }
2155             for (int avnum = 0; avnum < alview.length; avnum++)
2156             {
2157               if (alview[avnum] != alignment)
2158               {
2159                 // duplicate in a view other than the one with input focus
2160                 int avwidth = alview[avnum].getWidth() + 1;
2161                 // this relies on sann being preserved after we
2162                 // modify the sequence's annotation array for each duplication
2163                 for (int a = 0; a < sann.length; a++)
2164                 {
2165                   AlignmentAnnotation newann = new AlignmentAnnotation(
2166                           sann[a]);
2167                   sequences[i].addAlignmentAnnotation(newann);
2168                   newann.padAnnotation(avwidth);
2169                   alview[avnum].addAnnotation(newann); // annotation was
2170                   // duplicated earlier
2171                   // TODO JAL-1145 graphGroups are not updated for sequence
2172                   // annotation added to several views. This may cause
2173                   // strangeness
2174                   alview[avnum].setAnnotationIndex(newann, a);
2175                 }
2176               }
2177             }
2178           }
2179           buildSortByAnnotationScoresMenu();
2180         }
2181         viewport.firePropertyChange("alignment", null,
2182                 alignment.getSequences());
2183         if (alignPanels != null)
2184         {
2185           for (AlignmentPanel ap : alignPanels)
2186           {
2187             ap.validateAnnotationDimensions(false);
2188           }
2189         }
2190         else
2191         {
2192           alignPanel.validateAnnotationDimensions(false);
2193         }
2194
2195       }
2196       else
2197       {
2198         AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2199                 DEFAULT_HEIGHT);
2200         String newtitle = new String("Copied sequences");
2201
2202         if (Desktop.jalviewClipboard != null
2203                 && Desktop.jalviewClipboard[2] != null)
2204         {
2205           List<int[]> hc = (List<int[]>) Desktop.jalviewClipboard[2];
2206           for (int[] region : hc)
2207           {
2208             af.viewport.hideColumns(region[0], region[1]);
2209           }
2210         }
2211
2212         // >>>This is a fix for the moment, until a better solution is
2213         // found!!<<<
2214         af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2215                 .transferSettings(
2216                         alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer());
2217
2218         // TODO: maintain provenance of an alignment, rather than just make the
2219         // title a concatenation of operations.
2220         if (!externalPaste)
2221         {
2222           if (title.startsWith("Copied sequences"))
2223           {
2224             newtitle = title;
2225           }
2226           else
2227           {
2228             newtitle = newtitle.concat("- from " + title);
2229           }
2230         }
2231         else
2232         {
2233           newtitle = new String("Pasted sequences");
2234         }
2235
2236         Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
2237                 DEFAULT_HEIGHT);
2238
2239       }
2240
2241     } catch (Exception ex)
2242     {
2243       ex.printStackTrace();
2244       System.out.println("Exception whilst pasting: " + ex);
2245       // could be anything being pasted in here
2246     }
2247
2248   }
2249
2250   @Override
2251   protected void expand_newalign(ActionEvent e)
2252   {
2253     try
2254     {
2255       AlignmentI alignment = AlignmentUtils.expandContext(getViewport()
2256               .getAlignment(), -1);
2257       AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH,
2258               DEFAULT_HEIGHT);
2259       String newtitle = new String("Flanking alignment");
2260
2261       if (Desktop.jalviewClipboard != null
2262               && Desktop.jalviewClipboard[2] != null)
2263       {
2264         List<int[]> hc = (List<int[]>) Desktop.jalviewClipboard[2];
2265         for (int region[] : hc)
2266         {
2267           af.viewport.hideColumns(region[0], region[1]);
2268         }
2269       }
2270
2271       // >>>This is a fix for the moment, until a better solution is
2272       // found!!<<<
2273       af.alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer()
2274               .transferSettings(
2275                       alignPanel.getSeqPanel().seqCanvas.getFeatureRenderer());
2276
2277       // TODO: maintain provenance of an alignment, rather than just make the
2278       // title a concatenation of operations.
2279       {
2280         if (title.startsWith("Copied sequences"))
2281         {
2282           newtitle = title;
2283         }
2284         else
2285         {
2286           newtitle = newtitle.concat("- from " + title);
2287         }
2288       }
2289
2290       Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH, DEFAULT_HEIGHT);
2291
2292     } catch (Exception ex)
2293     {
2294       ex.printStackTrace();
2295       System.out.println("Exception whilst pasting: " + ex);
2296       // could be anything being pasted in here
2297     } catch (OutOfMemoryError oom)
2298     {
2299       new OOMWarning("Viewing flanking region of alignment", oom);
2300     }
2301   }
2302
2303   /**
2304    * DOCUMENT ME!
2305    * 
2306    * @param e
2307    *          DOCUMENT ME!
2308    */
2309   @Override
2310   protected void cut_actionPerformed(ActionEvent e)
2311   {
2312     copy_actionPerformed(null);
2313     delete_actionPerformed(null);
2314   }
2315
2316   /**
2317    * DOCUMENT ME!
2318    * 
2319    * @param e
2320    *          DOCUMENT ME!
2321    */
2322   @Override
2323   protected void delete_actionPerformed(ActionEvent evt)
2324   {
2325
2326     SequenceGroup sg = viewport.getSelectionGroup();
2327     if (sg == null)
2328     {
2329       return;
2330     }
2331
2332     List<SequenceI> seqs = new ArrayList<SequenceI>(sg.getSize());
2333     SequenceI seq;
2334     for (int i = 0; i < sg.getSize(); i++)
2335     {
2336       seq = sg.getSequenceAt(i);
2337       seqs.add(seq);
2338     }
2339
2340     // If the cut affects all sequences, warn, remove highlighted columns
2341     if (sg.getSize() == viewport.getAlignment().getHeight())
2342     {
2343       int confirm = JOptionPane.showConfirmDialog(this,
2344               MessageManager.getString("warn.delete_all"), // $NON-NLS-1$
2345               MessageManager.getString("label.delete_all"), // $NON-NLS-1$
2346               JOptionPane.OK_CANCEL_OPTION);
2347
2348       if (confirm == JOptionPane.CANCEL_OPTION
2349               || confirm == JOptionPane.CLOSED_OPTION)
2350       {
2351         return;
2352       }
2353       viewport.getColumnSelection().removeElements(sg.getStartRes(),
2354               sg.getEndRes() + 1);
2355     }
2356
2357     SequenceI[] cut = new SequenceI[seqs.size()];
2358     for (int i = 0; i < seqs.size(); i++)
2359     {
2360       cut[i] = seqs.get(i);
2361     }
2362
2363     /*
2364      * //ADD HISTORY ITEM
2365      */
2366     addHistoryItem(new EditCommand(
2367             MessageManager.getString("label.cut_sequences"), Action.CUT,
2368             cut, sg.getStartRes(), sg.getEndRes() - sg.getStartRes() + 1,
2369             viewport.getAlignment()));
2370
2371     viewport.setSelectionGroup(null);
2372     viewport.sendSelection();
2373     viewport.getAlignment().deleteGroup(sg);
2374
2375     viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2376             .getSequences());
2377     if (viewport.getAlignment().getHeight() < 1)
2378     {
2379       try
2380       {
2381         this.setClosed(true);
2382       } catch (Exception ex)
2383       {
2384       }
2385     }
2386   }
2387
2388   /**
2389    * DOCUMENT ME!
2390    * 
2391    * @param e
2392    *          DOCUMENT ME!
2393    */
2394   @Override
2395   protected void deleteGroups_actionPerformed(ActionEvent e)
2396   {
2397     if (avc.deleteGroups())
2398     {
2399       PaintRefresher.Refresh(this, viewport.getSequenceSetId());
2400       alignPanel.updateAnnotation();
2401       alignPanel.paintAlignment(true);
2402     }
2403   }
2404
2405   /**
2406    * DOCUMENT ME!
2407    * 
2408    * @param e
2409    *          DOCUMENT ME!
2410    */
2411   @Override
2412   public void selectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2413   {
2414     SequenceGroup sg = new SequenceGroup();
2415
2416     for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2417     {
2418       sg.addSequence(viewport.getAlignment().getSequenceAt(i), false);
2419     }
2420
2421     sg.setEndRes(viewport.getAlignment().getWidth() - 1);
2422     viewport.setSelectionGroup(sg);
2423     viewport.sendSelection();
2424     alignPanel.paintAlignment(true);
2425     PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2426   }
2427
2428   /**
2429    * DOCUMENT ME!
2430    * 
2431    * @param e
2432    *          DOCUMENT ME!
2433    */
2434   @Override
2435   public void deselectAllSequenceMenuItem_actionPerformed(ActionEvent e)
2436   {
2437     if (viewport.cursorMode)
2438     {
2439       alignPanel.getSeqPanel().keyboardNo1 = null;
2440       alignPanel.getSeqPanel().keyboardNo2 = null;
2441     }
2442     viewport.setSelectionGroup(null);
2443     viewport.getColumnSelection().clear();
2444     viewport.setSelectionGroup(null);
2445     alignPanel.getSeqPanel().seqCanvas.highlightSearchResults(null);
2446     alignPanel.getIdPanel().getIdCanvas().searchResults = null;
2447     alignPanel.paintAlignment(true);
2448     PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2449     viewport.sendSelection();
2450   }
2451
2452   /**
2453    * DOCUMENT ME!
2454    * 
2455    * @param e
2456    *          DOCUMENT ME!
2457    */
2458   @Override
2459   public void invertSequenceMenuItem_actionPerformed(ActionEvent e)
2460   {
2461     SequenceGroup sg = viewport.getSelectionGroup();
2462
2463     if (sg == null)
2464     {
2465       selectAllSequenceMenuItem_actionPerformed(null);
2466
2467       return;
2468     }
2469
2470     for (int i = 0; i < viewport.getAlignment().getSequences().size(); i++)
2471     {
2472       sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
2473     }
2474
2475     alignPanel.paintAlignment(true);
2476     PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
2477     viewport.sendSelection();
2478   }
2479
2480   @Override
2481   public void invertColSel_actionPerformed(ActionEvent e)
2482   {
2483     viewport.invertColumnSelection();
2484     alignPanel.paintAlignment(true);
2485     viewport.sendSelection();
2486   }
2487
2488   /**
2489    * DOCUMENT ME!
2490    * 
2491    * @param e
2492    *          DOCUMENT ME!
2493    */
2494   @Override
2495   public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
2496   {
2497     trimAlignment(true);
2498   }
2499
2500   /**
2501    * DOCUMENT ME!
2502    * 
2503    * @param e
2504    *          DOCUMENT ME!
2505    */
2506   @Override
2507   public void remove2RightMenuItem_actionPerformed(ActionEvent e)
2508   {
2509     trimAlignment(false);
2510   }
2511
2512   void trimAlignment(boolean trimLeft)
2513   {
2514     ColumnSelection colSel = viewport.getColumnSelection();
2515     int column;
2516
2517     if (colSel.size() > 0)
2518     {
2519       if (trimLeft)
2520       {
2521         column = colSel.getMin();
2522       }
2523       else
2524       {
2525         column = colSel.getMax();
2526       }
2527
2528       SequenceI[] seqs;
2529       if (viewport.getSelectionGroup() != null)
2530       {
2531         seqs = viewport.getSelectionGroup().getSequencesAsArray(
2532                 viewport.getHiddenRepSequences());
2533       }
2534       else
2535       {
2536         seqs = viewport.getAlignment().getSequencesArray();
2537       }
2538
2539       TrimRegionCommand trimRegion;
2540       if (trimLeft)
2541       {
2542         trimRegion = new TrimRegionCommand("Remove Left",
2543                 TrimRegionCommand.TRIM_LEFT, seqs, column,
2544                 viewport.getAlignment(), viewport.getColumnSelection(),
2545                 viewport.getSelectionGroup());
2546         viewport.setStartRes(0);
2547       }
2548       else
2549       {
2550         trimRegion = new TrimRegionCommand("Remove Right",
2551                 TrimRegionCommand.TRIM_RIGHT, seqs, column,
2552                 viewport.getAlignment(), viewport.getColumnSelection(),
2553                 viewport.getSelectionGroup());
2554       }
2555
2556       statusBar.setText(MessageManager.formatMessage(
2557               "label.removed_columns", new String[]
2558               { Integer.valueOf(trimRegion.getSize()).toString() }));
2559
2560       addHistoryItem(trimRegion);
2561
2562       for (SequenceGroup sg : viewport.getAlignment().getGroups())
2563       {
2564         if ((trimLeft && !sg.adjustForRemoveLeft(column))
2565                 || (!trimLeft && !sg.adjustForRemoveRight(column)))
2566         {
2567           viewport.getAlignment().deleteGroup(sg);
2568         }
2569       }
2570
2571       viewport.firePropertyChange("alignment", null, viewport
2572               .getAlignment().getSequences());
2573     }
2574   }
2575
2576   /**
2577    * DOCUMENT ME!
2578    * 
2579    * @param e
2580    *          DOCUMENT ME!
2581    */
2582   @Override
2583   public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
2584   {
2585     int start = 0, end = viewport.getAlignment().getWidth() - 1;
2586
2587     SequenceI[] seqs;
2588     if (viewport.getSelectionGroup() != null)
2589     {
2590       seqs = viewport.getSelectionGroup().getSequencesAsArray(
2591               viewport.getHiddenRepSequences());
2592       start = viewport.getSelectionGroup().getStartRes();
2593       end = viewport.getSelectionGroup().getEndRes();
2594     }
2595     else
2596     {
2597       seqs = viewport.getAlignment().getSequencesArray();
2598     }
2599
2600     RemoveGapColCommand removeGapCols = new RemoveGapColCommand(
2601             "Remove Gapped Columns", seqs, start, end,
2602             viewport.getAlignment());
2603
2604     addHistoryItem(removeGapCols);
2605
2606     statusBar.setText(MessageManager.formatMessage(
2607             "label.removed_empty_columns", new Object[]
2608             { Integer.valueOf(removeGapCols.getSize()).toString() }));
2609
2610     // This is to maintain viewport position on first residue
2611     // of first sequence
2612     SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2613     int startRes = seq.findPosition(viewport.startRes);
2614     // ShiftList shifts;
2615     // viewport.getAlignment().removeGaps(shifts=new ShiftList());
2616     // edit.alColumnChanges=shifts.getInverse();
2617     // if (viewport.hasHiddenColumns)
2618     // viewport.getColumnSelection().compensateForEdits(shifts);
2619     viewport.setStartRes(seq.findIndex(startRes) - 1);
2620     viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2621             .getSequences());
2622
2623   }
2624
2625   /**
2626    * DOCUMENT ME!
2627    * 
2628    * @param e
2629    *          DOCUMENT ME!
2630    */
2631   @Override
2632   public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
2633   {
2634     int start = 0, end = viewport.getAlignment().getWidth() - 1;
2635
2636     SequenceI[] seqs;
2637     if (viewport.getSelectionGroup() != null)
2638     {
2639       seqs = viewport.getSelectionGroup().getSequencesAsArray(
2640               viewport.getHiddenRepSequences());
2641       start = viewport.getSelectionGroup().getStartRes();
2642       end = viewport.getSelectionGroup().getEndRes();
2643     }
2644     else
2645     {
2646       seqs = viewport.getAlignment().getSequencesArray();
2647     }
2648
2649     // This is to maintain viewport position on first residue
2650     // of first sequence
2651     SequenceI seq = viewport.getAlignment().getSequenceAt(0);
2652     int startRes = seq.findPosition(viewport.startRes);
2653
2654     addHistoryItem(new RemoveGapsCommand("Remove Gaps", seqs, start, end,
2655             viewport.getAlignment()));
2656
2657     viewport.setStartRes(seq.findIndex(startRes) - 1);
2658
2659     viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2660             .getSequences());
2661
2662   }
2663
2664   /**
2665    * DOCUMENT ME!
2666    * 
2667    * @param e
2668    *          DOCUMENT ME!
2669    */
2670   @Override
2671   public void padGapsMenuitem_actionPerformed(ActionEvent e)
2672   {
2673     viewport.setPadGaps(padGapsMenuitem.isSelected());
2674     viewport.firePropertyChange("alignment", null, viewport.getAlignment()
2675             .getSequences());
2676   }
2677
2678   /**
2679    * DOCUMENT ME!
2680    * 
2681    * @param e
2682    *          DOCUMENT ME!
2683    */
2684   @Override
2685   public void findMenuItem_actionPerformed(ActionEvent e)
2686   {
2687     new Finder();
2688   }
2689
2690   /**
2691    * Create a new view of the current alignment.
2692    */
2693   @Override
2694   public void newView_actionPerformed(ActionEvent e)
2695   {
2696     newView(null, true);
2697   }
2698
2699   /**
2700    * Creates and shows a new view of the current alignment.
2701    * 
2702    * @param viewTitle
2703    *          title of newly created view; if null, one will be generated
2704    * @param copyAnnotation
2705    *          if true then duplicate all annnotation, groups and settings
2706    * @return new alignment panel, already displayed.
2707    */
2708   public AlignmentPanel newView(String viewTitle, boolean copyAnnotation)
2709   {
2710     /*
2711      * Create a new AlignmentPanel (with its own, new Viewport)
2712      */
2713     AlignmentPanel newap = new Jalview2XML().copyAlignPanel(alignPanel,
2714             true);
2715     if (!copyAnnotation)
2716     {
2717       /*
2718        * remove all groups and annotation except for the automatic stuff
2719        */
2720       newap.av.getAlignment().deleteAllGroups();
2721       newap.av.getAlignment().deleteAllAnnotations(false);
2722     }
2723
2724     newap.av.gatherViewsHere = false;
2725
2726     if (viewport.viewName == null)
2727     {
2728       viewport.viewName = MessageManager
2729               .getString("label.view_name_original");
2730     }
2731
2732     /*
2733      * Views share the same edits, undo and redo stacks, mappings.
2734      */
2735     newap.av.setHistoryList(viewport.getHistoryList());
2736     newap.av.setRedoList(viewport.getRedoList());
2737     newap.av.getAlignment().setCodonFrames(
2738             viewport.getAlignment().getCodonFrames());
2739
2740     newap.av.viewName = getNewViewName(viewTitle);
2741
2742     addAlignmentPanel(newap, true);
2743     newap.alignmentChanged();
2744
2745     if (alignPanels.size() == 2)
2746     {
2747       viewport.gatherViewsHere = true;
2748     }
2749     tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
2750     return newap;
2751   }
2752
2753   /**
2754    * Make a new name for the view, ensuring it is unique within the current
2755    * sequenceSetId. (This used to be essential for Jalview Project archives, but
2756    * these now use viewId. Unique view names are still desirable for usability.)
2757    * 
2758    * @param viewTitle
2759    * @return
2760    */
2761   protected String getNewViewName(String viewTitle)
2762   {
2763     int index = Desktop.getViewCount(viewport.getSequenceSetId());
2764     boolean addFirstIndex = false;
2765     if (viewTitle == null || viewTitle.trim().length() == 0)
2766     {
2767       viewTitle = MessageManager.getString("action.view");
2768       addFirstIndex = true;
2769     }
2770     else
2771     {
2772       index = 1;// we count from 1 if given a specific name
2773     }
2774     String newViewName = viewTitle + ((addFirstIndex) ? " " + index : "");
2775
2776     List<Component> comps = PaintRefresher.components.get(viewport
2777             .getSequenceSetId());
2778
2779     List<String> existingNames = getExistingViewNames(comps);
2780
2781     while (existingNames.contains(newViewName))
2782     {
2783       newViewName = viewTitle + " " + (++index);
2784     }
2785     return newViewName;
2786   }
2787
2788   /**
2789    * Returns a list of distinct view names found in the given list of
2790    * components. View names are held on the viewport of an AlignmentPanel.
2791    * 
2792    * @param comps
2793    * @return
2794    */
2795   protected List<String> getExistingViewNames(List<Component> comps)
2796   {
2797     List<String> existingNames = new ArrayList<String>();
2798     for (Component comp : comps)
2799     {
2800       if (comp instanceof AlignmentPanel)
2801       {
2802         AlignmentPanel ap = (AlignmentPanel) comp;
2803         if (!existingNames.contains(ap.av.viewName))
2804         {
2805           existingNames.add(ap.av.viewName);
2806         }
2807       }
2808     }
2809     return existingNames;
2810   }
2811
2812   /**
2813    * Explode tabbed views into separate windows.
2814    */
2815   @Override
2816   public void expandViews_actionPerformed(ActionEvent e)
2817   {
2818     Desktop.instance.explodeViews(this);
2819   }
2820
2821   /**
2822    * Gather views in separate windows back into a tabbed presentation.
2823    */
2824   @Override
2825   public void gatherViews_actionPerformed(ActionEvent e)
2826   {
2827     Desktop.instance.gatherViews(this);
2828   }
2829
2830   /**
2831    * DOCUMENT ME!
2832    * 
2833    * @param e
2834    *          DOCUMENT ME!
2835    */
2836   @Override
2837   public void font_actionPerformed(ActionEvent e)
2838   {
2839     new FontChooser(alignPanel);
2840   }
2841
2842   /**
2843    * DOCUMENT ME!
2844    * 
2845    * @param e
2846    *          DOCUMENT ME!
2847    */
2848   @Override
2849   protected void seqLimit_actionPerformed(ActionEvent e)
2850   {
2851     viewport.setShowJVSuffix(seqLimits.isSelected());
2852
2853     alignPanel.getIdPanel().getIdCanvas().setPreferredSize(alignPanel
2854             .calculateIdWidth());
2855     alignPanel.paintAlignment(true);
2856   }
2857
2858   @Override
2859   public void idRightAlign_actionPerformed(ActionEvent e)
2860   {
2861     viewport.setRightAlignIds(idRightAlign.isSelected());
2862     alignPanel.paintAlignment(true);
2863   }
2864
2865   @Override
2866   public void centreColumnLabels_actionPerformed(ActionEvent e)
2867   {
2868     viewport.centreColumnLabels = centreColumnLabelsMenuItem.getState();
2869     alignPanel.paintAlignment(true);
2870   }
2871
2872   /*
2873    * (non-Javadoc)
2874    * 
2875    * @see jalview.jbgui.GAlignFrame#followHighlight_actionPerformed()
2876    */
2877   @Override
2878   protected void followHighlight_actionPerformed()
2879   {
2880     if (viewport.followHighlight = this.followHighlightMenuItem.getState())
2881     {
2882       alignPanel.scrollToPosition(
2883               alignPanel.getSeqPanel().seqCanvas.searchResults, false);
2884     }
2885   }
2886
2887   /**
2888    * DOCUMENT ME!
2889    * 
2890    * @param e
2891    *          DOCUMENT ME!
2892    */
2893   @Override
2894   protected void colourTextMenuItem_actionPerformed(ActionEvent e)
2895   {
2896     viewport.setColourText(colourTextMenuItem.isSelected());
2897     alignPanel.paintAlignment(true);
2898   }
2899
2900   /**
2901    * DOCUMENT ME!
2902    * 
2903    * @param e
2904    *          DOCUMENT ME!
2905    */
2906   @Override
2907   public void wrapMenuItem_actionPerformed(ActionEvent e)
2908   {
2909     scaleAbove.setVisible(wrapMenuItem.isSelected());
2910     scaleLeft.setVisible(wrapMenuItem.isSelected());
2911     scaleRight.setVisible(wrapMenuItem.isSelected());
2912     viewport.setWrapAlignment(wrapMenuItem.isSelected());
2913     alignPanel.setWrapAlignment(wrapMenuItem.isSelected());
2914   }
2915
2916   @Override
2917   public void showAllSeqs_actionPerformed(ActionEvent e)
2918   {
2919     viewport.showAllHiddenSeqs();
2920   }
2921
2922   @Override
2923   public void showAllColumns_actionPerformed(ActionEvent e)
2924   {
2925     viewport.showAllHiddenColumns();
2926     repaint();
2927   }
2928
2929   @Override
2930   public void hideSelSequences_actionPerformed(ActionEvent e)
2931   {
2932     viewport.hideAllSelectedSeqs();
2933     alignPanel.paintAlignment(true);
2934   }
2935
2936   /**
2937    * called by key handler and the hide all/show all menu items
2938    * 
2939    * @param toggleSeqs
2940    * @param toggleCols
2941    */
2942   private void toggleHiddenRegions(boolean toggleSeqs, boolean toggleCols)
2943   {
2944
2945     boolean hide = false;
2946     SequenceGroup sg = viewport.getSelectionGroup();
2947     if (!toggleSeqs && !toggleCols)
2948     {
2949       // Hide everything by the current selection - this is a hack - we do the
2950       // invert and then hide
2951       // first check that there will be visible columns after the invert.
2952       if ((viewport.getColumnSelection() != null
2953               && viewport.getColumnSelection().getSelected() != null && viewport
2954               .getColumnSelection().getSelected().size() > 0)
2955               || (sg != null && sg.getSize() > 0 && sg.getStartRes() <= sg
2956                       .getEndRes()))
2957       {
2958         // now invert the sequence set, if required - empty selection implies
2959         // that no hiding is required.
2960         if (sg != null)
2961         {
2962           invertSequenceMenuItem_actionPerformed(null);
2963           sg = viewport.getSelectionGroup();
2964           toggleSeqs = true;
2965
2966         }
2967         viewport.expandColSelection(sg, true);
2968         // finally invert the column selection and get the new sequence
2969         // selection.
2970         invertColSel_actionPerformed(null);
2971         toggleCols = true;
2972       }
2973     }
2974
2975     if (toggleSeqs)
2976     {
2977       if (sg != null && sg.getSize() != viewport.getAlignment().getHeight())
2978       {
2979         hideSelSequences_actionPerformed(null);
2980         hide = true;
2981       }
2982       else if (!(toggleCols && viewport.getColumnSelection().getSelected()
2983               .size() > 0))
2984       {
2985         showAllSeqs_actionPerformed(null);
2986       }
2987     }
2988
2989     if (toggleCols)
2990     {
2991       if (viewport.getColumnSelection().getSelected().size() > 0)
2992       {
2993         hideSelColumns_actionPerformed(null);
2994         if (!toggleSeqs)
2995         {
2996           viewport.setSelectionGroup(sg);
2997         }
2998       }
2999       else if (!hide)
3000       {
3001         showAllColumns_actionPerformed(null);
3002       }
3003     }
3004   }
3005
3006   /*
3007    * (non-Javadoc)
3008    * 
3009    * @see
3010    * jalview.jbgui.GAlignFrame#hideAllButSelection_actionPerformed(java.awt.
3011    * event.ActionEvent)
3012    */
3013   @Override
3014   public void hideAllButSelection_actionPerformed(ActionEvent e)
3015   {
3016     toggleHiddenRegions(false, false);
3017   }
3018
3019   /*
3020    * (non-Javadoc)
3021    * 
3022    * @see
3023    * jalview.jbgui.GAlignFrame#hideAllSelection_actionPerformed(java.awt.event
3024    * .ActionEvent)
3025    */
3026   @Override
3027   public void hideAllSelection_actionPerformed(ActionEvent e)
3028   {
3029     SequenceGroup sg = viewport.getSelectionGroup();
3030     viewport.expandColSelection(sg, false);
3031     viewport.hideAllSelectedSeqs();
3032     viewport.hideSelectedColumns();
3033     alignPanel.paintAlignment(true);
3034   }
3035
3036   /*
3037    * (non-Javadoc)
3038    * 
3039    * @see
3040    * jalview.jbgui.GAlignFrame#showAllhidden_actionPerformed(java.awt.event.
3041    * ActionEvent)
3042    */
3043   @Override
3044   public void showAllhidden_actionPerformed(ActionEvent e)
3045   {
3046     viewport.showAllHiddenColumns();
3047     viewport.showAllHiddenSeqs();
3048     alignPanel.paintAlignment(true);
3049   }
3050
3051   @Override
3052   public void hideSelColumns_actionPerformed(ActionEvent e)
3053   {
3054     viewport.hideSelectedColumns();
3055     alignPanel.paintAlignment(true);
3056   }
3057
3058   @Override
3059   public void hiddenMarkers_actionPerformed(ActionEvent e)
3060   {
3061     viewport.setShowHiddenMarkers(hiddenMarkers.isSelected());
3062     repaint();
3063   }
3064
3065   /**
3066    * DOCUMENT ME!
3067    * 
3068    * @param e
3069    *          DOCUMENT ME!
3070    */
3071   @Override
3072   protected void scaleAbove_actionPerformed(ActionEvent e)
3073   {
3074     viewport.setScaleAboveWrapped(scaleAbove.isSelected());
3075     alignPanel.paintAlignment(true);
3076   }
3077
3078   /**
3079    * DOCUMENT ME!
3080    * 
3081    * @param e
3082    *          DOCUMENT ME!
3083    */
3084   @Override
3085   protected void scaleLeft_actionPerformed(ActionEvent e)
3086   {
3087     viewport.setScaleLeftWrapped(scaleLeft.isSelected());
3088     alignPanel.paintAlignment(true);
3089   }
3090
3091   /**
3092    * DOCUMENT ME!
3093    * 
3094    * @param e
3095    *          DOCUMENT ME!
3096    */
3097   @Override
3098   protected void scaleRight_actionPerformed(ActionEvent e)
3099   {
3100     viewport.setScaleRightWrapped(scaleRight.isSelected());
3101     alignPanel.paintAlignment(true);
3102   }
3103
3104   /**
3105    * DOCUMENT ME!
3106    * 
3107    * @param e
3108    *          DOCUMENT ME!
3109    */
3110   @Override
3111   public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
3112   {
3113     viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
3114     alignPanel.paintAlignment(true);
3115   }
3116
3117   /**
3118    * DOCUMENT ME!
3119    * 
3120    * @param e
3121    *          DOCUMENT ME!
3122    */
3123   @Override
3124   public void viewTextMenuItem_actionPerformed(ActionEvent e)
3125   {
3126     viewport.setShowText(viewTextMenuItem.isSelected());
3127     alignPanel.paintAlignment(true);
3128   }
3129
3130   /**
3131    * DOCUMENT ME!
3132    * 
3133    * @param e
3134    *          DOCUMENT ME!
3135    */
3136   @Override
3137   protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
3138   {
3139     viewport.setRenderGaps(renderGapsMenuItem.isSelected());
3140     alignPanel.paintAlignment(true);
3141   }
3142
3143   public FeatureSettings featureSettings;
3144
3145   @Override
3146   public void featureSettings_actionPerformed(ActionEvent e)
3147   {
3148     if (featureSettings != null)
3149     {
3150       featureSettings.close();
3151       featureSettings = null;
3152     }
3153     if (!showSeqFeatures.isSelected())
3154     {
3155       // make sure features are actually displayed
3156       showSeqFeatures.setSelected(true);
3157       showSeqFeatures_actionPerformed(null);
3158     }
3159     featureSettings = new FeatureSettings(this);
3160   }
3161
3162   /**
3163    * Set or clear 'Show Sequence Features'
3164    * 
3165    * @param evt
3166    *          DOCUMENT ME!
3167    */
3168   @Override
3169   public void showSeqFeatures_actionPerformed(ActionEvent evt)
3170   {
3171     viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
3172     alignPanel.paintAlignment(true);
3173     if (alignPanel.getOverviewPanel() != null)
3174     {
3175       alignPanel.getOverviewPanel().updateOverviewImage();
3176     }
3177   }
3178
3179   /**
3180    * Set or clear 'Show Sequence Features'
3181    * 
3182    * @param evt
3183    *          DOCUMENT ME!
3184    */
3185   @Override
3186   public void showSeqFeaturesHeight_actionPerformed(ActionEvent evt)
3187   {
3188     viewport.setShowSequenceFeaturesHeight(showSeqFeaturesHeight
3189             .isSelected());
3190     if (viewport.isShowSequenceFeaturesHeight())
3191     {
3192       // ensure we're actually displaying features
3193       viewport.setShowSequenceFeatures(true);
3194       showSeqFeatures.setSelected(true);
3195     }
3196     alignPanel.paintAlignment(true);
3197     if (alignPanel.getOverviewPanel() != null)
3198     {
3199       alignPanel.getOverviewPanel().updateOverviewImage();
3200     }
3201   }
3202
3203   /**
3204    * Action on toggle of the 'Show annotations' menu item. This shows or hides
3205    * the annotations panel as a whole.
3206    * 
3207    * The options to show/hide all annotations should be enabled when the panel
3208    * is shown, and disabled when the panel is hidden.
3209    * 
3210    * @param e
3211    */
3212   @Override
3213   public void annotationPanelMenuItem_actionPerformed(ActionEvent e)
3214   {
3215     final boolean setVisible = annotationPanelMenuItem.isSelected();
3216     viewport.setShowAnnotation(setVisible);
3217     alignPanel.setAnnotationVisible(setVisible);
3218     this.showAllSeqAnnotations.setEnabled(setVisible);
3219     this.hideAllSeqAnnotations.setEnabled(setVisible);
3220     this.showAllAlAnnotations.setEnabled(setVisible);
3221     this.hideAllAlAnnotations.setEnabled(setVisible);
3222   }
3223
3224   @Override
3225   public void alignmentProperties()
3226   {
3227     JEditorPane editPane = new JEditorPane("text/html", "");
3228     editPane.setEditable(false);
3229     StringBuffer contents = new AlignmentProperties(viewport.getAlignment())
3230             .formatAsHtml();
3231     editPane.setText(MessageManager.formatMessage("label.html_content",
3232             new Object[]
3233             { contents.toString() }));
3234     JInternalFrame frame = new JInternalFrame();
3235     frame.getContentPane().add(new JScrollPane(editPane));
3236
3237     Desktop.addInternalFrame(frame, MessageManager.formatMessage(
3238             "label.alignment_properties", new Object[]
3239             { getTitle() }), 500, 400);
3240   }
3241
3242   /**
3243    * DOCUMENT ME!
3244    * 
3245    * @param e
3246    *          DOCUMENT ME!
3247    */
3248   @Override
3249   public void overviewMenuItem_actionPerformed(ActionEvent e)
3250   {
3251     if (alignPanel.overviewPanel != null)
3252     {
3253       return;
3254     }
3255
3256     JInternalFrame frame = new JInternalFrame();
3257     OverviewPanel overview = new OverviewPanel(alignPanel);
3258     frame.setContentPane(overview);
3259     Desktop.addInternalFrame(frame, MessageManager.formatMessage(
3260             "label.overview_params", new Object[]
3261             { this.getTitle() }), frame.getWidth(), frame.getHeight());
3262     frame.pack();
3263     frame.setLayer(JLayeredPane.PALETTE_LAYER);
3264     frame.addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
3265     {
3266       @Override
3267       public void internalFrameClosed(
3268               javax.swing.event.InternalFrameEvent evt)
3269       {
3270         alignPanel.setOverviewPanel(null);
3271       };
3272     });
3273
3274     alignPanel.setOverviewPanel(overview);
3275   }
3276
3277   @Override
3278   public void textColour_actionPerformed(ActionEvent e)
3279   {
3280     new TextColourChooser().chooseColour(alignPanel, null);
3281   }
3282
3283   /**
3284    * DOCUMENT ME!
3285    * 
3286    * @param e
3287    *          DOCUMENT ME!
3288    */
3289   @Override
3290   protected void noColourmenuItem_actionPerformed(ActionEvent e)
3291   {
3292     changeColour(null);
3293   }
3294
3295   /**
3296    * DOCUMENT ME!
3297    * 
3298    * @param e
3299    *          DOCUMENT ME!
3300    */
3301   @Override
3302   public void clustalColour_actionPerformed(ActionEvent e)
3303   {
3304     changeColour(new ClustalxColourScheme(viewport.getAlignment(),
3305             viewport.getHiddenRepSequences()));
3306   }
3307
3308   /**
3309    * DOCUMENT ME!
3310    * 
3311    * @param e
3312    *          DOCUMENT ME!
3313    */
3314   @Override
3315   public void zappoColour_actionPerformed(ActionEvent e)
3316   {
3317     changeColour(new ZappoColourScheme());
3318   }
3319
3320   /**
3321    * DOCUMENT ME!
3322    * 
3323    * @param e
3324    *          DOCUMENT ME!
3325    */
3326   @Override
3327   public void taylorColour_actionPerformed(ActionEvent e)
3328   {
3329     changeColour(new TaylorColourScheme());
3330   }
3331
3332   /**
3333    * DOCUMENT ME!
3334    * 
3335    * @param e
3336    *          DOCUMENT ME!
3337    */
3338   @Override
3339   public void hydrophobicityColour_actionPerformed(ActionEvent e)
3340   {
3341     changeColour(new HydrophobicColourScheme());
3342   }
3343
3344   /**
3345    * DOCUMENT ME!
3346    * 
3347    * @param e
3348    *          DOCUMENT ME!
3349    */
3350   @Override
3351   public void helixColour_actionPerformed(ActionEvent e)
3352   {
3353     changeColour(new HelixColourScheme());
3354   }
3355
3356   /**
3357    * DOCUMENT ME!
3358    * 
3359    * @param e
3360    *          DOCUMENT ME!
3361    */
3362   @Override
3363   public void strandColour_actionPerformed(ActionEvent e)
3364   {
3365     changeColour(new StrandColourScheme());
3366   }
3367
3368   /**
3369    * DOCUMENT ME!
3370    * 
3371    * @param e
3372    *          DOCUMENT ME!
3373    */
3374   @Override
3375   public void turnColour_actionPerformed(ActionEvent e)
3376   {
3377     changeColour(new TurnColourScheme());
3378   }
3379
3380   /**
3381    * DOCUMENT ME!
3382    * 
3383    * @param e
3384    *          DOCUMENT ME!
3385    */
3386   @Override
3387   public void buriedColour_actionPerformed(ActionEvent e)
3388   {
3389     changeColour(new BuriedColourScheme());
3390   }
3391
3392   /**
3393    * DOCUMENT ME!
3394    * 
3395    * @param e
3396    *          DOCUMENT ME!
3397    */
3398   @Override
3399   public void nucleotideColour_actionPerformed(ActionEvent e)
3400   {
3401     changeColour(new NucleotideColourScheme());
3402   }
3403
3404   @Override
3405   public void purinePyrimidineColour_actionPerformed(ActionEvent e)
3406   {
3407     changeColour(new PurinePyrimidineColourScheme());
3408   }
3409
3410   /*
3411    * public void covariationColour_actionPerformed(ActionEvent e) {
3412    * changeColour(new
3413    * CovariationColourScheme(viewport.getAlignment().getAlignmentAnnotation
3414    * ()[0])); }
3415    */
3416   @Override
3417   public void annotationColour_actionPerformed(ActionEvent e)
3418   {
3419     new AnnotationColourChooser(viewport, alignPanel);
3420   }
3421
3422   @Override
3423   public void annotationColumn_actionPerformed(ActionEvent e)
3424   {
3425     new AnnotationColumnChooser(viewport, alignPanel);
3426   }
3427
3428   @Override
3429   public void rnahelicesColour_actionPerformed(ActionEvent e)
3430   {
3431     new RNAHelicesColourChooser(viewport, alignPanel);
3432   }
3433
3434   /**
3435    * DOCUMENT ME!
3436    * 
3437    * @param e
3438    *          DOCUMENT ME!
3439    */
3440   @Override
3441   protected void applyToAllGroups_actionPerformed(ActionEvent e)
3442   {
3443     viewport.setColourAppliesToAllGroups(applyToAllGroups.isSelected());
3444   }
3445
3446   /**
3447    * DOCUMENT ME!
3448    * 
3449    * @param cs
3450    *          DOCUMENT ME!
3451    */
3452   public void changeColour(ColourSchemeI cs)
3453   {
3454     // TODO: compare with applet and pull up to model method
3455     int threshold = 0;
3456
3457     if (cs != null)
3458     {
3459       if (viewport.getAbovePIDThreshold())
3460       {
3461         threshold = SliderPanel.setPIDSliderSource(alignPanel, cs,
3462                 "Background");
3463         cs.setThreshold(threshold, viewport.getIgnoreGapsConsensus());
3464       }
3465       else
3466       {
3467         cs.setThreshold(0, viewport.getIgnoreGapsConsensus());
3468       }
3469
3470       if (viewport.getConservationSelected())
3471       {
3472
3473         Alignment al = (Alignment) viewport.getAlignment();
3474         Conservation c = new Conservation("All",
3475                 ResidueProperties.propHash, 3, al.getSequences(), 0,
3476                 al.getWidth() - 1);
3477
3478         c.calculate();
3479         c.verdict(false, viewport.getConsPercGaps());
3480
3481         cs.setConservation(c);
3482
3483         cs.setConservationInc(SliderPanel.setConservationSlider(alignPanel,
3484                 cs, "Background"));
3485       }
3486       else
3487       {
3488         cs.setConservation(null);
3489       }
3490
3491       cs.setConsensus(viewport.getSequenceConsensusHash());
3492     }
3493
3494     viewport.setGlobalColourScheme(cs);
3495
3496     if (viewport.getColourAppliesToAllGroups())
3497     {
3498
3499       for (SequenceGroup sg : viewport.getAlignment().getGroups())
3500       {
3501         if (cs == null)
3502         {
3503           sg.cs = null;
3504           continue;
3505         }
3506
3507         if (cs instanceof ClustalxColourScheme)
3508         {
3509           sg.cs = new ClustalxColourScheme(sg,
3510                   viewport.getHiddenRepSequences());
3511         }
3512         else if (cs instanceof UserColourScheme)
3513         {
3514           sg.cs = new UserColourScheme(((UserColourScheme) cs).getColours());
3515         }
3516         else
3517         {
3518           try
3519           {
3520             sg.cs = cs.getClass().newInstance();
3521           } catch (Exception ex)
3522           {
3523           }
3524         }
3525
3526         if (viewport.getAbovePIDThreshold()
3527                 || cs instanceof PIDColourScheme
3528                 || cs instanceof Blosum62ColourScheme)
3529         {
3530           sg.cs.setThreshold(threshold, viewport.getIgnoreGapsConsensus());
3531
3532           sg.cs.setConsensus(AAFrequency.calculate(
3533                   sg.getSequences(viewport.getHiddenRepSequences()),
3534                   sg.getStartRes(), sg.getEndRes() + 1));
3535         }
3536         else
3537         {
3538           sg.cs.setThreshold(0, viewport.getIgnoreGapsConsensus());
3539         }
3540
3541         if (viewport.getConservationSelected())
3542         {
3543           Conservation c = new Conservation("Group",
3544                   ResidueProperties.propHash, 3, sg.getSequences(viewport
3545                           .getHiddenRepSequences()), sg.getStartRes(),
3546                   sg.getEndRes() + 1);
3547           c.calculate();
3548           c.verdict(false, viewport.getConsPercGaps());
3549           sg.cs.setConservation(c);
3550         }
3551         else
3552         {
3553           sg.cs.setConservation(null);
3554         }
3555       }
3556     }
3557
3558     if (alignPanel.getOverviewPanel() != null)
3559     {
3560       alignPanel.getOverviewPanel().updateOverviewImage();
3561     }
3562
3563     alignPanel.paintAlignment(true);
3564   }
3565
3566   /**
3567    * DOCUMENT ME!
3568    * 
3569    * @param e
3570    *          DOCUMENT ME!
3571    */
3572   @Override
3573   protected void modifyPID_actionPerformed(ActionEvent e)
3574   {
3575     if (viewport.getAbovePIDThreshold()
3576             && viewport.getGlobalColourScheme() != null)
3577     {
3578       SliderPanel.setPIDSliderSource(alignPanel,
3579               viewport.getGlobalColourScheme(), "Background");
3580       SliderPanel.showPIDSlider();
3581     }
3582   }
3583
3584   /**
3585    * DOCUMENT ME!
3586    * 
3587    * @param e
3588    *          DOCUMENT ME!
3589    */
3590   @Override
3591   protected void modifyConservation_actionPerformed(ActionEvent e)
3592   {
3593     if (viewport.getConservationSelected()
3594             && viewport.getGlobalColourScheme() != null)
3595     {
3596       SliderPanel.setConservationSlider(alignPanel,
3597               viewport.getGlobalColourScheme(), "Background");
3598       SliderPanel.showConservationSlider();
3599     }
3600   }
3601
3602   /**
3603    * DOCUMENT ME!
3604    * 
3605    * @param e
3606    *          DOCUMENT ME!
3607    */
3608   @Override
3609   protected void conservationMenuItem_actionPerformed(ActionEvent e)
3610   {
3611     viewport.setConservationSelected(conservationMenuItem.isSelected());
3612
3613     viewport.setAbovePIDThreshold(false);
3614     abovePIDThreshold.setSelected(false);
3615
3616     changeColour(viewport.getGlobalColourScheme());
3617
3618     modifyConservation_actionPerformed(null);
3619   }
3620
3621   /**
3622    * DOCUMENT ME!
3623    * 
3624    * @param e
3625    *          DOCUMENT ME!
3626    */
3627   @Override
3628   public void abovePIDThreshold_actionPerformed(ActionEvent e)
3629   {
3630     viewport.setAbovePIDThreshold(abovePIDThreshold.isSelected());
3631
3632     conservationMenuItem.setSelected(false);
3633     viewport.setConservationSelected(false);
3634
3635     changeColour(viewport.getGlobalColourScheme());
3636
3637     modifyPID_actionPerformed(null);
3638   }
3639
3640   /**
3641    * DOCUMENT ME!
3642    * 
3643    * @param e
3644    *          DOCUMENT ME!
3645    */
3646   @Override
3647   public void userDefinedColour_actionPerformed(ActionEvent e)
3648   {
3649     if (e.getActionCommand().equals(
3650             MessageManager.getString("action.user_defined")))
3651     {
3652       new UserDefinedColours(alignPanel, null);
3653     }
3654     else
3655     {
3656       UserColourScheme udc = (UserColourScheme) UserDefinedColours
3657               .getUserColourSchemes().get(e.getActionCommand());
3658
3659       changeColour(udc);
3660     }
3661   }
3662
3663   public void updateUserColourMenu()
3664   {
3665
3666     Component[] menuItems = colourMenu.getMenuComponents();
3667     int iSize = menuItems.length;
3668     for (int i = 0; i < iSize; i++)
3669     {
3670       if (menuItems[i].getName() != null
3671               && menuItems[i].getName().equals("USER_DEFINED"))
3672       {
3673         colourMenu.remove(menuItems[i]);
3674         iSize--;
3675       }
3676     }
3677     if (jalview.gui.UserDefinedColours.getUserColourSchemes() != null)
3678     {
3679       java.util.Enumeration userColours = jalview.gui.UserDefinedColours
3680               .getUserColourSchemes().keys();
3681
3682       while (userColours.hasMoreElements())
3683       {
3684         final JRadioButtonMenuItem radioItem = new JRadioButtonMenuItem(
3685                 userColours.nextElement().toString());
3686         radioItem.setName("USER_DEFINED");
3687         radioItem.addMouseListener(new MouseAdapter()
3688         {
3689           @Override
3690           public void mousePressed(MouseEvent evt)
3691           {
3692             if (evt.isControlDown()
3693                     || SwingUtilities.isRightMouseButton(evt))
3694             {
3695               radioItem.removeActionListener(radioItem.getActionListeners()[0]);
3696
3697               int option = JOptionPane.showInternalConfirmDialog(
3698                       jalview.gui.Desktop.desktop,
3699                       MessageManager
3700                               .getString("label.remove_from_default_list"),
3701                       MessageManager
3702                               .getString("label.remove_user_defined_colour"),
3703                       JOptionPane.YES_NO_OPTION);
3704               if (option == JOptionPane.YES_OPTION)
3705               {
3706                 jalview.gui.UserDefinedColours
3707                         .removeColourFromDefaults(radioItem.getText());
3708                 colourMenu.remove(radioItem);
3709               }
3710               else
3711               {
3712                 radioItem.addActionListener(new ActionListener()
3713                 {
3714                   @Override
3715                   public void actionPerformed(ActionEvent evt)
3716                   {
3717                     userDefinedColour_actionPerformed(evt);
3718                   }
3719                 });
3720               }
3721             }
3722           }
3723         });
3724         radioItem.addActionListener(new ActionListener()
3725         {
3726           @Override
3727           public void actionPerformed(ActionEvent evt)
3728           {
3729             userDefinedColour_actionPerformed(evt);
3730           }
3731         });
3732
3733         colourMenu.insert(radioItem, 15);
3734         colours.add(radioItem);
3735       }
3736     }
3737   }
3738
3739   /**
3740    * DOCUMENT ME!
3741    * 
3742    * @param e
3743    *          DOCUMENT ME!
3744    */
3745   @Override
3746   public void PIDColour_actionPerformed(ActionEvent e)
3747   {
3748     changeColour(new PIDColourScheme());
3749   }
3750
3751   /**
3752    * DOCUMENT ME!
3753    * 
3754    * @param e
3755    *          DOCUMENT ME!
3756    */
3757   @Override
3758   public void BLOSUM62Colour_actionPerformed(ActionEvent e)
3759   {
3760     changeColour(new Blosum62ColourScheme());
3761   }
3762
3763   /**
3764    * DOCUMENT ME!
3765    * 
3766    * @param e
3767    *          DOCUMENT ME!
3768    */
3769   @Override
3770   public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
3771   {
3772     SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3773     AlignmentSorter.sortByPID(viewport.getAlignment(), viewport
3774             .getAlignment().getSequenceAt(0), null);
3775     addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
3776             viewport.getAlignment()));
3777     alignPanel.paintAlignment(true);
3778   }
3779
3780   /**
3781    * DOCUMENT ME!
3782    * 
3783    * @param e
3784    *          DOCUMENT ME!
3785    */
3786   @Override
3787   public void sortIDMenuItem_actionPerformed(ActionEvent e)
3788   {
3789     SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3790     AlignmentSorter.sortByID(viewport.getAlignment());
3791     addHistoryItem(new OrderCommand("ID Sort", oldOrder,
3792             viewport.getAlignment()));
3793     alignPanel.paintAlignment(true);
3794   }
3795
3796   /**
3797    * DOCUMENT ME!
3798    * 
3799    * @param e
3800    *          DOCUMENT ME!
3801    */
3802   @Override
3803   public void sortLengthMenuItem_actionPerformed(ActionEvent e)
3804   {
3805     SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3806     AlignmentSorter.sortByLength(viewport.getAlignment());
3807     addHistoryItem(new OrderCommand("Length Sort", oldOrder,
3808             viewport.getAlignment()));
3809     alignPanel.paintAlignment(true);
3810   }
3811
3812   /**
3813    * DOCUMENT ME!
3814    * 
3815    * @param e
3816    *          DOCUMENT ME!
3817    */
3818   @Override
3819   public void sortGroupMenuItem_actionPerformed(ActionEvent e)
3820   {
3821     SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
3822     AlignmentSorter.sortByGroup(viewport.getAlignment());
3823     addHistoryItem(new OrderCommand("Group Sort", oldOrder,
3824             viewport.getAlignment()));
3825
3826     alignPanel.paintAlignment(true);
3827   }
3828
3829   /**
3830    * DOCUMENT ME!
3831    * 
3832    * @param e
3833    *          DOCUMENT ME!
3834    */
3835   @Override
3836   public void removeRedundancyMenuItem_actionPerformed(ActionEvent e)
3837   {
3838     new RedundancyPanel(alignPanel, this);
3839   }
3840
3841   /**
3842    * DOCUMENT ME!
3843    * 
3844    * @param e
3845    *          DOCUMENT ME!
3846    */
3847   @Override
3848   public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
3849   {
3850     if ((viewport.getSelectionGroup() == null)
3851             || (viewport.getSelectionGroup().getSize() < 2))
3852     {
3853       JOptionPane.showInternalMessageDialog(this, MessageManager
3854               .getString("label.you_must_select_least_two_sequences"),
3855               MessageManager.getString("label.invalid_selection"),
3856               JOptionPane.WARNING_MESSAGE);
3857     }
3858     else
3859     {
3860       JInternalFrame frame = new JInternalFrame();
3861       frame.setContentPane(new PairwiseAlignPanel(viewport));
3862       Desktop.addInternalFrame(frame,
3863               MessageManager.getString("action.pairwise_alignment"), 600,
3864               500);
3865     }
3866   }
3867
3868   /**
3869    * DOCUMENT ME!
3870    * 
3871    * @param e
3872    *          DOCUMENT ME!
3873    */
3874   @Override
3875   public void PCAMenuItem_actionPerformed(ActionEvent e)
3876   {
3877     if (((viewport.getSelectionGroup() != null)
3878             && (viewport.getSelectionGroup().getSize() < 4) && (viewport
3879             .getSelectionGroup().getSize() > 0))
3880             || (viewport.getAlignment().getHeight() < 4))
3881     {
3882       JOptionPane
3883               .showInternalMessageDialog(
3884                       this,
3885                       MessageManager
3886                               .getString("label.principal_component_analysis_must_take_least_four_input_sequences"),
3887                       MessageManager
3888                               .getString("label.sequence_selection_insufficient"),
3889                       JOptionPane.WARNING_MESSAGE);
3890
3891       return;
3892     }
3893
3894     new PCAPanel(alignPanel);
3895   }
3896
3897   @Override
3898   public void autoCalculate_actionPerformed(ActionEvent e)
3899   {
3900     viewport.autoCalculateConsensus = autoCalculate.isSelected();
3901     if (viewport.autoCalculateConsensus)
3902     {
3903       viewport.firePropertyChange("alignment", null, viewport
3904               .getAlignment().getSequences());
3905     }
3906   }
3907
3908   @Override
3909   public void sortByTreeOption_actionPerformed(ActionEvent e)
3910   {
3911     viewport.sortByTree = sortByTree.isSelected();
3912   }
3913
3914   @Override
3915   protected void listenToViewSelections_actionPerformed(ActionEvent e)
3916   {
3917     viewport.followSelection = listenToViewSelections.isSelected();
3918   }
3919
3920   /**
3921    * DOCUMENT ME!
3922    * 
3923    * @param e
3924    *          DOCUMENT ME!
3925    */
3926   @Override
3927   public void averageDistanceTreeMenuItem_actionPerformed(ActionEvent e)
3928   {
3929     newTreePanel("AV", "PID", "Average distance tree using PID");
3930   }
3931
3932   /**
3933    * DOCUMENT ME!
3934    * 
3935    * @param e
3936    *          DOCUMENT ME!
3937    */
3938   @Override
3939   public void neighbourTreeMenuItem_actionPerformed(ActionEvent e)
3940   {
3941     newTreePanel("NJ", "PID", "Neighbour joining tree using PID");
3942   }
3943
3944   /**
3945    * DOCUMENT ME!
3946    * 
3947    * @param e
3948    *          DOCUMENT ME!
3949    */
3950   @Override
3951   protected void njTreeBlosumMenuItem_actionPerformed(ActionEvent e)
3952   {
3953     newTreePanel("NJ", "BL", "Neighbour joining tree using BLOSUM62");
3954   }
3955
3956   /**
3957    * DOCUMENT ME!
3958    * 
3959    * @param e
3960    *          DOCUMENT ME!
3961    */
3962   @Override
3963   protected void avTreeBlosumMenuItem_actionPerformed(ActionEvent e)
3964   {
3965     newTreePanel("AV", "BL", "Average distance tree using BLOSUM62");
3966   }
3967
3968   /**
3969    * DOCUMENT ME!
3970    * 
3971    * @param type
3972    *          DOCUMENT ME!
3973    * @param pwType
3974    *          DOCUMENT ME!
3975    * @param title
3976    *          DOCUMENT ME!
3977    */
3978   void newTreePanel(String type, String pwType, String title)
3979   {
3980     TreePanel tp;
3981
3982     if (viewport.getSelectionGroup() != null
3983             && viewport.getSelectionGroup().getSize() > 0)
3984     {
3985       if (viewport.getSelectionGroup().getSize() < 3)
3986       {
3987         JOptionPane
3988                 .showMessageDialog(
3989                         Desktop.desktop,
3990                         MessageManager
3991                                 .getString("label.you_need_more_two_sequences_selected_build_tree"),
3992                         MessageManager
3993                                 .getString("label.not_enough_sequences"),
3994                         JOptionPane.WARNING_MESSAGE);
3995         return;
3996       }
3997
3998       SequenceGroup sg = viewport.getSelectionGroup();
3999
4000       /* Decide if the selection is a column region */
4001       for (SequenceI _s : sg.getSequences())
4002       {
4003         if (_s.getLength() < sg.getEndRes())
4004         {
4005           JOptionPane
4006                   .showMessageDialog(
4007                           Desktop.desktop,
4008                           MessageManager
4009                                   .getString("label.selected_region_to_tree_may_only_contain_residues_or_gaps"),
4010                           MessageManager
4011                                   .getString("label.sequences_selection_not_aligned"),
4012                           JOptionPane.WARNING_MESSAGE);
4013
4014           return;
4015         }
4016       }
4017
4018       title = title + " on region";
4019       tp = new TreePanel(alignPanel, type, pwType);
4020     }
4021     else
4022     {
4023       // are the visible sequences aligned?
4024       if (!viewport.getAlignment().isAligned(false))
4025       {
4026         JOptionPane
4027                 .showMessageDialog(
4028                         Desktop.desktop,
4029                         MessageManager
4030                                 .getString("label.sequences_must_be_aligned_before_creating_tree"),
4031                         MessageManager
4032                                 .getString("label.sequences_not_aligned"),
4033                         JOptionPane.WARNING_MESSAGE);
4034
4035         return;
4036       }
4037
4038       if (viewport.getAlignment().getHeight() < 2)
4039       {
4040         return;
4041       }
4042
4043       tp = new TreePanel(alignPanel, type, pwType);
4044     }
4045
4046     title += " from ";
4047
4048     if (viewport.viewName != null)
4049     {
4050       title += viewport.viewName + " of ";
4051     }
4052
4053     title += this.title;
4054
4055     Desktop.addInternalFrame(tp, title, 600, 500);
4056   }
4057
4058   /**
4059    * DOCUMENT ME!
4060    * 
4061    * @param title
4062    *          DOCUMENT ME!
4063    * @param order
4064    *          DOCUMENT ME!
4065    */
4066   public void addSortByOrderMenuItem(String title,
4067           final AlignmentOrder order)
4068   {
4069     final JMenuItem item = new JMenuItem(MessageManager.formatMessage("action.by_title_param", new Object[]{title}));
4070     sort.add(item);
4071     item.addActionListener(new java.awt.event.ActionListener()
4072     {
4073       @Override
4074       public void actionPerformed(ActionEvent e)
4075       {
4076         SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4077
4078         // TODO: JBPNote - have to map order entries to curent SequenceI
4079         // pointers
4080         AlignmentSorter.sortBy(viewport.getAlignment(), order);
4081
4082         addHistoryItem(new OrderCommand(order.getName(), oldOrder, viewport
4083                 .getAlignment()));
4084
4085         alignPanel.paintAlignment(true);
4086       }
4087     });
4088   }
4089
4090   /**
4091    * Add a new sort by annotation score menu item
4092    * 
4093    * @param sort
4094    *          the menu to add the option to
4095    * @param scoreLabel
4096    *          the label used to retrieve scores for each sequence on the
4097    *          alignment
4098    */
4099   public void addSortByAnnotScoreMenuItem(JMenu sort,
4100           final String scoreLabel)
4101   {
4102     final JMenuItem item = new JMenuItem(scoreLabel);
4103     sort.add(item);
4104     item.addActionListener(new java.awt.event.ActionListener()
4105     {
4106       @Override
4107       public void actionPerformed(ActionEvent e)
4108       {
4109         SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4110         AlignmentSorter.sortByAnnotationScore(scoreLabel,
4111                 viewport.getAlignment());// ,viewport.getSelectionGroup());
4112         addHistoryItem(new OrderCommand("Sort by " + scoreLabel, oldOrder,
4113                 viewport.getAlignment()));
4114         alignPanel.paintAlignment(true);
4115       }
4116     });
4117   }
4118
4119   /**
4120    * last hash for alignment's annotation array - used to minimise cost of
4121    * rebuild.
4122    */
4123   protected int _annotationScoreVectorHash;
4124
4125   /**
4126    * search the alignment and rebuild the sort by annotation score submenu the
4127    * last alignment annotation vector hash is stored to minimize cost of
4128    * rebuilding in subsequence calls.
4129    * 
4130    */
4131   @Override
4132   public void buildSortByAnnotationScoresMenu()
4133   {
4134     if (viewport.getAlignment().getAlignmentAnnotation() == null)
4135     {
4136       return;
4137     }
4138
4139     if (viewport.getAlignment().getAlignmentAnnotation().hashCode() != _annotationScoreVectorHash)
4140     {
4141       sortByAnnotScore.removeAll();
4142       // almost certainly a quicker way to do this - but we keep it simple
4143       Hashtable scoreSorts = new Hashtable();
4144       AlignmentAnnotation aann[];
4145       for (SequenceI sqa : viewport.getAlignment().getSequences())
4146       {
4147         aann = sqa.getAnnotation();
4148         for (int i = 0; aann != null && i < aann.length; i++)
4149         {
4150           if (aann[i].hasScore() && aann[i].sequenceRef != null)
4151           {
4152             scoreSorts.put(aann[i].label, aann[i].label);
4153           }
4154         }
4155       }
4156       Enumeration labels = scoreSorts.keys();
4157       while (labels.hasMoreElements())
4158       {
4159         addSortByAnnotScoreMenuItem(sortByAnnotScore,
4160                 (String) labels.nextElement());
4161       }
4162       sortByAnnotScore.setVisible(scoreSorts.size() > 0);
4163       scoreSorts.clear();
4164
4165       _annotationScoreVectorHash = viewport.getAlignment()
4166               .getAlignmentAnnotation().hashCode();
4167     }
4168   }
4169
4170   /**
4171    * Maintain the Order by->Displayed Tree menu. Creates a new menu item for a
4172    * TreePanel with an appropriate <code>jalview.analysis.AlignmentSorter</code>
4173    * call. Listeners are added to remove the menu item when the treePanel is
4174    * closed, and adjust the tree leaf to sequence mapping when the alignment is
4175    * modified.
4176    * 
4177    * @param treePanel
4178    *          Displayed tree window.
4179    * @param title
4180    *          SortBy menu item title.
4181    */
4182   @Override
4183   public void buildTreeMenu()
4184   {
4185     calculateTree.removeAll();
4186     // build the calculate menu
4187
4188     for (final String type : new String[]
4189     { "NJ", "AV" })
4190     {
4191       String treecalcnm = MessageManager.getString("label.tree_calc_"
4192               + type.toLowerCase());
4193       for (final String pwtype : ResidueProperties.scoreMatrices.keySet())
4194       {
4195         JMenuItem tm = new JMenuItem();
4196         ScoreModelI sm = ResidueProperties.scoreMatrices.get(pwtype);
4197         if (sm.isProtein() == !viewport.getAlignment().isNucleotide())
4198         {
4199           String smn = MessageManager.getStringOrReturn(
4200                   "label.score_model_", sm.getName());
4201           final String title = MessageManager.formatMessage(
4202                   "label.treecalc_title", treecalcnm, smn);
4203           tm.setText(title);//
4204           tm.addActionListener(new java.awt.event.ActionListener()
4205           {
4206             @Override
4207             public void actionPerformed(ActionEvent e)
4208             {
4209               newTreePanel(type, pwtype, title);
4210             }
4211           });
4212           calculateTree.add(tm);
4213         }
4214
4215       }
4216     }
4217     sortByTreeMenu.removeAll();
4218
4219     List<Component> comps = PaintRefresher.components.get(viewport
4220             .getSequenceSetId());
4221     List<TreePanel> treePanels = new ArrayList<TreePanel>();
4222     for (Component comp : comps)
4223     {
4224       if (comp instanceof TreePanel)
4225       {
4226         treePanels.add((TreePanel) comp);
4227       }
4228     }
4229
4230     if (treePanels.size() < 1)
4231     {
4232       sortByTreeMenu.setVisible(false);
4233       return;
4234     }
4235
4236     sortByTreeMenu.setVisible(true);
4237
4238     for (final TreePanel tp : treePanels)
4239     {
4240       final JMenuItem item = new JMenuItem(tp.getTitle());
4241       item.addActionListener(new java.awt.event.ActionListener()
4242       {
4243         @Override
4244         public void actionPerformed(ActionEvent e)
4245         {
4246           tp.sortByTree_actionPerformed();
4247           addHistoryItem(tp.sortAlignmentIn(alignPanel));
4248
4249         }
4250       });
4251
4252       sortByTreeMenu.add(item);
4253     }
4254   }
4255
4256   public boolean sortBy(AlignmentOrder alorder, String undoname)
4257   {
4258     SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
4259     AlignmentSorter.sortBy(viewport.getAlignment(), alorder);
4260     if (undoname != null)
4261     {
4262       addHistoryItem(new OrderCommand(undoname, oldOrder,
4263               viewport.getAlignment()));
4264     }
4265     alignPanel.paintAlignment(true);
4266     return true;
4267   }
4268
4269   /**
4270    * Work out whether the whole set of sequences or just the selected set will
4271    * be submitted for multiple alignment.
4272    * 
4273    */
4274   public jalview.datamodel.AlignmentView gatherSequencesForAlignment()
4275   {
4276     // Now, check we have enough sequences
4277     AlignmentView msa = null;
4278
4279     if ((viewport.getSelectionGroup() != null)
4280             && (viewport.getSelectionGroup().getSize() > 1))
4281     {
4282       // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to
4283       // some common interface!
4284       /*
4285        * SequenceGroup seqs = viewport.getSelectionGroup(); int sz; msa = new
4286        * SequenceI[sz = seqs.getSize(false)];
4287        * 
4288        * for (int i = 0; i < sz; i++) { msa[i] = (SequenceI)
4289        * seqs.getSequenceAt(i); }
4290        */
4291       msa = viewport.getAlignmentView(true);
4292     }
4293     else if (viewport.getSelectionGroup() != null
4294             && viewport.getSelectionGroup().getSize() == 1)
4295     {
4296       int option = JOptionPane.showConfirmDialog(this,
4297               MessageManager.getString("warn.oneseq_msainput_selection"),
4298               MessageManager.getString("label.invalid_selection"),
4299               JOptionPane.OK_CANCEL_OPTION);
4300       if (option == JOptionPane.OK_OPTION)
4301       {
4302         msa = viewport.getAlignmentView(false);
4303       }
4304     }
4305     else
4306     {
4307       msa = viewport.getAlignmentView(false);
4308     }
4309     return msa;
4310   }
4311
4312   /**
4313    * Decides what is submitted to a secondary structure prediction service: the
4314    * first sequence in the alignment, or in the current selection, or, if the
4315    * alignment is 'aligned' (ie padded with gaps), then the currently selected
4316    * region or the whole alignment. (where the first sequence in the set is the
4317    * one that the prediction will be for).
4318    */
4319   public AlignmentView gatherSeqOrMsaForSecStrPrediction()
4320   {
4321     AlignmentView seqs = null;
4322
4323     if ((viewport.getSelectionGroup() != null)
4324             && (viewport.getSelectionGroup().getSize() > 0))
4325     {
4326       seqs = viewport.getAlignmentView(true);
4327     }
4328     else
4329     {
4330       seqs = viewport.getAlignmentView(false);
4331     }
4332     // limit sequences - JBPNote in future - could spawn multiple prediction
4333     // jobs
4334     // TODO: viewport.getAlignment().isAligned is a global state - the local
4335     // selection may well be aligned - we preserve 2.0.8 behaviour for moment.
4336     if (!viewport.getAlignment().isAligned(false))
4337     {
4338       seqs.setSequences(new SeqCigar[]
4339       { seqs.getSequences()[0] });
4340       // TODO: if seqs.getSequences().length>1 then should really have warned
4341       // user!
4342
4343     }
4344     return seqs;
4345   }
4346
4347   /**
4348    * DOCUMENT ME!
4349    * 
4350    * @param e
4351    *          DOCUMENT ME!
4352    */
4353   @Override
4354   protected void LoadtreeMenuItem_actionPerformed(ActionEvent e)
4355   {
4356     // Pick the tree file
4357     JalviewFileChooser chooser = new JalviewFileChooser(
4358             jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
4359     chooser.setFileView(new JalviewFileView());
4360     chooser.setDialogTitle(MessageManager
4361             .getString("label.select_newick_like_tree_file"));
4362     chooser.setToolTipText(MessageManager.getString("label.load_tree_file"));
4363
4364     int value = chooser.showOpenDialog(null);
4365
4366     if (value == JalviewFileChooser.APPROVE_OPTION)
4367     {
4368       String choice = chooser.getSelectedFile().getPath();
4369       jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
4370       jalview.io.NewickFile fin = null;
4371       try
4372       {
4373         fin = new jalview.io.NewickFile(choice, "File");
4374         viewport.setCurrentTree(ShowNewickTree(fin, choice).getTree());
4375       } catch (Exception ex)
4376       {
4377         JOptionPane
4378                 .showMessageDialog(
4379                         Desktop.desktop,
4380                         ex.getMessage(),
4381                         MessageManager
4382                                 .getString("label.problem_reading_tree_file"),
4383                         JOptionPane.WARNING_MESSAGE);
4384         ex.printStackTrace();
4385       }
4386       if (fin != null && fin.hasWarningMessage())
4387       {
4388         JOptionPane.showMessageDialog(Desktop.desktop, fin
4389                 .getWarningMessage(), MessageManager
4390                 .getString("label.possible_problem_with_tree_file"),
4391                 JOptionPane.WARNING_MESSAGE);
4392       }
4393     }
4394   }
4395
4396   @Override
4397   protected void tcoffeeColorScheme_actionPerformed(ActionEvent e)
4398   {
4399     changeColour(new TCoffeeColourScheme(alignPanel.getAlignment()));
4400   }
4401
4402   public TreePanel ShowNewickTree(NewickFile nf, String title)
4403   {
4404     return ShowNewickTree(nf, title, 600, 500, 4, 5);
4405   }
4406
4407   public TreePanel ShowNewickTree(NewickFile nf, String title,
4408           AlignmentView input)
4409   {
4410     return ShowNewickTree(nf, title, input, 600, 500, 4, 5);
4411   }
4412
4413   public TreePanel ShowNewickTree(NewickFile nf, String title, int w,
4414           int h, int x, int y)
4415   {
4416     return ShowNewickTree(nf, title, null, w, h, x, y);
4417   }
4418
4419   /**
4420    * Add a treeviewer for the tree extracted from a newick file object to the
4421    * current alignment view
4422    * 
4423    * @param nf
4424    *          the tree
4425    * @param title
4426    *          tree viewer title
4427    * @param input
4428    *          Associated alignment input data (or null)
4429    * @param w
4430    *          width
4431    * @param h
4432    *          height
4433    * @param x
4434    *          position
4435    * @param y
4436    *          position
4437    * @return TreePanel handle
4438    */
4439   public TreePanel ShowNewickTree(NewickFile nf, String title,
4440           AlignmentView input, int w, int h, int x, int y)
4441   {
4442     TreePanel tp = null;
4443
4444     try
4445     {
4446       nf.parse();
4447
4448       if (nf.getTree() != null)
4449       {
4450         tp = new TreePanel(alignPanel, "FromFile", title, nf, input);
4451
4452         tp.setSize(w, h);
4453
4454         if (x > 0 && y > 0)
4455         {
4456           tp.setLocation(x, y);
4457         }
4458
4459         Desktop.addInternalFrame(tp, title, w, h);
4460       }
4461     } catch (Exception ex)
4462     {
4463       ex.printStackTrace();
4464     }
4465
4466     return tp;
4467   }
4468
4469   private boolean buildingMenu = false;
4470
4471   /**
4472    * Generates menu items and listener event actions for web service clients
4473    * 
4474    */
4475   public void BuildWebServiceMenu()
4476   {
4477     while (buildingMenu)
4478     {
4479       try
4480       {
4481         System.err.println("Waiting for building menu to finish.");
4482         Thread.sleep(10);
4483       } catch (Exception e)
4484       {
4485       }
4486     }
4487     final AlignFrame me = this;
4488     buildingMenu = true;
4489     new Thread(new Runnable()
4490     {
4491       @Override
4492       public void run()
4493       {
4494         final List<JMenuItem> legacyItems = new ArrayList<JMenuItem>();
4495         try
4496         {
4497           System.err.println("Building ws menu again "
4498                   + Thread.currentThread());
4499           // TODO: add support for context dependent disabling of services based
4500           // on
4501           // alignment and current selection
4502           // TODO: add additional serviceHandle parameter to specify abstract
4503           // handler
4504           // class independently of AbstractName
4505           // TODO: add in rediscovery GUI function to restart discoverer
4506           // TODO: group services by location as well as function and/or
4507           // introduce
4508           // object broker mechanism.
4509           final Vector<JMenu> wsmenu = new Vector<JMenu>();
4510           final IProgressIndicator af = me;
4511           final JMenu msawsmenu = new JMenu("Alignment");
4512           final JMenu secstrmenu = new JMenu(
4513                   "Secondary Structure Prediction");
4514           final JMenu seqsrchmenu = new JMenu("Sequence Database Search");
4515           final JMenu analymenu = new JMenu("Analysis");
4516           final JMenu dismenu = new JMenu("Protein Disorder");
4517           // final JMenu msawsmenu = new
4518           // JMenu(MessageManager.getString("label.alignment"));
4519           // final JMenu secstrmenu = new
4520           // JMenu(MessageManager.getString("label.secondary_structure_prediction"));
4521           // final JMenu seqsrchmenu = new
4522           // JMenu(MessageManager.getString("label.sequence_database_search"));
4523           // final JMenu analymenu = new
4524           // JMenu(MessageManager.getString("label.analysis"));
4525           // final JMenu dismenu = new
4526           // JMenu(MessageManager.getString("label.protein_disorder"));
4527           // JAL-940 - only show secondary structure prediction services from
4528           // the legacy server
4529           if (// Cache.getDefault("SHOW_JWS1_SERVICES", true)
4530               // &&
4531           Discoverer.services != null && (Discoverer.services.size() > 0))
4532           {
4533             // TODO: refactor to allow list of AbstractName/Handler bindings to
4534             // be
4535             // stored or retrieved from elsewhere
4536             // No MSAWS used any more:
4537             // Vector msaws = null; // (Vector)
4538             // Discoverer.services.get("MsaWS");
4539             Vector secstrpr = (Vector) Discoverer.services
4540                     .get("SecStrPred");
4541             if (secstrpr != null)
4542             {
4543               // Add any secondary structure prediction services
4544               for (int i = 0, j = secstrpr.size(); i < j; i++)
4545               {
4546                 final ext.vamsas.ServiceHandle sh = (ext.vamsas.ServiceHandle) secstrpr
4547                         .get(i);
4548                 jalview.ws.WSMenuEntryProviderI impl = jalview.ws.jws1.Discoverer
4549                         .getServiceClient(sh);
4550                 int p = secstrmenu.getItemCount();
4551                 impl.attachWSMenuEntry(secstrmenu, me);
4552                 int q = secstrmenu.getItemCount();
4553                 for (int litm = p; litm < q; litm++)
4554                 {
4555                   legacyItems.add(secstrmenu.getItem(litm));
4556                 }
4557               }
4558             }
4559           }
4560
4561           // Add all submenus in the order they should appear on the web
4562           // services menu
4563           wsmenu.add(msawsmenu);
4564           wsmenu.add(secstrmenu);
4565           wsmenu.add(dismenu);
4566           wsmenu.add(analymenu);
4567           // No search services yet
4568           // wsmenu.add(seqsrchmenu);
4569
4570           javax.swing.SwingUtilities.invokeLater(new Runnable()
4571           {
4572             @Override
4573             public void run()
4574             {
4575               try
4576               {
4577                 webService.removeAll();
4578                 // first, add discovered services onto the webservices menu
4579                 if (wsmenu.size() > 0)
4580                 {
4581                   for (int i = 0, j = wsmenu.size(); i < j; i++)
4582                   {
4583                     webService.add(wsmenu.get(i));
4584                   }
4585                 }
4586                 else
4587                 {
4588                   webService.add(me.webServiceNoServices);
4589                 }
4590                 // TODO: move into separate menu builder class.
4591                 boolean new_sspred = false;
4592                 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
4593                 {
4594                   Jws2Discoverer jws2servs = Jws2Discoverer.getDiscoverer();
4595                   if (jws2servs != null)
4596                   {
4597                     if (jws2servs.hasServices())
4598                     {
4599                       jws2servs.attachWSMenuEntry(webService, me);
4600                       for (Jws2Instance sv : jws2servs.getServices())
4601                       {
4602                         if (sv.description.toLowerCase().contains("jpred"))
4603                         {
4604                           for (JMenuItem jmi : legacyItems)
4605                           {
4606                             jmi.setVisible(false);
4607                           }
4608                         }
4609                       }
4610
4611                     }
4612                     if (jws2servs.isRunning())
4613                     {
4614                       JMenuItem tm = new JMenuItem(
4615                               "Still discovering JABA Services");
4616                       tm.setEnabled(false);
4617                       webService.add(tm);
4618                     }
4619                   }
4620                 }
4621                 build_urlServiceMenu(me.webService);
4622                 build_fetchdbmenu(webService);
4623                 for (JMenu item : wsmenu)
4624                 {
4625                   if (item.getItemCount() == 0)
4626                   {
4627                     item.setEnabled(false);
4628                   }
4629                   else
4630                   {
4631                     item.setEnabled(true);
4632                   }
4633                 }
4634               } catch (Exception e)
4635               {
4636                 Cache.log
4637                         .debug("Exception during web service menu building process.",
4638                                 e);
4639               }
4640             }
4641           });
4642         } catch (Exception e)
4643         {
4644         }
4645         buildingMenu = false;
4646       }
4647     }).start();
4648
4649   }
4650
4651   /**
4652    * construct any groupURL type service menu entries.
4653    * 
4654    * @param webService
4655    */
4656   private void build_urlServiceMenu(JMenu webService)
4657   {
4658     // TODO: remove this code when 2.7 is released
4659     // DEBUG - alignmentView
4660     /*
4661      * JMenuItem testAlView = new JMenuItem("Test AlignmentView"); final
4662      * AlignFrame af = this; testAlView.addActionListener(new ActionListener() {
4663      * 
4664      * @Override public void actionPerformed(ActionEvent e) {
4665      * jalview.datamodel.AlignmentView
4666      * .testSelectionViews(af.viewport.getAlignment(),
4667      * af.viewport.getColumnSelection(), af.viewport.selectionGroup); }
4668      * 
4669      * }); webService.add(testAlView);
4670      */
4671     // TODO: refactor to RestClient discoverer and merge menu entries for
4672     // rest-style services with other types of analysis/calculation service
4673     // SHmmr test client - still being implemented.
4674     // DEBUG - alignmentView
4675
4676     for (jalview.ws.rest.RestClient client : jalview.ws.rest.RestClient
4677             .getRestClients())
4678     {
4679       client.attachWSMenuEntry(
4680               JvSwingUtils.findOrCreateMenu(webService, client.getAction()),
4681               this);
4682     }
4683   }
4684
4685   /*
4686    * public void vamsasStore_actionPerformed(ActionEvent e) { JalviewFileChooser
4687    * chooser = new JalviewFileChooser(jalview.bin.Cache.
4688    * getProperty("LAST_DIRECTORY"));
4689    * 
4690    * chooser.setFileView(new JalviewFileView()); chooser.setDialogTitle("Export
4691    * to Vamsas file"); chooser.setToolTipText("Export");
4692    * 
4693    * int value = chooser.showSaveDialog(this);
4694    * 
4695    * if (value == JalviewFileChooser.APPROVE_OPTION) {
4696    * jalview.io.VamsasDatastore vs = new jalview.io.VamsasDatastore(viewport);
4697    * //vs.store(chooser.getSelectedFile().getAbsolutePath() ); vs.storeJalview(
4698    * chooser.getSelectedFile().getAbsolutePath(), this); } }
4699    */
4700   /**
4701    * prototype of an automatically enabled/disabled analysis function
4702    * 
4703    */
4704   protected void setShowProductsEnabled()
4705   {
4706     SequenceI[] selection = viewport.getSequenceSelection();
4707     if (canShowProducts(selection, viewport.getSelectionGroup() != null,
4708             viewport.getAlignment().getDataset()))
4709     {
4710       showProducts.setEnabled(true);
4711
4712     }
4713     else
4714     {
4715       showProducts.setEnabled(false);
4716     }
4717   }
4718
4719   /**
4720    * search selection for sequence xRef products and build the show products
4721    * menu.
4722    * 
4723    * @param selection
4724    * @param dataset
4725    * @return true if showProducts menu should be enabled.
4726    */
4727   public boolean canShowProducts(SequenceI[] selection,
4728           boolean isRegionSelection, Alignment dataset)
4729   {
4730     boolean showp = false;
4731     try
4732     {
4733       showProducts.removeAll();
4734       final boolean dna = viewport.getAlignment().isNucleotide();
4735       final Alignment ds = dataset;
4736       String[] ptypes = (selection == null || selection.length == 0) ? null
4737               : CrossRef.findSequenceXrefTypes(dna, selection, dataset);
4738       // Object[] prods =
4739       // CrossRef.buildXProductsList(viewport.getAlignment().isNucleotide(),
4740       // selection, dataset, true);
4741       final SequenceI[] sel = selection;
4742       for (int t = 0; ptypes != null && t < ptypes.length; t++)
4743       {
4744         showp = true;
4745         final boolean isRegSel = isRegionSelection;
4746         final AlignFrame af = this;
4747         final String source = ptypes[t];
4748         JMenuItem xtype = new JMenuItem(ptypes[t]);
4749         xtype.addActionListener(new ActionListener()
4750         {
4751
4752           @Override
4753           public void actionPerformed(ActionEvent e)
4754           {
4755             // TODO: new thread for this call with vis-delay
4756             af.showProductsFor(af.viewport.getSequenceSelection(), ds,
4757                     isRegSel, dna, source);
4758           }
4759
4760         });
4761         showProducts.add(xtype);
4762       }
4763       showProducts.setVisible(showp);
4764       showProducts.setEnabled(showp);
4765     } catch (Exception e)
4766     {
4767       jalview.bin.Cache.log
4768               .warn("canTranslate threw an exception - please report to help@jalview.org",
4769                       e);
4770       return false;
4771     }
4772     return showp;
4773   }
4774
4775   protected void showProductsFor(SequenceI[] sel, Alignment ds,
4776           boolean isRegSel, boolean dna, String source)
4777   {
4778     final boolean fisRegSel = isRegSel;
4779     final boolean fdna = dna;
4780     final String fsrc = source;
4781     final AlignFrame ths = this;
4782     final SequenceI[] fsel = sel;
4783     Runnable foo = new Runnable()
4784     {
4785
4786       @Override
4787       public void run()
4788       {
4789         final long sttime = System.currentTimeMillis();
4790         ths.setProgressBar(MessageManager.formatMessage("status.searching_for_sequences_from", new Object[]{fsrc}), sttime);
4791         try
4792         {
4793           Alignment ds = ths.getViewport().getAlignment().getDataset(); // update
4794           // our local
4795           // dataset
4796           // reference
4797           Alignment prods = CrossRef
4798                   .findXrefSequences(fsel, fdna, fsrc, ds);
4799           if (prods != null)
4800           {
4801             SequenceI[] sprods = new SequenceI[prods.getHeight()];
4802             for (int s = 0; s < sprods.length; s++)
4803             {
4804               sprods[s] = (prods.getSequenceAt(s)).deriveSequence();
4805               if (ds.getSequences() == null
4806                       || !ds.getSequences().contains(
4807                               sprods[s].getDatasetSequence()))
4808               {
4809                 ds.addSequence(sprods[s].getDatasetSequence());
4810               }
4811               sprods[s].updatePDBIds();
4812             }
4813             Alignment al = new Alignment(sprods);
4814             Set<AlignedCodonFrame> cf = prods.getCodonFrames();
4815             al.setDataset(ds);
4816             for (AlignedCodonFrame acf : cf)
4817             {
4818               al.addCodonFrame(acf);
4819             }
4820             AlignFrame naf = new AlignFrame(al, DEFAULT_WIDTH,
4821                     DEFAULT_HEIGHT);
4822             String newtitle = "" + ((fdna) ? "Proteins " : "Nucleotides ")
4823                     + " for " + ((fisRegSel) ? "selected region of " : "")
4824                     + getTitle();
4825             Desktop.addInternalFrame(naf, newtitle, DEFAULT_WIDTH,
4826                     DEFAULT_HEIGHT);
4827           }
4828           else
4829           {
4830             System.err.println("No Sequences generated for xRef type "
4831                     + fsrc);
4832           }
4833         } catch (Exception e)
4834         {
4835           jalview.bin.Cache.log.error(
4836                   "Exception when finding crossreferences", e);
4837         } catch (OutOfMemoryError e)
4838         {
4839           new OOMWarning("whilst fetching crossreferences", e);
4840         } catch (Error e)
4841         {
4842           jalview.bin.Cache.log.error("Error when finding crossreferences",
4843                   e);
4844         }
4845         ths.setProgressBar(MessageManager.formatMessage("status.finished_searching_for_sequences_from", new Object[]{fsrc}),
4846                 sttime);
4847       }
4848
4849     };
4850     Thread frunner = new Thread(foo);
4851     frunner.start();
4852   }
4853
4854   public boolean canShowTranslationProducts(SequenceI[] selection,
4855           AlignmentI alignment)
4856   {
4857     // old way
4858     try
4859     {
4860       return (jalview.analysis.Dna.canTranslate(selection,
4861               viewport.getViewAsVisibleContigs(true)));
4862     } catch (Exception e)
4863     {
4864       jalview.bin.Cache.log
4865               .warn("canTranslate threw an exception - please report to help@jalview.org",
4866                       e);
4867       return false;
4868     }
4869   }
4870
4871   /**
4872    * Construct and display a new frame containing the translation of this
4873    * frame's cDNA sequences to their aligned protein (amino acid) equivalents.
4874    */
4875   @Override
4876   public void showTranslation_actionPerformed(ActionEvent e)
4877   {
4878     AlignmentI al = null;
4879     try
4880     {
4881       Dna dna = new Dna(viewport, viewport.getViewAsVisibleContigs(true));
4882
4883       al = dna.translateCdna();
4884     } catch (Exception ex)
4885     {
4886       jalview.bin.Cache.log.error(
4887               "Exception during translation. Please report this !", ex);
4888       final String msg = MessageManager
4889               .getString("label.error_when_translating_sequences_submit_bug_report");
4890       final String title = MessageManager
4891               .getString("label.implementation_error")
4892               + MessageManager.getString("translation_failed");
4893       JOptionPane.showMessageDialog(Desktop.desktop, msg, title,
4894               JOptionPane.ERROR_MESSAGE);
4895       return;
4896     }
4897     if (al == null || al.getHeight() == 0)
4898     {
4899       final String msg = MessageManager
4900               .getString("label.select_at_least_three_bases_in_at_least_one_sequence_to_cDNA_translation");
4901       final String title = MessageManager
4902               .getString("label.translation_failed");
4903       JOptionPane.showMessageDialog(Desktop.desktop, msg, title,
4904               JOptionPane.WARNING_MESSAGE);
4905     }
4906     else
4907     {
4908       AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
4909       Desktop.addInternalFrame(af, MessageManager.formatMessage(
4910               "label.translation_of_params", new Object[]
4911               { this.getTitle() }), DEFAULT_WIDTH, DEFAULT_HEIGHT);
4912       // enable next line for linked editing
4913       // viewport.getStructureSelectionManager().addCommandListener(viewport);
4914     }
4915   }
4916
4917   /**
4918    * Try to load a features file onto the alignment.
4919    * 
4920    * @param file
4921    *          contents or path to retrieve file
4922    * @param type
4923    *          access mode of file (see jalview.io.AlignFile)
4924    * @return true if features file was parsed corectly.
4925    */
4926   public boolean parseFeaturesFile(String file, String type)
4927   {
4928     boolean featuresFile = false;
4929     try
4930     {
4931       featuresFile = new FeaturesFile(file, type).parse(viewport
4932               .getAlignment().getDataset(), alignPanel.getSeqPanel().seqCanvas
4933               .getFeatureRenderer().getFeatureColours(), false,
4934               jalview.bin.Cache.getDefault("RELAXEDSEQIDMATCHING", false));
4935     } catch (Exception ex)
4936     {
4937       ex.printStackTrace();
4938     }
4939
4940     if (featuresFile)
4941     {
4942       viewport.setShowSequenceFeatures(true);
4943       showSeqFeatures.setSelected(true);
4944       if (alignPanel.getSeqPanel().seqCanvas.fr != null)
4945       {
4946         // update the min/max ranges where necessary
4947         alignPanel.getSeqPanel().seqCanvas.fr.findAllFeatures(true);
4948       }
4949       if (featureSettings != null)
4950       {
4951         featureSettings.setTableData();
4952       }
4953       alignPanel.paintAlignment(true);
4954     }
4955
4956     return featuresFile;
4957   }
4958
4959   @Override
4960   public void dragEnter(DropTargetDragEvent evt)
4961   {
4962   }
4963
4964   @Override
4965   public void dragExit(DropTargetEvent evt)
4966   {
4967   }
4968
4969   @Override
4970   public void dragOver(DropTargetDragEvent evt)
4971   {
4972   }
4973
4974   @Override
4975   public void dropActionChanged(DropTargetDragEvent evt)
4976   {
4977   }
4978
4979   @Override
4980   public void drop(DropTargetDropEvent evt)
4981   {
4982     Transferable t = evt.getTransferable();
4983     java.util.List files = null;
4984
4985     try
4986     {
4987       DataFlavor uriListFlavor = new DataFlavor(
4988               "text/uri-list;class=java.lang.String");
4989       if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor))
4990       {
4991         // Works on Windows and MacOSX
4992         evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
4993         files = (java.util.List) t
4994                 .getTransferData(DataFlavor.javaFileListFlavor);
4995       }
4996       else if (t.isDataFlavorSupported(uriListFlavor))
4997       {
4998         // This is used by Unix drag system
4999         evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
5000         String data = (String) t.getTransferData(uriListFlavor);
5001         files = new java.util.ArrayList(1);
5002         for (java.util.StringTokenizer st = new java.util.StringTokenizer(
5003                 data, "\r\n"); st.hasMoreTokens();)
5004         {
5005           String s = st.nextToken();
5006           if (s.startsWith("#"))
5007           {
5008             // the line is a comment (as per the RFC 2483)
5009             continue;
5010           }
5011
5012           java.net.URI uri = new java.net.URI(s);
5013           // check to see if we can handle this kind of URI
5014           if (uri.getScheme().toLowerCase().startsWith("http"))
5015           {
5016             files.add(uri.toString());
5017           }
5018           else
5019           {
5020             // otherwise preserve old behaviour: catch all for file objects
5021             java.io.File file = new java.io.File(uri);
5022             files.add(file.toString());
5023           }
5024         }
5025       }
5026     } catch (Exception e)
5027     {
5028       e.printStackTrace();
5029     }
5030     if (files != null)
5031     {
5032       try
5033       {
5034         // check to see if any of these files have names matching sequences in
5035         // the alignment
5036         SequenceIdMatcher idm = new SequenceIdMatcher(viewport
5037                 .getAlignment().getSequencesArray());
5038         /**
5039          * Object[] { String,SequenceI}
5040          */
5041         ArrayList<Object[]> filesmatched = new ArrayList<Object[]>();
5042         ArrayList<String> filesnotmatched = new ArrayList<String>();
5043         for (int i = 0; i < files.size(); i++)
5044         {
5045           String file = files.get(i).toString();
5046           String pdbfn = "";
5047           String protocol = FormatAdapter.checkProtocol(file);
5048           if (protocol == jalview.io.FormatAdapter.FILE)
5049           {
5050             File fl = new File(file);
5051             pdbfn = fl.getName();
5052           }
5053           else if (protocol == jalview.io.FormatAdapter.URL)
5054           {
5055             URL url = new URL(file);
5056             pdbfn = url.getFile();
5057           }
5058           if (pdbfn.length() > 0)
5059           {
5060             // attempt to find a match in the alignment
5061             SequenceI[] mtch = idm.findAllIdMatches(pdbfn);
5062             int l = 0, c = pdbfn.indexOf(".");
5063             while (mtch == null && c != -1)
5064             {
5065               do
5066               {
5067                 l = c;
5068               } while ((c = pdbfn.indexOf(".", l)) > l);
5069               if (l > -1)
5070               {
5071                 pdbfn = pdbfn.substring(0, l);
5072               }
5073               mtch = idm.findAllIdMatches(pdbfn);
5074             }
5075             if (mtch != null)
5076             {
5077               String type = null;
5078               try
5079               {
5080                 type = new IdentifyFile().Identify(file, protocol);
5081               } catch (Exception ex)
5082               {
5083                 type = null;
5084               }
5085               if (type != null)
5086               {
5087                 if (type.equalsIgnoreCase("PDB"))
5088                 {
5089                   filesmatched.add(new Object[]
5090                   { file, protocol, mtch });
5091                   continue;
5092                 }
5093               }
5094             }
5095             // File wasn't named like one of the sequences or wasn't a PDB file.
5096             filesnotmatched.add(file);
5097           }
5098         }
5099         int assocfiles = 0;
5100         if (filesmatched.size() > 0)
5101         {
5102           if (Cache.getDefault("AUTOASSOCIATE_PDBANDSEQS", false)
5103                   || JOptionPane
5104                           .showConfirmDialog(
5105                                   this,
5106                                   MessageManager
5107                                           .formatMessage(
5108                                                   "label.automatically_associate_pdb_files_with_sequences_same_name",
5109                                                   new Object[]
5110                                                   { Integer.valueOf(
5111                                                           filesmatched
5112                                                                   .size())
5113                                                           .toString() }),
5114                                   MessageManager
5115                                           .getString("label.automatically_associate_pdb_files_by_name"),
5116                                   JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
5117
5118           {
5119             for (Object[] fm : filesmatched)
5120             {
5121               // try and associate
5122               // TODO: may want to set a standard ID naming formalism for
5123               // associating PDB files which have no IDs.
5124               for (SequenceI toassoc : (SequenceI[]) fm[2])
5125               {
5126                 PDBEntry pe = new AssociatePdbFileWithSeq()
5127                         .associatePdbWithSeq((String) fm[0],
5128                                 (String) fm[1], toassoc, false,
5129                                 Desktop.instance);
5130                 if (pe != null)
5131                 {
5132                   System.err.println("Associated file : "
5133                           + ((String) fm[0]) + " with "
5134                           + toassoc.getDisplayId(true));
5135                   assocfiles++;
5136                 }
5137               }
5138               alignPanel.paintAlignment(true);
5139             }
5140           }
5141         }
5142         if (filesnotmatched.size() > 0)
5143         {
5144           if (assocfiles > 0
5145                   && (Cache.getDefault(
5146                           "AUTOASSOCIATE_PDBANDSEQS_IGNOREOTHERS", false) || JOptionPane
5147                           .showConfirmDialog(
5148                                   this,
5149                                   "<html>"+MessageManager
5150                                           .formatMessage(
5151                                                   "label.ignore_unmatched_dropped_files_info",
5152                                                   new Object[]
5153                                                   { Integer.valueOf(
5154                                                           filesnotmatched
5155                                                                   .size())
5156                                                           .toString() })+"</html>",
5157                                   MessageManager
5158                                           .getString("label.ignore_unmatched_dropped_files"),
5159                                   JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION))
5160           {
5161             return;
5162           }
5163           for (String fn : filesnotmatched)
5164           {
5165             loadJalviewDataFile(fn, null, null, null);
5166           }
5167
5168         }
5169       } catch (Exception ex)
5170       {
5171         ex.printStackTrace();
5172       }
5173     }
5174   }
5175
5176   /**
5177    * Attempt to load a "dropped" file or URL string: First by testing whether
5178    * it's and Annotation file, then a JNet file, and finally a features file. If
5179    * all are false then the user may have dropped an alignment file onto this
5180    * AlignFrame.
5181    * 
5182    * @param file
5183    *          either a filename or a URL string.
5184    */
5185   public void loadJalviewDataFile(String file, String protocol,
5186           String format, SequenceI assocSeq)
5187   {
5188     try
5189     {
5190       if (protocol == null)
5191       {
5192         protocol = jalview.io.FormatAdapter.checkProtocol(file);
5193       }
5194       // if the file isn't identified, or not positively identified as some
5195       // other filetype (PFAM is default unidentified alignment file type) then
5196       // try to parse as annotation.
5197       boolean isAnnotation = (format == null || format
5198               .equalsIgnoreCase("PFAM")) ? new AnnotationFile()
5199               .annotateAlignmentView(viewport, file, protocol)
5200               : false;
5201
5202       if (!isAnnotation)
5203       {
5204         // first see if its a T-COFFEE score file
5205         TCoffeeScoreFile tcf = null;
5206         try
5207         {
5208           tcf = new TCoffeeScoreFile(file, protocol);
5209           if (tcf.isValid())
5210           {
5211             if (tcf.annotateAlignment(viewport.getAlignment(), true))
5212             {
5213               tcoffeeColour.setEnabled(true);
5214               tcoffeeColour.setSelected(true);
5215               changeColour(new TCoffeeColourScheme(viewport.getAlignment()));
5216               isAnnotation = true;
5217               statusBar
5218                       .setText(MessageManager
5219                               .getString("label.successfully_pasted_tcoffee_scores_to_alignment"));
5220             }
5221             else
5222             {
5223               // some problem - if no warning its probable that the ID matching
5224               // process didn't work
5225               JOptionPane
5226                       .showMessageDialog(
5227                               Desktop.desktop,
5228                               tcf.getWarningMessage() == null ? MessageManager
5229                                       .getString("label.check_file_matches_sequence_ids_alignment")
5230                                       : tcf.getWarningMessage(),
5231                               MessageManager
5232                                       .getString("label.problem_reading_tcoffee_score_file"),
5233                               JOptionPane.WARNING_MESSAGE);
5234             }
5235           }
5236           else
5237           {
5238             tcf = null;
5239           }
5240         } catch (Exception x)
5241         {
5242           Cache.log
5243                   .debug("Exception when processing data source as T-COFFEE score file",
5244                           x);
5245           tcf = null;
5246         }
5247         if (tcf == null)
5248         {
5249           // try to see if its a JNet 'concise' style annotation file *before*
5250           // we
5251           // try to parse it as a features file
5252           if (format == null)
5253           {
5254             format = new IdentifyFile().Identify(file, protocol);
5255           }
5256           if (format.equalsIgnoreCase("JnetFile"))
5257           {
5258             jalview.io.JPredFile predictions = new jalview.io.JPredFile(
5259                     file, protocol);
5260             new JnetAnnotationMaker();
5261             JnetAnnotationMaker.add_annotation(predictions,
5262                     viewport.getAlignment(), 0, false);
5263             isAnnotation = true;
5264           }
5265           else
5266           {
5267             /*
5268              * if (format.equalsIgnoreCase("PDB")) {
5269              * 
5270              * String pdbfn = ""; // try to match up filename with sequence id
5271              * try { if (protocol == jalview.io.FormatAdapter.FILE) { File fl =
5272              * new File(file); pdbfn = fl.getName(); } else if (protocol ==
5273              * jalview.io.FormatAdapter.URL) { URL url = new URL(file); pdbfn =
5274              * url.getFile(); } } catch (Exception e) { } ; if (assocSeq ==
5275              * null) { SequenceIdMatcher idm = new SequenceIdMatcher(viewport
5276              * .getAlignment().getSequencesArray()); if (pdbfn.length() > 0) {
5277              * // attempt to find a match in the alignment SequenceI mtch =
5278              * idm.findIdMatch(pdbfn); int l = 0, c = pdbfn.indexOf("."); while
5279              * (mtch == null && c != -1) { while ((c = pdbfn.indexOf(".", l)) >
5280              * l) { l = c; } if (l > -1) { pdbfn = pdbfn.substring(0, l); } mtch
5281              * = idm.findIdMatch(pdbfn); } if (mtch != null) { // try and
5282              * associate // prompt ? PDBEntry pe = new AssociatePdbFileWithSeq()
5283              * .associatePdbWithSeq(file, protocol, mtch, true); if (pe != null)
5284              * { System.err.println("Associated file : " + file + " with " +
5285              * mtch.getDisplayId(true)); alignPanel.paintAlignment(true); } } //
5286              * TODO: maybe need to load as normal otherwise return; } }
5287              */
5288             // try to parse it as a features file
5289             boolean isGroupsFile = parseFeaturesFile(file, protocol);
5290             // if it wasn't a features file then we just treat it as a general
5291             // alignment file to load into the current view.
5292             if (!isGroupsFile)
5293             {
5294               new FileLoader().LoadFile(viewport, file, protocol, format);
5295             }
5296             else
5297             {
5298               alignPanel.paintAlignment(true);
5299             }
5300           }
5301         }
5302       }
5303       if (isAnnotation)
5304       {
5305
5306         alignPanel.adjustAnnotationHeight();
5307         viewport.updateSequenceIdColours();
5308         buildSortByAnnotationScoresMenu();
5309         alignPanel.paintAlignment(true);
5310       }
5311     } catch (Exception ex)
5312     {
5313       ex.printStackTrace();
5314     } catch (OutOfMemoryError oom)
5315     {
5316       try
5317       {
5318         System.gc();
5319       } catch (Exception x)
5320       {
5321       }
5322       ;
5323       new OOMWarning(
5324               "loading data "
5325                       + (protocol != null ? (protocol.equals(FormatAdapter.PASTE) ? "from clipboard."
5326                               : "using " + protocol + " from " + file)
5327                               : ".")
5328                       + (format != null ? "(parsing as '" + format
5329                               + "' file)" : ""), oom, Desktop.desktop);
5330     }
5331   }
5332
5333   /**
5334    * Method invoked by the ChangeListener on the tabbed pane, in other words
5335    * when a different tabbed pane is selected by the user or programmatically.
5336    */
5337   @Override
5338   public void tabSelectionChanged(int index)
5339   {
5340     if (index > -1)
5341     {
5342       alignPanel = alignPanels.get(index);
5343       viewport = alignPanel.av;
5344       avc.setViewportAndAlignmentPanel(viewport, alignPanel);
5345       setMenusFromViewport(viewport);
5346     }
5347
5348     /*
5349      * If there is a frame linked to this one in a SplitPane, switch it to the
5350      * same view tab index. No infinite recursion of calls should happen, since
5351      * tabSelectionChanged() should not get invoked on setting the selected
5352      * index to an unchanged value. Guard against setting an invalid index
5353      * before the new view peer tab has been created.
5354      */
5355     final AlignViewportI peer = viewport.getCodingComplement();
5356     if (peer != null)
5357     {
5358       AlignFrame linkedAlignFrame = ((AlignViewport) peer).getAlignPanel().alignFrame;
5359       if (linkedAlignFrame.tabbedPane.getTabCount() > index)
5360       {
5361         linkedAlignFrame.tabbedPane.setSelectedIndex(index);
5362       }
5363     }
5364   }
5365
5366   /**
5367    * On right mouse click on view tab, prompt for and set new view name.
5368    */
5369   @Override
5370   public void tabbedPane_mousePressed(MouseEvent e)
5371   {
5372     if (SwingUtilities.isRightMouseButton(e))
5373     {
5374       String msg = MessageManager.getString("label.enter_view_name");
5375       String reply = JOptionPane.showInternalInputDialog(this, msg, msg,
5376               JOptionPane.QUESTION_MESSAGE);
5377
5378       if (reply != null)
5379       {
5380         viewport.viewName = reply;
5381         // TODO warn if reply is in getExistingViewNames()?
5382         tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), reply);
5383       }
5384     }
5385   }
5386
5387   public AlignViewport getCurrentView()
5388   {
5389     return viewport;
5390   }
5391
5392   /**
5393    * Open the dialog for regex description parsing.
5394    */
5395   @Override
5396   protected void extractScores_actionPerformed(ActionEvent e)
5397   {
5398     ParseProperties pp = new jalview.analysis.ParseProperties(
5399             viewport.getAlignment());
5400     // TODO: verify regex and introduce GUI dialog for version 2.5
5401     // if (pp.getScoresFromDescription("col", "score column ",
5402     // "\\W*([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)",
5403     // true)>0)
5404     if (pp.getScoresFromDescription("description column",
5405             "score in description column ", "\\W*([-+eE0-9.]+)", true) > 0)
5406     {
5407       buildSortByAnnotationScoresMenu();
5408     }
5409   }
5410
5411   /*
5412    * (non-Javadoc)
5413    * 
5414    * @see
5415    * jalview.jbgui.GAlignFrame#showDbRefs_actionPerformed(java.awt.event.ActionEvent
5416    * )
5417    */
5418   @Override
5419   protected void showDbRefs_actionPerformed(ActionEvent e)
5420   {
5421     viewport.setShowDbRefs(showDbRefsMenuitem.isSelected());
5422   }
5423
5424   /*
5425    * (non-Javadoc)
5426    * 
5427    * @seejalview.jbgui.GAlignFrame#showNpFeats_actionPerformed(java.awt.event.
5428    * ActionEvent)
5429    */
5430   @Override
5431   protected void showNpFeats_actionPerformed(ActionEvent e)
5432   {
5433     viewport.setShowNpFeats(showNpFeatsMenuitem.isSelected());
5434   }
5435
5436   /**
5437    * find the viewport amongst the tabs in this alignment frame and close that
5438    * tab
5439    * 
5440    * @param av
5441    */
5442   public boolean closeView(AlignViewportI av)
5443   {
5444     if (viewport == av)
5445     {
5446       this.closeMenuItem_actionPerformed(false);
5447       return true;
5448     }
5449     Component[] comp = tabbedPane.getComponents();
5450     for (int i = 0; comp != null && i < comp.length; i++)
5451     {
5452       if (comp[i] instanceof AlignmentPanel)
5453       {
5454         if (((AlignmentPanel) comp[i]).av == av)
5455         {
5456           // close the view.
5457           closeView((AlignmentPanel) comp[i]);
5458           return true;
5459         }
5460       }
5461     }
5462     return false;
5463   }
5464
5465   protected void build_fetchdbmenu(JMenu webService)
5466   {
5467     // Temporary hack - DBRef Fetcher always top level ws entry.
5468     // TODO We probably want to store a sequence database checklist in
5469     // preferences and have checkboxes.. rather than individual sources selected
5470     // here
5471     final JMenu rfetch = new JMenu(
5472             MessageManager.getString("action.fetch_db_references"));
5473     rfetch.setToolTipText(MessageManager
5474             .getString("label.retrieve_parse_sequence_database_records_alignment_or_selected_sequences"));
5475     webService.add(rfetch);
5476
5477     final JCheckBoxMenuItem trimrs = new JCheckBoxMenuItem(
5478             MessageManager.getString("option.trim_retrieved_seqs"));
5479     trimrs.setToolTipText(MessageManager
5480             .getString("label.trim_retrieved_sequences"));
5481     trimrs.setSelected(Cache.getDefault("TRIM_FETCHED_DATASET_SEQS", true));
5482     trimrs.addActionListener(new ActionListener()
5483     {
5484       @Override
5485       public void actionPerformed(ActionEvent e)
5486       {
5487         trimrs.setSelected(trimrs.isSelected());
5488         Cache.setProperty("TRIM_FETCHED_DATASET_SEQS",
5489                 Boolean.valueOf(trimrs.isSelected()).toString());
5490       };
5491     });
5492     rfetch.add(trimrs);
5493     JMenuItem fetchr = new JMenuItem(
5494             MessageManager.getString("label.standard_databases"));
5495     fetchr.setToolTipText(MessageManager
5496             .getString("label.fetch_embl_uniprot"));
5497     fetchr.addActionListener(new ActionListener()
5498     {
5499
5500       @Override
5501       public void actionPerformed(ActionEvent e)
5502       {
5503         new Thread(new Runnable()
5504         {
5505
5506           @Override
5507           public void run()
5508           {
5509             new jalview.ws.DBRefFetcher(alignPanel.av
5510                     .getSequenceSelection(), alignPanel.alignFrame)
5511                     .fetchDBRefs(false);
5512           }
5513         }).start();
5514
5515       }
5516
5517     });
5518     rfetch.add(fetchr);
5519     final AlignFrame me = this;
5520     new Thread(new Runnable()
5521     {
5522       @Override
5523       public void run()
5524       {
5525         final jalview.ws.SequenceFetcher sf = SequenceFetcher
5526                 .getSequenceFetcherSingleton(me);
5527         javax.swing.SwingUtilities.invokeLater(new Runnable()
5528         {
5529           @Override
5530           public void run()
5531           {
5532             String[] dbclasses = sf.getOrderedSupportedSources();
5533             // sf.getDbInstances(jalview.ws.dbsources.DasSequenceSource.class);
5534             // jalview.util.QuickSort.sort(otherdb, otherdb);
5535             List<DbSourceProxy> otherdb;
5536             JMenu dfetch = new JMenu();
5537             JMenu ifetch = new JMenu();
5538             JMenuItem fetchr = null;
5539             int comp = 0, icomp = 0, mcomp = 15;
5540             String mname = null;
5541             int dbi = 0;
5542             for (String dbclass : dbclasses)
5543             {
5544               otherdb = sf.getSourceProxy(dbclass);
5545               // add a single entry for this class, or submenu allowing 'fetch
5546               // all' or pick one
5547               if (otherdb == null || otherdb.size() < 1)
5548               {
5549                 continue;
5550               }
5551               // List<DbSourceProxy> dbs=otherdb;
5552               // otherdb=new ArrayList<DbSourceProxy>();
5553               // for (DbSourceProxy db:dbs)
5554               // {
5555               // if (!db.isA(DBRefSource.ALIGNMENTDB)
5556               // }
5557               if (mname == null)
5558               {
5559                 mname = "From " + dbclass;
5560               }
5561               if (otherdb.size() == 1)
5562               {
5563                 final DbSourceProxy[] dassource = otherdb
5564                         .toArray(new DbSourceProxy[0]);
5565                 DbSourceProxy src = otherdb.get(0);
5566                 fetchr = new JMenuItem(src.getDbSource());
5567                 fetchr.addActionListener(new ActionListener()
5568                 {
5569
5570                   @Override
5571                   public void actionPerformed(ActionEvent e)
5572                   {
5573                     new Thread(new Runnable()
5574                     {
5575
5576                       @Override
5577                       public void run()
5578                       {
5579                         new jalview.ws.DBRefFetcher(alignPanel.av
5580                                 .getSequenceSelection(),
5581                                 alignPanel.alignFrame, dassource)
5582                                 .fetchDBRefs(false);
5583                       }
5584                     }).start();
5585                   }
5586
5587                 });
5588                 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true, MessageManager.formatMessage("label.fetch_retrieve_from", new Object[]{src.getDbName()})));
5589                 dfetch.add(fetchr);
5590                 comp++;
5591               }
5592               else
5593               {
5594                 final DbSourceProxy[] dassource = otherdb
5595                         .toArray(new DbSourceProxy[0]);
5596                 // fetch all entry
5597                 DbSourceProxy src = otherdb.get(0);
5598                 fetchr = new JMenuItem(MessageManager.formatMessage(
5599                         "label.fetch_all_param", new Object[]
5600                         { src.getDbSource() }));
5601                 fetchr.addActionListener(new ActionListener()
5602                 {
5603                   @Override
5604                   public void actionPerformed(ActionEvent e)
5605                   {
5606                     new Thread(new Runnable()
5607                     {
5608
5609                       @Override
5610                       public void run()
5611                       {
5612                         new jalview.ws.DBRefFetcher(alignPanel.av
5613                                 .getSequenceSelection(),
5614                                 alignPanel.alignFrame, dassource)
5615                                 .fetchDBRefs(false);
5616                       }
5617                     }).start();
5618                   }
5619                 });
5620
5621                 fetchr.setToolTipText(JvSwingUtils.wrapTooltip(true, MessageManager.formatMessage("label.fetch_retrieve_from_all_sources", new Object[]{Integer.valueOf(otherdb.size()).toString(), src.getDbSource(), src.getDbName()})));
5622                 dfetch.add(fetchr);
5623                 comp++;
5624                 // and then build the rest of the individual menus
5625                 ifetch = new JMenu(MessageManager.formatMessage("label.source_from_db_source", new Object[]{src.getDbSource()}));
5626                 icomp = 0;
5627                 String imname = null;
5628                 int i = 0;
5629                 for (DbSourceProxy sproxy : otherdb)
5630                 {
5631                   String dbname = sproxy.getDbName();
5632                   String sname = dbname.length() > 5 ? dbname.substring(0,
5633                           5) + "..." : dbname;
5634                   String msname = dbname.length() > 10 ? dbname.substring(
5635                           0, 10) + "..." : dbname;
5636                   if (imname == null)
5637                   {
5638                     imname = MessageManager.formatMessage("label.from_msname", new Object[]{sname});
5639                   }
5640                   fetchr = new JMenuItem(msname);
5641                   final DbSourceProxy[] dassrc =
5642                   { sproxy };
5643                   fetchr.addActionListener(new ActionListener()
5644                   {
5645
5646                     @Override
5647                     public void actionPerformed(ActionEvent e)
5648                     {
5649                       new Thread(new Runnable()
5650                       {
5651
5652                         @Override
5653                         public void run()
5654                         {
5655                           new jalview.ws.DBRefFetcher(alignPanel.av
5656                                   .getSequenceSelection(),
5657                                   alignPanel.alignFrame, dassrc)
5658                                   .fetchDBRefs(false);
5659                         }
5660                       }).start();
5661                     }
5662
5663                   });
5664                   fetchr.setToolTipText("<html>"
5665                           + MessageManager.formatMessage("label.fetch_retrieve_from", new Object[]{dbname}));
5666                   ifetch.add(fetchr);
5667                   ++i;
5668                   if (++icomp >= mcomp || i == (otherdb.size()))
5669                   {
5670                     ifetch.setText(MessageManager.formatMessage(
5671                             "label.source_to_target", imname, sname));
5672                     dfetch.add(ifetch);
5673                     ifetch = new JMenu();
5674                     imname = null;
5675                     icomp = 0;
5676                     comp++;
5677                   }
5678                 }
5679               }
5680               ++dbi;
5681               if (comp >= mcomp || dbi >= (dbclasses.length))
5682               {
5683                 dfetch.setText(MessageManager.formatMessage(
5684                         "label.source_to_target", mname, dbclass));
5685                 rfetch.add(dfetch);
5686                 dfetch = new JMenu();
5687                 mname = null;
5688                 comp = 0;
5689               }
5690             }
5691           }
5692         });
5693       }
5694     }).start();
5695
5696   }
5697
5698   /**
5699    * Left justify the whole alignment.
5700    */
5701   @Override
5702   protected void justifyLeftMenuItem_actionPerformed(ActionEvent e)
5703   {
5704     AlignmentI al = viewport.getAlignment();
5705     al.justify(false);
5706     viewport.firePropertyChange("alignment", null, al);
5707   }
5708
5709   /**
5710    * Right justify the whole alignment.
5711    */
5712   @Override
5713   protected void justifyRightMenuItem_actionPerformed(ActionEvent e)
5714   {
5715     AlignmentI al = viewport.getAlignment();
5716     al.justify(true);
5717     viewport.firePropertyChange("alignment", null, al);
5718   }
5719
5720   public void setShowSeqFeatures(boolean b)
5721   {
5722     showSeqFeatures.setSelected(true);
5723     viewport.setShowSequenceFeatures(true);
5724   }
5725
5726   /*
5727    * (non-Javadoc)
5728    * 
5729    * @see
5730    * jalview.jbgui.GAlignFrame#showUnconservedMenuItem_actionPerformed(java.
5731    * awt.event.ActionEvent)
5732    */
5733   @Override
5734   protected void showUnconservedMenuItem_actionPerformed(ActionEvent e)
5735   {
5736     viewport.setShowUnconserved(showNonconservedMenuItem.getState());
5737     alignPanel.paintAlignment(true);
5738   }
5739
5740   /*
5741    * (non-Javadoc)
5742    * 
5743    * @see
5744    * jalview.jbgui.GAlignFrame#showGroupConsensus_actionPerformed(java.awt.event
5745    * .ActionEvent)
5746    */
5747   @Override
5748   protected void showGroupConsensus_actionPerformed(ActionEvent e)
5749   {
5750     viewport.setShowGroupConsensus(showGroupConsensus.getState());
5751     alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5752
5753   }
5754
5755   /*
5756    * (non-Javadoc)
5757    * 
5758    * @see
5759    * jalview.jbgui.GAlignFrame#showGroupConservation_actionPerformed(java.awt
5760    * .event.ActionEvent)
5761    */
5762   @Override
5763   protected void showGroupConservation_actionPerformed(ActionEvent e)
5764   {
5765     viewport.setShowGroupConservation(showGroupConservation.getState());
5766     alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5767   }
5768
5769   /*
5770    * (non-Javadoc)
5771    * 
5772    * @see
5773    * jalview.jbgui.GAlignFrame#showConsensusHistogram_actionPerformed(java.awt
5774    * .event.ActionEvent)
5775    */
5776   @Override
5777   protected void showConsensusHistogram_actionPerformed(ActionEvent e)
5778   {
5779     viewport.setShowConsensusHistogram(showConsensusHistogram.getState());
5780     alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5781   }
5782
5783   /*
5784    * (non-Javadoc)
5785    * 
5786    * @see
5787    * jalview.jbgui.GAlignFrame#showConsensusProfile_actionPerformed(java.awt
5788    * .event.ActionEvent)
5789    */
5790   @Override
5791   protected void showSequenceLogo_actionPerformed(ActionEvent e)
5792   {
5793     viewport.setShowSequenceLogo(showSequenceLogo.getState());
5794     alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5795   }
5796
5797   @Override
5798   protected void normaliseSequenceLogo_actionPerformed(ActionEvent e)
5799   {
5800     showSequenceLogo.setState(true);
5801     viewport.setShowSequenceLogo(true);
5802     viewport.setNormaliseSequenceLogo(normaliseSequenceLogo.getState());
5803     alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5804   }
5805
5806   @Override
5807   protected void applyAutoAnnotationSettings_actionPerformed(ActionEvent e)
5808   {
5809     alignPanel.updateAnnotation(applyAutoAnnotationSettings.getState());
5810   }
5811
5812   /*
5813    * (non-Javadoc)
5814    * 
5815    * @see
5816    * jalview.jbgui.GAlignFrame#makeGrpsFromSelection_actionPerformed(java.awt
5817    * .event.ActionEvent)
5818    */
5819   @Override
5820   protected void makeGrpsFromSelection_actionPerformed(ActionEvent e)
5821   {
5822     if (avc.makeGroupsFromSelection())
5823     {
5824       PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5825       alignPanel.updateAnnotation();
5826       alignPanel.paintAlignment(true);
5827     }
5828   }
5829   public void clearAlignmentSeqRep()
5830   {
5831     // TODO refactor alignmentseqrep to controller
5832     if (viewport.getAlignment().hasSeqrep()) {
5833       viewport.getAlignment().setSeqrep(null);
5834       PaintRefresher.Refresh(this, viewport.getSequenceSetId());
5835       alignPanel.updateAnnotation();
5836       alignPanel.paintAlignment(true);
5837     }
5838   }
5839
5840   @Override
5841   protected void createGroup_actionPerformed(ActionEvent e)
5842   {
5843     if (avc.createGroup())
5844     {
5845       alignPanel.alignmentChanged();
5846     }
5847   }
5848
5849   @Override
5850   protected void unGroup_actionPerformed(ActionEvent e)
5851   {
5852     if (avc.unGroup())
5853     {
5854       alignPanel.alignmentChanged();
5855     }
5856   }
5857
5858   /**
5859    * make the given alignmentPanel the currently selected tab
5860    * 
5861    * @param alignmentPanel
5862    */
5863   public void setDisplayedView(AlignmentPanel alignmentPanel)
5864   {
5865     if (!viewport.getSequenceSetId().equals(
5866             alignmentPanel.av.getSequenceSetId()))
5867     {
5868       throw new Error(MessageManager.getString("error.implementation_error_cannot_show_view_alignment_frame"));
5869     }
5870     if (tabbedPane != null
5871             & alignPanels.indexOf(alignmentPanel) != tabbedPane
5872                     .getSelectedIndex())
5873     {
5874       tabbedPane.setSelectedIndex(alignPanels.indexOf(alignmentPanel));
5875     }
5876   }
5877
5878   /**
5879    * Action on selection of menu options to Show or Hide annotations.
5880    * 
5881    * @param visible
5882    * @param forSequences
5883    *          update sequence-related annotations
5884    * @param forAlignment
5885    *          update non-sequence-related annotations
5886    */
5887   @Override
5888   protected void setAnnotationsVisibility(boolean visible,
5889           boolean forSequences, boolean forAlignment)
5890   {
5891     for (AlignmentAnnotation aa : alignPanel.getAlignment()
5892             .getAlignmentAnnotation())
5893     {
5894       boolean apply = (aa.sequenceRef == null && forAlignment)
5895               || (aa.sequenceRef != null && forSequences);
5896       if (apply)
5897       {
5898         aa.visible = visible;
5899       }
5900     }
5901     alignPanel.validateAnnotationDimensions(false);
5902     alignPanel.alignmentChanged();
5903   }
5904
5905   /**
5906    * Store selected annotation sort order for the view and repaint.
5907    */
5908   @Override
5909   protected void sortAnnotations_actionPerformed()
5910   {
5911     this.alignPanel.av.setSortAnnotationsBy(getAnnotationSortOrder());
5912     this.alignPanel.av
5913             .setShowAutocalculatedAbove(isShowAutoCalculatedAbove());
5914     alignPanel.paintAlignment(true);
5915   }
5916
5917   /**
5918    * 
5919    * @return alignment panels in this alignment frame
5920    */
5921   public List<? extends AlignmentViewPanel> getAlignPanels()
5922   {
5923     return alignPanels == null ? Arrays.asList(alignPanel)
5924             : alignPanels;
5925   }
5926
5927   /**
5928    * Open a new alignment window, with the cDNA associated with this (protein)
5929    * alignment, aligned as is the protein.
5930    */
5931   @Override
5932   protected void viewAsCdna_actionPerformed()
5933   {
5934     final AlignmentI alignment = getViewport().getAlignment();
5935     Set<AlignedCodonFrame> mappings = alignment.getCodonFrames();
5936     if (mappings == null)
5937     {
5938       return;
5939     }
5940     List<SequenceI> cdnaSeqs = new ArrayList<SequenceI>();
5941     for (SequenceI aaSeq : alignment.getSequences()) {
5942       for (AlignedCodonFrame acf : mappings) {
5943         SequenceI dnaSeq = acf.getDnaForAaSeq(aaSeq.getDatasetSequence());
5944         if (dnaSeq != null)
5945         {
5946           /*
5947            * There is a cDNA mapping for this protein sequence - add to new
5948            * alignment. It will share the same dataset sequence as other mapped
5949            * cDNA (no new mappings need to be created).
5950            */
5951           final Sequence newSeq = new Sequence(dnaSeq);
5952           newSeq.setDatasetSequence(dnaSeq);
5953           cdnaSeqs.add(newSeq);
5954         }
5955       }
5956     }
5957     if (cdnaSeqs.size() == 0)
5958     {
5959       // show a warning dialog no mapped cDNA
5960       return;
5961     }
5962     AlignmentI cdna = new Alignment(cdnaSeqs.toArray(new SequenceI[cdnaSeqs
5963             .size()]));
5964     AlignFrame alignFrame = new AlignFrame(cdna, AlignFrame.DEFAULT_WIDTH,
5965             AlignFrame.DEFAULT_HEIGHT);
5966     cdna.alignAs(alignment);
5967     String newtitle = "cDNA " + MessageManager.getString("label.for") + " "
5968             + this.title;
5969     Desktop.addInternalFrame(alignFrame, newtitle,
5970             AlignFrame.DEFAULT_WIDTH,
5971             AlignFrame.DEFAULT_HEIGHT);
5972
5973   }
5974 }
5975
5976 class PrintThread extends Thread
5977 {
5978   AlignmentPanel ap;
5979
5980   public PrintThread(AlignmentPanel ap)
5981   {
5982     this.ap = ap;
5983   }
5984
5985   static PageFormat pf;
5986
5987   @Override
5988   public void run()
5989   {
5990     PrinterJob printJob = PrinterJob.getPrinterJob();
5991
5992     if (pf != null)
5993     {
5994       printJob.setPrintable(ap, pf);
5995     }
5996     else
5997     {
5998       printJob.setPrintable(ap);
5999     }
6000
6001     if (printJob.printDialog())
6002     {
6003       try
6004       {
6005         printJob.print();
6006       } catch (Exception PrintException)
6007       {
6008         PrintException.printStackTrace();
6009       }
6010     }
6011   }
6012 }