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