Skip to content

Latest commit

 

History

History
334 lines (263 loc) · 18.9 KB

using.md

File metadata and controls

334 lines (263 loc) · 18.9 KB

How to use litehtml

To use litehtml, you need some easy steps:

  1. Implement litehtml::document_container class.
  2. Call some functions from litehtml::document to parse, render and draw HTML text.

Implementing litehtml::document_container

The first step to integrate litehtml into your application is implementing abstract class litehtml::document_container. This class draws the HTML elements and performs some actions depended on the platform.

Loading HTML page

To load HTML page you have to call litehtml::document::createFromString function. This function creates the litehtml::document object from the HTML string. The HTML string must be in UTF-8 encoding. The function has the following signature:

static document::ptr  document::createFromString(
	const estring&       str,
	document_container*  container,
	const string&        master_styles = litehtml::master_css,
	const string&        user_styles = "");

Please refer to the document::createFromString document for more details.

Building the element tree yourself

If your application already has its own HTML tree (for example one built by another parser, or a UI tree that is not HTML at all), you can build the litehtml element tree directly instead of serializing it back to an HTML string for createFromString to parse again:

auto doc = std::make_shared<litehtml::document>(container);
// must be done before any element is created
doc->set_document_mode(litehtml::no_quirks_mode);

auto html = doc->create_element("html", {});
auto body = doc->create_element("body", {});
html->appendChild(body);

auto div = doc->create_element("div", {{"class", "hello"}});
body->appendChild(div);
container->split_text("Hello world",
    [&](const char* word)  { div->appendChild(std::make_shared<litehtml::el_text>(word, doc)); },
    [&](const char* space) { div->appendChild(std::make_shared<litehtml::el_space>(space, doc)); });

doc->finalize_from_external_root(html);

finalize_from_external_root takes the same master_styles and user_styles arguments as createFromString and performs the same finalization: it applies the stylesheets, computes the styles and builds the render tree. After that the document is used exactly like a parsed one (render, draw, and so on).

A document is finalized once, when its tree is complete - just like a parsed document is built once. Finalization accumulates state (parsed stylesheets, media lists, tabular elements, the render tree and the used selectors of every element), so a second call would duplicate it and is ignored. Build a new document if you need to rebuild.

createFromString returns the litehtml::document pointer. Call litehtml::document::render(max_width) to render HTML elements:

m_doc->render(max_width);

The parameter max_width usually the browser window width. Also render returns the optimal width for HTML text. You can use the returned value to render elements into the optimal width. This can be useful for tooltips.

Use height and width litehtml::document functions to find the width and height of the rendered document:

m_doc->height()
m_doc->width()

Now call draw function:

m_doc->draw(hdc, m_left, m_top, &clip);

draw accepts 4 parameters:

  • uint_ptr hdc - usually device context or something where to draw. For example HDC in windows. This parameter will be passed into all draw functions of litehtml::document_container.
  • int x, int y - position where to draw HTML.
  • const position* clip* - clipping area. litehtml does not draw the elements that don't intersect the clipping rectangle. But note, you have to set your own clipping if you want to clip HTML content.

That's all! Your HTML page is painted!

Fit to the document

If you don't have the fixed size window to draw HTML, you need to get the HTML best width. It is straightforward: document::render returns the best width for you.

So the example looks like this:

pixel_t best_width = m_doc->render(max_width);
if(best_width < max_width)
{
	m_doc->render(best_width);
}

First, you render document with the maximum possible width and document::render returns the best width for HTML. If the best width is less then maximum width, you have to render your document with the returned best width. Now you can use document::width to get the actual document width.

You can use this technique to show HTML tooltips in your application or to create the HTML widgets.

Scrolling and Clipping

Scrolling of html document is released via x,y parameters of the document::draw function. For example, if you want to scroll document on 50px horizontally and 100px vertically:

m_doc->draw(hdc, -50, -100, litehtml::position(50, 100, window_width, window_height));

Note, the x and y parameters are screen relative. The clip parameter is always document relative. Also note, defining the clip parameter in draw does not guarantee the valid clipping. Some elements can be drawn out off the clipping area. litehtml just checks if the element's bounding rectangle is intersected with clipping rectangle to draw elements. So you must implement your own clipping.

Scrolling of the internal elements

The content of a block can be scrolled when element has CSS property overflow: auto or overflow: scroll. To make this possible call document::on_scroll function:

std::vector<scroll_values> on_scroll(pixel_t dx, pixel_t dy, pixel_t x, pixel_t y, pixel_t client_x, pixel_t client_y) const;

Arguments:

  • dx, dy - number of pixels to scroll horizontally and/or vertically
  • x, y - cursor position in the document coordinates
  • client_x, client_y - cursor position in the window/view port coordinates (for fixed elements)

