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