dialog_search_engine.py 10.6 KB
Newer Older
Cédric Bellegarde's avatar
Cédric Bellegarde committed
1
# Copyright (c) 2017-2019 Cedric Bellegarde <cedric.bellegarde@adishatz.org>
2 3 4 5 6 7 8 9 10 11 12
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.

13
from gi.repository import Gtk, GLib, GObject
14 15 16 17 18

from gettext import gettext as _
from urllib.parse import urlparse

from eolie.search import Search
19
from eolie.define import App
20
from eolie.logger import Logger
21 22 23 24 25 26 27 28 29


class Item(GObject.GObject):
    name = GObject.Property(type=str,
                            default="")
    uri = GObject.Property(type=str,
                           default="")
    search = GObject.Property(type=str,
                              default="")
30 31 32 33
    keyword = GObject.Property(type=str,
                               default="")
    encoding = GObject.Property(type=str,
                                default="")
34 35 36 37 38 39 40 41 42 43 44 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 108 109 110 111 112 113 114
    bang = GObject.Property(type=str,
                            default="")

    def __init__(self):
        GObject.GObject.__init__(self)


class Row(Gtk.ListBoxRow):
    """
        A cookie row
    """

    def __init__(self, item):
        """
            Init row
            @param item as Item
        """
        Gtk.ListBoxRow.__init__(self)
        self.__item = item
        self.__label = Gtk.Label.new(item.get_property("name"))
        self.__label.set_max_width_chars(20)
        self.__label.set_property("halign", Gtk.Align.START)
        self.__label.show()
        self.add(self.__label)

    def set_name(self, name):
        """
            Set name
            @param name as str
        """
        self.__label.set_text(name)

    @property
    def is_valid(self):
        """
            True if item is valid
            @return bool
        """
        uri = self.__item.get_property("uri")
        search = self.__item.get_property("search")
        parsed = urlparse(uri)
        if parsed.scheme not in ["http", "https"] or not parsed.netloc:
            return False
        parsed = urlparse(search)
        if parsed.scheme not in ["http", "https"] or search.find("%s") == -1:
            return False
        return True

    @property
    def item(self):
        """
            Get associated item
            @return item
        """
        return self.__item


class SearchEngineDialog:
    """
        A search engine dialog
        THANKS TO EPIPHANY DEVS FOR UI FILE!
    """

    def __init__(self, parent):
        """
            Init widget
            @param parent as Gtk.Window
        """
        builder = Gtk.Builder()
        builder.add_from_resource("/org/gnome/Eolie/DialogSearchEngine.ui")
        self.__dialog = builder.get_object("dialog")
        self.__dialog.set_transient_for(parent)
        self.__edit_box = builder.get_object("edit_box")
        self.__listbox = builder.get_object("list_box")
        self.__name_entry = builder.get_object("name_entry")
        self.__uri_entry = builder.get_object("uri_entry")
        self.__search_entry = builder.get_object("search_entry")
        self.__bang_entry = builder.get_object("bang_entry")
        self.__default_switch = builder.get_object("default_switch")
        self.__add_button = builder.get_object("add_button")
        self.__remove_button = builder.get_object("remove_button")
Cédric Bellegarde's avatar
Cédric Bellegarde committed
115
        self.__remove_button.set_sensitive(False)
116 117 118 119 120 121 122 123 124 125 126
        builder.connect_signals(self)

    def run(self):
        """
            Run dialog
        """
        self.__populate()
        self.__dialog.run()
        # Save engines
        engines = {}
        for child in self.__listbox.get_children():
Cédric Bellegarde's avatar
Cédric Bellegarde committed
127
            if child.is_valid:
128 129 130
                name = child.item.get_property("name")
                uri = child.item.get_property("uri")
                search = child.item.get_property("search")
131 132
                keyword = child.item.get_property("keyword")
                encoding = child.item.get_property("encoding")
133 134
                bang = child.item.get_property("bang")
                if name and search:
135
                    engines[name] = [uri, search, keyword, encoding, bang]
136 137
        App().search.save_engines(engines)
        App().search.update_default_engine()
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
        self.__dialog.destroy()

#######################
# PROTECTED           #
#######################
    def _on_default_switch_state_set(self, switch, state):
        """
            Update engine state
            @param switch as Gtk.Switch
            @param state as bool
        """
        if state:
            row = self.__listbox.get_selected_row()
            if row is not None:
                name = row.item.get_property("name")
153 154
                App().settings.set_value("search-engine",
                                         GLib.Variant("s", name))
155 156 157 158 159 160 161 162 163 164 165 166

    def _on_add_button_clicked(self, button):
        """
            Add a new engine
            @param button as Gtk.Button
        """
        # Only one New engine
        for child in self.__listbox.get_children():
            if child.item.name == _("New engine"):
                return

        item = Item()
Cédric Bellegarde's avatar
Cédric Bellegarde committed
167
        item.set_property("name", _("New engine"))
