]> spindle.queued.net Git - midori/commitdiff
Initial code for the form history extension
authorAlexander Butenko <a.butenka@gmail.com>
Tue, 6 Oct 2009 18:35:56 +0000 (20:35 +0200)
committerChristian Dywan <christian@twotoasts.de>
Tue, 6 Oct 2009 18:35:56 +0000 (20:35 +0200)
data/autosuggestcontrol.css [new file with mode: 0644]
data/autosuggestcontrol.js [new file with mode: 0644]
extensions/formhistory.c [new file with mode: 0644]

diff --git a/data/autosuggestcontrol.css b/data/autosuggestcontrol.css
new file mode 100644 (file)
index 0000000..a7ca89d
--- /dev/null
@@ -0,0 +1,16 @@
+div.suggestions {
+    -moz-box-sizing: border-box;
+    box-sizing: border-box;
+    border: 1px solid #cccccc;
+    text-align: left;
+    background-color: #ffffff;
+    position: absolute;
+}
+div.suggestions div {
+    cursor: default;
+    padding: 0px 3px;
+}
+div.suggestions div.current {
+    background-color: #3366cc;
+    color: white;
+}
diff --git a/data/autosuggestcontrol.js b/data/autosuggestcontrol.js
new file mode 100644 (file)
index 0000000..0b58336
--- /dev/null
@@ -0,0 +1,366 @@
+/**
+ * An autosuggest textbox control.
+ * from Nicholas C. Zakas (Author) example: http://www.nczonline.net/
+ * @class
+ * @scope public
+ */
+function AutoSuggestControl(oTextbox /*:HTMLInputElement*/,
+                            oProvider /*:SuggestionProvider*/) {
+    /**
+     * The currently selected suggestions.
+     * @scope private
+     */
+    this.cur /*:int*/ = -1;
+    /**
+     * The dropdown list layer.
+     * @scope private
+     */
+    this.layer = null;
+    /**
+     * Suggestion provider for the autosuggest feature.
+     * @scope private.
+     */
+    this.provider /*:SuggestionProvider*/ = oProvider;
+    /**
+     * The textbox to capture.
+     * @scope private
+     */
+    this.textbox /*:HTMLInputElement*/ = oTextbox;
+    //initialize the control
+    this.init();
+
+}
+
+/**
+ * Autosuggests one or more suggestions for what the user has typed.
+ * If no suggestions are passed in, then no autosuggest occurs.
+ * @scope private
+ * @param aSuggestions An array of suggestion strings.
+ * @param bTypeAhead If the control should provide a type ahead suggestion.
+ */
+AutoSuggestControl.prototype.autosuggest = function (aSuggestions /*:Array*/,
+                                                     bTypeAhead /*:boolean*/) {
+    //make sure theres at least one suggestion
+    if (aSuggestions.length > 0) {
+        if (bTypeAhead) {
+           this.typeAhead(aSuggestions[0]);
+        }
+        this.showSuggestions(aSuggestions);
+    } else {
+        this.hideSuggestions();
+    }
+};
+
+/**
+ * Creates the dropdown layer to display multiple suggestions.
+ * @scope private
+ */
+AutoSuggestControl.prototype.createDropDown = function () {
+
+    var oThis = this;
+
+    //create the layer and assign styles
+    this.layer = document.createElement("div");
+    this.layer.className = "suggestions";
+    this.layer.style.visibility = "hidden";
+    this.layer.style.width = this.textbox.offsetWidth + 10;
+
+    //when the user clicks on the a suggestion, get the text (innerHTML)
+    //and place it into a textbox
+    this.layer.onmousedown =
+    this.layer.onmouseup =
+    this.layer.onmouseover = function (oEvent) {
+        oEvent = oEvent || window.event;
+        oTarget = oEvent.target || oEvent.srcElement;
+
+        if (oEvent.type == "mousedown") {
+            oThis.textbox.value = oTarget.firstChild.nodeValue;
+            oThis.hideSuggestions();
+        } else if (oEvent.type == "mouseover") {
+            oThis.highlightSuggestion(oTarget);
+        } else {
+            oThis.textbox.focus();
+        }
+    };
+
+
+    document.body.appendChild(this.layer);
+};
+
+/**
+ * Gets the left coordinate of the textbox.
+ * @scope private
+ * @return The left coordinate of the textbox in pixels.
+ */
+AutoSuggestControl.prototype.getLeft = function () /*:int*/ {
+
+    var oNode = this.textbox;
+    var iLeft = 0;
+
+    while(oNode.tagName != "BODY") {
+        iLeft += oNode.offsetLeft;
+        oNode = oNode.offsetParent;
+    }
+
+    return iLeft;
+};
+
+/**
+ * Gets the top coordinate of the textbox.
+ * @scope private
+ * @return The top coordinate of the textbox in pixels.
+ */
+AutoSuggestControl.prototype.getTop = function () /*:int*/ {
+    var oNode = this.textbox;
+    var iTop = 0;
+    while(oNode.tagName != "BODY") {
+        iTop += oNode.offsetTop;
+        oNode = oNode.offsetParent;
+    }
+    return iTop;
+};
+
+/**
+ * Handles three keydown events.
+ * @scope private
+ * @param oEvent The event object for the keydown event.
+ */
+AutoSuggestControl.prototype.handleKeyDown = function (oEvent /*:Event*/) {
+    switch(oEvent.keyCode) {
+        case 38: //up arrow
+            this.previousSuggestion();
+            break;
+        case 40: //down arrow
+            this.nextSuggestion();
+            break;
+        case 13: //enter
+            this.hideSuggestions();
+            break;
+    }
+};
+
+/**
+ * Handles keyup events.
+ * @scope private
+ * @param oEvent The event object for the keyup event.
+ */
+AutoSuggestControl.prototype.handleKeyUp = function (oEvent /*:Event*/) {
+    var iKeyCode = oEvent.keyCode;
+    //for backspace (8) and delete (46), shows suggestions without typeahead
+    if (iKeyCode == 8 || iKeyCode == 46) {
+        this.provider.requestSuggestions(this, false);
+
+    //make sure not to interfere with non-character keys
+    } else if (iKeyCode < 32 || (iKeyCode >= 33 && iKeyCode < 46) || (iKeyCode >= 112 && iKeyCode <= 123) ) {
+        //ignore
+    } else if (oEvent.ctrlKey) {
+       iKeyCode = 0;
+        this.hideSuggestions();
+    } else {
+        //request suggestions from the suggestion provider with typeahead
+        this.provider.requestSuggestions(this, true);
+    }
+
+
+
+};
+
+/**
+ * Hides the suggestion dropdown.
+ * @scope private
+ */
+AutoSuggestControl.prototype.hideSuggestions = function () {
+    this.layer.style.visibility = "hidden";
+};
+
+/**
+ * Highlights the given node in the suggestions dropdown.
+ * @scope private
+ * @param oSuggestionNode The node representing a suggestion in the dropdown.
+ */
+AutoSuggestControl.prototype.highlightSuggestion = function (oSuggestionNode) {
+    for (var i=0; i < this.layer.childNodes.length; i++) {
+        var oNode = this.layer.childNodes[i];
+        if (oNode == oSuggestionNode) {
+            oNode.className = "current"
+        } else if (oNode.className == "current") {
+            oNode.className = "";
+        }
+    }
+};
+
+/**
+ * Initializes the textbox with event handlers for
+ * auto suggest functionality.
+ * @scope private
+ */
+AutoSuggestControl.prototype.init = function () {
+
+    //save a reference to this object
+    var oThis = this;
+
+    //assign the onkeyup event handler
+    this.textbox.onkeyup = function (oEvent) {
+
+        //check for the proper location of the event object
+        if (!oEvent) {
+            oEvent = window.event;
+        }
+
+        //call the handleKeyUp() method with the event object
+        oThis.handleKeyUp(oEvent);
+    };
+
+    //assign onkeydown event handler
+    this.textbox.onkeydown = function (oEvent) {
+
+        //check for the proper location of the event object
+        if (!oEvent) {
+            oEvent = window.event;
+        }
+
+        //call the handleKeyDown() method with the event object
+        oThis.handleKeyDown(oEvent);
+    };
+
+    //assign onblur event handler (hides suggestions)
+    this.textbox.onblur = function () {
+        oThis.hideSuggestions();
+    };
+
+    this.textbox.onclick = function () {
+        oThis.hideSuggestions();
+    };
+
+
+    //create the suggestions dropdown
+    this.createDropDown();
+};
+
+/**
+ * Highlights the next suggestion in the dropdown and
+ * places the suggestion into the textbox.
+ * @scope private
+ */
+AutoSuggestControl.prototype.nextSuggestion = function () {
+    var cSuggestionNodes = this.layer.childNodes;
+
+    if (cSuggestionNodes.length > 0 && this.cur < cSuggestionNodes.length-1) {
+        var oNode = cSuggestionNodes[++this.cur];
+        this.highlightSuggestion(oNode);
+        this.textbox.value = oNode.firstChild.nodeValue;
+    }
+};
+
+/**
+ * Highlights the previous suggestion in the dropdown and
+ * places the suggestion into the textbox.
+ * @scope private
+ */
+AutoSuggestControl.prototype.previousSuggestion = function () {
+    var cSuggestionNodes = this.layer.childNodes;
+
+    if (cSuggestionNodes.length > 0 && this.cur > 0) {
+        var oNode = cSuggestionNodes[--this.cur];
+        this.highlightSuggestion(oNode);
+        this.textbox.value = oNode.firstChild.nodeValue;
+    }
+};
+
+/**
+ * Selects a range of text in the textbox.
+ * @scope public
+ * @param iStart The start index (base 0) of the selection.
+ * @param iLength The number of characters to select.
+ */
+AutoSuggestControl.prototype.selectRange = function (iStart /*:int*/, iLength /*:int*/) {
+
+    //use text ranges for Internet Explorer
+    if (this.textbox.createTextRange) {
+        var oRange = this.textbox.createTextRange();
+        oRange.moveStart("character", iStart);
+        oRange.moveEnd("character", iLength - this.textbox.value.length);
+        oRange.select();
+
+    //use setSelectionRange() for Mozilla
+    } else if (this.textbox.setSelectionRange) {
+        this.textbox.setSelectionRange(iStart, iLength);
+    }
+
+    //set focus back to the textbox
+    this.textbox.focus();
+};
+
+/**
+ * Builds the suggestion layer contents, moves it into position,
+ * and displays the layer.
+ * @scope private
+ * @param aSuggestions An array of suggestions for the control.
+ */
+AutoSuggestControl.prototype.showSuggestions = function (aSuggestions /*:Array*/) {
+
+    var oDiv = null;
+    this.layer.innerHTML = "";  //clear contents of the layer
+
+    for (var i=0; i < aSuggestions.length; i++) {
+        oDiv = document.createElement("div");
+        oDiv.appendChild(document.createTextNode(aSuggestions[i]));
+        this.layer.appendChild(oDiv);
+    }
+
+    this.layer.style.left = this.getLeft() + "px";
+    this.layer.style.top = (this.getTop()+this.textbox.offsetHeight) + "px";
+    this.layer.style.visibility = "visible";
+
+};
+
+/**
+ * Inserts a suggestion into the textbox, highlighting the
+ * suggested part of the text.
+ * @scope private
+ * @param sSuggestion The suggestion for the textbox.
+ */
+AutoSuggestControl.prototype.typeAhead = function (sSuggestion /*:String*/) {
+
+    //check for support of typeahead functionality
+    if (this.textbox.createTextRange || this.textbox.setSelectionRange){
+        var iLen = this.textbox.value.length;
+        this.textbox.value = sSuggestion;
+        this.selectRange(iLen, sSuggestion.length);
+    }
+};
+
+
+/**
+ * Request suggestions for the given autosuggest control.
+ * @scope protected
+ * @param oAutoSuggestControl The autosuggest control to provide suggestions for.
+ */
+FormSuggestions.prototype.requestSuggestions = function (oAutoSuggestControl /*:AutoSuggestControl*/,
+                                                          bTypeAhead /*:boolean*/) {
+    var aSuggestions = [];
+    var sTextboxValue = oAutoSuggestControl.textbox.value;
+
+    if (sTextboxValue.length > 0){
+        //search for matching suggestions
+        for (var i=0; i < this.suggestions.length; i++) {
+            if (this.suggestions[i].indexOf(sTextboxValue) == 0) {
+                aSuggestions.push(this.suggestions[i]);
+            }
+        }
+    }
+    //provide suggestions to the control
+    oAutoSuggestControl.autosuggest(aSuggestions, bTypeAhead);
+};
+
+function initSuggestions () {
+    var inputs = document.getElementsByTagName("input");
+    for (i=0;i<inputs.length;i++)
+    {
+        var ename = inputs[i].getAttribute("name");
+        var eid = inputs[i].getAttribute("id");
+        if (!ename && eid)
+                ename=eid;
+        var smth = new AutoSuggestControl(inputs[i], new FormSuggestions(ename));
+    }
+};
diff --git a/extensions/formhistory.c b/extensions/formhistory.c
new file mode 100644 (file)
index 0000000..5907f78
--- /dev/null
@@ -0,0 +1,205 @@
+/*
+ Copyright (C) 2009 Alexander Butenko <a.butenka@gmail.com>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License as published by the Free Software Foundation; either
+ version 2.1 of the License, or (at your option) any later version.
+
+*/
+
+#include <midori/midori.h>
+
+#include <midori/sokoke.h>
+#include "config.h"
+
+#include <glib/gstdio.h>
+#if HAVE_UNISTD_H
+    #include <unistd.h>
+#endif
+
+static gchar* jsforms;
+
+static void
+formhistory_prepare_js ()
+{
+   gchar* autosuggest;
+   gchar* style;
+   guint i;
+
+   /* FIXME: Don't hardcode paths */
+   g_file_get_contents ("/usr/local/share/midori/autosuggestcontrol.js", &autosuggest, NULL, NULL);
+   g_strchomp (autosuggest);
+
+   g_file_get_contents ("/usr/local/share/midori/autosuggestcontrol.css", &style, NULL, NULL);
+   g_strchomp (style);
+   i = 0;
+   while (style[i])
+   {
+       if (style[i] == '\n')
+           style[i] = ' ';
+       i++;
+   }
+   g_print ("%s\n", style);
+
+   jsforms = g_strdup_printf (
+        "%s"
+        "window.addEventListener (\"load\", function () { initSuggestions (); }, true);"
+        "window.addEventListener ('DOMContentLoaded',"
+        "function () {"
+        "var mystyle = document.createElement(\"style\");"
+        "mystyle.setAttribute(\"type\", \"text/css\");"
+        "mystyle.appendChild(document.createTextNode(\"%s\"));"
+        "var head = document.getElementsByTagName(\"head\")[0];"
+        "if (head) head.appendChild(mystyle);"
+        "else document.documentElement.insertBefore(mystyle, document.documentElement.firstChild);"
+        "}, true);",
+        autosuggest,
+        style);
+   g_strstrip (jsforms);
+   g_free (style);
+   g_free (autosuggest);
+}
+
+static gchar*
+formhistory_build_js ()
+{
+    const gchar* suggestions = "arr[\"txt1\"] = [\"Alabama\", \"Alaska\", \"Arizona\", \"Arkansas\"];"
+                               "arr[\"txt2\"] = [\"Alabama\", \"Alaska\", \"Arizona\", \"Arkansas\"];";
+    gchar* script = g_strdup_printf ("function FormSuggestions(eid) { "
+                                     "arr = new Array();"
+                                     "%s"
+                                     "this.suggestions = arr[eid]; }"
+                                     "%s",
+                                     suggestions,
+                                     jsforms);
+   return script;
+}
+
+static void
+formhistory_session_request_queued_cb (SoupSession* session,
+                                       SoupMessage* msg)
+{
+    gchar* method = katze_object_get_string (msg, "method");
+    if (method[0] == 'P' && method[1] == 'O' && method[2] == 'S')
+    {
+        SoupMessageHeaders* hdrs = msg->request_headers;
+        SoupMessageHeadersIter iter;
+        const gchar* name, *value;
+        SoupMessageBody* body = msg->request_body;
+
+        soup_message_headers_iter_init (&iter, hdrs);
+        while (soup_message_headers_iter_next (&iter, &name, &value))
+        {
+            g_warning ("%s=%s\n", name, value);
+        }
+        soup_buffer_free (soup_message_body_flatten (body));
+        g_warning ("BODY: %s\n", body->data);
+    }
+    g_free (method);
+}
+
+
+static void
+formhistory_window_object_cleared_cb (GtkWidget*      web_view,
+                                      WebKitWebFrame* web_frame,
+                                      JSContextRef    js_context,
+                                      JSObjectRef     js_window)
+{
+    webkit_web_view_execute_script (WEBKIT_WEB_VIEW (web_view),
+                                    formhistory_build_js ());
+}
+
+static void
+formhistory_add_tab_cb (MidoriBrowser* browser,
+                        MidoriView*    view)
+{
+    GtkWidget* web_view = gtk_bin_get_child (GTK_BIN (view));
+    SoupSession *session = webkit_get_default_session ();
+    g_signal_connect (web_view, "window-object-cleared",
+            G_CALLBACK (formhistory_window_object_cleared_cb), 0);
+    /* FIXME: Deactivate request-queued on unload */
+    g_signal_connect (session, "request-queued",
+       G_CALLBACK (formhistory_session_request_queued_cb), 0);
+}
+
+static void
+formhistory_deactivate_cb (MidoriExtension* extension,
+                           MidoriBrowser*   browser);
+
+static void
+formhistory_add_tab_foreach_cb (MidoriView*    view,
+                                MidoriBrowser* browser)
+{
+    formhistory_add_tab_cb (browser, view);
+}
+
+static void
+formhistory_app_add_browser_cb (MidoriApp*       app,
+                                MidoriBrowser*   browser,
+                                MidoriExtension* extension)
+{
+    midori_browser_foreach (browser,
+        (GtkCallback)formhistory_add_tab_foreach_cb, browser);
+    g_signal_connect (browser, "add-tab", G_CALLBACK (formhistory_add_tab_cb), 0);
+    g_signal_connect (extension, "deactivate",
+        G_CALLBACK (formhistory_deactivate_cb), browser);
+}
+
+static void
+formhistory_deactivate_tabs (MidoriView*    view,
+                             MidoriBrowser* browser)
+{
+    GtkWidget* web_view = gtk_bin_get_child (GTK_BIN (view));
+    g_signal_handlers_disconnect_by_func (
+       browser, formhistory_add_tab_cb, 0);
+    g_signal_handlers_disconnect_by_func (
+       web_view, formhistory_window_object_cleared_cb, 0);
+}
+
+static void
+formhistory_deactivate_cb (MidoriExtension* extension,
+                       MidoriBrowser*   browser)
+{
+    MidoriApp* app = midori_extension_get_app (extension);
+
+    g_signal_handlers_disconnect_by_func (
+        extension, formhistory_deactivate_cb, browser);
+    g_signal_handlers_disconnect_by_func (
+        app, formhistory_app_add_browser_cb, extension);
+    midori_browser_foreach (browser, (GtkCallback)formhistory_deactivate_tabs, browser);
+}
+
+static void
+formhistory_activate_cb (MidoriExtension* extension,
+                         MidoriApp*       app)
+{
+    KatzeArray* browsers;
+    MidoriBrowser* browser;
+    guint i;
+
+    formhistory_prepare_js ();
+    browsers = katze_object_get_object (app, "browsers");
+    i = 0;
+    while ((browser = katze_array_get_nth_item (browsers, i++)))
+        formhistory_app_add_browser_cb (app, browser, extension);
+    g_signal_connect (app, "add-browser",
+        G_CALLBACK (formhistory_app_add_browser_cb), extension);
+
+    g_object_unref (browsers);
+}
+
+MidoriExtension*
+extension_init (void)
+{
+    MidoriExtension* extension = g_object_new (MIDORI_TYPE_EXTENSION,
+        "name", _("Form history filler"),
+        "description", _("Stores history of entered form data"),
+        "version", "0.1",
+        "authors", "Alexander V. Butenko <a.butenka@gmail.com>",
+        NULL);
+    g_signal_connect (extension, "activate",
+        G_CALLBACK (formhistory_activate_cb), NULL);
+
+    return extension;
+}