util-webkit.vala 17.5 KB
Newer Older
1
/* Copyright 2011-2013 Yorba Foundation
2 3
 *
 * This software is licensed under the GNU Lesser General Public License
4
 * (version 2.1 or later).  See the COPYING file in this distribution.
5 6
 */

7 8 9 10 11 12 13
// Regex to detect URLs.
// Originally from here: http://daringfireball.net/2010/07/improved_regex_for_matching_urls
public const string URL_REGEX = "(?i)\\b((?:[a-z][\\w-]+:(?:/{1,3}|[a-z0-9%])|www\\d{0,3}[.]|[a-z0-9.\\-]+[.][a-z]{2,4}/)(?:[^\\s()<>]+|\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\))+(?:\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\)|[^\\s`!()\\[\\]{};:'\".,<>?«»“”‘’]))";

// Regex to determine if a URL has a known protocol.
public const string PROTOCOL_REGEX = "^(aim|apt|bitcoin|cvs|ed2k|ftp|file|finger|git|gtalk|http|https|irc|ircs|irc6|lastfm|ldap|ldaps|magnet|news|nntp|rsync|sftp|skype|smb|sms|svn|telnet|tftp|ssh|webcal|xmpp):";

14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
// TODO Move these other functions and variables into this namespace.
namespace Util.DOM {
    public WebKit.DOM.HTMLElement? select(WebKit.DOM.Node node, string selector) {
        try {
            if (node is WebKit.DOM.Document) {
                return (node as WebKit.DOM.Document).query_selector(selector) as WebKit.DOM.HTMLElement;
            } else {
                return (node as WebKit.DOM.Element).query_selector(selector) as WebKit.DOM.HTMLElement;
            }
        } catch (Error error) {
            debug("Error selecting element %s: %s", selector, error.message);
            return null;
        }
    }

    public WebKit.DOM.HTMLElement? clone_node(WebKit.DOM.Node node, bool deep = true) {
        return node.clone_node(deep) as WebKit.DOM.HTMLElement;
    }

    public WebKit.DOM.HTMLElement? clone_select(WebKit.DOM.Node node, string selector,
        bool deep = true) {
        return clone_node(select(node, selector), deep);
    }

    public void toggle_class(WebKit.DOM.DOMTokenList class_list, string clas, bool add) throws Error {
        if (add) {
            class_list.add(clas);
        } else {
            class_list.remove(clas);
        }
    }
Avi Levy's avatar
Avi Levy committed
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
    
    // Returns the text contained in the DOM document, after ignoring tags of type "exclude"
    // and padding newlines where appropriate. Used to scan for attachment keywords.
    public string get_text_representation(WebKit.DOM.Document doc, string exclude) {
        WebKit.DOM.HTMLElement? copy = Util.DOM.clone_node(doc.get_body());
        if (copy == null) {
            return "";
        }
        
        // Keep deleting the next excluded element until there are none left
        while (true) {
            WebKit.DOM.HTMLElement? current = Util.DOM.select(copy, exclude);
            if (current == null) {
                break;
            }
            
            WebKit.DOM.Node parent = current.get_parent_node();
            try {
                parent.remove_child(current);
            } catch (Error error) {
                debug("Error removing blockquotes: %s", error.message);
                break;
            }
        }
        
        WebKit.DOM.NodeList node_list;
        try {
            node_list = copy.query_selector_all("br");
        } catch (Error error) {
            debug("Error finding <br>s: %s", error.message);
            return copy.get_inner_text();
        }
        
        // Replace <br> tags with newlines
        for (int i = 0; i < node_list.length; ++i) {
            WebKit.DOM.Node br = node_list.item(i);
            WebKit.DOM.Node parent = br.get_parent_node();
            try {
                parent.replace_child(doc.create_text_node("\n"), br);
            } catch (Error error) {
                debug("Error replacing <br>: %s", error.message);
            }
        }
        
        try {
            node_list = copy.query_selector_all("div");
        } catch (Error error) {
            debug("Error finding <div>s: %s", error.message);
            return copy.get_inner_text();
        }
        
        // Pad each <div> with newlines
        for (int i = 0; i < node_list.length; ++i) {
            WebKit.DOM.Node div = node_list.item(i);
            try {
                div.insert_before(doc.create_text_node("\n"), div.first_child);
                div.append_child(doc.create_text_node("\n"));
            } catch (Error error) {
                debug("Error padding <div> with newlines: %s", error.message);
            }
        }
        return copy.get_inner_text();
    }
108 109
}

