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