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