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