If something has been scrolled the function returns non-empty array of scroll_values. The structure scroll_values defined as:

struct scroll_values
{
    pixel_t	dx;
    pixel_t dy;
    position scroll_box;
};

Members:

  • dx, dy - number of pixels scrolled horizontally and/or vertically. Note, these values can differ from arguments with the same names.
  • scroll_box - position of the box that has been scrolled.

Handling the mouse

If you want to handle the mouse you have call some functions from litehtml::document:

bool litehtml::document::on_mouse_over( pixel_t x,
                                        pixel_t y,
                                        pixel_t client_x,
                                        pixel_t client_y,
                                        const std::function<void(const litehtml::position&)>& redraw_box );
bool litehtml::document::on_mouse_leave( pixel_t x, 
                                         pixel_t y,
                                         pixel_t client_x,
                                         pixel_t client_y,
                                         const std::function<void(const litehtml::position&)>& redraw_box );
bool litehtml::document::on_lbutton_down( pixel_t x, 
                                         pixel_t y,
                                         pixel_t client_x,
                                         pixel_t client_y,
                                         const std::function<void(const litehtml::position&)>& redraw_box );
bool litehtml::document::on_lbutton_up( pixel_t x, 
                                        pixel_t y,
                                        pixel_t client_x,
                                        pixel_t client_y,
                                        const std::function<void(const litehtml::position&)>& redraw_box );
bool litehtml::document::on_mouse_leave( pixel_t x, 
                                         pixel_t y,
                                         pixel_t client_x,
                                         pixel_t client_y,
                                         const std::function<void(const litehtml::position&)>& redraw_box );

All these functions accept the redraw_box function to be called when you need to redraw some part of the document. The parameter of the redraw_box is the rectangle that you need to redraw. Functions call redraw_box multiple times if you need to redraw several rectangles. Please note, you should queue the redraw of the rectangles and call the actual redraw after functions are called.

A style change that affects layout is applied before the functions return. The document is laid out again, and the changed element is reported both with the boxes it had before the change and with the boxes it has afterwards. So it is normal to receive overlapping rectangles for the same element; they do not need to be merged, just repainted.

All functions returns the bool to indicate that you have to redraw something. Also note the x and y are relative to the HTML layout. So 0,0 is the top-left corner. The parameters client_x and client_y are the mouse position in the client area (draw area). These parameters are used to handle the elements with fixed position.

Keyboard navigation and focus

litehtml keeps the focus state of the document and can move it in the sequential focus navigation order (Tab and Shift+Tab):

std::optional<litehtml::position> litehtml::document::focus_next(
    const std::function<void(const litehtml::position&)>& redraw_box);
std::optional<litehtml::position> litehtml::document::focus_prev(
    const std::function<void(const litehtml::position&)>& redraw_box);

Both functions focus the next/previous focusable element and return its document relative position. The position can be used to scroll the focused element into view. The value is empty when the document has no focusable elements. Like the mouse functions, they accept the redraw_box callback, which is called for the areas that need to be repainted when the focus state changes the element styles.

The sequential focus navigation order is:

  • elements with a positive tabindex, in ascending order,
  • elements with tabindex="0" or without a tabindex (links with href), in document order.

Elements with a negative tabindex can be focused by a mouse click or programmatically, but are skipped by focus_next/focus_prev. Elements with display: none or visibility: hidden, and elements inside a subtree with the inert attribute are skipped as well. The focus wraps around: Tab on the last element focuses the first one and Shift+Tab on the first element focuses the last one.

By default only <a href> elements can be focused. Any element can be made focusable with the tabindex attribute. Applications that create custom element types can override litehtml::element::can_be_focused() (the default implementation returns false).

The focus can also be changed programmatically:

bool litehtml::document::set_focus(const std::shared_ptr<litehtml::element>& el,
                                   bool focus_visible,
                                   const std::function<void(const litehtml::position&)>& redraw_box);
std::shared_ptr<litehtml::element> litehtml::document::get_focused_element() const;

set_focus focuses the element (nullptr removes the focus) and returns whether the focus changed. The redraw_box callback is called for the areas that need to be repainted. focus_visible controls the :focus-visible pseudo class and should be true when the focus was moved with the keyboard.

The document maintains the focus pseudo classes:

  • :focus matches the focused element.
  • :focus-visible matches the focused element when the focus was set by the keyboard, or when set_focus was called with focus_visible = true. A mouse focus does not match it.
  • :focus-within matches the focused element and all of its ancestors.

document::on_lbutton_down focuses the nearest focusable ancestor of the clicked element, without :focus-visible, and a click outside any focusable element removes the focus. The inert attribute makes an element and its descendants non-focusable and non-clickable.

Forms and controls