110 111 112 113 114 115 116 117 118 119 120 121 122 123
public void bind_event(WebKit.WebView view, string selector, string event, Callback callback,
    Object? extra = null) {
    try {
        WebKit.DOM.NodeList node_list = view.get_dom_document().query_selector_all(selector);
        for (int i = 0; i < node_list.length; ++i) {
            WebKit.DOM.EventTarget node = node_list.item(i) as WebKit.DOM.EventTarget;
            node.remove_event_listener(event, callback, false);
            node.add_event_listener(event, callback, false, extra);
        }
    } catch (Error error) {
        warning("Error setting up click handlers: %s", error.message);
    }
}

124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
// Linkifies plain text links in an HTML document.
public void linkify_document(WebKit.DOM.Document document) {
    linkify_recurse(document, document.get_body());
}

// Validates a URL.
// Ensures the URL begins with a valid protocol specifier.  (If not, we don't
// want to linkify it.)
// Note that the output of this will place '\01' chars before and after a link,
// which we use to split the string in linkify()
private bool pre_split_urls(MatchInfo match_info, StringBuilder result) {
    try {
        string? url = match_info.fetch(0);
        Regex r = new Regex(PROTOCOL_REGEX, RegexCompileFlags.CASELESS);
        result.append(r.match(url) ? "\01%s\01".printf(url) : url);
    } catch (Error e) {
        debug("URL parsing error: %s\n", e.message);
    }
    return false; // False to continue processing.
}

// Linkifies "plain text" links in the HTML doc.  If you want to do this
// for the entire document, use the get_dom_document().get_body() for the
// node param and leave _in_link as false.
private void linkify_recurse(WebKit.DOM.Document document, WebKit.DOM.Node node,
    bool _in_link = false) {
    
    bool in_link = _in_link;
    if (node is WebKit.DOM.HTMLAnchorElement)
        in_link = true;
    
    string input = node.get_node_value();
    if (!in_link && !Geary.String.is_empty(input)) {
        try {
            Regex r = new Regex(URL_REGEX, RegexCompileFlags.CASELESS);
            string output = r.replace_eval(input, -1, 0, 0, pre_split_urls);
            if (input != output) {
                // We got one!  Now split the text and swap out the node.
                Regex tester = new Regex(PROTOCOL_REGEX, RegexCompileFlags.CASELESS);
                string[] pieces = output.split("\01");
                Gee.ArrayList<WebKit.DOM.Node> new_nodes = new Gee.ArrayList<WebKit.DOM.Node>();
                
                for(int i = 0; i < pieces.length; i++) {
                    //WebKit.DOM.Node new_node;
                    if (tester.match(pieces[i])) {
                        // Link part.
                        WebKit.DOM.HTMLAnchorElement anchor = document.create_element("a")
                            as WebKit.DOM.HTMLAnchorElement;
                        anchor.href = pieces[i];
                        anchor.set_inner_text(pieces[i]);
                        new_nodes.add(anchor);
                    } else {
                        // Text part.
                        WebKit.DOM.Node new_node = node.clone_node(false);
                        new_node.set_node_value(pieces[i]);
                        new_nodes.add(new_node);
                    }
                }
                
                // Add our new nodes.
                WebKit.DOM.Node? sibling = node.get_next_sibling();
                for (int i = 0; i < new_nodes.size; i++) {
                    WebKit.DOM.Node new_node = new_nodes.get(i);
                    if (sibling == null)
                        node.get_parent_node().append_child(new_node);
                    else
                        node.get_parent_node().insert_before(new_node, sibling);
                }
                
                // Remove the original node's text.
                node.set_node_value("");
            }
        } catch (Error e) {
            debug("Error linkifying outgoing mail: %s", e.message);
        }
    }
    
    // Visit children.
    WebKit.DOM.NodeList list = node.get_child_nodes();
    for (int i = 0; i < list.length; i++) {
        linkify_recurse(document, list.item(i), in_link);
    }
}

208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290
// Validates a URL.  Intended to be used as a RegexEvalCallback.
// Ensures the URL begins with a valid protocol specifier.  (If not, we don't
// want to linkify it.)
public bool is_valid_url(MatchInfo match_info, StringBuilder result) {
    try {
        string? url = match_info.fetch(0);
        Regex r = new Regex(PROTOCOL_REGEX, RegexCompileFlags.CASELESS);
        
        result.append(r.match(url) ? "<a href=\"%s\">%s</a>".printf(url, url) : url);
    } catch (Error e) {
        debug("URL parsing error: %s\n", e.message);
    }
    return false; // False to continue processing.
}

