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