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