litehtml creates form elements for <form>, <input> (button, checkbox, hidden, image, number, password, radio, reset, search, submit, text), <textarea>, <select>, <option>, <optgroup>, <label>, <fieldset>, <legend> and <button>. Default styles are part of the built-in master stylesheet.

A <button> with child elements (<img>, <span>, <strong>, <br>, …) is laid out as an inline-block container, so its phrasing content keeps its own formatting; a text-only button is rendered as a replaced control with the label centered by the container.

Controls are focused with the same navigation as links. The container receives the control through document_container::on_focus_change with its type and current data.

When the user edits a control, the container applies the new state with:

bool litehtml::document::update_focused(const litehtml::control_data& data,
                                        const std::function<void(const litehtml::position&)>& redraw_box);

The payload is bool for checkbox/radio, text_control_data for text-like controls and select_control_data for select. The document updates the focused element, applies :checked or other state pseudo classes and calls redraw_box for the control. Value changes are also reported through document_container::on_change.

Text controls ask the container for the text state while drawing through document_container::get_text_data. The control draws the text, selection and caret itself using the container drawing functions.

Text-like <input> controls (text, search, password; not number) and <textarea> render their placeholder attribute while the value is empty. Placeholder text is paint-only: it creates no box and does not affect layout. It is styled through ::placeholder, which the built-in stylesheet gives color: darkgray; author rules such as input::placeholder { color: #757575 } (including :focus::placeholder) override it. The control matches :placeholder-shown while the attribute is present and the value is empty.

The select dropdown marker and the checkbox tick are drawn by the container through document_container::draw_combobox_marker and document_container::draw_checkbox_marker, so they do not depend on the control font containing those glyphs.

A single-line select is a dropdown: a click calls document_container::show_select_popup. The container shows the option list and applies the result with document::update_focused.

A select with multiple or size > 1 is a listbox. litehtml draws its option rows inline (including <optgroup> labels, disabled options and the selected rows), selects a row directly on click (in a multiple listbox a click toggles that row), and scrolls the rows with the mouse wheel when they do not fit. Listboxes never call show_select_popup. Listbox keyboard navigation (arrows, Home/End, Page Up/Page Down, Shift/Ctrl modifiers, Space toggling and type-ahead) is implemented by the container; see the gtkmm4 widget and webpage guides.

Submitting a form (submit button, image button or Enter) calls document_container::on_submit with a litehtml::form_data object containing the form attributes and the ordered list of successful fields. Like on_anchor_click, do not destroy the document inside on_submit; start navigation after the document mouse/key event function returns. Programmatic submission is available with:

bool litehtml::document::submit_form(const std::shared_ptr<litehtml::element>& form,
                                     const std::shared_ptr<litehtml::element>& submitter = nullptr);
bool litehtml::document::submit_focused_form(const std::function<void(const litehtml::position&)>& redraw_box);

Processing anchor click

If you process the mouse, the clicking on anchor tag will call the function document_container::on_anchor_click. This function gets the url of the anchor as parameter and pointer to litehtml::element. You can open the new document at this point.

NOTE: Don't delete the document inside document_container::on_anchor_click, this will cause the crash. The document_container::on_anchor_click is generated by document::on_lbutton_up, so it is safe to delete old document and show new one after document::on_lbutton_up is finished.

Processing named anchors

litehtml does not have the special handling of the named anchors. But it is easy to process the named anchors manually. You get the url with the anchor name into document_container::on_anchor_click. Find the hash char (#) and extract the name. In the example below, the variable anchor_name contains the anchor name:

if(anchor_name.empty())
{
    std::string selector = "#" + anchor_name;
    litehtml::element::ptr el = m_html->root()->select_one(selector);
    if (!el)
    {
        selector = "[name=" + anchor_name + "]";
        el = m_html->root()->select_one(selector);
    }
    if (el)
    {
        litehtml::position pos = el->get_placement();
        m_html_host->scroll_to(0, pos.top());
    }
}

The function element::select_one returns the first element for the CSS selector. So select_one("#name") returns the element with attribute id="name". el->get_placement() returns the absolute position of the element (document relative coordinates).

So, you have the position of the named anchor and now you can scroll your document into this position.

Images

litehtml does not cache the images. So if you want to increase the performance, you have to create your own images cache. Also, you can implement the delayed images loading. Start image downloading in document_container::load_image function. If the image is not loaded return fake sizes and draw placeholder. When the image is loaded call litehtml::document::render, and redraw the page.

Support for CSS media features

litehtml supports CSS @media at-rule as well are media attribute in the <link> and <style> html tags. To make CSS media support you need:

  1. Implement document_container::get_media_features function and fill the media parameter with valid media features (like width, height etc.).
  2. Call document::media_changed function when any media feature is changed (for example user is changed the window size).