minor formatting of tooltip
[jalview.git] / src / jalview / gui / AnnotationLabels.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer
3  * Copyright (C) 2007 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License
7  * as published by the Free Software Foundation; either version 2
8  * of the License, or (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
18  */
19 package jalview.gui;
20
21 import java.util.*;
22
23 import java.awt.*;
24 import java.awt.datatransfer.*;
25 import java.awt.event.*;
26 import java.awt.image.*;
27 import javax.swing.*;
28
29 import jalview.datamodel.*;
30 import jalview.io.*;
31
32 /**
33  * DOCUMENT ME!
34  *
35  * @author $author$
36  * @version $Revision$
37  */
38 public class AnnotationLabels
39     extends JPanel implements MouseListener,
40     MouseMotionListener, ActionListener
41 {
42   static String ADDNEW = "Add New Row";
43   static String EDITNAME = "Edit Label/Description";
44   static String HIDE = "Hide This Row";
45   static String DELETE = "Delete This Row";
46   static String SHOWALL = "Show All Hidden Rows";
47   static String OUTPUT_TEXT = "Export Annotation";
48   static String COPYCONS_SEQ = "Copy Consensus Sequence";
49   boolean resizePanel = false;
50   Image image;
51   AlignmentPanel ap;
52   AlignViewport av;
53   boolean resizing = false;
54   MouseEvent dragEvent;
55   int oldY;
56   int selectedRow;
57   int scrollOffset = 0;
58   Font font = new Font("Arial", Font.PLAIN, 11);
59
60   /**
61    * Creates a new AnnotationLabels object.
62    *
63    * @param ap DOCUMENT ME!
64    */
65   public AnnotationLabels(AlignmentPanel ap)
66   {
67     this.ap = ap;
68     av = ap.av;
69     ToolTipManager.sharedInstance().registerComponent(this);
70
71     java.net.URL url = getClass().getResource("/images/idwidth.gif");
72     Image temp = null;
73
74     if (url != null)
75     {
76       temp = java.awt.Toolkit.getDefaultToolkit().createImage(url);
77     }
78
79     try
80     {
81       MediaTracker mt = new MediaTracker(this);
82       mt.addImage(temp, 0);
83       mt.waitForID(0);
84     }
85     catch (Exception ex)
86     {
87     }
88
89     BufferedImage bi = new BufferedImage(temp.getHeight(this),
90                                          temp.getWidth(this),
91                                          BufferedImage.TYPE_INT_RGB);
92     Graphics2D g = (Graphics2D) bi.getGraphics();
93     g.rotate(Math.toRadians(90));
94     g.drawImage(temp, 0, -bi.getWidth(this), this);
95     image = (Image) bi;
96
97     addMouseListener(this);
98     addMouseMotionListener(this);
99   }
100
101   public AnnotationLabels(AlignViewport av)
102   {
103     this.av = av;
104   }
105
106   /**
107    * DOCUMENT ME!
108    *
109    * @param y DOCUMENT ME!
110    */
111   public void setScrollOffset(int y)
112   {
113     scrollOffset = y;
114     repaint();
115   }
116
117   void getSelectedRow(int y)
118   {
119     int height = 0;
120     AlignmentAnnotation[] aa = ap.av.alignment.getAlignmentAnnotation();
121
122     if (aa != null)
123     {
124       for (int i = 0; i < aa.length; i++)
125       {
126         if (!aa[i].visible)
127         {
128           continue;
129         }
130
131         height += aa[i].height;
132
133         if (y < height)
134         {
135           selectedRow = i;
136
137           break;
138         }
139       }
140     }
141   }
142
143   /**
144    * DOCUMENT ME!
145    *
146    * @param evt DOCUMENT ME!
147    */
148   public void actionPerformed(ActionEvent evt)
149   {
150     AlignmentAnnotation[] aa = ap.av.alignment.getAlignmentAnnotation();
151
152     if (evt.getActionCommand().equals(ADDNEW))
153     {
154       AlignmentAnnotation newAnnotation = new AlignmentAnnotation(null,
155           null,
156           new Annotation[ap.av.alignment.getWidth()]);
157
158       if (!editLabelDescription(newAnnotation))
159       {
160         return;
161       }
162
163       ap.av.alignment.addAnnotation(newAnnotation);
164       ap.av.alignment.setAnnotationIndex(newAnnotation, 0);
165     }
166     else if (evt.getActionCommand().equals(EDITNAME))
167     {
168       editLabelDescription(aa[selectedRow]);
169       repaint();
170     }
171     else if (evt.getActionCommand().equals(HIDE))
172     {
173       aa[selectedRow].visible = false;
174
175       if (aa[selectedRow].label.equals("Quality"))
176       {
177         ap.av.quality = null;
178       }
179     }
180     else if (evt.getActionCommand().equals(DELETE))
181     {
182       ap.av.alignment.deleteAnnotation(aa[selectedRow]);
183     }
184     else if (evt.getActionCommand().equals(SHOWALL))
185     {
186       for (int i = 0; i < aa.length; i++)
187       {
188         if (!aa[i].visible && aa[i].annotations!=null)
189         {
190           aa[i].visible = true;
191         }
192       }
193     }
194     else if (evt.getActionCommand().equals(OUTPUT_TEXT))
195     {
196       new AnnotationExporter().exportAnnotations(
197           ap,
198           new AlignmentAnnotation[]
199           {aa[selectedRow]},
200           null, null
201           );
202     }
203     else if (evt.getActionCommand().equals(COPYCONS_SEQ))
204     {
205       SequenceI cons = av.getConsensusSeq();
206       if (cons != null)
207       {
208         copy_annotseqtoclipboard(cons);
209       }
210
211     }
212
213     ap.annotationPanel.adjustPanelHeight();
214     ap.annotationScroller.validate();
215     ap.paintAlignment(true);
216   }
217
218   /**
219    * DOCUMENT ME!
220    *
221    * @param e DOCUMENT ME!
222    */
223   boolean editLabelDescription(AlignmentAnnotation annotation)
224   {
225     EditNameDialog dialog = new EditNameDialog(annotation.label,
226                                                annotation.description,
227                                                "       Annotation Name ",
228                                                "Annotation Description ",
229                                                "Edit Annotation Name/Description");
230
231     if (!dialog.accept)
232     {
233       return false;
234     }
235
236     annotation.label = dialog.getName();
237
238     String text = dialog.getDescription();
239     if (text!=null && text.length() == 0)
240     {
241       text = null;
242     }
243     annotation.description = text;
244
245     return true;
246   }
247
248   /**
249    * DOCUMENT ME!
250    *
251    * @param evt DOCUMENT ME!
252    */
253   public void mousePressed(MouseEvent evt)
254   {
255     getSelectedRow(evt.getY() - scrollOffset);
256     oldY = evt.getY();
257   }
258
259   /**
260    * DOCUMENT ME!
261    *
262    * @param evt DOCUMENT ME!
263    */
264   public void mouseReleased(MouseEvent evt)
265   {
266     int start = selectedRow;
267     getSelectedRow(evt.getY() - scrollOffset);
268     int end = selectedRow;
269
270     if (start != end)
271     {
272       //Swap these annotations
273       AlignmentAnnotation startAA = ap.av.alignment.getAlignmentAnnotation()[
274           start];
275       AlignmentAnnotation endAA = ap.av.alignment.getAlignmentAnnotation()[end];
276
277       ap.av.alignment.getAlignmentAnnotation()[end] = startAA;
278       ap.av.alignment.getAlignmentAnnotation()[start] = endAA;
279     }
280
281     resizePanel = false;
282     dragEvent = null;
283     repaint();
284     ap.annotationPanel.repaint();
285   }
286
287   /**
288    * DOCUMENT ME!
289    *
290    * @param evt DOCUMENT ME!
291    */
292   public void mouseEntered(MouseEvent evt)
293   {
294     if (evt.getY() < 10)
295     {
296       resizePanel = true;
297       repaint();
298     }
299   }
300
301   /**
302    * DOCUMENT ME!
303    *
304    * @param evt DOCUMENT ME!
305    */
306   public void mouseExited(MouseEvent evt)
307   {
308     if (dragEvent == null)
309     {
310       resizePanel = false;
311       repaint();
312     }
313   }
314
315   /**
316    * DOCUMENT ME!
317    *
318    * @param evt DOCUMENT ME!
319    */
320   public void mouseDragged(MouseEvent evt)
321   {
322     dragEvent = evt;
323
324     if (resizePanel)
325     {
326       Dimension d = ap.annotationScroller.getPreferredSize();
327       int dif = evt.getY() - oldY;
328
329       dif /= ap.av.charHeight;
330       dif *= ap.av.charHeight;
331
332       if ( (d.height - dif) > 20)
333       {
334         ap.annotationScroller.setPreferredSize(new Dimension(d.width,
335             d.height - dif));
336         d = ap.annotationSpaceFillerHolder.getPreferredSize();
337         ap.annotationSpaceFillerHolder.setPreferredSize(new Dimension(
338             d.width, d.height - dif));
339         ap.paintAlignment(true);
340       }
341
342       ap.addNotify();
343     }
344     else
345     {
346       repaint();
347     }
348   }
349
350   /**
351    * DOCUMENT ME!
352    *
353    * @param evt DOCUMENT ME!
354    */
355   public void mouseMoved(MouseEvent evt)
356   {
357     resizePanel = evt.getY() < 10;
358
359     getSelectedRow(evt.getY() - scrollOffset);
360
361
362     if (selectedRow > -1
363         && ap.av.alignment.getAlignmentAnnotation().length > selectedRow)
364     {
365       AlignmentAnnotation aa = ap.av.alignment.
366           getAlignmentAnnotation()[selectedRow];
367
368       StringBuffer desc = new StringBuffer("<html>");
369
370       if (aa.description != null && !aa.description.equals("New description"))
371       {
372         desc.append(aa.description);
373         if(aa.hasScore)
374           desc.append("<br>");
375       }
376       if(aa.hasScore())
377       {
378         desc.append("Score: "+aa.score);
379       }
380
381       if(desc.length()!=6)
382       {
383         desc.append("</html>");
384         this.setToolTipText(desc.toString());
385       }
386       else
387         this.setToolTipText(null);
388     }
389
390   }
391
392   /**
393    * DOCUMENT ME!
394    *
395    * @param evt DOCUMENT ME!
396    */
397   public void mouseClicked(MouseEvent evt)
398   {
399     if (!SwingUtilities.isRightMouseButton(evt))
400     {
401       return;
402     }
403
404     AlignmentAnnotation[] aa = ap.av.alignment.getAlignmentAnnotation();
405
406     if ( (aa == null) || (aa.length == 0))
407     {
408       JPopupMenu pop = new JPopupMenu("Annotations");
409       JMenuItem item = new JMenuItem(ADDNEW);
410       item.addActionListener(this);
411       pop.add(item);
412       pop.show(this, evt.getX(), evt.getY());
413
414       return;
415     }
416
417     JPopupMenu pop = new JPopupMenu("Annotations");
418     JMenuItem item = new JMenuItem(ADDNEW);
419     item.addActionListener(this);
420     pop.add(item);
421     item = new JMenuItem(EDITNAME);
422     item.addActionListener(this);
423     pop.add(item);
424     item = new JMenuItem(HIDE);
425     item.addActionListener(this);
426     pop.add(item);
427     item = new JMenuItem(DELETE);
428     item.addActionListener(this);
429     pop.add(item);
430     item = new JMenuItem(SHOWALL);
431     item.addActionListener(this);
432     pop.add(item);
433     item = new JMenuItem(OUTPUT_TEXT);
434     item.addActionListener(this);
435     pop.add(item);
436     // annotation object should be typed
437     if (aa[selectedRow] == ap.av.consensus)
438     {
439       pop.addSeparator();
440       final JCheckBoxMenuItem cbmi = new JCheckBoxMenuItem(
441           "Ignore Gaps In Consensus",
442           ap.av.getIgnoreGapsConsensus());
443       cbmi.addActionListener(new ActionListener()
444       {
445         public void actionPerformed(ActionEvent e)
446         {
447           ap.av.setIgnoreGapsConsensus(cbmi.getState(), ap);
448         }
449       });
450       pop.add(cbmi);
451       final JMenuItem consclipbrd = new JMenuItem(COPYCONS_SEQ);
452       consclipbrd.addActionListener(this);
453       pop.add(consclipbrd);
454     }
455
456     pop.show(this, evt.getX(), evt.getY());
457   }
458
459   /**
460    * do a single sequence copy to jalview and the system clipboard
461    *
462    * @param sq sequence to be copied to clipboard
463    */
464   protected void copy_annotseqtoclipboard(SequenceI sq)
465   {
466     SequenceI[] seqs = new SequenceI[]
467         {
468         sq};
469     String[] omitHidden = null;
470     SequenceI[] dseqs = new SequenceI[]
471         {
472         sq.getDatasetSequence()};
473     if (dseqs[0] == null)
474     {
475       dseqs[0] = new Sequence(sq);
476       dseqs[0].setSequence(
477           jalview.analysis.AlignSeq.extractGaps(
478               jalview.util.Comparison.GapChars,
479               sq.getSequenceAsString()));
480
481       sq.setDatasetSequence(dseqs[0]);
482     }
483     Alignment ds = new Alignment(dseqs);
484     if (av.hasHiddenColumns)
485     {
486       omitHidden = av.getColumnSelection().getVisibleSequenceStrings(0,
487           sq.getLength(), seqs);
488     }
489
490     String output = new FormatAdapter().formatSequences(
491         "Fasta",
492         seqs,
493         omitHidden);
494
495     Toolkit.getDefaultToolkit().getSystemClipboard()
496         .setContents(new StringSelection(output), Desktop.instance);
497
498     Vector hiddenColumns = null;
499     if (av.hasHiddenColumns)
500     {
501       hiddenColumns = new Vector();
502       for (int i = 0; i < av.getColumnSelection().getHiddenColumns().size(); i++)
503       {
504         int[] region = (int[])
505             av.getColumnSelection().getHiddenColumns().elementAt(i);
506
507         hiddenColumns.addElement(new int[]
508                                  {region[0],
509                                  region[1]});
510       }
511     }
512
513     Desktop.jalviewClipboard = new Object[]
514         {
515         seqs,
516         ds, // what is the dataset of a consensus sequence ? need to flag sequence as special.
517         hiddenColumns};
518   }
519
520   /**
521    * DOCUMENT ME!
522    *
523    * @param g1 DOCUMENT ME!
524    */
525   public void paintComponent(Graphics g)
526   {
527
528     int width = getWidth();
529     if (width == 0)
530     {
531       width = ap.calculateIdWidth().width + 4;
532     }
533
534     Graphics2D g2 = (Graphics2D) g;
535     if (av.antiAlias)
536     {
537       g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
538                           RenderingHints.VALUE_ANTIALIAS_ON);
539     }
540
541     drawComponent(g2, width);
542
543   }
544
545   /**
546    * DOCUMENT ME!
547    *
548    * @param g DOCUMENT ME!
549    */
550   public void drawComponent(Graphics g, int width)
551   {
552     if (av.getFont().getSize() < 10)
553     {
554       g.setFont(font);
555     }
556     else
557     {
558       g.setFont(av.getFont());
559     }
560
561     FontMetrics fm = g.getFontMetrics(g.getFont());
562     g.setColor(Color.white);
563     g.fillRect(0, 0, getWidth(), getHeight());
564
565     g.translate(0, scrollOffset);
566     g.setColor(Color.black);
567
568     AlignmentAnnotation[] aa = av.alignment.getAlignmentAnnotation();
569     int fontHeight = g.getFont().getSize();
570     int y = 0;
571     int x = 0;
572     int graphExtras = 0;
573     int offset =0;
574
575     if (aa != null)
576     {
577       for (int i = 0; i < aa.length; i++)
578       {
579         g.setColor(Color.black);
580
581         if (!aa[i].visible)
582         {
583           continue;
584         }
585
586
587         y += aa[i].height;
588
589         offset = -aa[i].height/2;
590
591         if(aa[i].hasText)
592         {
593           offset += fm.getHeight()/2;
594           offset -= fm.getDescent();
595         }
596         else
597           offset += fm.getDescent();
598
599         x = width - fm.stringWidth(aa[i].label) - 3;
600
601         if (aa[i].graphGroup > -1)
602         {
603           int groupSize = 0;
604           for (int gg = 0; gg < aa.length; gg++)
605           {
606             if (aa[gg].graphGroup == aa[i].graphGroup)
607             {
608               groupSize++;
609             }
610           }
611
612           if (groupSize * (fontHeight + 8) < aa[i].height)
613           {
614             graphExtras = (aa[i].height - (groupSize * (fontHeight + 8))) / 2;
615           }
616
617           for (int gg = 0; gg < aa.length; gg++)
618           {
619             if (aa[gg].graphGroup == aa[i].graphGroup)
620             {
621               x = width - fm.stringWidth(aa[gg].label) - 3;
622               g.drawString(aa[gg].label, x,y - graphExtras);
623               if (aa[gg].annotations[0] != null)
624               {
625                 g.setColor(aa[gg].annotations[0].colour);
626               }
627
628               g.drawLine(x, y - graphExtras - 3,
629                          x + fm.stringWidth(aa[gg].label),
630                          y - graphExtras - 3);
631
632               g.setColor(Color.black);
633               graphExtras += fontHeight + 8;
634             }
635           }
636         }
637         else
638         {
639           g.drawString(aa[i].label, x, y +offset);
640         }
641       }
642     }
643
644     if (resizePanel)
645     {
646       g.drawImage(image, 2, 0 - scrollOffset, this);
647     }
648     else if (dragEvent != null && aa != null)
649     {
650       g.setColor(Color.lightGray);
651       g.drawString(aa[selectedRow].label, dragEvent.getX(),
652                    dragEvent.getY() - scrollOffset);
653     }
654
655     if ( (aa == null) || (aa.length < 1))
656     {
657       g.drawString("Right click", 2, 8);
658       g.drawString("to add annotation", 2, 18);
659     }
660   }
661 }