// Converts plain text emails to something safe and usable in HTML.
public string linkify_and_escape_plain_text(string input) throws Error {
    // Convert < and > into non-printable characters, and change & to &amp;.
    string output = input.replace("<", " \01 ").replace(">", " \02 ").replace("&", "&amp;");
    
    // Converts text links into HTML hyperlinks.
    Regex r = new Regex(URL_REGEX, RegexCompileFlags.CASELESS);
    
    output = r.replace_eval(output, -1, 0, 0, is_valid_url);
    return output.replace(" \01 ", "&lt;").replace(" \02 ", "&gt;");
}

public bool node_is_child_of(WebKit.DOM.Node node, string ancestor_tag) {
    WebKit.DOM.Element? ancestor = node.get_parent_element();
    for (; ancestor != null; ancestor = ancestor.get_parent_element()) {
        if (ancestor.get_tag_name() == ancestor_tag) {
            return true;
        }
    }
    return false;
}

public WebKit.DOM.HTMLElement? closest_ancestor(WebKit.DOM.Element element, string selector) {
    try {
        WebKit.DOM.Element? parent = element.get_parent_element();
        while (parent != null && !parent.webkit_matches_selector(selector)) {
            parent = parent.get_parent_element();
        }
        return parent as WebKit.DOM.HTMLElement;
    } catch (Error error) {
        warning("Failed to find ancestor: %s", error.message);
        return null;
    }
}

public string decorate_quotes(string text) throws Error {
    int level = 0;
    string outtext = "";
    Regex quote_leader = new Regex("^(&gt;)* ?");  // Some &gt; followed by optional space
    
    foreach (string line in text.split("\n")) {
        MatchInfo match_info;
        if (quote_leader.match_all(line, 0, out match_info)) {
            int start, end, new_level;
            match_info.fetch_pos(0, out start, out end);
            new_level = end / 4;  // Cast to int removes 0.25 from space at end, if present
            while (new_level > level) {
                outtext += "<blockquote>";
                level += 1;
            }
            while (new_level < level) {
                outtext += "</blockquote>";
                level -= 1;
            }
            outtext += line.substring(end);
        } else {
            debug("This line didn't match the quote regex: %s", line);
            outtext += line;
        }
    }
    // Close any remaining blockquotes.
    while (level > 0) {
        outtext += "</blockquote>";
        level -= 1;
    }
    return outtext;
}

291
// This will modify/reset the DOM
292 293 294
public string html_to_flowed_text(WebKit.DOM.Document doc) {
    WebKit.DOM.NodeList blockquotes;
    try {
295
        blockquotes = doc.query_selector_all("blockquote");
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
    } catch (Error error) {
        debug("Error selecting blockquotes: %s", error.message);
        return "";
    }
    
    int nbq = (int) blockquotes.length;
    WebKit.DOM.Text[] tokens = new WebKit.DOM.Text[nbq];
    string[] bqtexts = new string[nbq];
    
    // Get text of blockquotes and pull them out of DOM.  We need to get the text while they're
    // still in the DOM to get newlines at appropriate places.  We go through the list of blockquotes
    // from the end so that we get the innermost ones first.
    for (int i = nbq - 1; i >= 0; i--) {
        WebKit.DOM.Node bq = blockquotes.item(i);
        WebKit.DOM.Node parent = bq.get_parent_node();
        bqtexts[i] = ((WebKit.DOM.HTMLElement) bq).get_inner_text();
        tokens[i] = doc.create_text_node(@"‘$i’");
        try {
            parent.replace_child(tokens[i], bq);
        } catch (Error error) {
            debug("Error manipulating DOM: %s", error.message);
        }
    }
    
320
    // Reassemble plain text out of parts, replace non-breaking space with regular space
321
    string doctext = resolve_nesting(doc.get_body().get_inner_text(), bqtexts).replace("\xc2\xa0", " ");
322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376
    
    // Reassemble DOM
    for (int i = 0; i < nbq; i++) {
        WebKit.DOM.Node parent = tokens[i].get_parent_node();
        try {
            parent.replace_child(blockquotes.item(i), tokens[i]);
        } catch (Error error) {
            debug("Error manipulating DOM: %s", error.message);
        }
    }
    
    // Wrap, space stuff, quote
    string[] lines = doctext.split("\n");
    GLib.StringBuilder flowed = new GLib.StringBuilder.sized(doctext.length);
    foreach (string line in lines) {
        int quote_level = 0;
        while (line[quote_level] == Geary.RFC822.Utils.QUOTE_MARKER)
            quote_level += 1;
        line = line[quote_level:line.length];
        string prefix = quote_level > 0 ? string.nfill(quote_level, '>') + " " : "";
        int max_len = 72 - prefix.length;
        
        do {
            if (quote_level == 0 && (line.has_prefix(">") || line.has_prefix("From")))
                line = " " + line;
            
            int cut_ind = line.length;
            if (cut_ind > max_len) {
                string beg = line[0:max_len];
                cut_ind = beg.last_index_of(" ") + 1;
                if (cut_ind == 0) {
                    cut_ind = line.index_of(" ") + 1;
                    if (cut_ind == 0)
                        cut_ind = line.length;
                    if (cut_ind > 998 - prefix.length)
                        cut_ind = 998 - prefix.length;
                }
            }
            flowed.append(prefix + line[0:cut_ind] + "\n");
            line = line[cut_ind:line.length];
        } while (line.length > 0);
    }
    
    return flowed.str;
}

