From: Michael Orlitzky Date: Thu, 12 Oct 2023 18:43:39 +0000 (-0400) Subject: src/svgtiny_css.c: implement sibling_node() select handler X-Git-Url: http://gitweb.michael.orlitzky.com/?a=commitdiff_plain;h=99489346fc8214d7c9473b89361b0c8d17b985db;p=libsvgtiny.git src/svgtiny_css.c: implement sibling_node() select handler --- diff --git a/src/svgtiny_css.c b/src/svgtiny_css.c index 76ee4cc..c7faffd 100644 --- a/src/svgtiny_css.c +++ b/src/svgtiny_css.c @@ -14,6 +14,7 @@ static css_error named_sibling_node(void *pw, void *node, static css_error named_generic_sibling_node(void *pw, void *node, const css_qname *qname, void **sibling); static css_error parent_node(void *pw, void *node, void **parent); +static css_error sibling_node(void *pw, void *node, void **sibling); /** @@ -433,3 +434,73 @@ css_error parent_node(void *pw, void *node, void **parent) return CSS_OK; } + + +/** + * Find the "next-sibling" of the given element + * + * This search corresponds "+ *" in CSS and will find the first + * element node that immediately precedes the given node under the + * same parent in the DOM. In CSS the tree is viewed top-down and in + * libdom it is viewed from the bottom-up; as a result "next" and + * "previous" are sometimes backwards. + * + * \param pw Pointer to the current SVG parser state + * \param node Libdom SVG node + * \param sibling Address at which to store the sibling node pointer + * + * \return Always returns CSS_OK + * + * \post If a suitable element is found, a pointer to it will be + * stored at the address pointed to by \a sibling; otherwise, + * NULL will be stored at the address pointed to by \a sibling + */ +css_error sibling_node(void *pw, void *node, void **sibling) +{ + UNUSED(pw); + dom_node *n = node; /* the current node */ + dom_node *prev; /* the previous node */ + dom_exception err; + dom_node_type type; + + *sibling = NULL; /* default to nothing found */ + + /* Begin the search; the first iteration we do outside of the + * loop. Implementation detil: dom_node_get_previous_sibling() + * increments the reference counter on the returned node. A + * comment within named_parent_node() explains why we + * decrement it ASAP. */ + err = dom_node_get_previous_sibling(n, &n); + if (err != DOM_NO_ERR) { + return CSS_OK; + } + + while (n != NULL) { + err = dom_node_get_node_type(n, &type); + if (err != DOM_NO_ERR) { + dom_node_unref(n); + return CSS_OK; + } + + if (type == DOM_ELEMENT_NODE) { + /* We found a sibling node that is also an + element and that's all we wanted. */ + *sibling = n; + dom_node_unref(n); + return CSS_OK; + } + + /* This sibling node was not an element; move on to + the previous sibling */ + err = dom_node_get_previous_sibling(n, &prev); + if (err != DOM_NO_ERR) { + dom_node_unref(n); + return CSS_OK; + } + + dom_node_unref(n); + n = prev; + } + + return CSS_OK; +}