Monday, September 7, 2009

Google Wave TextView styling with annotations

TextView textView = robotBlip.getDocument();
textView.append("Text awaiting some wave styling ");
textView.setAnnotation(new Range(2, 100), "style/fontWeight", "bold");
While developing a bot for Google Wave, I found out that styles are set using setAnnotations method which take a range of indices for the characters to be styles. Also this method takes a string for the style function name, and the actual string value. This is a wasteful operation since the server has to send the events "setAnnotation" back to the bot without consideration of whether or not the annotation already exists. This will cause unnecessary network traffic and makes bots more prone to loop errors.
Work around by:

private void maybeAnnotate(TextView doc, Range range, String name,
      String value) {
    // If this annotation is already present, give up now.  Note that
    // we allow the existing annotation to be bigger than the one we're
    // creating, because in that case, setting the new annotation won't
    // do anything useful.
    for (Annotation annotation : doc.getAnnotations(range, name)) {
      if (annotation.getValue().equals(value) &&
          annotation.getRange().getStart() <= range.getStart() &&
          range.getEnd() <= annotation.getRange().getEnd())
    doc.setAnnotation(range, name, value);

Google Wave API: