JAL-564 (annotation panel height adjustment) and alignment annotation popup menu...
[jalview.git] / src / jalview / appletgui / AnnotationLabels.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.6)
3  * Copyright (C) 2010 J Procter, AM Waterhouse, G Barton, M Clamp, S Searle
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 of the License, or (at your option) any later version.
10  * 
11  * Jalview is distributed in the hope that it will be useful, but 
12  * WITHOUT ANY WARRANTY; without even the implied warranty 
13  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
14  * PURPOSE.  See the GNU General Public License for more details.
15  * 
16  * You should have received a copy of the GNU General Public License along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
17  */
18 package jalview.appletgui;
19
20 import java.util.*;
21
22 import java.awt.*;
23 import java.awt.event.*;
24 import java.awt.image.BufferedImage;
25
26
27 import jalview.datamodel.*;
28
29 public class AnnotationLabels extends Panel implements ActionListener,
30         MouseListener, MouseMotionListener
31 {
32   Image image;
33
34   boolean active = false;
35
36   AlignmentPanel ap;
37
38   AlignViewport av;
39
40   boolean resizing = false;
41
42   int oldY, mouseX;
43
44   static String ADDNEW = "Add New Row";
45
46   static String EDITNAME = "Edit Label/Description";
47
48   static String HIDE = "Hide This Row";
49
50   static String SHOWALL = "Show All Hidden Rows";
51
52   static String OUTPUT_TEXT = "Show Values In Textbox";
53
54   static String COPYCONS_SEQ = "Copy Consensus Sequence";
55
56   int scrollOffset = 0;
57
58   int selectedRow = -1;
59
60   Tooltip tooltip;
61
62   private boolean hasHiddenRows;
63
64   public AnnotationLabels(AlignmentPanel ap)
65   {
66     this.ap = ap;
67     this.av = ap.av;
68     setLayout(null);
69
70     /**
71      * this retrieves the adjustable height glyph from resources. we don't use
72      * it at the moment. java.net.URL url =
73      * getClass().getResource("/images/idwidth.gif"); Image temp = null;
74      * 
75      * if (url != null) { temp =
76      * java.awt.Toolkit.getDefaultToolkit().createImage(url); }
77      * 
78      * try { MediaTracker mt = new MediaTracker(this); mt.addImage(temp, 0);
79      * mt.waitForID(0); } catch (Exception ex) { }
80      * 
81      * BufferedImage bi = new BufferedImage(temp.getHeight(this),
82      * temp.getWidth(this), BufferedImage.TYPE_INT_RGB); Graphics2D g =
83      * (Graphics2D) bi.getGraphics(); g.rotate(Math.toRadians(90));
84      * g.drawImage(temp, 0, -bi.getWidth(this), this); image = (Image) bi;
85      */
86     addMouseListener(this);
87     addMouseMotionListener(this);
88   }
89
90   public AnnotationLabels(AlignViewport av)
91   {
92     this.av = av;
93   }
94
95   public void setScrollOffset(int y)
96   {
97     scrollOffset = y;
98     repaint();
99   }
100
101   /**
102    * 
103    * @param y
104    * @return -2 if no rows are visible at all, -1 if no visible rows were
105    *         selected
106    */
107   int getSelectedRow(int y)
108   {
109     int row = -2;
110     AlignmentAnnotation[] aa = ap.av.alignment.getAlignmentAnnotation();
111
112     if (aa == null)
113     {
114       return row;
115     }
116     int height = 0;
117     for (int i = 0; i < aa.length; i++)
118     {
119       row = -1;
120       if (!aa[i].visible)
121       {
122         continue;
123       }
124       height += aa[i].height;
125       if (y < height)
126       {
127         row = i;
128         break;
129       }
130     }
131
132     return row;
133   }
134
135   public void actionPerformed(ActionEvent evt)
136   {
137     AlignmentAnnotation[] aa = av.alignment.getAlignmentAnnotation();
138
139     if (evt.getActionCommand().equals(ADDNEW))
140     {
141       AlignmentAnnotation newAnnotation = new AlignmentAnnotation("", null,
142               new Annotation[ap.av.alignment.getWidth()]);
143
144       if (!editLabelDescription(newAnnotation))
145       {
146         return;
147       }
148
149       ap.av.alignment.addAnnotation(newAnnotation);
150       ap.av.alignment.setAnnotationIndex(newAnnotation, 0);
151     }
152     else if (evt.getActionCommand().equals(EDITNAME))
153     {
154       editLabelDescription(aa[selectedRow]);
155     }
156     else if (evt.getActionCommand().equals(HIDE))
157     {
158       aa[selectedRow].visible = false;
159     }
160     else if (evt.getActionCommand().equals(SHOWALL))
161     {
162       for (int i = 0; i < aa.length; i++)
163       {
164         aa[i].visible = (aa[i].annotations == null) ? false : true;
165       }
166     }
167     else if (evt.getActionCommand().equals(OUTPUT_TEXT))
168     {
169       CutAndPasteTransfer cap = new CutAndPasteTransfer(false,
170               ap.alignFrame);
171       Frame frame = new Frame();
172       frame.add(cap);
173       jalview.bin.JalviewLite.addFrame(frame, ap.alignFrame.getTitle()
174               + " - " + aa[selectedRow].label, 500, 100);
175       cap.setText(aa[selectedRow].toString());
176     }
177     else if (evt.getActionCommand().equals(COPYCONS_SEQ))
178     {
179       SequenceI cons = av.getConsensusSeq();
180       if (cons != null)
181       {
182         copy_annotseqtoclipboard(cons);
183       }
184
185     }
186     ap.annotationPanel.adjustPanelHeight();
187     setSize(getSize().width, ap.annotationPanel.getSize().height);
188     ap.validate();
189     ap.paintAlignment(true);
190   }
191
192   boolean editLabelDescription(AlignmentAnnotation annotation)
193   {
194     Checkbox padGaps = new Checkbox("Fill Empty Gaps With \""
195             + ap.av.getGapCharacter() + "\"", annotation.padGaps);
196
197     EditNameDialog dialog = new EditNameDialog(annotation.label,
198             annotation.description, "      Annotation Label",
199             "Annotation Description", ap.alignFrame,
200             "Edit Annotation Name / Description", 500, 180, false);
201
202     Panel empty = new Panel(new FlowLayout());
203     empty.add(padGaps);
204     dialog.add(empty);
205     dialog.pack();
206
207     dialog.setVisible(true);
208
209     if (dialog.accept)
210     {
211       annotation.label = dialog.getName();
212       annotation.description = dialog.getDescription();
213       annotation.setPadGaps(padGaps.getState(), av.getGapCharacter());
214       repaint();
215       return true;
216     }
217     else
218       return false;
219
220   }
221
222   boolean resizePanel = false;
223
224   public void mouseMoved(MouseEvent evt)
225   {
226     resizePanel = evt.getY() < 10 && evt.getX() < 14;
227
228     int row = getSelectedRow(evt.getY() + scrollOffset);
229
230     if (row > -1)
231     {
232       if (tooltip == null)
233       {
234         tooltip = new Tooltip(
235                 ap.av.alignment.getAlignmentAnnotation()[row]
236                         .getDescription(true),
237                 this);
238       }
239       else
240       {
241         tooltip.setTip(ap.av.alignment.getAlignmentAnnotation()[row]
242                 .getDescription(true));
243       }
244     }
245     else if (tooltip != null)
246     {
247       tooltip.setTip("");
248     }
249
250   }
251
252   MouseEvent dragEvent = null;
253
254   public void mouseDragged(MouseEvent evt)
255   {
256     dragEvent = evt;
257
258     if (resizePanel)
259     {
260       Dimension d = ap.annotationPanelHolder.getSize(), e = ap.annotationSpaceFillerHolder
261               .getSize(), f = ap.seqPanelHolder.getSize();
262       int dif = evt.getY() - oldY;
263
264       dif /= ap.av.charHeight;
265       dif *= ap.av.charHeight;
266
267       if ((d.height - dif) > 20 && (f.height + dif) > 20)
268       {
269         ap.annotationPanel.setSize(d.width, d.height - dif);
270         setSize(new Dimension(e.width, d.height - dif));
271         ap.annotationSpaceFillerHolder.setSize(new Dimension(e.width,
272                 d.height - dif));
273         ap.annotationPanelHolder.setSize(new Dimension(d.width, d.height
274                 - dif));
275         ap.apvscroll.setValues(ap.apvscroll.getValue(), d.height - dif, 0,
276                 ap.annotationPanel.calcPanelHeight());
277         f.height += dif;
278         ap.seqPanelHolder.setPreferredSize(f);
279         ap.setScrollValues(av.getStartRes(), av.getStartSeq());
280         ap.validate();
281         // ap.paintAlignment(true);
282         ap.addNotify();
283       }
284
285     }
286     else
287     {
288       repaint();
289     }
290   }
291
292   public void mouseClicked(MouseEvent evt)
293   {
294   }
295
296   public void mouseReleased(MouseEvent evt)
297   {
298     resizePanel = false;
299     dragEvent = null;
300     repaint();
301     ap.annotationPanel.repaint();
302   }
303
304   public void mouseEntered(MouseEvent evt)
305   {
306     if (evt.getY() < 10 && evt.getX() < 14)
307     {
308       resizePanel = true;
309       repaint();
310     }
311   }
312
313   public void mouseExited(MouseEvent evt)
314   {
315
316     if (dragEvent == null)
317     {
318       resizePanel = false;
319     }
320     else
321     {
322       if (!resizePanel)
323       {
324         dragEvent = null;
325       }
326     }
327     repaint();
328   }
329
330   public void mousePressed(MouseEvent evt)
331   {
332     oldY = evt.getY();
333     if (resizePanel)
334     {
335       return;
336     }
337     // todo: move below to mouseClicked ?
338     selectedRow = getSelectedRow(evt.getY() + scrollOffset);
339
340     AlignmentAnnotation[] aa = ap.av.alignment.getAlignmentAnnotation();
341
342     // DETECT RIGHT MOUSE BUTTON IN AWT
343     if ((evt.getModifiers() & InputEvent.BUTTON3_MASK) == InputEvent.BUTTON3_MASK)
344     {
345
346       PopupMenu popup = new PopupMenu("Annotations");
347
348       MenuItem item = new MenuItem(ADDNEW);
349       item.addActionListener(this);
350       popup.add(item);
351       if (selectedRow < 0)
352       {
353         // this never happens at moment: - see comment on JAL-563
354         if (hasHiddenRows)
355         {
356           item = new MenuItem(SHOWALL);
357           item.addActionListener(this);
358           popup.add(item);
359         }
360         this.add(popup);
361         popup.show(this, evt.getX(), evt.getY());
362         return;
363       }
364       // add the rest if there are actually rows to show
365       item = new MenuItem(EDITNAME);
366       item.addActionListener(this);
367       popup.add(item);
368       item = new MenuItem(HIDE);
369       item.addActionListener(this);
370       popup.add(item);
371       if (hasHiddenRows)
372       {
373         item = new MenuItem(SHOWALL);
374         item.addActionListener(this);
375         popup.add(item);
376       }
377       this.add(popup);
378       item = new MenuItem(OUTPUT_TEXT);
379       item.addActionListener(this);
380       popup.add(item);
381       if (selectedRow < aa.length)
382       {
383         if (aa[selectedRow].autoCalculated)
384         {
385           if (aa[selectedRow].label.indexOf("Consensus") > -1)
386           {
387             popup.addSeparator();
388             final CheckboxMenuItem cbmi = new CheckboxMenuItem(
389                     "Ignore Gaps In Consensus",
390                     (aa[selectedRow].groupRef != null) ? aa[selectedRow].groupRef
391                             .getIgnoreGapsConsensus() : ap.av
392                             .getIgnoreGapsConsensus());
393             final AlignmentAnnotation aaa = aa[selectedRow];
394             cbmi.addItemListener(new ItemListener()
395             {
396               public void itemStateChanged(ItemEvent e)
397               {
398                 if (aaa.groupRef != null)
399                 {
400                   // TODO: pass on reference to ap so the view can be updated.
401                   aaa.groupRef.setIgnoreGapsConsensus(cbmi.getState());
402                 }
403                 else
404                 {
405                   ap.av.setIgnoreGapsConsensus(cbmi.getState());
406                 }
407                 ap.paintAlignment(true);
408               }
409             });
410             popup.add(cbmi);
411             if (aaa.groupRef != null)
412             {
413               final CheckboxMenuItem chist = new CheckboxMenuItem(
414                       "Show Group Histogram",
415                       aa[selectedRow].groupRef.isShowConsensusHistogram());
416               chist.addItemListener(new ItemListener()
417               {
418                 public void itemStateChanged(ItemEvent e)
419                 {
420                   // TODO: pass on reference
421                   // to ap
422                   // so the
423                   // view
424                   // can be
425                   // updated.
426                   aaa.groupRef.setShowConsensusHistogram(chist.getState());
427                   ap.repaint();
428                   // ap.annotationPanel.paint(ap.annotationPanel.getGraphics());
429                 }
430               });
431               popup.add(chist);
432               final CheckboxMenuItem cprofl = new CheckboxMenuItem(
433                       "Show Group Logo",
434                       aa[selectedRow].groupRef.isShowSequenceLogo());
435               cprofl.addItemListener(new ItemListener()
436               {
437                 public void itemStateChanged(ItemEvent e)
438                 {
439                   // TODO: pass on reference
440                   // to ap
441                   // so the
442                   // view
443                   // can be
444                   // updated.
445                   aaa.groupRef.setshowSequenceLogo(cprofl.getState());
446                   ap.repaint();
447                   // ap.annotationPanel.paint(ap.annotationPanel.getGraphics());
448                 }
449               });
450               popup.add(cprofl);
451             }
452             else
453             {
454               final CheckboxMenuItem chist = new CheckboxMenuItem(
455                       "Show Histogram", av.isShowConsensusHistogram());
456               chist.addItemListener(new ItemListener()
457               {
458                 public void itemStateChanged(ItemEvent e)
459                 {
460                   // TODO: pass on reference
461                   // to ap
462                   // so the
463                   // view
464                   // can be
465                   // updated.
466                   av.setShowConsensusHistogram(chist.getState());
467                   ap.repaint();
468                   // ap.annotationPanel.paint(ap.annotationPanel.getGraphics());
469                 }
470               });
471               popup.add(chist);
472               final CheckboxMenuItem cprof = new CheckboxMenuItem(
473                       "Show Logo", av.isShowSequenceLogo());
474               cprof.addItemListener(new ItemListener()
475               {
476                 public void itemStateChanged(ItemEvent e)
477                 {
478                   // TODO: pass on reference
479                   // to ap
480                   // so the
481                   // view
482                   // can be
483                   // updated.
484                   av.setShowSequenceLogo(cprof.getState());
485                   ap.repaint();
486                   // ap.annotationPanel.paint(ap.annotationPanel.getGraphics());
487                 }
488               });
489               popup.add(cprof);
490             }
491
492             item = new MenuItem(COPYCONS_SEQ);
493             item.addActionListener(this);
494             popup.add(item);
495           }
496         }
497       }
498       popup.show(this, evt.getX(), evt.getY());
499     }
500     else
501     {
502       // selection action.
503       if (selectedRow > -1 && selectedRow < aa.length)
504       {
505         if (aa[selectedRow].groupRef != null)
506         {
507           if (evt.getClickCount() >= 2)
508           {
509             // todo: make the ap scroll to the selection - not necessary, first
510             // click highlights/scrolls, second selects
511             ap.seqPanel.ap.idPanel.highlightSearchResults(null);
512             ap.av.setSelectionGroup(// new SequenceGroup(
513             aa[selectedRow].groupRef); // );
514             ap.av.sendSelection();
515             ap.paintAlignment(false);
516             PaintRefresher.Refresh(ap, ap.av.getSequenceSetId());
517           }
518           else
519           {
520             ap.seqPanel.ap.idPanel
521                     .highlightSearchResults(aa[selectedRow].groupRef
522                             .getSequences(null));
523           }
524           return;
525         }
526         else if (aa[selectedRow].sequenceRef != null)
527         {
528           Vector sr = new Vector();
529           sr.addElement(aa[selectedRow].sequenceRef);
530           if (evt.getClickCount() == 1)
531           {
532             ap.seqPanel.ap.idPanel.highlightSearchResults(sr);
533           }
534           else if (evt.getClickCount() >= 2)
535           {
536             ap.seqPanel.ap.idPanel.highlightSearchResults(null);
537             SequenceGroup sg = new SequenceGroup();
538             sg.addSequence(aa[selectedRow].sequenceRef, false);
539             ap.av.setSelectionGroup(sg);
540             ap.paintAlignment(false);
541             PaintRefresher.Refresh(ap, ap.av.getSequenceSetId());
542             ap.av.sendSelection();
543           }
544
545         }
546       }
547
548     }
549   }
550
551   /**
552    * DOCUMENT ME!
553    * 
554    * @param e
555    *          DOCUMENT ME!
556    */
557   protected void copy_annotseqtoclipboard(SequenceI sq)
558   {
559     if (sq == null || sq.getLength() < 1)
560     {
561       return;
562     }
563     jalview.appletgui.AlignFrame.copiedSequences = new StringBuffer();
564     jalview.appletgui.AlignFrame.copiedSequences.append(sq.getName() + "\t"
565             + sq.getStart() + "\t" + sq.getEnd() + "\t"
566             + sq.getSequenceAsString() + "\n");
567     if (av.hasHiddenColumns)
568     {
569       jalview.appletgui.AlignFrame.copiedHiddenColumns = new Vector();
570       for (int i = 0; i < av.getColumnSelection().getHiddenColumns().size(); i++)
571       {
572         int[] region = (int[]) av.getColumnSelection().getHiddenColumns()
573                 .elementAt(i);
574
575         jalview.appletgui.AlignFrame.copiedHiddenColumns
576                 .addElement(new int[]
577                 { region[0], region[1] });
578       }
579     }
580   }
581
582   public void update(Graphics g)
583   {
584     paint(g);
585   }
586
587   public void paint(Graphics g)
588   {
589     int w = getSize().width;
590     if (image == null || w != image.getWidth(this))
591     {
592       image = createImage(w, ap.annotationPanel.getSize().height);
593     }
594
595     drawComponent(image.getGraphics(), w);
596     g.drawImage(image, 0, 0, this);
597   }
598
599   public void drawComponent(Graphics g, int width)
600   {
601     g.setFont(av.getFont());
602     FontMetrics fm = g.getFontMetrics(av.getFont());
603     g.setColor(Color.white);
604     g.fillRect(0, 0, getSize().width, getSize().height);
605
606     g.translate(0, -scrollOffset);
607     g.setColor(Color.black);
608
609     AlignmentAnnotation[] aa = av.alignment.getAlignmentAnnotation();
610     int y = 0, fy = g.getFont().getSize();
611     int x = 0, offset;
612
613     if (aa != null)
614     {
615       hasHiddenRows = false;
616       for (int i = 0; i < aa.length; i++)
617       {
618         if (!aa[i].visible)
619         {
620           hasHiddenRows = true;
621           continue;
622         }
623
624         x = width - fm.stringWidth(aa[i].label) - 3;
625
626         y += aa[i].height;
627         offset = -(aa[i].height - fy) / 2;
628
629         g.drawString(aa[i].label, x, y + offset);
630       }
631     }
632     g.translate(0, +scrollOffset);
633     if (resizePanel)
634     {
635       g.setColor(Color.red);
636       g.setPaintMode();
637       g.drawLine(2, 8, 5, 2);
638       g.drawLine(5, 2, 8, 8);
639     }
640     else if (dragEvent != null && aa != null)
641     {
642       g.setColor(Color.lightGray);
643       g.drawString(aa[selectedRow].label, dragEvent.getX(),
644               dragEvent.getY());
645     }
646
647     if ((aa == null) || (aa.length < 1))
648     {
649       g.setColor(Color.black);
650       g.drawString("Right click", 2, 8);
651       g.drawString("to add annotation", 2, 18);
652     }
653   }
654
655 }