panthera-www.cc
C++ source, ASCII text, with very long lines (382)
1#include "gpanthera.hh" 2#include <gtkmm.h> 3#include <glibmm.h> 4#include <glibmm/ustring.h> 5#include <iostream> 6#include <memory> 7#include <libintl.h> 8#include <locale.h> 9#include <gtk/gtk.h> 10#include <gdk/gdk.h> 11#include <webkit/webkit.h> 12#include <fstream> 13#include <nlohmann/json.hpp> 14#include <iomanip> 15#include <sstream> 16#include <dlfcn.h> 17#include "external/sqlite_orm/sqlite_orm.h" 18//#include "plugin_api.h" 19#define _(STRING) gettext(STRING) 20 21using plugin_entrypoint_type = void(*)(void); 22 23std::string url_encode(const std::string &value) { 24// Thanks https://stackoverflow.com/a/17708801 25std::ostringstream escaped; 26escaped.fill('0'); 27escaped << std::hex; 28 29for(char c : value) { 30// Keep alphanumeric and other accepted characters intact 31if (isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~') { 32escaped << c; 33continue; 34} 35 36// Any other characters are percent-encoded 37escaped << std::uppercase; 38escaped << '%' << std::setw(2) << int((unsigned char) c); 39escaped << std::nouppercase; 40} 41 42return escaped.str(); 43} 44 45bool starts_with(const Glib::ustring &str, const Glib::ustring &prefix) { 46return str.size() >= prefix.size() && str.compare(0, prefix.size(), prefix) == 0; 47} 48 49bool ends_with(const Glib::ustring &str, const Glib::ustring &suffix) { 50return str.size() >= suffix.size() && str.compare(str.size() - suffix.size(), suffix.size(), suffix) == 0; 51} 52 53struct SearchEngine { 54Glib::ustring name; 55Glib::ustring url; 56Glib::ustring get_search_url(const std::string &query) { 57auto pos = url.find("%s"); 58if(pos == Glib::ustring::npos) { 59throw std::runtime_error("Invalid search engine URL: missing '%s' placeholder"); 60} 61auto new_url = url; 62new_url.replace(pos, 2, url_encode(query)); 63return new_url; 64} 65}; 66 67struct HistoryEntry { 68int id; 69std::string url, title; 70int64_t timestamp; 71}; 72 73using StorageType = decltype(sqlite_orm::make_storage("", 74sqlite_orm::make_table("history", 75sqlite_orm::make_column("id", &HistoryEntry::id, sqlite_orm::primary_key()), 76sqlite_orm::make_column("url", &HistoryEntry::url), 77sqlite_orm::make_column("title", &HistoryEntry::title), 78sqlite_orm::make_column("timestamp", &HistoryEntry::timestamp) 79) 80)); 81 82class HistoryManager { 83public: 84static auto make_storage(const std::string& path) { 85return sqlite_orm::make_storage(path, 86sqlite_orm::make_table("history", 87sqlite_orm::make_column("id", &HistoryEntry::id, sqlite_orm::primary_key()), 88sqlite_orm::make_column("url", &HistoryEntry::url), 89sqlite_orm::make_column("title", &HistoryEntry::title), 90sqlite_orm::make_column("timestamp", &HistoryEntry::timestamp) 91) 92); 93} 94StorageType storage; 95explicit HistoryManager(const std::string &db_path) : storage(make_storage(db_path)) { 96storage.sync_schema(); 97} 98 99void log_url(const std::string &url, const std::string title, const int64_t timestamp = Glib::DateTime::create_now_local().to_unix()) { 100storage.insert(HistoryEntry{-1, url, title, timestamp}); 101} 102 103std::vector<HistoryEntry> get_history() { 104return storage.get_all<HistoryEntry>(); 105} 106 107std::vector<HistoryEntry> get_history_between(int64_t start_time, int64_t end_time) { 108using namespace sqlite_orm; 109return storage.get_all<HistoryEntry>( 110where(c(&HistoryEntry::timestamp) >= start_time and c(&HistoryEntry::timestamp) < end_time), 111order_by(&HistoryEntry::timestamp).desc() 112); 113} 114}; 115 116class HistoryViewer : public gPanthera::DockablePane { 117protected: 118std::shared_ptr<HistoryManager> history_manager; 119Gtk::Calendar *calendar; 120Gtk::Label *date_label; 121Gtk::Box *box_place; 122public: 123sigc::signal<void(const std::string &url)> signal_open_url; 124HistoryViewer(std::shared_ptr<gPanthera::LayoutManager> layout_manager, std::shared_ptr<HistoryManager> history_manager) : gPanthera::DockablePane(layout_manager, *Gtk::make_managed<Gtk::Box>(Gtk::Orientation::VERTICAL, 0), "history", _("History"), Gtk::make_managed<Gtk::Image>(Gio::Icon::create("document-open-recent-symbolic"))), history_manager(std::move(history_manager)) { 125auto history_toolbar = Gtk::make_managed<Gtk::Box>(Gtk::Orientation::HORIZONTAL, 0); 126auto history_button_previous = Gtk::make_managed<Gtk::Button>(); 127history_button_previous->set_child(*Gtk::make_managed<Gtk::Image>(Gio::Icon::create("go-previous-symbolic"))); 128history_button_previous->set_tooltip_text(_("Previous day")); 129auto history_button_next = Gtk::make_managed<Gtk::Button>(); 130history_button_next->set_child(*Gtk::make_managed<Gtk::Image>(Gio::Icon::create("go-next-symbolic"))); 131history_button_next->set_tooltip_text(_("Next day")); 132 133date_label = Gtk::make_managed<Gtk::Label>(""); 134auto date_button = Gtk::make_managed<Gtk::MenuButton>(); 135date_button->set_child(*date_label); 136date_button->set_tooltip_text(_("Select date")); 137date_button->set_direction(Gtk::ArrowType::NONE); 138auto date_popover = Gtk::make_managed<Gtk::Popover>(); 139calendar = Gtk::make_managed<Gtk::Calendar>(); 140date_popover->set_child(*calendar); 141date_button->set_popover(*date_popover); 142date_button->set_has_frame(false); 143date_button->set_hexpand(true); 144 145history_toolbar->append(*history_button_previous); 146history_toolbar->append(*date_button); 147history_toolbar->append(*history_button_next); 148auto box = dynamic_cast<Gtk::Box*>(this->child); 149box->append(*history_toolbar); 150 151history_button_next->signal_clicked().connect([this]() { 152Glib::DateTime calendar_day = calendar->get_date(); 153Glib::DateTime datetime = Glib::DateTime::create_local( 154calendar_day.get_year(), 155calendar_day.get_month(), 156calendar_day.get_day_of_month(), 1570, 0, 0 158); 159auto next_entries = this->history_manager->storage.get_all<HistoryEntry>( 160sqlite_orm::where(sqlite_orm::c(&HistoryEntry::timestamp) >= datetime.to_unix() + 86400), 161sqlite_orm::order_by(&HistoryEntry::timestamp).asc() 162); 163if(next_entries.empty()) { 164return; 165} 166auto last_entry = next_entries.front(); 167Glib::DateTime next_day = Glib::DateTime::create_now_local(last_entry.timestamp); 168Glib::DateTime new_date = Glib::DateTime::create_local( 169next_day.get_year(), 170next_day.get_month(), 171next_day.get_day_of_month(), 1720, 0, 0 173); 174calendar->select_day(new_date); 175reload_history(); 176}); 177 178history_button_previous->signal_clicked().connect([this]() { 179Glib::DateTime calendar_day = calendar->get_date(); 180Glib::DateTime datetime = Glib::DateTime::create_local( 181calendar_day.get_year(), 182calendar_day.get_month(), 183calendar_day.get_day_of_month(), 1840, 0, 0 185); 186auto previous_entries = this->history_manager->storage.get_all<HistoryEntry>( 187sqlite_orm::where(sqlite_orm::c(&HistoryEntry::timestamp) < datetime.to_unix()), 188sqlite_orm::order_by(&HistoryEntry::timestamp).desc() 189); 190if(previous_entries.empty()) { 191return; 192} 193auto last_entry = previous_entries.front(); 194Glib::DateTime previous_day = Glib::DateTime::create_now_local(last_entry.timestamp); 195Glib::DateTime new_date = Glib::DateTime::create_local( 196previous_day.get_year(), 197previous_day.get_month(), 198previous_day.get_day_of_month(), 1990, 0, 0 200); 201calendar->select_day(new_date); 202reload_history(); 203}); 204 205calendar->signal_day_selected().connect(sigc::mem_fun(*this, &HistoryViewer::reload_history)); 206calendar->signal_prev_month().connect(sigc::mem_fun(*this, &HistoryViewer::reload_history)); 207calendar->signal_next_month().connect(sigc::mem_fun(*this, &HistoryViewer::reload_history)); 208calendar->signal_prev_year().connect(sigc::mem_fun(*this, &HistoryViewer::reload_history)); 209calendar->signal_next_year().connect(sigc::mem_fun(*this, &HistoryViewer::reload_history)); 210Glib::DateTime datetime = Glib::DateTime::create_now_local(); 211calendar->select_day(datetime); 212 213this->signal_pane_shown.connect([this]() { 214// Load the current date 215reload_history(); 216}); 217 218auto scrolled_window = Gtk::make_managed<Gtk::ScrolledWindow>(); 219box_place = Gtk::make_managed<Gtk::Box>(Gtk::Orientation::VERTICAL, 0); 220auto viewport = Gtk::make_managed<Gtk::Viewport>(nullptr, nullptr); 221viewport->set_child(*box_place); 222scrolled_window->set_child(*viewport); 223scrolled_window->set_policy(Gtk::PolicyType::AUTOMATIC, Gtk::PolicyType::AUTOMATIC); 224scrolled_window->set_vexpand(true); 225scrolled_window->set_hexpand(true); 226box->append(*scrolled_window); 227 228// TODO: allow deleting entries 229} 230 231void reload_history() { 232Glib::DateTime calendar_day = calendar->get_date(); 233Glib::DateTime datetime = Glib::DateTime::create_local( 234calendar_day.get_year(), 235calendar_day.get_month(), 236calendar_day.get_day_of_month(), 2370, 0, 0 238); 239date_label->set_text(datetime.format("%x")); 240auto box = Gtk::make_managed<Gtk::ListBox>(); 241auto history_entries = history_manager->get_history_between(datetime.to_unix(), datetime.to_unix() + 86400); 242for(const auto &entry : history_entries) { 243auto row = Gtk::make_managed<Gtk::Box>(Gtk::Orientation::VERTICAL, 4); 244auto title = Gtk::make_managed<Gtk::Label>(entry.title.empty() ? "Untitled" : entry.title); 245title->set_halign(Gtk::Align::START); 246title->set_ellipsize(Pango::EllipsizeMode::MIDDLE); 247auto label = Gtk::make_managed<Gtk::Label>(entry.url); 248label->set_halign(Gtk::Align::START); 249label->set_ellipsize(Pango::EllipsizeMode::MIDDLE); 250row->append(*title); 251row->append(*label); 252if(auto time = Glib::DateTime::create_now_local(entry.timestamp)) { 253label->set_tooltip_text(time.format("%c")); 254box->append(*row); 255} 256} 257if(box_place->get_first_child()) { 258box_place->remove(*box_place->get_first_child()); 259} 260box->signal_row_activated().connect([this](Gtk::ListBoxRow *row) { 261if(auto box_row = dynamic_cast<Gtk::Box*>(row->get_child())) { 262if(auto label = dynamic_cast<Gtk::Label*>(box_row->get_last_child())) { 263auto url = label->get_text(); 264if(!url.empty()) { 265signal_open_url.emit(url); 266} 267} 268} 269}); 270box_place->append(*box); 271} 272}; 273 274class PantheraWindow; 275 276class PantheraWww : public Gtk::Application { 277private: 278std::shared_ptr<gPanthera::ContentManager> content_manager; 279std::string cookie_file; 280std::vector<SearchEngine> search_engines; 281SearchEngine *default_search_engine; 282std::shared_ptr<HistoryManager> history_manager; 283Glib::RefPtr<Gio::Menu> main_menu; 284std::string new_tab_page; 285 286static void load_change_callback(WebKitWebView* object, WebKitLoadEvent load_event, gpointer data); 287static void notify_callback(GObject* object, GParamSpec* pspec, gpointer data); 288static void notify_focused_callback(GObject* object, GParamSpec* pspec, gpointer data); 289static void on_back_pressed(GtkGestureClick* gesture, int n_press, double x, double y, gpointer user_data); 290static void on_forward_pressed(GtkGestureClick* gesture, int n_press, double x, double y, gpointer user_data); 291static gboolean on_decide_policy(WebKitWebView* source, WebKitPolicyDecision* decision, WebKitPolicyDecisionType type, gpointer user_data); 292 293protected: 294void on_startup() override; 295void on_activate() override; 296void on_shutdown() override; 297PantheraWindow *make_window(); 298 299public: 300PantheraWww(); 301~PantheraWww(); 302friend class PantheraWindow; 303void on_new_tab(gPanthera::ContentStack* stack, const Glib::ustring& url = "", bool focus = true, bool new_window = false); 304void set_search_engines_from_json(const std::string& json_string); 305static Glib::RefPtr<PantheraWww> create(); 306std::shared_ptr<gPanthera::ContentManager> get_content_manager(); 307void load_plugin(const std::string& plugin_path); 308}; 309 310class PantheraWindow : public Gtk::ApplicationWindow { 311private: 312std::shared_ptr<gPanthera::LayoutManager> layout_manager; 313Gtk::Entry *url_bar; 314HistoryViewer *history_viewer; 315gPanthera::ContentPage *controlled_page = nullptr; 316public: 317friend class PantheraWww; 318explicit PantheraWindow(Gtk::Application *application) : Gtk::ApplicationWindow() { 319// There is a constructor with Glib::RefPtr<Gtk::Application>, but it is not appropriate 320// because the window will own the application, creating a cycle 321auto panthera = dynamic_cast<PantheraWww*>(application); 322if(!panthera) { 323throw std::runtime_error("Application is not a PantheraWww instance"); 324} 325panthera->add_window(*this); 326this->set_default_size(800, 600); 327layout_manager = std::make_shared<gPanthera::LayoutManager>(); 328 329auto dock_stack_1 = Gtk::make_managed<gPanthera::DockStack>(layout_manager, _("One"), "one"); 330auto switcher_1 = Gtk::make_managed<gPanthera::DockStackSwitcher>(dock_stack_1, Gtk::Orientation::HORIZONTAL); 331auto dock_stack_2 = Gtk::make_managed<gPanthera::DockStack>(layout_manager, _("Two"), "two"); 332auto switcher_2 = Gtk::make_managed<gPanthera::DockStackSwitcher>(dock_stack_2, Gtk::Orientation::VERTICAL); 333auto pane_1_content = Gtk::make_managed<Gtk::Box>(Gtk::Orientation::VERTICAL, 0); 334auto debug_button = Gtk::make_managed<Gtk::Button>("Debug"); 335auto print_history_button = Gtk::make_managed<Gtk::Button>("Print history"); 336print_history_button->signal_clicked().connect([this, panthera]() { 337auto history = panthera->history_manager->get_history(); 338for(const auto &entry : history) { 339std::cout << "entry " << entry.id << ", url " << entry.url << ", unix time " << entry.timestamp << std::endl; 340// TODO: exclude redirecting URLs 341} 342}); 343pane_1_content->append(*debug_button); 344pane_1_content->append(*print_history_button); 345auto pane_1_icon = Gtk::make_managed<Gtk::Image>(Gio::Icon::create("help-about-symbolic")); 346auto pane_1 = Gtk::make_managed<gPanthera::DockablePane>(layout_manager, *pane_1_content, "debug", _("Debugging options"), pane_1_icon); 347 348dock_stack_1->set_transition_type(Gtk::StackTransitionType::SLIDE_LEFT_RIGHT); 349dock_stack_1->set_transition_duration(125); 350dock_stack_1->set_expand(true); 351dock_stack_2->set_transition_type(Gtk::StackTransitionType::SLIDE_UP_DOWN); 352dock_stack_2->set_transition_duration(125); 353dock_stack_2->set_expand(true); 354 355auto outer_grid = Gtk::make_managed<Gtk::Grid>(); 356outer_grid->attach(*switcher_2, 0, 2, 1, 1); 357outer_grid->attach(*switcher_1, 1, 3, 1, 1); 358auto outer_paned = Gtk::make_managed<Gtk::Paned>(Gtk::Orientation::HORIZONTAL); 359outer_paned->set_start_child(*dock_stack_2); 360auto inner_paned = Gtk::make_managed<Gtk::Paned>(Gtk::Orientation::VERTICAL); 361auto content = Gtk::make_managed<Gtk::Box>(Gtk::Orientation::VERTICAL, 0); 362panthera->content_manager = std::make_shared<gPanthera::ContentManager>(); 363std::function<bool(gPanthera::ContentPage*)> detach_handler; 364detach_handler = [](gPanthera::ContentPage *widget) { 365auto new_stack = Gtk::make_managed<gPanthera::ContentStack>(widget->content_manager, widget->get_stack()->get_detach_handler()); 366auto new_switcher = Gtk::make_managed<gPanthera::ContentTabBar>(new_stack, Gtk::Orientation::HORIZONTAL, dynamic_cast<gPanthera::ContentTabBar*>(widget->get_stack()->get_parent()->get_first_child())->get_extra_child_function()); 367auto new_notebook = Gtk::make_managed<gPanthera::ContentNotebook>(new_stack, new_switcher); 368auto window = new gPanthera::ContentWindow(new_notebook); 369widget->redock(new_stack); 370window->present(); 371new_stack->signal_leave_empty.connect([window]() { 372window->close(); 373delete window; 374}); 375return true; 376}; 377 378auto return_extra_child = [this, panthera](gPanthera::ContentTabBar *switcher) { 379auto new_tab_button = Gtk::make_managed<Gtk::Button>(); 380new_tab_button->set_child(*Gtk::make_managed<Gtk::Image>(Gio::Icon::create("list-add-symbolic"))); 381new_tab_button->set_tooltip_text("New tab"); 382new_tab_button->signal_clicked().connect([this, switcher, panthera]() { 383panthera->on_new_tab(switcher->get_stack()); 384}); 385return new_tab_button; 386}; 387auto content_stack = Gtk::make_managed<gPanthera::ContentStack>(panthera->content_manager, detach_handler); 388auto content_stack_switcher = Gtk::make_managed<gPanthera::ContentTabBar>(content_stack, Gtk::Orientation::HORIZONTAL, return_extra_child); 389panthera->content_manager->add_stack(content_stack); 390WebKitWebView *webview = WEBKIT_WEB_VIEW(webkit_web_view_new()); // for some reason, this has to be created 391content->set_name("content_box"); 392auto content_notebook = Gtk::make_managed<gPanthera::ContentNotebook>(content_stack, content_stack_switcher, Gtk::PositionType::TOP); 393content->append(*content_notebook); 394inner_paned->set_start_child(*content); 395inner_paned->set_end_child(*dock_stack_1); 396outer_paned->set_end_child(*inner_paned); 397outer_grid->attach(*outer_paned, 1, 2, 1, 1); 398// Create the toolbar 399auto main_toolbar = Gtk::make_managed<Gtk::Box>(Gtk::Orientation::HORIZONTAL, 8); 400// URL bar 401url_bar = Gtk::make_managed<Gtk::Entry>(); 402url_bar->set_placeholder_text(_("Enter URL")); 403url_bar->set_hexpand(true); 404auto load_url_callback = [this, panthera]() { 405bool has_protocol = url_bar->get_text().find("://") != std::string::npos; 406if(!has_protocol) { 407url_bar->set_text("http://" + url_bar->get_text()); 408} 409if(controlled_page) { 410if(auto webview = WEBKIT_WEB_VIEW(controlled_page->get_child()->get_first_child()->gobj())) { 411webkit_web_view_load_uri(webview, url_bar->get_text().c_str()); 412} 413} 414}; 415// Go 416auto go_button = Gtk::make_managed<Gtk::Button>(_("Go")); 417go_button->signal_clicked().connect(load_url_callback); 418url_bar->signal_activate().connect(load_url_callback); 419panthera->content_manager->signal_page_operated.connect([this, panthera](gPanthera::ContentPage *page) { 420if(!page->get_child()) { 421return; 422} 423if(!page->get_child()->get_first_child()) { 424return; 425} 426if(page->get_root() != this) { 427// The page is in some other window 428return; 429} 430controlled_page = page; 431url_bar->set_text(webkit_web_view_get_uri(WEBKIT_WEB_VIEW(page->get_child()->get_first_child()->gobj()))); 432guint url_update_handler = g_signal_connect(page->get_child()->get_first_child()->gobj(), "notify", G_CALLBACK(panthera->notify_focused_callback), this); 433std::shared_ptr<sigc::connection> control_signal_handler = std::make_shared<sigc::connection>(); 434*control_signal_handler = page->signal_control_status_changed.connect([this, page, control_signal_handler, url_update_handler](bool controlled) { 435if(!controlled) { 436control_signal_handler->disconnect(); 437if(page->get_child() && page->get_child()->get_first_child() && WEBKIT_IS_WEB_VIEW(page->get_child()->get_first_child()->gobj())) { 438g_signal_handler_disconnect(page->get_child()->get_first_child()->gobj(), url_update_handler); 439} 440} 441}); 442}); 443history_viewer = Gtk::make_managed<HistoryViewer>(layout_manager, panthera->history_manager); 444history_viewer->signal_open_url.connect([this, panthera](const std::string &url) { 445panthera->on_new_tab(nullptr, url, true); 446}); 447// Back, forward, reload 448auto back_button = Gtk::make_managed<Gtk::Button>(); 449back_button->set_child(*Gtk::make_managed<Gtk::Image>(Gio::Icon::create("go-previous-symbolic"))); 450back_button->set_tooltip_text("Back"); 451auto forward_button = Gtk::make_managed<Gtk::Button>(); 452forward_button->set_child(*Gtk::make_managed<Gtk::Image>(Gio::Icon::create("go-next-symbolic"))); 453forward_button->set_tooltip_text("Forward"); 454auto reload_button = Gtk::make_managed<Gtk::Button>(); 455reload_button->set_child(*Gtk::make_managed<Gtk::Image>(Gio::Icon::create("view-refresh-symbolic"))); 456reload_button->set_tooltip_text("Reload"); 457 458auto back_action = Gio::SimpleAction::create("go_back"); 459add_action(back_action); 460back_action->signal_activate().connect([this, panthera](const Glib::VariantBase&) { 461if(controlled_page) { 462if(auto webview = WEBKIT_WEB_VIEW(controlled_page->get_child()->get_first_child()->gobj())) { 463webkit_web_view_go_back(webview); 464} 465} 466}); 467back_button->set_action_name("win.go_back"); 468 469auto forward_action = Gio::SimpleAction::create("go_forward"); 470add_action(forward_action); 471forward_action->signal_activate().connect([this, panthera](const Glib::VariantBase&) { 472if(controlled_page) { 473if(auto webview = WEBKIT_WEB_VIEW(controlled_page->get_child()->get_first_child()->gobj())) { 474webkit_web_view_go_forward(webview); 475} 476} 477}); 478forward_button->set_action_name("win.go_forward"); 479 480auto reload_action = Gio::SimpleAction::create("reload"); 481add_action(reload_action); 482reload_action->signal_activate().connect([this, panthera](const Glib::VariantBase&) { 483if(controlled_page) { 484if(auto webview = WEBKIT_WEB_VIEW(controlled_page->get_child()->get_first_child()->gobj())) { 485webkit_web_view_reload(webview); 486} 487} 488}); 489reload_button->set_action_name("win.reload"); 490 491// Search bar 492// TODO: provide history, provide a menu button with the other engines 493auto search_bar = Gtk::make_managed<Gtk::Entry>(); 494search_bar->set_placeholder_text(_("Search")); 495search_bar->set_hexpand(true); 496if(panthera->search_engines.empty()) { 497search_bar->set_sensitive(false); 498search_bar->set_placeholder_text(_("No search")); 499} 500auto search_callback = [this, search_bar, content_stack, panthera]() { 501// Create a new tab with the search results 502if(panthera->content_manager->get_last_operated_page()) { 503panthera->on_new_tab(nullptr); 504} else { 505panthera->on_new_tab(content_stack); 506} 507auto page = panthera->content_manager->get_last_operated_page(); 508if(page) { 509if(auto webview = WEBKIT_WEB_VIEW(page->get_child()->get_first_child()->gobj())) { 510auto search_url = panthera->default_search_engine->get_search_url(search_bar->get_text()); 511webkit_web_view_load_uri(webview, search_url.c_str()); 512} 513} 514}; 515if(panthera->default_search_engine) { 516search_bar->signal_activate().connect(search_callback); 517} 518 519// Assemble the toolbar 520main_toolbar->append(*back_button); 521main_toolbar->append(*forward_button); 522main_toolbar->append(*reload_button); 523main_toolbar->append(*url_bar); 524main_toolbar->append(*go_button); 525main_toolbar->append(*search_bar); 526if(panthera->default_search_engine) { 527auto search_button = Gtk::make_managed<Gtk::Button>(panthera->default_search_engine->name); 528search_button->signal_clicked().connect(search_callback); 529main_toolbar->append(*search_button); 530} 531outer_grid->attach(*main_toolbar, 0, 1, 2, 1); 532this->set_child(*outer_grid); 533debug_button->signal_clicked().connect([this, panthera]() { 534if(panthera->content_manager->get_last_operated_page()) { 535std::cout << "Last operated page: " << panthera->content_manager->get_last_operated_page()->get_name() << std::endl; 536} else { 537std::cout << "No page operated!" << std::endl; 538} 539}); 540// TODO: Use the last operated page and allow opening tabs next to the last operated page using certain panes 541// Load the existing layout, if it exists 542std::ifstream layout_file_in("layout.json"); 543if(layout_file_in) { 544std::string layout_json((std::istreambuf_iterator<char>(layout_file_in)), std::istreambuf_iterator<char>()); 545layout_file_in.close(); 546layout_manager->restore_json_layout(layout_json); 547} else { 548// Create a new layout if the file doesn't exist 549layout_file_in.close(); 550 551dock_stack_1->add_pane(*pane_1); 552dock_stack_1->add_pane(*history_viewer); 553 554std::ofstream layout_file_out("layout.json"); 555layout_file_out << layout_manager->get_layout_as_json(); 556layout_file_out.close(); 557} 558// Save the layout when changed 559layout_manager->signal_pane_moved.connect([this, panthera](gPanthera::DockablePane *pane) { 560std::ofstream layout_file_out("layout.json"); 561layout_file_out << layout_manager->get_layout_as_json(); 562layout_file_out.close(); 563std::cout << "Layout changed: " << layout_manager->get_layout_as_json() << std::endl; 564}); 565set_show_menubar(true); 566} 567~PantheraWindow() override = default; 568}; 569 570void PantheraWww::load_change_callback(WebKitWebView *object, WebKitLoadEvent load_event, gpointer data) { 571if(auto self = static_cast<PantheraWww*>(data)) { 572if(load_event == WEBKIT_LOAD_COMMITTED) { 573if(webkit_web_view_get_title(WEBKIT_WEB_VIEW(object)) == nullptr) { 574self->history_manager->log_url(webkit_web_view_get_uri(WEBKIT_WEB_VIEW(object)), ""); 575} else { 576self->history_manager->log_url(webkit_web_view_get_uri(WEBKIT_WEB_VIEW(object)), 577webkit_web_view_get_title(WEBKIT_WEB_VIEW(object))); 578} 579// TODO: reload visible history viewers 580} 581} 582} 583 584void PantheraWww::notify_callback(GObject *object, GParamSpec *pspec, gpointer data) { 585if(!gtk_widget_get_parent(GTK_WIDGET(object))) { 586return; 587} 588if(auto self = static_cast<PantheraWww*>(data)) { 589auto parent = gtk_widget_get_parent(gtk_widget_get_parent(GTK_WIDGET(object))); 590if(auto page = dynamic_cast<gPanthera::ContentPage*>(Glib::wrap(parent))) { 591if(g_strcmp0(pspec->name, "title") == 0) { 592if(auto label = dynamic_cast<Gtk::Label*>(page->tab_widget->get_last_child())) { 593if(strlen(webkit_web_view_get_title(WEBKIT_WEB_VIEW(object))) == 0) { 594label->set_label(_("Untitled")); 595} else { 596label->set_label(webkit_web_view_get_title(WEBKIT_WEB_VIEW(object))); 597} 598} 599} else if(g_strcmp0(pspec->name, "favicon") == 0) { 600// Update favicons 601if(auto image = dynamic_cast<Gtk::Image*>(page->tab_widget->get_first_child())) { 602image->set_from_icon_name("image-loading-symbolic"); 603if(auto favicon = webkit_web_view_get_favicon(WEBKIT_WEB_VIEW(object))) { 604gtk_image_set_from_paintable(image->gobj(), GDK_PAINTABLE(favicon)); 605} 606} 607} 608} 609} 610} 611 612void PantheraWww::notify_focused_callback(GObject *object, GParamSpec *pspec, gpointer data) { 613if(!gtk_widget_get_parent(GTK_WIDGET(object))) { 614return; 615} 616auto this_ = static_cast<PantheraWww*>(data); 617auto parent = gtk_widget_get_parent(gtk_widget_get_parent(GTK_WIDGET(object))); 618if(auto page = dynamic_cast<gPanthera::ContentPage*>(Glib::wrap(parent))) { 619if(g_strcmp0(pspec->name, "uri") == 0) { 620if(auto main_window = dynamic_cast<PantheraWindow*>(page->get_root())) { 621main_window->url_bar->set_text(webkit_web_view_get_uri(WEBKIT_WEB_VIEW(object))); 622} 623} 624} 625} 626 627void PantheraWww::on_back_pressed(GtkGestureClick *gesture, int n_press, double x, double y, gpointer user_data) { 628WebKitWebView *webview = WEBKIT_WEB_VIEW(user_data); 629webkit_web_view_go_back(webview); 630} 631 632void PantheraWww::on_forward_pressed(GtkGestureClick *gesture, int n_press, double x, double y, gpointer user_data) { 633WebKitWebView *webview = WEBKIT_WEB_VIEW(user_data); 634webkit_web_view_go_forward(webview); 635} 636 637gboolean PantheraWww::on_decide_policy(WebKitWebView *source, WebKitPolicyDecision *decision, WebKitPolicyDecisionType type, gpointer user_data) { 638if(auto self = static_cast<PantheraWww*>(user_data)) { 639if(type == WEBKIT_POLICY_DECISION_TYPE_NAVIGATION_ACTION) { 640auto action = webkit_navigation_policy_decision_get_navigation_action(WEBKIT_NAVIGATION_POLICY_DECISION(decision)); 641Glib::ustring url = Glib::ustring(webkit_uri_request_get_uri(webkit_navigation_action_get_request(action))); 642if(!starts_with(url, "about:") && url.find("://") == Glib::ustring::npos) { 643// It is a special scheme (mailto:, tel: etc.) 644try { 645Gio::AppInfo::launch_default_for_uri(url); 646} catch(const Glib::Error &exception) { 647std::cerr << "Failed to launch special URI: " << exception.what() << std::endl; 648} 649webkit_policy_decision_ignore(decision); 650return true; 651} 652if(webkit_navigation_action_get_mouse_button(action) == 2) { 653// Middle-click opens in a new window 654self->on_new_tab(nullptr, url, false); 655webkit_policy_decision_ignore(decision); 656return true; 657} 658} else if(type == WEBKIT_POLICY_DECISION_TYPE_NEW_WINDOW_ACTION) { 659auto action = webkit_navigation_policy_decision_get_navigation_action(WEBKIT_NAVIGATION_POLICY_DECISION(decision)); 660self->on_new_tab(nullptr, webkit_uri_request_get_uri(webkit_navigation_action_get_request(action)), false, true); 661return true; 662} 663} 664return false; 665} 666 667void PantheraWww::on_new_tab(gPanthera::ContentStack *stack, const Glib::ustring &url, bool focus, bool new_window) { 668if(!stack) { 669// Find the current area 670stack = content_manager->get_last_operated_page()->get_stack(); 671} 672Glib::ustring url_ = url; 673if(url.empty()) { 674url_ = new_tab_page; 675} 676 677WebKitWebView *webview = WEBKIT_WEB_VIEW(webkit_web_view_new()); 678gtk_widget_set_hexpand(GTK_WIDGET(webview), true); 679gtk_widget_set_vexpand(GTK_WIDGET(webview), true); 680auto page_content = Gtk::make_managed<Gtk::Box>(); 681gtk_box_append(page_content->gobj(), GTK_WIDGET(webview)); 682auto page_tab = new Gtk::Box(); 683page_tab->set_orientation(Gtk::Orientation::HORIZONTAL); 684auto initial_icon = Gtk::make_managed<Gtk::Image>(Gio::Icon::create("image-loading-symbolic")); 685page_tab->append(*initial_icon); 686page_tab->append(*Gtk::make_managed<Gtk::Label>("Untitled")); 687page_tab->set_spacing(4); 688auto page = Gtk::make_managed<gPanthera::ContentPage>(content_manager, stack, page_content, page_tab); 689g_signal_connect(webview, "notify", G_CALLBACK(notify_callback), this); 690g_signal_connect(webview, "load-changed", G_CALLBACK(load_change_callback), this); 691g_signal_connect(webview, "decide-policy", G_CALLBACK(on_decide_policy), this); 692webkit_web_view_load_uri(webview, url_.data()); 693auto cookie_manager = webkit_network_session_get_cookie_manager(webkit_web_view_get_network_session(webview)); 694webkit_cookie_manager_set_persistent_storage(cookie_manager, cookie_file.c_str(), WEBKIT_COOKIE_PERSISTENT_STORAGE_TEXT); 695webkit_cookie_manager_set_accept_policy(cookie_manager, WEBKIT_COOKIE_POLICY_ACCEPT_ALWAYS); 696auto website_data_manager = webkit_network_session_get_website_data_manager(webkit_web_view_get_network_session(webview)); 697webkit_website_data_manager_set_favicons_enabled(website_data_manager, true); 698GtkEventController *click_controller_back = GTK_EVENT_CONTROLLER(gtk_gesture_click_new()); 699gtk_gesture_single_set_button(GTK_GESTURE_SINGLE(click_controller_back), 8); 700g_signal_connect(click_controller_back, "pressed", G_CALLBACK(on_back_pressed), webview); 701gtk_widget_add_controller(GTK_WIDGET(webview), click_controller_back); 702 703GtkEventController *click_controller_forward = GTK_EVENT_CONTROLLER(gtk_gesture_click_new()); 704gtk_gesture_single_set_button(GTK_GESTURE_SINGLE(click_controller_forward), 9); 705g_signal_connect(click_controller_forward, "pressed", G_CALLBACK(on_forward_pressed), webview); 706gtk_widget_add_controller(GTK_WIDGET(webview), click_controller_forward); 707 708stack->add_page(*page); 709if(focus) { 710stack->set_visible_child(*page); 711content_manager->set_last_operated_page(page); 712} 713if(new_window) { 714bool result = stack->signal_detach.emit(page); 715} 716} 717 718PantheraWindow *PantheraWww::make_window() { 719auto window = Gtk::make_managed<PantheraWindow>(this); 720return window; 721} 722 723void PantheraWww::on_startup() { 724bindtextdomain("panthera-www", "./locales"); 725textdomain("panthera-www"); 726Gtk::Application::on_startup(); 727// Get search engines 728std::ifstream search_engines_file_in("search_engines.json"); 729if(search_engines_file_in) { 730std::string search_engines_json((std::istreambuf_iterator<char>(search_engines_file_in)), std::istreambuf_iterator<char>()); 731search_engines_file_in.close(); 732set_search_engines_from_json(search_engines_json); 733} else { 734search_engines_file_in.close(); 735auto empty_json = nlohmann::json::array(); 736std::ofstream search_engines_file_out("search_engines.json"); 737search_engines_file_out << empty_json.dump(4); 738} 739 740// Load settings 741new_tab_page = "about:blank"; 742std::ifstream settings_file_in("settings.json"); 743if(settings_file_in) { 744std::string settings_json((std::istreambuf_iterator<char>(settings_file_in)), std::istreambuf_iterator<char>()); 745settings_file_in.close(); 746auto json = nlohmann::json::parse(settings_json); 747if(json.contains("ntp")) { 748new_tab_page = json["ntp"].get<std::string>(); 749} 750} else { 751settings_file_in.close(); 752auto empty_json = nlohmann::json::object(); 753empty_json["ntp"] = "about:blank"; 754std::ofstream settings_file_out("settings.json"); 755settings_file_out << empty_json.dump(4); 756settings_file_out.close(); 757} 758 759// Load plugins 760std::ifstream plugin_file_in("plugins.json"); 761if(plugin_file_in) { 762std::string plugin_json((std::istreambuf_iterator<char>(plugin_file_in)), std::istreambuf_iterator<char>()); 763plugin_file_in.close(); 764auto json = nlohmann::json::parse(plugin_json); 765for(auto &plugin : json) { 766auto plugin_path = plugin["path"].get<std::string>(); 767//load_plugin(plugin_path); 768} 769} else { 770plugin_file_in.close(); 771auto empty_json = nlohmann::json::array(); 772std::ofstream plugin_file_out("plugins.json"); 773plugin_file_out << empty_json.dump(4); 774plugin_file_out.close(); 775} 776history_manager = std::make_shared<HistoryManager>("history.db"); 777 778// Known bug <https://gitlab.gnome.org/GNOME/epiphany/-/issues/2714>: 779// JS can't veto the application's accelerators using `preventDefault()`. This is 780// not possible in WebKitGTK, or at least I can't find a way to do it. 781 782main_menu = Gio::Menu::create(); 783// File 784auto file_menu = Gio::Menu::create(); 785// New tab 786auto new_tab_action = Gio::SimpleAction::create("new_tab"); 787new_tab_action->signal_activate().connect([this](const Glib::VariantBase&) { 788on_new_tab(nullptr); 789}); 790add_action(new_tab_action); 791set_accels_for_action("app.new_tab", {"<Primary>T"}); 792file_menu->append(_("New _Tab"), "app.new_tab"); 793// Close tab 794auto close_tab_action = Gio::SimpleAction::create("close_tab"); 795close_tab_action->signal_activate().connect([this](const Glib::VariantBase&) { 796auto page = content_manager->get_last_operated_page(); 797if(page) { 798page->close(); 799} 800}); 801add_action(close_tab_action); 802set_accels_for_action("app.close_tab", {"<Primary>W"}); 803file_menu->append(_("_Close Tab"), "app.close_tab"); 804// New window 805auto new_window_action = Gio::SimpleAction::create("new_window"); 806new_window_action->signal_activate().connect([this](const Glib::VariantBase&) { 807on_activate(); 808}); 809add_action(new_window_action); 810set_accels_for_action("app.new_window", {"<Primary>N"}); 811file_menu->append(_("_New Window"), "app.new_window"); 812// Quit 813auto quit_action = Gio::SimpleAction::create("quit"); 814quit_action->signal_activate().connect([this](const Glib::VariantBase&) { 815quit(); 816}); 817add_action(quit_action); 818set_accels_for_action("app.quit", {"<Primary>Q"}); 819file_menu->append(_("_Quit"), "app.quit"); 820 821main_menu->append_submenu(_("_File"), file_menu); 822 823// Go 824auto go_menu = Gio::Menu::create(); 825// Back 826set_accels_for_action("win.go_back", {"<Alt>Left"}); 827go_menu->append(_("_Back"), "win.go_back"); 828// Forward 829set_accels_for_action("win.go_forward", {"<Alt>Right"}); 830go_menu->append(_("_Forward"), "win.go_forward"); 831 832main_menu->append_submenu(_("_Go"), go_menu); 833 834// View 835auto view_menu = Gio::Menu::create(); 836// Reload 837set_accels_for_action("win.reload", {"F5", "<Primary>R"}); 838view_menu->append(_("_Reload"), "win.reload"); 839 840main_menu->append_submenu(_("_View"), view_menu); 841 842set_menubar(main_menu); 843} 844 845void PantheraWww::on_activate() { 846auto window = make_window(); 847window->present(); 848} 849 850void PantheraWww::on_shutdown() { 851Gtk::Application::on_shutdown(); 852} 853 854void PantheraWww::set_search_engines_from_json(const std::string &json_string) { 855auto json = nlohmann::json::parse(json_string); 856Glib::ustring default_search_engine_name; 857for(auto &engine : json) { 858SearchEngine search_engine; 859search_engine.name = engine["name"].get<std::string>(); 860search_engine.url = engine["url"].get<std::string>(); 861search_engines.push_back(search_engine); 862if(engine.contains("default") && engine["default"].get<bool>()) { 863default_search_engine_name = engine["name"].get<std::string>(); 864} 865} 866for(auto &search_engine : search_engines) { 867if(search_engine.name == default_search_engine_name) { 868default_search_engine = &search_engine; 869break; 870} 871} 872} 873 874PantheraWww::PantheraWww() : Gtk::Application("com.roundabout_host.roundabout.PantheraWww", Gio::Application::Flags::NONE) { 875} 876 877Glib::RefPtr<PantheraWww> PantheraWww::create() { 878return Glib::make_refptr_for_instance<PantheraWww>(new PantheraWww()); 879} 880 881void PantheraWww::load_plugin(const std::string &plugin_path) { 882// TODO: needs to be reworked, to work with multi-window 883void *handle = dlopen(plugin_path.c_str(), RTLD_LAZY | RTLD_GLOBAL); 884if(!handle) { 885std::cerr << "Failed to load plugin: " << dlerror() << std::endl; 886return; 887} 888auto entrypoint = (plugin_entrypoint_type)dlsym(handle, "plugin_init"); 889if(!entrypoint) { 890std::cerr << "Failed to find entrypoint in plugin: " << dlerror() << std::endl; 891dlclose(handle); 892return; 893} 894entrypoint(); 895} 896 897PantheraWww::~PantheraWww() = default; 898 899/* 900extern "C" { 901void panthera_log(const char *message) { 902std::cerr << message << std::endl; 903} 904 905void panthera_add_pane(const char *id, const char *label, GtkImage *icon, GtkWidget *pane) { 906auto pane_child = Glib::wrap(pane); 907auto icon_cc = Glib::wrap(icon); 908auto label_cc = Glib::ustring(label); 909auto id_cc = Glib::ustring(id); 910//auto new_pane = Gtk::make_managed<gPanthera::DockablePane>(app->get_layout_manager(), *pane_child, id_cc, label_cc, icon_cc); 911// TODO: Port to multi-window 912//app->get_layout_manager()->add_pane(new_pane); 913} 914} 915*/ 916 917int main(int argc, char *argv[]) { 918gPanthera::init(); 919 920auto app = PantheraWww::create(); 921 922return app->run(argc, argv); 923} 924