public string quote_lines(string text) {
    string[] lines = text.split("\n");
    for (int i=0; i<lines.length; i++)
        lines[i] = @"$(Geary.RFC822.Utils.QUOTE_MARKER)" + lines[i];
    return string.joinv("\n", lines);
}

public string resolve_nesting(string text, string[] values) {
    try {
377
        GLib.Regex tokenregex = new GLib.Regex("(.?)‘([0-9]*)’(.?)");
378
        return tokenregex.replace_eval(text, -1, 0, 0, (info, res) => {
379 380 381 382 383
            int key = int.parse(info.fetch(2));
            string prev_char = info.fetch(1), next_char = info.fetch(3);
            // Make sure there's a newline before and after the quote.
            if (prev_char != "" && prev_char != "\n")
                prev_char = prev_char + "\n";
384 385 386
            if (next_char != "" && next_char != "\n")
                next_char = "\n" + next_char;
            if (key >= 0 && key < values.length) {
387
                res.append(prev_char + quote_lines(resolve_nesting(values[key], values)) + next_char);
388 389 390 391 392 393 394 395 396 397 398 399
            } else {
                debug("Regex error in denesting blockquotes: Invalid key");
                res.append("");
            }
            return false;
        });
    } catch (Error error) {
        debug("Regex error in denesting blockquotes: %s", error.message);
        return "";
    }
}

400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440
// Returns a URI suitable for an IMG SRC attribute (or elsewhere, potentially) that is the
// memory buffer unpacked into a Base-64 encoded data: URI
public string assemble_data_uri(string mimetype, Geary.Memory.Buffer buffer) {
    // attempt to use UnownedBytesBuffer to avoid memcpying a potentially huge buffer only to
    // free it when the encoding operation is completed
    string base64;
    Geary.Memory.UnownedBytesBuffer? unowned_bytes = buffer as Geary.Memory.UnownedBytesBuffer;
    if (unowned_bytes != null)
        base64 = Base64.encode(unowned_bytes.to_unowned_uint8_array());
    else
        base64 = Base64.encode(buffer.get_uint8_array());
    
    return "data:%s;base64,%s".printf(mimetype, base64);
}

// Turns the data: URI created by assemble_data_uri() back into its components.  The returned
// buffer is decoded.
//
// TODO: Return mimetype
public bool dissasemble_data_uri(string uri, out Geary.Memory.Buffer? buffer) {
    buffer = null;
    
    if (!uri.has_prefix("data:"))
        return false;
    
    // count from semicolon past encoding type specifier
    int start_index = uri.index_of(";");
    if (start_index <= 0)
        return false;
    
    // watch for string termination to avoid overflow
    int base64_len = "base64,".length;
    for (int ctr = 0; ctr < base64_len; ctr++) {
        if (uri[start_index++] == Geary.String.EOS)
            return false;
    }
    
    // avoid a memory copy of the substring by manually calculating the start address
    uint8[] bytes = Base64.decode((string) (((char *) uri) + start_index));
    
    // transfer ownership of the byte array directly to the Buffer; this prevents an
441 442 443
    // unnecessary copy ... save length before transferring ownership (which frees the array)
    int bytes_length = bytes.length;
    buffer = new Geary.Memory.ByteBuffer.take((owned) bytes, bytes_length);
444 445 446 447
    
    return true;
}