JAL-3048 DialogRunnerI reduced to minimal implementation
[jalview.git] / src / jalview / gui / AnnotationLabels.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
7  * Jalview is free software: you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License 
9  * as published by the Free Software Foundation, either version 3
10  * of the License, or (at your option) any later version.
11  *  
12  * Jalview is distributed in the hope that it will be useful, but 
13  * WITHOUT ANY WARRANTY; without even the implied warranty 
14  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
15  * PURPOSE.  See the GNU General Public License for more details.
16  * 
17  * You should have received a copy of the GNU General Public License
18  * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
19  * The Jalview Authors are detailed in the 'AUTHORS' file.
20  */
21 package jalview.gui;
22
23 import jalview.analysis.AlignSeq;
24 import jalview.analysis.AlignmentUtils;
25 import jalview.datamodel.Alignment;
26 import jalview.datamodel.AlignmentAnnotation;
27 import jalview.datamodel.Annotation;
28 import jalview.datamodel.HiddenColumns;
29 import jalview.datamodel.Sequence;
30 import jalview.datamodel.SequenceGroup;
31 import jalview.datamodel.SequenceI;
32 import jalview.io.FileFormat;
33 import jalview.io.FormatAdapter;
34 import jalview.util.Comparison;
35 import jalview.util.MessageManager;
36 import jalview.util.Platform;
37
38 import java.awt.Color;
39 import java.awt.Cursor;
40 import java.awt.Dimension;
41 import java.awt.Font;
42 import java.awt.FontMetrics;
43 import java.awt.Graphics;
44 import java.awt.Graphics2D;
45 import java.awt.RenderingHints;
46 import java.awt.Toolkit;
47 import java.awt.datatransfer.StringSelection;
48 import java.awt.event.ActionEvent;
49 import java.awt.event.ActionListener;
50 import java.awt.event.MouseEvent;
51 import java.awt.event.MouseListener;
52 import java.awt.event.MouseMotionListener;
53 import java.awt.geom.AffineTransform;
54 import java.util.Arrays;
55 import java.util.Collections;
56 import java.util.Iterator;
57 import java.util.regex.Pattern;
58
59 import javax.swing.JCheckBoxMenuItem;
60 import javax.swing.JMenuItem;
61 import javax.swing.JPanel;
62 import javax.swing.JPopupMenu;
63 import javax.swing.SwingUtilities;
64 import javax.swing.ToolTipManager;
65
66 /**
67  * The panel that holds the labels for alignment annotations, providing
68  * tooltips, context menus, drag to reorder rows, and drag to adjust panel
69  * height
70  */
71 public class AnnotationLabels extends JPanel
72         implements MouseListener, MouseMotionListener, ActionListener
73 {
74   /**
75    * width in pixels within which height adjuster arrows are shown and active
76    */
77   private static final int HEIGHT_ADJUSTER_WIDTH = 50;
78
79   /**
80    * height in pixels for allowing height adjuster to be active
81    */
82   private static int HEIGHT_ADJUSTER_HEIGHT = 10;
83
84   private static final Pattern LEFT_ANGLE_BRACKET_PATTERN = Pattern
85           .compile("<");
86
87   private static final Font font = new Font("Arial", Font.PLAIN, 11);
88
89   private static final String TOGGLE_LABELSCALE = MessageManager
90           .getString("label.scale_label_to_column");
91
92   private static final String ADDNEW = MessageManager
93           .getString("label.add_new_row");
94
95   private static final String EDITNAME = MessageManager
96           .getString("label.edit_label_description");
97
98   private static final String HIDE = MessageManager
99           .getString("label.hide_row");
100
101   private static final String DELETE = MessageManager
102           .getString("label.delete_row");
103
104   private static final String SHOWALL = MessageManager
105           .getString("label.show_all_hidden_rows");
106
107   private static final String OUTPUT_TEXT = MessageManager
108           .getString("label.export_annotation");
109
110   private static final String COPYCONS_SEQ = MessageManager
111           .getString("label.copy_consensus_sequence");
112
113   private final boolean debugRedraw = false;
114
115   private AlignmentPanel ap;
116
117   AlignViewport av;
118
119   private MouseEvent dragEvent;
120
121   private int oldY;
122
123   private int selectedRow;
124
125   private int scrollOffset = 0;
126
127   private boolean hasHiddenRows;
128
129   private boolean resizePanel = false;
130
131   /**
132    * Creates a new AnnotationLabels object
133    * 
134    * @param ap
135    */
136   public AnnotationLabels(AlignmentPanel ap)
137   {
138     this.ap = ap;
139     av = ap.av;
140     ToolTipManager.sharedInstance().registerComponent(this);
141
142     addMouseListener(this);
143     addMouseMotionListener(this);
144     addMouseWheelListener(ap.getAnnotationPanel());
145   }
146
147   public AnnotationLabels(AlignViewport av)
148   {
149     this.av = av;
150   }
151
152   /**
153    * DOCUMENT ME!
154    * 
155    * @param y
156    *          DOCUMENT ME!
157    */
158   public void setScrollOffset(int y)
159   {
160     scrollOffset = y;
161     repaint();
162   }
163
164   /**
165    * sets selectedRow to -2 if no annotation preset, -1 if no visible row is at
166    * y
167    * 
168    * @param y
169    *          coordinate position to search for a row
170    */
171   void getSelectedRow(int y)
172   {
173     int height = 0;
174     AlignmentAnnotation[] aa = ap.av.getAlignment()
175             .getAlignmentAnnotation();
176     selectedRow = -2;
177     if (aa != null)
178     {
179       for (int i = 0; i < aa.length; i++)
180       {
181         selectedRow = -1;
182         if (!aa[i].visible)
183         {
184           continue;
185         }
186
187         height += aa[i].height;
188
189         if (y < height)
190         {
191           selectedRow = i;
192
193           break;
194         }
195       }
196     }
197   }
198
199   /**
200    * DOCUMENT ME!
201    * 
202    * @param evt
203    *          DOCUMENT ME!
204    */
205   @Override
206   public void actionPerformed(ActionEvent evt)
207   {
208     AlignmentAnnotation[] aa = ap.av.getAlignment()
209             .getAlignmentAnnotation();
210
211     String action = evt.getActionCommand();
212     if (ADDNEW.equals(action))
213     {
214       /*
215        * non-returning dialog
216        */
217       AlignmentAnnotation newAnnotation = new AlignmentAnnotation(null,
218               null, new Annotation[ap.av.getAlignment().getWidth()]);
219       editLabelDescription(newAnnotation, true);
220     }
221     else if (EDITNAME.equals(action))
222     {
223       /*
224        * non-returning dialog
225        */
226       editLabelDescription(aa[selectedRow], false);
227     }
228     else if (HIDE.equals(action))
229     {
230       aa[selectedRow].visible = false;
231     }
232     else if (DELETE.equals(action))
233     {
234       ap.av.getAlignment().deleteAnnotation(aa[selectedRow]);
235       ap.av.getCalcManager().removeWorkerForAnnotation(aa[selectedRow]);
236     }
237     else if (SHOWALL.equals(action))
238     {
239       for (int i = 0; i < aa.length; i++)
240       {
241         if (!aa[i].visible && aa[i].annotations != null)
242         {
243           aa[i].visible = true;
244         }
245       }
246     }
247     else if (OUTPUT_TEXT.equals(action))
248     {
249       new AnnotationExporter(ap).exportAnnotation(aa[selectedRow]);
250     }
251     else if (COPYCONS_SEQ.equals(action))
252     {
253       SequenceI cons = null;
254       if (aa[selectedRow].groupRef != null)
255       {
256         cons = aa[selectedRow].groupRef.getConsensusSeq();
257       }
258       else
259       {
260         cons = av.getConsensusSeq();
261       }
262       if (cons != null)
263       {
264         copy_annotseqtoclipboard(cons);
265       }
266     }
267     else if (TOGGLE_LABELSCALE.equals(action))
268     {
269       aa[selectedRow].scaleColLabel = !aa[selectedRow].scaleColLabel;
270     }
271
272     ap.refresh(true);
273   }
274
275   /**
276    * Shows a dialog where the annotation name and description may be edited. If
277    * parameter addNew is true, then on confirmation, a new AlignmentAnnotation
278    * is added, else an existing annotation is updated.
279    * 
280    * @param annotation
281    * @param addNew
282    */
283   void editLabelDescription(AlignmentAnnotation annotation, boolean addNew)
284   {
285     String name = MessageManager.getString("label.annotation_name");
286     String description = MessageManager
287             .getString("label.annotation_description");
288     String title = MessageManager
289             .getString("label.edit_annotation_name_description");
290     EditNameDialog dialog = new EditNameDialog(annotation.label,
291             annotation.description, name, description);
292
293     dialog.showDialog(ap.alignFrame, title,
294             new Runnable()
295             {
296               @Override
297               public void run()
298               {
299                 annotation.label = dialog.getName();
300                 String text = dialog.getDescription();
301                 if (text != null && text.length() == 0)
302                 {
303                   text = null;
304                 }
305                 annotation.description = text;
306                 if (addNew)
307                 {
308                   ap.av.getAlignment().addAnnotation(annotation);
309                   ap.av.getAlignment().setAnnotationIndex(annotation, 0);
310                 }
311                 ap.refresh(true);
312               }
313             });
314   }
315
316   @Override
317   public void mousePressed(MouseEvent evt)
318   {
319     getSelectedRow(evt.getY() - getScrollOffset());
320     oldY = evt.getY();
321     if (evt.isPopupTrigger())
322     {
323       showPopupMenu(evt);
324     }
325   }
326
327   /**
328    * Build and show the Pop-up menu at the right-click mouse position
329    * 
330    * @param evt
331    */
332   void showPopupMenu(MouseEvent evt)
333   {
334     evt.consume();
335     final AlignmentAnnotation[] aa = ap.av.getAlignment()
336             .getAlignmentAnnotation();
337
338     JPopupMenu pop = new JPopupMenu(
339             MessageManager.getString("label.annotations"));
340     JMenuItem item = new JMenuItem(ADDNEW);
341     item.addActionListener(this);
342     pop.add(item);
343     if (selectedRow < 0)
344     {
345       if (hasHiddenRows)
346       { // let the user make everything visible again
347         item = new JMenuItem(SHOWALL);
348         item.addActionListener(this);
349         pop.add(item);
350       }
351       pop.show(this, evt.getX(), evt.getY());
352       return;
353     }
354     item = new JMenuItem(EDITNAME);
355     item.addActionListener(this);
356     pop.add(item);
357     item = new JMenuItem(HIDE);
358     item.addActionListener(this);
359     pop.add(item);
360     // JAL-1264 hide all sequence-specific annotations of this type
361     if (selectedRow < aa.length)
362     {
363       if (aa[selectedRow].sequenceRef != null)
364       {
365         final String label = aa[selectedRow].label;
366         JMenuItem hideType = new JMenuItem();
367         String text = MessageManager.getString("label.hide_all") + " "
368                 + label;
369         hideType.setText(text);
370         hideType.addActionListener(new ActionListener()
371         {
372           @Override
373           public void actionPerformed(ActionEvent e)
374           {
375             AlignmentUtils.showOrHideSequenceAnnotations(
376                     ap.av.getAlignment(), Collections.singleton(label),
377                     null, false, false);
378             // for (AlignmentAnnotation ann : ap.av.getAlignment()
379             // .getAlignmentAnnotation())
380             // {
381             // if (ann.sequenceRef != null && ann.label != null
382             // && ann.label.equals(label))
383             // {
384             // ann.visible = false;
385             // }
386             // }
387             ap.refresh(true);
388           }
389         });
390         pop.add(hideType);
391       }
392     }
393     item = new JMenuItem(DELETE);
394     item.addActionListener(this);
395     pop.add(item);
396     if (hasHiddenRows)
397     {
398       item = new JMenuItem(SHOWALL);
399       item.addActionListener(this);
400       pop.add(item);
401     }
402     item = new JMenuItem(OUTPUT_TEXT);
403     item.addActionListener(this);
404     pop.add(item);
405     // TODO: annotation object should be typed for autocalculated/derived
406     // property methods
407     if (selectedRow < aa.length)
408     {
409       final String label = aa[selectedRow].label;
410       if (!aa[selectedRow].autoCalculated)
411       {
412         if (aa[selectedRow].graph == AlignmentAnnotation.NO_GRAPH)
413         {
414           // display formatting settings for this row.
415           pop.addSeparator();
416           // av and sequencegroup need to implement same interface for
417           item = new JCheckBoxMenuItem(TOGGLE_LABELSCALE,
418                   aa[selectedRow].scaleColLabel);
419           item.addActionListener(this);
420           pop.add(item);
421         }
422       }
423       else if (label.indexOf("Consensus") > -1)
424       {
425         pop.addSeparator();
426         // av and sequencegroup need to implement same interface for
427         final JCheckBoxMenuItem cbmi = new JCheckBoxMenuItem(
428                 MessageManager.getString("label.ignore_gaps_consensus"),
429                 (aa[selectedRow].groupRef != null)
430                         ? aa[selectedRow].groupRef.getIgnoreGapsConsensus()
431                         : ap.av.isIgnoreGapsConsensus());
432         final AlignmentAnnotation aaa = aa[selectedRow];
433         cbmi.addActionListener(new ActionListener()
434         {
435           @Override
436           public void actionPerformed(ActionEvent e)
437           {
438             if (aaa.groupRef != null)
439             {
440               // TODO: pass on reference to ap so the view can be updated.
441               aaa.groupRef.setIgnoreGapsConsensus(cbmi.getState());
442               ap.getAnnotationPanel()
443                       .paint(ap.getAnnotationPanel().getGraphics());
444             }
445             else
446             {
447               ap.av.setIgnoreGapsConsensus(cbmi.getState(), ap);
448             }
449             ap.alignmentChanged();
450           }
451         });
452         pop.add(cbmi);
453         // av and sequencegroup need to implement same interface for
454         if (aaa.groupRef != null)
455         {
456           final JCheckBoxMenuItem chist = new JCheckBoxMenuItem(
457                   MessageManager.getString("label.show_group_histogram"),
458                   aa[selectedRow].groupRef.isShowConsensusHistogram());
459           chist.addActionListener(new ActionListener()
460           {
461             @Override
462             public void actionPerformed(ActionEvent e)
463             {
464               // TODO: pass on reference
465               // to ap
466               // so the
467               // view
468               // can be
469               // updated.
470               aaa.groupRef.setShowConsensusHistogram(chist.getState());
471               ap.repaint();
472               // ap.annotationPanel.paint(ap.annotationPanel.getGraphics());
473             }
474           });
475           pop.add(chist);
476           final JCheckBoxMenuItem cprofl = new JCheckBoxMenuItem(
477                   MessageManager.getString("label.show_group_logo"),
478                   aa[selectedRow].groupRef.isShowSequenceLogo());
479           cprofl.addActionListener(new ActionListener()
480           {
481             @Override
482             public void actionPerformed(ActionEvent e)
483             {
484               // TODO: pass on reference
485               // to ap
486               // so the
487               // view
488               // can be
489               // updated.
490               aaa.groupRef.setshowSequenceLogo(cprofl.getState());
491               ap.repaint();
492               // ap.annotationPanel.paint(ap.annotationPanel.getGraphics());
493             }
494           });
495           pop.add(cprofl);
496           final JCheckBoxMenuItem cproflnorm = new JCheckBoxMenuItem(
497                   MessageManager.getString("label.normalise_group_logo"),
498                   aa[selectedRow].groupRef.isNormaliseSequenceLogo());
499           cproflnorm.addActionListener(new ActionListener()
500           {
501             @Override
502             public void actionPerformed(ActionEvent e)
503             {
504
505               // TODO: pass on reference
506               // to ap
507               // so the
508               // view
509               // can be
510               // updated.
511               aaa.groupRef.setNormaliseSequenceLogo(cproflnorm.getState());
512               // automatically enable logo display if we're clicked
513               aaa.groupRef.setshowSequenceLogo(true);
514               ap.repaint();
515               // ap.annotationPanel.paint(ap.annotationPanel.getGraphics());
516             }
517           });
518           pop.add(cproflnorm);
519         }
520         else
521         {
522           final JCheckBoxMenuItem chist = new JCheckBoxMenuItem(
523                   MessageManager.getString("label.show_histogram"),
524                   av.isShowConsensusHistogram());
525           chist.addActionListener(new ActionListener()
526           {
527             @Override
528             public void actionPerformed(ActionEvent e)
529             {
530               // TODO: pass on reference
531               // to ap
532               // so the
533               // view
534               // can be
535               // updated.
536               av.setShowConsensusHistogram(chist.getState());
537               ap.alignFrame.setMenusForViewport();
538               ap.repaint();
539               // ap.annotationPanel.paint(ap.annotationPanel.getGraphics());
540             }
541           });
542           pop.add(chist);
543           final JCheckBoxMenuItem cprof = new JCheckBoxMenuItem(
544                   MessageManager.getString("label.show_logo"),
545                   av.isShowSequenceLogo());
546           cprof.addActionListener(new ActionListener()
547           {
548             @Override
549             public void actionPerformed(ActionEvent e)
550             {
551               // TODO: pass on reference
552               // to ap
553               // so the
554               // view
555               // can be
556               // updated.
557               av.setShowSequenceLogo(cprof.getState());
558               ap.alignFrame.setMenusForViewport();
559               ap.repaint();
560               // ap.annotationPanel.paint(ap.annotationPanel.getGraphics());
561             }
562           });
563           pop.add(cprof);
564           final JCheckBoxMenuItem cprofnorm = new JCheckBoxMenuItem(
565                   MessageManager.getString("label.normalise_logo"),
566                   av.isNormaliseSequenceLogo());
567           cprofnorm.addActionListener(new ActionListener()
568           {
569             @Override
570             public void actionPerformed(ActionEvent e)
571             {
572               // TODO: pass on reference
573               // to ap
574               // so the
575               // view
576               // can be
577               // updated.
578               av.setShowSequenceLogo(true);
579               av.setNormaliseSequenceLogo(cprofnorm.getState());
580               ap.alignFrame.setMenusForViewport();
581               ap.repaint();
582               // ap.annotationPanel.paint(ap.annotationPanel.getGraphics());
583             }
584           });
585           pop.add(cprofnorm);
586         }
587         final JMenuItem consclipbrd = new JMenuItem(COPYCONS_SEQ);
588         consclipbrd.addActionListener(this);
589         pop.add(consclipbrd);
590       }
591     }
592     pop.show(this, evt.getX(), evt.getY());
593   }
594
595   /**
596    * Reorders annotation rows after a drag of a label
597    * 
598    * @param evt
599    */
600   @Override
601   public void mouseReleased(MouseEvent evt)
602   {
603     if (evt.isPopupTrigger())
604     {
605       showPopupMenu(evt);
606       return;
607     }
608
609     int start = selectedRow;
610     getSelectedRow(evt.getY() - getScrollOffset());
611     int end = selectedRow;
612
613     /*
614      * if dragging to resize instead, start == end
615      */
616     if (start != end)
617     {
618       // Swap these annotations
619       AlignmentAnnotation startAA = ap.av.getAlignment()
620               .getAlignmentAnnotation()[start];
621       if (end == -1)
622       {
623         end = ap.av.getAlignment().getAlignmentAnnotation().length - 1;
624       }
625       AlignmentAnnotation endAA = ap.av.getAlignment()
626               .getAlignmentAnnotation()[end];
627
628       ap.av.getAlignment().getAlignmentAnnotation()[end] = startAA;
629       ap.av.getAlignment().getAlignmentAnnotation()[start] = endAA;
630     }
631
632     resizePanel = false;
633     dragEvent = null;
634     repaint();
635     ap.getAnnotationPanel().repaint();
636   }
637
638   /**
639    * Removes the height adjuster image on leaving the panel, unless currently
640    * dragging it
641    */
642   @Override
643   public void mouseExited(MouseEvent evt)
644   {
645     if (resizePanel && dragEvent == null)
646     {
647       resizePanel = false;
648       repaint();
649     }
650   }
651
652   /**
653    * A mouse drag may be either an adjustment of the panel height (if flag
654    * resizePanel is set on), or a reordering of the annotation rows. The former
655    * is dealt with by this method, the latter in mouseReleased.
656    * 
657    * @param evt
658    */
659   @Override
660   public void mouseDragged(MouseEvent evt)
661   {
662     dragEvent = evt;
663
664     if (resizePanel)
665     {
666       Dimension d = ap.annotationScroller.getPreferredSize();
667       int dif = evt.getY() - oldY;
668
669       dif /= ap.av.getCharHeight();
670       dif *= ap.av.getCharHeight();
671
672       if ((d.height - dif) > 20)
673       {
674         ap.annotationScroller
675                 .setPreferredSize(new Dimension(d.width, d.height - dif));
676         d = ap.annotationSpaceFillerHolder.getPreferredSize();
677         ap.annotationSpaceFillerHolder
678                 .setPreferredSize(new Dimension(d.width, d.height - dif));
679         ap.paintAlignment(true, false);
680       }
681
682       ap.addNotify();
683     }
684     else
685     {
686       repaint();
687     }
688   }
689
690   /**
691    * Updates the tooltip as the mouse moves over the labels
692    * 
693    * @param evt
694    */
695   @Override
696   public void mouseMoved(MouseEvent evt)
697   {
698     showOrHideAdjuster(evt);
699
700     getSelectedRow(evt.getY() - getScrollOffset());
701
702     if (selectedRow > -1 && ap.av.getAlignment()
703             .getAlignmentAnnotation().length > selectedRow)
704     {
705       AlignmentAnnotation aa = ap.av.getAlignment()
706               .getAlignmentAnnotation()[selectedRow];
707
708       StringBuffer desc = new StringBuffer();
709       if (aa.description != null
710               && !aa.description.equals("New description"))
711       {
712         // TODO: we could refactor and merge this code with the code in
713         // jalview.gui.SeqPanel.mouseMoved(..) that formats sequence feature
714         // tooltips
715         desc.append(aa.getDescription(true).trim());
716         // check to see if the description is an html fragment.
717         if (desc.length() < 6 || (desc.substring(0, 6).toLowerCase()
718                 .indexOf("<html>") < 0))
719         {
720           // clean the description ready for embedding in html
721           desc = new StringBuffer(LEFT_ANGLE_BRACKET_PATTERN.matcher(desc)
722                   .replaceAll("&lt;"));
723           desc.insert(0, "<html>");
724         }
725         else
726         {
727           // remove terminating html if any
728           int i = desc.substring(desc.length() - 7).toLowerCase()
729                   .lastIndexOf("</html>");
730           if (i > -1)
731           {
732             desc.setLength(desc.length() - 7 + i);
733           }
734         }
735         if (aa.hasScore())
736         {
737           desc.append("<br/>");
738         }
739         // if (aa.hasProperties())
740         // {
741         // desc.append("<table>");
742         // for (String prop : aa.getProperties())
743         // {
744         // desc.append("<tr><td>" + prop + "</td><td>"
745         // + aa.getProperty(prop) + "</td><tr>");
746         // }
747         // desc.append("</table>");
748         // }
749       }
750       else
751       {
752         // begin the tooltip's html fragment
753         desc.append("<html>");
754         if (aa.hasScore())
755         {
756           // TODO: limit precision of score to avoid noise from imprecise
757           // doubles
758           // (64.7 becomes 64.7+/some tiny value).
759           desc.append(" Score: " + aa.score);
760         }
761       }
762       if (desc.length() > 6)
763       {
764         desc.append("</html>");
765         this.setToolTipText(desc.toString());
766       }
767       else
768       {
769         this.setToolTipText(null);
770       }
771     }
772   }
773
774   /**
775    * Shows the height adjuster image if the mouse moves into the top left
776    * region, or hides it if the mouse leaves the regio
777    * 
778    * @param evt
779    */
780   protected void showOrHideAdjuster(MouseEvent evt)
781   {
782     boolean was = resizePanel;
783     resizePanel = evt.getY() < HEIGHT_ADJUSTER_HEIGHT
784             && evt.getX() < HEIGHT_ADJUSTER_WIDTH;
785
786     if (resizePanel != was)
787     {
788       setCursor(Cursor
789               .getPredefinedCursor(resizePanel ? Cursor.S_RESIZE_CURSOR
790                       : Cursor.DEFAULT_CURSOR));
791       repaint();
792     }
793   }
794
795   @Override
796   public void mouseClicked(MouseEvent evt)
797   {
798     final AlignmentAnnotation[] aa = ap.av.getAlignment()
799             .getAlignmentAnnotation();
800     if (!evt.isPopupTrigger() && SwingUtilities.isLeftMouseButton(evt))
801     {
802       if (selectedRow > -1 && selectedRow < aa.length)
803       {
804         if (aa[selectedRow].groupRef != null)
805         {
806           if (evt.getClickCount() >= 2)
807           {
808             // todo: make the ap scroll to the selection - not necessary, first
809             // click highlights/scrolls, second selects
810             ap.getSeqPanel().ap.getIdPanel().highlightSearchResults(null);
811             // process modifiers
812             SequenceGroup sg = ap.av.getSelectionGroup();
813             if (sg == null || sg == aa[selectedRow].groupRef
814                     || !(Platform.isControlDown(evt) || evt.isShiftDown()))
815             {
816               if (Platform.isControlDown(evt) || evt.isShiftDown())
817               {
818                 // clone a new selection group from the associated group
819                 ap.av.setSelectionGroup(
820                         new SequenceGroup(aa[selectedRow].groupRef));
821               }
822               else
823               {
824                 // set selection to the associated group so it can be edited
825                 ap.av.setSelectionGroup(aa[selectedRow].groupRef);
826               }
827             }
828             else
829             {
830               // modify current selection with associated group
831               int remainToAdd = aa[selectedRow].groupRef.getSize();
832               for (SequenceI sgs : aa[selectedRow].groupRef.getSequences())
833               {
834                 if (jalview.util.Platform.isControlDown(evt))
835                 {
836                   sg.addOrRemove(sgs, --remainToAdd == 0);
837                 }
838                 else
839                 {
840                   // notionally, we should also add intermediate sequences from
841                   // last added sequence ?
842                   sg.addSequence(sgs, --remainToAdd == 0);
843                 }
844               }
845             }
846
847             ap.paintAlignment(false, false);
848             PaintRefresher.Refresh(ap, ap.av.getSequenceSetId());
849             ap.av.sendSelection();
850           }
851           else
852           {
853             ap.getSeqPanel().ap.getIdPanel().highlightSearchResults(
854                     aa[selectedRow].groupRef.getSequences(null));
855           }
856           return;
857         }
858         else if (aa[selectedRow].sequenceRef != null)
859         {
860           if (evt.getClickCount() == 1)
861           {
862             ap.getSeqPanel().ap.getIdPanel()
863                     .highlightSearchResults(Arrays.asList(new SequenceI[]
864                     { aa[selectedRow].sequenceRef }));
865           }
866           else if (evt.getClickCount() >= 2)
867           {
868             ap.getSeqPanel().ap.getIdPanel().highlightSearchResults(null);
869             SequenceGroup sg = ap.av.getSelectionGroup();
870             if (sg != null)
871             {
872               // we make a copy rather than edit the current selection if no
873               // modifiers pressed
874               // see Enhancement JAL-1557
875               if (!(Platform.isControlDown(evt) || evt.isShiftDown()))
876               {
877                 sg = new SequenceGroup(sg);
878                 sg.clear();
879                 sg.addSequence(aa[selectedRow].sequenceRef, false);
880               }
881               else
882               {
883                 if (Platform.isControlDown(evt))
884                 {
885                   sg.addOrRemove(aa[selectedRow].sequenceRef, true);
886                 }
887                 else
888                 {
889                   // notionally, we should also add intermediate sequences from
890                   // last added sequence ?
891                   sg.addSequence(aa[selectedRow].sequenceRef, true);
892                 }
893               }
894             }
895             else
896             {
897               sg = new SequenceGroup();
898               sg.setStartRes(0);
899               sg.setEndRes(ap.av.getAlignment().getWidth() - 1);
900               sg.addSequence(aa[selectedRow].sequenceRef, false);
901             }
902             ap.av.setSelectionGroup(sg);
903             ap.paintAlignment(false, false);
904             PaintRefresher.Refresh(ap, ap.av.getSequenceSetId());
905             ap.av.sendSelection();
906           }
907
908         }
909       }
910       return;
911     }
912   }
913
914   /**
915    * do a single sequence copy to jalview and the system clipboard
916    * 
917    * @param sq
918    *          sequence to be copied to clipboard
919    */
920   protected void copy_annotseqtoclipboard(SequenceI sq)
921   {
922     SequenceI[] seqs = new SequenceI[] { sq };
923     String[] omitHidden = null;
924     SequenceI[] dseqs = new SequenceI[] { sq.getDatasetSequence() };
925     if (dseqs[0] == null)
926     {
927       dseqs[0] = new Sequence(sq);
928       dseqs[0].setSequence(AlignSeq.extractGaps(Comparison.GapChars,
929               sq.getSequenceAsString()));
930
931       sq.setDatasetSequence(dseqs[0]);
932     }
933     Alignment ds = new Alignment(dseqs);
934     if (av.hasHiddenColumns())
935     {
936       Iterator<int[]> it = av.getAlignment().getHiddenColumns()
937               .getVisContigsIterator(0, sq.getLength(), false);
938       omitHidden = new String[] { sq.getSequenceStringFromIterator(it) };
939     }
940
941     int[] alignmentStartEnd = new int[] { 0, ds.getWidth() - 1 };
942     if (av.hasHiddenColumns())
943     {
944       alignmentStartEnd = av.getAlignment().getHiddenColumns()
945               .getVisibleStartAndEndIndex(av.getAlignment().getWidth());
946     }
947
948     String output = new FormatAdapter().formatSequences(FileFormat.Fasta,
949             seqs, omitHidden, alignmentStartEnd);
950
951     Toolkit.getDefaultToolkit().getSystemClipboard()
952             .setContents(new StringSelection(output), Desktop.instance);
953
954     HiddenColumns hiddenColumns = null;
955
956     if (av.hasHiddenColumns())
957     {
958       hiddenColumns = new HiddenColumns(
959               av.getAlignment().getHiddenColumns());
960     }
961
962     Desktop.jalviewClipboard = new Object[] { seqs, ds, // what is the dataset
963                                                         // of a consensus
964                                                         // sequence ? need to
965                                                         // flag
966         // sequence as special.
967         hiddenColumns };
968   }
969
970   /**
971    * DOCUMENT ME!
972    * 
973    * @param g1
974    *          DOCUMENT ME!
975    */
976   @Override
977   public void paintComponent(Graphics g)
978   {
979
980     int width = getWidth();
981     if (width == 0)
982     {
983       width = ap.calculateIdWidth().width + 4;
984     }
985
986     Graphics2D g2 = (Graphics2D) g;
987     if (av.antiAlias)
988     {
989       g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
990               RenderingHints.VALUE_ANTIALIAS_ON);
991     }
992
993     drawComponent(g2, true, width);
994
995   }
996
997   /**
998    * Draw the full set of annotation Labels for the alignment at the given
999    * cursor
1000    * 
1001    * @param g
1002    *          Graphics2D instance (needed for font scaling)
1003    * @param width
1004    *          Width for scaling labels
1005    * 
1006    */
1007   public void drawComponent(Graphics g, int width)
1008   {
1009     drawComponent(g, false, width);
1010   }
1011
1012   /**
1013    * Draw the full set of annotation Labels for the alignment at the given
1014    * cursor
1015    * 
1016    * @param g
1017    *          Graphics2D instance (needed for font scaling)
1018    * @param clip
1019    *          - true indicates that only current visible area needs to be
1020    *          rendered
1021    * @param width
1022    *          Width for scaling labels
1023    */
1024   public void drawComponent(Graphics g, boolean clip, int width)
1025   {
1026     if (av.getFont().getSize() < 10)
1027     {
1028       g.setFont(font);
1029     }
1030     else
1031     {
1032       g.setFont(av.getFont());
1033     }
1034
1035     FontMetrics fm = g.getFontMetrics(g.getFont());
1036     g.setColor(Color.white);
1037     g.fillRect(0, 0, getWidth(), getHeight());
1038
1039     g.translate(0, getScrollOffset());
1040     g.setColor(Color.black);
1041
1042     AlignmentAnnotation[] aa = av.getAlignment().getAlignmentAnnotation();
1043     int fontHeight = g.getFont().getSize();
1044     int y = 0;
1045     int x = 0;
1046     int graphExtras = 0;
1047     int offset = 0;
1048     Font baseFont = g.getFont();
1049     FontMetrics baseMetrics = fm;
1050     int ofontH = fontHeight;
1051     int sOffset = 0;
1052     int visHeight = 0;
1053     int[] visr = (ap != null && ap.getAnnotationPanel() != null)
1054             ? ap.getAnnotationPanel().getVisibleVRange()
1055             : null;
1056     if (clip && visr != null)
1057     {
1058       sOffset = visr[0];
1059       visHeight = visr[1];
1060     }
1061     boolean visible = true, before = false, after = false;
1062     if (aa != null)
1063     {
1064       hasHiddenRows = false;
1065       int olY = 0;
1066       for (int i = 0; i < aa.length; i++)
1067       {
1068         visible = true;
1069         if (!aa[i].visible)
1070         {
1071           hasHiddenRows = true;
1072           continue;
1073         }
1074         olY = y;
1075         y += aa[i].height;
1076         if (clip)
1077         {
1078           if (y < sOffset)
1079           {
1080             if (!before)
1081             {
1082               if (debugRedraw)
1083               {
1084                 System.out.println("before vis: " + i);
1085               }
1086               before = true;
1087             }
1088             // don't draw what isn't visible
1089             continue;
1090           }
1091           if (olY > visHeight)
1092           {
1093
1094             if (!after)
1095             {
1096               if (debugRedraw)
1097               {
1098                 System.out.println(
1099                         "Scroll offset: " + sOffset + " after vis: " + i);
1100               }
1101               after = true;
1102             }
1103             // don't draw what isn't visible
1104             continue;
1105           }
1106         }
1107         g.setColor(Color.black);
1108
1109         offset = -aa[i].height / 2;
1110
1111         if (aa[i].hasText)
1112         {
1113           offset += fm.getHeight() / 2;
1114           offset -= fm.getDescent();
1115         }
1116         else
1117         {
1118           offset += fm.getDescent();
1119         }
1120
1121         x = width - fm.stringWidth(aa[i].label) - 3;
1122
1123         if (aa[i].graphGroup > -1)
1124         {
1125           int groupSize = 0;
1126           // TODO: JAL-1291 revise rendering model so the graphGroup map is
1127           // computed efficiently for all visible labels
1128           for (int gg = 0; gg < aa.length; gg++)
1129           {
1130             if (aa[gg].graphGroup == aa[i].graphGroup)
1131             {
1132               groupSize++;
1133             }
1134           }
1135           if (groupSize * (fontHeight + 8) < aa[i].height)
1136           {
1137             graphExtras = (aa[i].height - (groupSize * (fontHeight + 8)))
1138                     / 2;
1139           }
1140           else
1141           {
1142             // scale font to fit
1143             float h = aa[i].height / (float) groupSize, s;
1144             if (h < 9)
1145             {
1146               visible = false;
1147             }
1148             else
1149             {
1150               fontHeight = -8 + (int) h;
1151               s = ((float) fontHeight) / (float) ofontH;
1152               Font f = baseFont
1153                       .deriveFont(AffineTransform.getScaleInstance(s, s));
1154               g.setFont(f);
1155               fm = g.getFontMetrics();
1156               graphExtras = (aa[i].height - (groupSize * (fontHeight + 8)))
1157                       / 2;
1158             }
1159           }
1160           if (visible)
1161           {
1162             for (int gg = 0; gg < aa.length; gg++)
1163             {
1164               if (aa[gg].graphGroup == aa[i].graphGroup)
1165               {
1166                 x = width - fm.stringWidth(aa[gg].label) - 3;
1167                 g.drawString(aa[gg].label, x, y - graphExtras);
1168
1169                 if (aa[gg]._linecolour != null)
1170                 {
1171
1172                   g.setColor(aa[gg]._linecolour);
1173                   g.drawLine(x, y - graphExtras + 3,
1174                           x + fm.stringWidth(aa[gg].label),
1175                           y - graphExtras + 3);
1176                 }
1177
1178                 g.setColor(Color.black);
1179                 graphExtras += fontHeight + 8;
1180               }
1181             }
1182           }
1183           g.setFont(baseFont);
1184           fm = baseMetrics;
1185           fontHeight = ofontH;
1186         }
1187         else
1188         {
1189           g.drawString(aa[i].label, x, y + offset);
1190         }
1191       }
1192     }
1193
1194     if (!resizePanel && dragEvent != null && aa != null)
1195     {
1196       g.setColor(Color.lightGray);
1197       g.drawString(aa[selectedRow].label, dragEvent.getX(),
1198               dragEvent.getY() - getScrollOffset());
1199     }
1200
1201     if (!av.getWrapAlignment() && ((aa == null) || (aa.length < 1)))
1202     {
1203       g.drawString(MessageManager.getString("label.right_click"), 2, 8);
1204       g.drawString(MessageManager.getString("label.to_add_annotation"), 2,
1205               18);
1206     }
1207   }
1208
1209   public int getScrollOffset()
1210   {
1211     return scrollOffset;
1212   }
1213
1214   @Override
1215   public void mouseEntered(MouseEvent e)
1216   {
1217   }
1218 }