conversation-web-view.vala 13.4 KB
Newer Older
1
/* Copyright 2012-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
public class ConversationWebView : WebKit.WebView {
8 9 10 11 12
    private const string[] always_loaded_prefixes = {
        "http://www.gravatar.com/avatar/",
        "data:"
    };
    
13 14
    private const string USER_CSS = "user-message.css";
    private const string STYLE_NAME = "STYLE";
15 16
    private const string PREVENT_HIDE_STYLE = "nohide";
    
17 18
    // HTML element that contains message DIVs.
    public WebKit.DOM.HTMLDivElement? container { get; private set; default = null; }
19 20
    
    public string allow_prefix { get; private set; default = ""; }
21 22 23 24 25

    private FileMonitor? user_style_monitor = null;

    public signal void link_selected(string link);

26 27 28
    public ConversationWebView() {
        // Set defaults.
        set_border_width(0);
29
        allow_prefix = random_string(10) + ":";
30 31 32 33 34
        
        WebKit.WebSettings config = new WebKit.WebSettings();
        config.enable_scripts = false;
        config.enable_java_applet = false;
        config.enable_plugins = false;
35
        config.enable_developer_extras = Args.inspector;
36 37 38 39 40 41 42
        settings = config;
        
        // Hook up signals.
        load_finished.connect(on_load_finished);
        resource_request_starting.connect(on_resource_request_starting);
        navigation_policy_decision_requested.connect(on_navigation_policy_decision_requested);
        new_window_policy_decision_requested.connect(on_navigation_policy_decision_requested);
43
        web_inspector.inspect_web_view.connect(activate_inspector);
44 45 46 47 48 49 50
        
        // Load the HTML into WebKit.
        // Note: load_finished signal MUST be hooked up before this call.
        string html_text = GearyApplication.instance.read_theme_file("message-viewer.html") ?? "";
        load_string(html_text, "text/html", "UTF8", "");
    }
    
51 52 53 54 55 56 57 58 59
    private string random_string(int length) {
        // No upper case letters, since request gets lower-cased.
        string chars = "abcdefghijklmnopqrstuvwxyz";
        char[] random = new char[length];
        for (int i = 0; i < length; i++)
            random[i] = chars[Random.int_range(0, chars.length)];
        return (string) random;
    }
    
60 61 62 63
    public override bool query_tooltip(int x, int y, bool keyboard_tooltip, Gtk.Tooltip tooltip) {
        // Disable tooltips from within WebKit itself.
        return false;
    }
64
    
65 66 67 68 69 70 71 72 73 74 75 76
    public override bool scroll_event(Gdk.EventScroll event) {
        if ((event.state & Gdk.ModifierType.CONTROL_MASK) != 0) {
            if (event.direction == Gdk.ScrollDirection.UP) {
                zoom_in();
                return true;
            } else if (event.direction == Gdk.ScrollDirection.DOWN) {
                zoom_out();
                return true;
            }
        }
        return false;
    }
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
    
    public void hide_element_by_id(string element_id) throws Error {
        get_dom_document().get_element_by_id(element_id).set_attribute("style", "display:none");
    }
    
    public void show_element_by_id(string element_id) throws Error {
        get_dom_document().get_element_by_id(element_id).set_attribute("style", "display:block");
    }
    
    // Scrolls back up to the top.
    public void scroll_reset() {
        get_dom_document().get_default_view().scroll(0, 0);
    }
    
    private void on_resource_request_starting(WebKit.WebFrame web_frame,
        WebKit.WebResource web_resource, WebKit.NetworkRequest request,
        WebKit.NetworkResponse? response) {
94 95 96 97 98
        if (response != null) {
            // A request that was previously approved resulted in a redirect.
            return;
        }

99
        string? uri = request.get_uri();
100 101 102 103 104 105 106 107
        if (!is_always_loaded(uri)) {
            if (uri.has_prefix(allow_prefix))
                request.set_uri(uri.substring(allow_prefix.length));
            else
                request.set_uri("about:blank");
        }
    }
    
108
    public bool is_always_loaded(string? uri) {
109 110 111 112 113 114 115 116 117
        if (uri == null)
            return true;
        
        foreach (string prefix in always_loaded_prefixes) {
            if (uri.has_prefix(prefix))
                return true;
        }
        
        return false;
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
    }
    
    private void on_load_finished(WebKit.WebFrame frame) {
        // Load the style.
        try {
            WebKit.DOM.Document document = get_dom_document();
            WebKit.DOM.Element style_element = document.create_element(STYLE_NAME);
            
            string css_text = GearyApplication.instance.read_theme_file("message-viewer.css") ?? "";
            WebKit.DOM.Text text_node = document.create_text_node(css_text);
            style_element.append_child(text_node);
            
            WebKit.DOM.HTMLHeadElement head_element = document.get_head();
            head_element.append_child(style_element);
        } catch (Error error) {
            debug("Unable to load message-viewer document from files: %s", error.message);
        }
        
        load_user_style();
        
        // Grab the HTML container.
        WebKit.DOM.Element? _container = get_dom_document().get_element_by_id("message_container");
        assert(_container != null);
        container = _container as WebKit.DOM.HTMLDivElement;
        assert(container != null);
        
        // Load the icons.
145 146 147 148 149 150
        set_icon_src("#email_template .menu .icon", "go-down-symbolic");
        set_icon_src("#email_template .starred .icon", "star-symbolic");
        set_icon_src("#email_template .unstarred .icon", "unstarred-symbolic");
        set_icon_src("#email_template .attachment.icon", "mail-attachment-symbolic");
        set_icon_src("#email_template .close_show_images", "close-symbolic");
        set_icon_src("#link_warning_template .close_link_warning", "close-symbolic");
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
    }
    
    private void load_user_style() {
        try {
            WebKit.DOM.Document document = get_dom_document();
            WebKit.DOM.Element style_element = document.create_element(STYLE_NAME);
            style_element.set_attribute("id", "user_style");
            WebKit.DOM.HTMLHeadElement head_element = document.get_head();
            head_element.append_child(style_element);
            
            File user_style = GearyApplication.instance.get_user_config_directory().get_child(USER_CSS);
            user_style_monitor = user_style.monitor_file(FileMonitorFlags.NONE, null);
            user_style_monitor.changed.connect(on_user_style_changed);
            
            // And call it once to load the initial user style
            on_user_style_changed(user_style, null, FileMonitorEvent.CREATED);
        } catch (Error error) {
            debug("Error setting up user style: %s", error.message);
        }
    }
    
    private void on_user_style_changed(File user_style, File? other_file, FileMonitorEvent event_type) {
        // Changing a file produces 1 created signal, 3 changes done hints, and 0 changed
        if (event_type != FileMonitorEvent.CHANGED && event_type != FileMonitorEvent.CREATED
            && event_type != FileMonitorEvent.DELETED) {
            return;
        }
        
        debug("Loading new message viewer style from %s...", user_style.get_path());
        
        WebKit.DOM.Document document = get_dom_document();
        WebKit.DOM.Element style_element = document.get_element_by_id("user_style");
        ulong n = style_element.child_nodes.length;
        try {
            for (int i = 0; i < n; i++)
                style_element.remove_child(style_element.first_child);
        } catch (Error error) {
            debug("Error removing old user style: %s", error.message);
        }
        
        try {
            DataInputStream data_input_stream = new DataInputStream(user_style.read());
            size_t length;
            string user_css = data_input_stream.read_upto("\0", 1, out length);
            WebKit.DOM.Text text_node = document.create_text_node(user_css);
            style_element.append_child(text_node);
        } catch (Error error) {
            // Expected if file was deleted.
        }
    }
    
    private void set_icon_src(string selector, string icon_name) {
        try {
204
            // Load icon.
205
            uint8[]? icon_content = null;
206 207 208
            Gdk.Pixbuf? pixbuf = IconFactory.instance.load_symbolic_colored(icon_name, 16);
            if (pixbuf != null)
                pixbuf.save_to_buffer(out icon_content, "png"); // Load as PNG.
209
            
210 211 212
            if (icon_content == null || icon_content.length == 0)
                return;
            
213 214
            // Save length before transferring ownership (which frees the array)
            int icon_length = icon_content.length;
215
            Geary.Memory.ByteBuffer buffer = new Geary.Memory.ByteBuffer.take((owned) icon_content,
216
                icon_length);
217
            
218 219 220
            // Then set the source to a data url.
            WebKit.DOM.HTMLImageElement img = Util.DOM.select(get_dom_document(), selector)
                as WebKit.DOM.HTMLImageElement;
221
            img.set_attribute("src", assemble_data_uri("image/png", buffer));
222 223 224 225 226
        } catch (Error error) {
            warning("Failed to load icon '%s': %s", icon_name, error.message);
        }
    }
    
227 228
    public void set_attachment_src(WebKit.DOM.HTMLImageElement img, Geary.Mime.ContentType content_type,
        string filename, int maxwidth, int maxheight = -1) {
229 230 231 232 233 234 235
        if( maxheight == -1 ){
            maxheight = maxwidth;
        }
        
        try {
            // If the file is an image, use it. Otherwise get the icon for this mime_type.
            uint8[] content;
236 237 238
            string gio_content_type = ContentType.from_mime_type(content_type.get_mime_type());
            string icon_mime_type = content_type.get_mime_type();
            if (content_type.has_media_type("image")) {
239 240 241 242 243 244
                // Get a thumbnail for the image.
                // TODO Generate and save the thumbnail when extracting the attachments rather than
                // when showing them in the viewer.
                img.get_class_list().add("thumbnail");
                Gdk.Pixbuf image = new Gdk.Pixbuf.from_file_at_scale(filename, maxwidth, maxheight,
                    true);
245
                image = image.apply_embedded_orientation();
246 247 248 249
                image.save_to_buffer(out content, "png");
                icon_mime_type = "image/png";
            } else {
                // Load the icon for this mime type.
250
                ThemedIcon icon = ContentType.get_icon(gio_content_type) as ThemedIcon;
251 252 253 254 255 256 257 258
                string icon_filename = IconFactory.instance.lookup_icon(icon.names[0], maxwidth)
                    .get_filename();
                FileUtils.get_data(icon_filename, out content);
                icon_mime_type = ContentType.get_mime_type(ContentType.guess(icon_filename, content,
                    null));
            }
            
            // Then set the source to a data url.
259 260
            // Save length before transferring ownership (which frees the array)
            int content_length = content.length;
261
            Geary.Memory.Buffer buffer = new Geary.Memory.ByteBuffer.take((owned) content,
262
                content_length);
263
            img.set_attribute("src", assemble_data_uri(icon_mime_type, buffer));
264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
        } catch (Error error) {
            warning("Failed to load image '%s': %s", filename, error.message);
        }
    }
    
    private bool on_navigation_policy_decision_requested(WebKit.WebFrame frame,
        WebKit.NetworkRequest request, WebKit.WebNavigationAction navigation_action,
        WebKit.WebPolicyDecision policy_decision) {
        policy_decision.ignore();
        
        // Other policy-decisions may be requested for various reasons. The existence of an iframe,
        // for example, causes a policy-decision request with an "OTHER" reason. We don't want to
        // open a webpage in the browser just because an email contains an iframe.
        if (navigation_action.reason == WebKit.WebNavigationReason.LINK_CLICKED)
            link_selected(request.uri);
        return true;
    }
    
    public WebKit.DOM.HTMLDivElement create_div() throws Error {
        return get_dom_document().create_element("div") as WebKit.DOM.HTMLDivElement;
    }
285 286 287 288

    public void scroll_to_element(WebKit.DOM.HTMLElement element) {
        get_dom_document().get_default_view().scroll(element.offset_left, element.offset_top);
    }
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
    
    private unowned WebKit.WebView activate_inspector(WebKit.WebInspector inspector, WebKit.WebView target_view) {
        Gtk.Window window = new Gtk.Window();
        window.set_default_size(600, 600);
        window.set_title(_("%s - Conversation Inspector").printf(GearyApplication.NAME));
        Gtk.ScrolledWindow scrolled = new Gtk.ScrolledWindow(null, null);
        WebKit.WebView inspector_view = new WebKit.WebView();
        scrolled.add(inspector_view);
        window.add(scrolled);
        window.show_all();
        window.delete_event.connect(() => {
            inspector.close();
            return false;
        });
        
        unowned WebKit.WebView r = inspector_view;
        return r;
    }
307 308 309 310 311 312 313 314 315 316 317
    
    public void allow_collapsing(bool allow) {
        try {
            if (allow)
                get_dom_document().get_body().get_class_list().remove("nohide");
            else
                get_dom_document().get_body().get_class_list().add("nohide");
        } catch (Error error) {
            debug("Error setting body class: %s", error.message);
        }
    }
318
}
319