168 169 170 171 172 173 174
        item.set_property("uri", "")
        item.set_property("search", "")
        item.set_property("bang", "")
        child = Row(item)
        child.show()
        self.__listbox.add(child)
        self.__listbox.select_row(child)
Cédric Bellegarde's avatar
Cédric Bellegarde committed
175
        self.__remove_button.set_sensitive(True)
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192

    def _on_remove_button_clicked(self, button):
        """
            Remove engine
            @param button as Gtk.Button
        """
        row = self.__listbox.get_selected_row()
        if row is not None:
            row.destroy()

    def _on_row_selected(self, listbox, row):
        """
            Update entries
            @param listbox as Gtk.ListBox
            @param row as Row
        """
        if row is None:
Cédric Bellegarde's avatar
Cédric Bellegarde committed
193 194 195 196 197 198
            children = listbox.get_children()
            if children:
                GLib.idle_add(listbox.select_row, children[0])
            else:
                self.__remove_button.set_sensitive(False)
                self.__edit_box.set_sensitive(False)
199
            return
Cédric Bellegarde's avatar
Cédric Bellegarde committed
200 201
        self.__remove_button.set_sensitive(True)
        self.__edit_box.set_sensitive(True)
202 203 204 205
        self.__name_entry.set_text(row.item.get_property("name"))
        self.__uri_entry.set_text(row.item.get_property("uri"))
        self.__search_entry.set_text(row.item.get_property("search"))
        self.__bang_entry.set_text(row.item.get_property("bang"))
206
        default_search_engine = App().settings.get_value(
Cédric Bellegarde's avatar
Cédric Bellegarde committed
207
            "search-engine").get_string()
208 209 210 211 212 213 214 215 216 217 218 219 220 221
        self.__default_switch.set_active(default_search_engine ==
                                         row.item.get_property("name"))

    def _on_name_entry_changed(self, entry):
        """
            Update search engine name
            @param entry as Gtk.Entry
        """
        new_name = entry.get_text()
        row = self.__listbox.get_selected_row()
        if row is None or not new_name:
            return
        # Update search engine if needed
        name = row.item.get_property("name")
222 223 224
        if name == App().settings.get_value("search-engine").get_string():
            App().settings.set_value("search-engine",
                                     GLib.Variant("s", new_name))
225 226 227 228 229
        row.item.set_property("name", new_name)
        row.set_name(new_name)

    def _on_uri_entry_changed(self, entry):
        """
Allan Nordhøy's avatar
Allan Nordhøy committed
230
            Update search engine URI
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
            @param entry as Gtk.Entry
        """
        uri = entry.get_text()
        row = self.__listbox.get_selected_row()
        if row is None or not uri:
            return
        row.item.set_property("uri", uri)
        parsed = urlparse(uri)
        if parsed.scheme not in ["http", "https"] or not parsed.netloc:
            entry.get_style_context().add_class("invalid-entry")
        else:
            entry.get_style_context().remove_class("invalid-entry")

    def _on_search_entry_changed(self, entry):
        """
Allan Nordhøy's avatar
Allan Nordhøy committed
246
            Update search engine search URI
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 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
            @param entry as Gtk.Entry
        """
        search = entry.get_text()
        row = self.__listbox.get_selected_row()
        if row is None or not search:
            return
        row.item.set_property("search", search)
        parsed = urlparse(search)
        if parsed.scheme not in ["http", "https"] or search.find("%s") == -1:
            entry.get_style_context().add_class("invalid-entry")
        else:
            entry.get_style_context().remove_class("invalid-entry")

    def _on_bang_entry_changed(self, entry):
        """
            Update search engine bang
            @param entry as Gtk.Entry
        """
        row = self.__listbox.get_selected_row()
        if row is None or not entry.get_text():
            return
        row.item.set_property("bang", entry.get_text())

    def _on_bang_key_press_event(self, entry, event):
        """
            Validate bang value
            @param entry as Gtk.Entry
            @param event as Gdk.EventKey
        """
        row = self.__listbox.get_selected_row()
        if row is None:
            return
        # Get all bang
        bangs = []
        for child in self.__listbox.get_children():
            if child == row:
                continue
            bang = child.item.get_property("bang")
            if bang:
                bangs.append(bang)
        if event.string in bangs:
            return True

#######################
# PRIVATE             #
#######################
    def __populate(self):
        """
            Populate the view with engines
        """
        search = Search()
        engines = search.engines
        try:
            # First load static engines
            for key in engines.keys():
                item = Item()
                item.set_property("name", key)
                item.set_property("uri", engines[key][0])
                item.set_property("search", engines[key][1])
306 307
                item.set_property("keyword", engines[key][2])
                item.set_property("encoding", engines[key][3])
308 309 310 311 312
                item.set_property("bang", engines[key][4])
                child = Row(item)
                child.show()
                self.__listbox.add(child)
        except Exception as e:
313
            Logger.error("DialogSearchEngine::__populate(): %s", e)