BrowserWindow.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779
  1. /*
  2. * Copyright (c) 2021, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2021, networkException <networkexception@serenityos.org>
  4. * Copyright (c) 2021, Sam Atkins <atkinssj@serenityos.org>
  5. * Copyright (c) 2022, the SerenityOS developers.
  6. *
  7. * SPDX-License-Identifier: BSD-2-Clause
  8. */
  9. #include "BrowserWindow.h"
  10. #include "BookmarksBarWidget.h"
  11. #include "Browser.h"
  12. #include "ConsoleWidget.h"
  13. #include "CookieJar.h"
  14. #include "InspectorWidget.h"
  15. #include "Tab.h"
  16. #include <AK/LexicalPath.h>
  17. #include <Applications/Browser/BrowserWindowGML.h>
  18. #include <LibConfig/Client.h>
  19. #include <LibCore/DateTime.h>
  20. #include <LibCore/StandardPaths.h>
  21. #include <LibCore/Stream.h>
  22. #include <LibCore/Version.h>
  23. #include <LibGUI/AboutDialog.h>
  24. #include <LibGUI/Application.h>
  25. #include <LibGUI/Clipboard.h>
  26. #include <LibGUI/Icon.h>
  27. #include <LibGUI/InputBox.h>
  28. #include <LibGUI/Menu.h>
  29. #include <LibGUI/Menubar.h>
  30. #include <LibGUI/MessageBox.h>
  31. #include <LibGUI/Process.h>
  32. #include <LibGUI/SeparatorWidget.h>
  33. #include <LibGUI/Statusbar.h>
  34. #include <LibGUI/TabWidget.h>
  35. #include <LibGUI/ToolbarContainer.h>
  36. #include <LibGUI/Widget.h>
  37. #include <LibGfx/PNGWriter.h>
  38. #include <LibJS/Interpreter.h>
  39. #include <LibWeb/CSS/PreferredColorScheme.h>
  40. #include <LibWeb/Dump.h>
  41. #include <LibWeb/Layout/InitialContainingBlock.h>
  42. #include <LibWeb/Loader/ResourceLoader.h>
  43. #include <LibWebView/OutOfProcessWebView.h>
  44. #include <LibWebView/WebContentClient.h>
  45. namespace Browser {
  46. static String bookmarks_file_path()
  47. {
  48. StringBuilder builder;
  49. builder.append(Core::StandardPaths::config_directory());
  50. builder.append("/bookmarks.json"sv);
  51. return builder.to_string();
  52. }
  53. static String search_engines_file_path()
  54. {
  55. StringBuilder builder;
  56. builder.append(Core::StandardPaths::config_directory());
  57. builder.append("/SearchEngines.json"sv);
  58. return builder.to_string();
  59. }
  60. BrowserWindow::BrowserWindow(CookieJar& cookie_jar, URL url)
  61. : m_cookie_jar(cookie_jar)
  62. , m_window_actions(*this)
  63. {
  64. auto app_icon = GUI::Icon::default_icon("app-browser"sv);
  65. m_bookmarks_bar = Browser::BookmarksBarWidget::construct(Browser::bookmarks_file_path(), true);
  66. resize(730, 560);
  67. set_icon(app_icon.bitmap_for_size(16));
  68. set_title("Browser");
  69. auto& widget = set_main_widget<GUI::Widget>();
  70. widget.load_from_gml(browser_window_gml);
  71. auto& top_line = *widget.find_descendant_of_type_named<GUI::HorizontalSeparator>("top_line");
  72. m_tab_widget = *widget.find_descendant_of_type_named<GUI::TabWidget>("tab_widget");
  73. m_tab_widget->on_tab_count_change = [&top_line](size_t tab_count) {
  74. top_line.set_visible(tab_count > 1);
  75. };
  76. m_tab_widget->on_change = [this](auto& active_widget) {
  77. auto& tab = static_cast<Browser::Tab&>(active_widget);
  78. set_window_title_for_tab(tab);
  79. tab.did_become_active();
  80. };
  81. m_tab_widget->on_middle_click = [](auto& clicked_widget) {
  82. auto& tab = static_cast<Browser::Tab&>(clicked_widget);
  83. tab.on_tab_close_request(tab);
  84. };
  85. m_tab_widget->on_tab_close_click = [](auto& clicked_widget) {
  86. auto& tab = static_cast<Browser::Tab&>(clicked_widget);
  87. tab.on_tab_close_request(tab);
  88. };
  89. m_tab_widget->on_context_menu_request = [](auto& clicked_widget, const GUI::ContextMenuEvent& context_menu_event) {
  90. auto& tab = static_cast<Browser::Tab&>(clicked_widget);
  91. tab.context_menu_requested(context_menu_event.screen_position());
  92. };
  93. m_window_actions.on_create_new_tab = [this] {
  94. create_new_tab(Browser::url_from_user_input(Browser::g_new_tab_url), true);
  95. };
  96. m_window_actions.on_create_new_window = [this] {
  97. GUI::Process::spawn_or_show_error(this, "/bin/Browser"sv);
  98. };
  99. m_window_actions.on_next_tab = [this] {
  100. m_tab_widget->activate_next_tab();
  101. };
  102. m_window_actions.on_previous_tab = [this] {
  103. m_tab_widget->activate_previous_tab();
  104. };
  105. for (size_t i = 0; i <= 7; ++i) {
  106. m_window_actions.on_tabs.append([this, i] {
  107. if (i >= m_tab_widget->tab_count())
  108. return;
  109. m_tab_widget->set_tab_index(i);
  110. });
  111. }
  112. m_window_actions.on_tabs.append([this] {
  113. m_tab_widget->activate_last_tab();
  114. });
  115. m_window_actions.on_about = [this] {
  116. auto app_icon = GUI::Icon::default_icon("app-browser"sv);
  117. GUI::AboutDialog::show("Browser"sv, Core::Version::read_long_version_string(), app_icon.bitmap_for_size(32), this);
  118. };
  119. m_window_actions.on_show_bookmarks_bar = [](auto& action) {
  120. Browser::BookmarksBarWidget::the().set_visible(action.is_checked());
  121. Config::write_bool("Browser"sv, "Preferences"sv, "ShowBookmarksBar"sv, action.is_checked());
  122. };
  123. bool show_bookmarks_bar = Config::read_bool("Browser"sv, "Preferences"sv, "ShowBookmarksBar"sv, true);
  124. m_window_actions.show_bookmarks_bar_action().set_checked(show_bookmarks_bar);
  125. Browser::BookmarksBarWidget::the().set_visible(show_bookmarks_bar);
  126. m_window_actions.on_vertical_tabs = [this](auto& action) {
  127. m_tab_widget->set_tab_position(action.is_checked() ? GUI::TabWidget::TabPosition::Left : GUI::TabWidget::TabPosition::Top);
  128. Config::write_bool("Browser"sv, "Preferences"sv, "VerticalTabs"sv, action.is_checked());
  129. };
  130. bool vertical_tabs = Config::read_bool("Browser"sv, "Preferences"sv, "VerticalTabs"sv, false);
  131. m_window_actions.vertical_tabs_action().set_checked(vertical_tabs);
  132. m_tab_widget->set_tab_position(vertical_tabs ? GUI::TabWidget::TabPosition::Left : GUI::TabWidget::TabPosition::Top);
  133. build_menus();
  134. create_new_tab(move(url), true);
  135. }
  136. void BrowserWindow::build_menus()
  137. {
  138. auto& file_menu = add_menu("&File");
  139. file_menu.add_action(WindowActions::the().create_new_tab_action());
  140. file_menu.add_action(WindowActions::the().create_new_window_action());
  141. auto close_tab_action = GUI::CommonActions::make_close_tab_action([this](auto&) {
  142. active_tab().on_tab_close_request(active_tab());
  143. },
  144. this);
  145. file_menu.add_action(close_tab_action);
  146. file_menu.add_separator();
  147. file_menu.add_action(GUI::CommonActions::make_quit_action([](auto&) {
  148. GUI::Application::the()->quit();
  149. }));
  150. auto& view_menu = add_menu("&View");
  151. view_menu.add_action(WindowActions::the().show_bookmarks_bar_action());
  152. view_menu.add_action(WindowActions::the().vertical_tabs_action());
  153. view_menu.add_separator();
  154. view_menu.add_action(GUI::CommonActions::make_fullscreen_action(
  155. [this](auto&) {
  156. auto& tab = active_tab();
  157. set_fullscreen(!is_fullscreen());
  158. auto is_fullscreen = this->is_fullscreen();
  159. tab_widget().set_bar_visible(!is_fullscreen && tab_widget().children().size() > 1);
  160. tab.m_toolbar_container->set_visible(!is_fullscreen);
  161. tab.m_statusbar->set_visible(!is_fullscreen);
  162. if (is_fullscreen) {
  163. tab.view().set_frame_thickness(0);
  164. } else {
  165. tab.view().set_frame_thickness(2);
  166. }
  167. },
  168. this));
  169. m_go_back_action = GUI::CommonActions::make_go_back_action([this](auto&) { active_tab().go_back(); }, this);
  170. m_go_forward_action = GUI::CommonActions::make_go_forward_action([this](auto&) { active_tab().go_forward(); }, this);
  171. m_go_home_action = GUI::CommonActions::make_go_home_action([this](auto&) { active_tab().load(Browser::url_from_user_input(g_home_url)); }, this);
  172. m_go_home_action->set_status_tip("Go to home page");
  173. m_reload_action = GUI::CommonActions::make_reload_action([this](auto&) { active_tab().reload(); }, this);
  174. m_reload_action->set_status_tip("Reload current page");
  175. auto& go_menu = add_menu("&Go");
  176. go_menu.add_action(*m_go_back_action);
  177. go_menu.add_action(*m_go_forward_action);
  178. go_menu.add_action(*m_go_home_action);
  179. go_menu.add_separator();
  180. go_menu.add_action(*m_reload_action);
  181. m_copy_selection_action = GUI::CommonActions::make_copy_action([this](auto&) {
  182. auto& tab = active_tab();
  183. auto selected_text = tab.view().selected_text();
  184. if (!selected_text.is_empty())
  185. GUI::Clipboard::the().set_plain_text(selected_text);
  186. });
  187. m_select_all_action = GUI::CommonActions::make_select_all_action([this](auto&) {
  188. active_tab().view().select_all();
  189. });
  190. m_view_source_action = GUI::Action::create(
  191. "View &Source", { Mod_Ctrl, Key_U }, g_icon_bag.code, [this](auto&) {
  192. active_tab().view().get_source();
  193. },
  194. this);
  195. m_view_source_action->set_status_tip("View source code of the current page");
  196. m_inspect_dom_tree_action = GUI::Action::create(
  197. "Inspect &DOM Tree", { Mod_None, Key_F12 }, g_icon_bag.dom_tree, [this](auto&) {
  198. active_tab().show_inspector_window(Tab::InspectorTarget::Document);
  199. },
  200. this);
  201. m_inspect_dom_tree_action->set_status_tip("Open inspector window for this page");
  202. m_inspect_dom_node_action = GUI::Action::create(
  203. "&Inspect Element", g_icon_bag.inspect, [this](auto&) {
  204. active_tab().show_inspector_window(Tab::InspectorTarget::HoveredElement);
  205. },
  206. this);
  207. m_inspect_dom_node_action->set_status_tip("Open inspector for this element");
  208. m_take_visible_screenshot_action = GUI::Action::create(
  209. "Take &Visible Screenshot"sv, g_icon_bag.filetype_image, [this](auto&) {
  210. if (auto result = take_screenshot(ScreenshotType::Visible); result.is_error())
  211. GUI::MessageBox::show_error(this, String::formatted("{}", result.error()));
  212. },
  213. this);
  214. m_take_visible_screenshot_action->set_status_tip("Save a screenshot of the visible portion of the current tab to the Downloads directory"sv);
  215. m_take_full_screenshot_action = GUI::Action::create(
  216. "Take &Full Screenshot"sv, g_icon_bag.filetype_image, [this](auto&) {
  217. if (auto result = take_screenshot(ScreenshotType::Full); result.is_error())
  218. GUI::MessageBox::show_error(this, String::formatted("{}", result.error()));
  219. },
  220. this);
  221. m_take_full_screenshot_action->set_status_tip("Save a screenshot of the entirety of the current tab to the Downloads directory"sv);
  222. auto& inspect_menu = add_menu("&Inspect");
  223. inspect_menu.add_action(*m_view_source_action);
  224. inspect_menu.add_action(*m_inspect_dom_tree_action);
  225. auto js_console_action = GUI::Action::create(
  226. "Open &JS Console", { Mod_Ctrl, Key_I }, g_icon_bag.filetype_javascript, [this](auto&) {
  227. active_tab().show_console_window();
  228. },
  229. this);
  230. js_console_action->set_status_tip("Open JavaScript console for this page");
  231. inspect_menu.add_action(js_console_action);
  232. auto storage_window_action = GUI::Action::create(
  233. "Open S&torage Inspector", g_icon_bag.cookie, [this](auto&) {
  234. active_tab().show_storage_inspector();
  235. },
  236. this);
  237. storage_window_action->set_status_tip("Show Storage inspector for this page");
  238. inspect_menu.add_action(storage_window_action);
  239. auto& settings_menu = add_menu("&Settings");
  240. m_change_homepage_action = GUI::Action::create(
  241. "Set Homepage URL...", g_icon_bag.go_home, [this](auto&) {
  242. auto homepage_url = Config::read_string("Browser"sv, "Preferences"sv, "Home"sv, "about:blank"sv);
  243. if (GUI::InputBox::show(this, homepage_url, "Enter URL"sv, "Change homepage URL"sv) == GUI::InputBox::ExecResult::OK) {
  244. if (URL(homepage_url).is_valid()) {
  245. Config::write_string("Browser"sv, "Preferences"sv, "Home"sv, homepage_url);
  246. Browser::g_home_url = homepage_url;
  247. } else {
  248. GUI::MessageBox::show_error(this, "The URL you have entered is not valid"sv);
  249. }
  250. }
  251. },
  252. this);
  253. settings_menu.add_action(*m_change_homepage_action);
  254. auto load_search_engines_result = load_search_engines(settings_menu);
  255. if (load_search_engines_result.is_error()) {
  256. dbgln("Failed to open search-engines file: {}", load_search_engines_result.error());
  257. }
  258. auto& color_scheme_menu = settings_menu.add_submenu("&Color Scheme");
  259. color_scheme_menu.set_icon(g_icon_bag.color_chooser);
  260. {
  261. auto current_setting = Web::CSS::preferred_color_scheme_from_string(Config::read_string("Browser"sv, "Preferences"sv, "ColorScheme"sv, "auto"sv));
  262. m_color_scheme_actions.set_exclusive(true);
  263. auto add_color_scheme_action = [&](auto& name, Web::CSS::PreferredColorScheme preference_value) {
  264. auto action = GUI::Action::create_checkable(
  265. name, [=, this](auto&) {
  266. Config::write_string("Browser"sv, "Preferences"sv, "ColorScheme"sv, Web::CSS::preferred_color_scheme_to_string(preference_value));
  267. active_tab().view().set_preferred_color_scheme(preference_value);
  268. },
  269. this);
  270. if (current_setting == preference_value)
  271. action->set_checked(true);
  272. color_scheme_menu.add_action(action);
  273. m_color_scheme_actions.add_action(action);
  274. };
  275. add_color_scheme_action("Follow system theme", Web::CSS::PreferredColorScheme::Auto);
  276. add_color_scheme_action("Light", Web::CSS::PreferredColorScheme::Light);
  277. add_color_scheme_action("Dark", Web::CSS::PreferredColorScheme::Dark);
  278. }
  279. settings_menu.add_separator();
  280. auto open_settings_action = GUI::Action::create("Browser &Settings", Gfx::Bitmap::try_load_from_file("/res/icons/16x16/settings.png"sv).release_value_but_fixme_should_propagate_errors(),
  281. [this](auto&) {
  282. GUI::Process::spawn_or_show_error(this, "/bin/BrowserSettings"sv);
  283. });
  284. settings_menu.add_action(move(open_settings_action));
  285. auto& debug_menu = add_menu("&Debug");
  286. debug_menu.add_action(GUI::Action::create(
  287. "Dump &DOM Tree", g_icon_bag.dom_tree, [this](auto&) {
  288. active_tab().view().debug_request("dump-dom-tree");
  289. },
  290. this));
  291. debug_menu.add_action(GUI::Action::create(
  292. "Dump &Layout Tree", g_icon_bag.layout, [this](auto&) {
  293. active_tab().view().debug_request("dump-layout-tree");
  294. },
  295. this));
  296. debug_menu.add_action(GUI::Action::create(
  297. "Dump S&tacking Context Tree", g_icon_bag.layers, [this](auto&) {
  298. active_tab().view().debug_request("dump-stacking-context-tree");
  299. },
  300. this));
  301. debug_menu.add_action(GUI::Action::create(
  302. "Dump &Style Sheets", g_icon_bag.filetype_css, [this](auto&) {
  303. active_tab().view().debug_request("dump-style-sheets");
  304. },
  305. this));
  306. debug_menu.add_action(GUI::Action::create("Dump &History", { Mod_Ctrl, Key_H }, g_icon_bag.history, [this](auto&) {
  307. active_tab().m_history.dump();
  308. }));
  309. debug_menu.add_action(GUI::Action::create("Dump C&ookies", g_icon_bag.cookie, [this](auto&) {
  310. auto& tab = active_tab();
  311. if (tab.on_dump_cookies)
  312. tab.on_dump_cookies();
  313. }));
  314. debug_menu.add_action(GUI::Action::create("Dump Loc&al Storage", g_icon_bag.local_storage, [this](auto&) {
  315. active_tab().view().debug_request("dump-local-storage");
  316. }));
  317. debug_menu.add_separator();
  318. auto line_box_borders_action = GUI::Action::create_checkable(
  319. "Line &Box Borders", [this](auto& action) {
  320. active_tab().view().debug_request("set-line-box-borders", action.is_checked() ? "on" : "off");
  321. },
  322. this);
  323. line_box_borders_action->set_checked(false);
  324. debug_menu.add_action(line_box_borders_action);
  325. debug_menu.add_separator();
  326. debug_menu.add_action(GUI::Action::create("Collect &Garbage", { Mod_Ctrl | Mod_Shift, Key_G }, g_icon_bag.trash_can, [this](auto&) {
  327. active_tab().view().debug_request("collect-garbage");
  328. }));
  329. debug_menu.add_action(GUI::Action::create("Clear &Cache", { Mod_Ctrl | Mod_Shift, Key_C }, g_icon_bag.clear_cache, [this](auto&) {
  330. active_tab().view().debug_request("clear-cache");
  331. }));
  332. m_user_agent_spoof_actions.set_exclusive(true);
  333. auto& spoof_user_agent_menu = debug_menu.add_submenu("Spoof &User Agent");
  334. m_disable_user_agent_spoofing = GUI::Action::create_checkable("Disabled", [this](auto&) {
  335. active_tab().view().debug_request("spoof-user-agent", Web::default_user_agent);
  336. });
  337. m_disable_user_agent_spoofing->set_status_tip(Web::default_user_agent);
  338. spoof_user_agent_menu.add_action(*m_disable_user_agent_spoofing);
  339. spoof_user_agent_menu.set_icon(g_icon_bag.spoof);
  340. m_user_agent_spoof_actions.add_action(*m_disable_user_agent_spoofing);
  341. m_disable_user_agent_spoofing->set_checked(true);
  342. auto add_user_agent = [this, &spoof_user_agent_menu](auto& name, auto& user_agent) {
  343. auto action = GUI::Action::create_checkable(name, [this, user_agent](auto&) {
  344. active_tab().view().debug_request("spoof-user-agent", user_agent);
  345. });
  346. action->set_status_tip(user_agent);
  347. spoof_user_agent_menu.add_action(action);
  348. m_user_agent_spoof_actions.add_action(action);
  349. };
  350. add_user_agent("Chrome Linux Desktop", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.128 Safari/537.36");
  351. add_user_agent("Firefox Linux Desktop", "Mozilla/5.0 (X11; Linux i686; rv:87.0) Gecko/20100101 Firefox/87.0");
  352. add_user_agent("Safari macOS Desktop", "Mozilla/5.0 (Macintosh; Intel Mac OS X 11_2_3) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0.3 Safari/605.1.15");
  353. add_user_agent("Chrome Android Mobile", "Mozilla/5.0 (Linux; Android 10) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.66 Mobile Safari/537.36");
  354. add_user_agent("Firefox Android Mobile", "Mozilla/5.0 (Android 11; Mobile; rv:68.0) Gecko/68.0 Firefox/86.0");
  355. add_user_agent("Safari iOS Mobile", "Mozilla/5.0 (iPhone; CPU iPhone OS 14_4_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0 Mobile/15E148 Safari/604.1");
  356. auto custom_user_agent = GUI::Action::create_checkable("Custom...", [this](auto& action) {
  357. String user_agent;
  358. if (GUI::InputBox::show(this, user_agent, "Enter User Agent:"sv, "Custom User Agent"sv) != GUI::InputBox::ExecResult::OK || user_agent.is_empty() || user_agent.is_null()) {
  359. m_disable_user_agent_spoofing->activate();
  360. return;
  361. }
  362. active_tab().view().debug_request("spoof-user-agent", user_agent);
  363. action.set_status_tip(user_agent);
  364. });
  365. spoof_user_agent_menu.add_action(custom_user_agent);
  366. m_user_agent_spoof_actions.add_action(custom_user_agent);
  367. debug_menu.add_separator();
  368. auto scripting_enabled_action = GUI::Action::create_checkable(
  369. "Enable Scripting", [this](auto& action) {
  370. active_tab().view().debug_request("scripting", action.is_checked() ? "on" : "off");
  371. },
  372. this);
  373. scripting_enabled_action->set_checked(true);
  374. debug_menu.add_action(scripting_enabled_action);
  375. auto same_origin_policy_action = GUI::Action::create_checkable(
  376. "Enable Same Origin &Policy", [this](auto& action) {
  377. active_tab().view().debug_request("same-origin-policy", action.is_checked() ? "on" : "off");
  378. },
  379. this);
  380. same_origin_policy_action->set_checked(false);
  381. debug_menu.add_action(same_origin_policy_action);
  382. auto& help_menu = add_menu("&Help");
  383. help_menu.add_action(GUI::CommonActions::make_command_palette_action(this));
  384. help_menu.add_action(WindowActions::the().about_action());
  385. }
  386. ErrorOr<void> BrowserWindow::load_search_engines(GUI::Menu& settings_menu)
  387. {
  388. m_search_engine_actions.set_exclusive(true);
  389. auto& search_engine_menu = settings_menu.add_submenu("&Search Engine");
  390. search_engine_menu.set_icon(g_icon_bag.find);
  391. bool search_engine_set = false;
  392. m_disable_search_engine_action = GUI::Action::create_checkable(
  393. "Disable", [](auto&) {
  394. g_search_engine = {};
  395. Config::write_string("Browser"sv, "Preferences"sv, "SearchEngine"sv, g_search_engine);
  396. },
  397. this);
  398. search_engine_menu.add_action(*m_disable_search_engine_action);
  399. m_search_engine_actions.add_action(*m_disable_search_engine_action);
  400. m_disable_search_engine_action->set_checked(true);
  401. auto search_engines_file = TRY(Core::Stream::File::open(Browser::search_engines_file_path(), Core::Stream::OpenMode::Read));
  402. auto file_size = TRY(search_engines_file->size());
  403. auto buffer = TRY(ByteBuffer::create_uninitialized(file_size));
  404. if (search_engines_file->read_or_error(buffer)) {
  405. StringView buffer_contents { buffer.bytes() };
  406. if (auto json = TRY(JsonValue::from_string(buffer_contents)); json.is_array()) {
  407. auto json_array = json.as_array();
  408. for (auto& json_item : json_array.values()) {
  409. if (!json_item.is_object())
  410. continue;
  411. auto search_engine = json_item.as_object();
  412. auto name = search_engine.get("title"sv).to_string();
  413. auto url_format = search_engine.get("url_format"sv).to_string();
  414. auto action = GUI::Action::create_checkable(
  415. name, [&, url_format](auto&) {
  416. g_search_engine = url_format;
  417. Config::write_string("Browser"sv, "Preferences"sv, "SearchEngine"sv, g_search_engine);
  418. },
  419. this);
  420. search_engine_menu.add_action(action);
  421. m_search_engine_actions.add_action(action);
  422. if (g_search_engine == url_format) {
  423. action->set_checked(true);
  424. search_engine_set = true;
  425. }
  426. action->set_status_tip(url_format);
  427. }
  428. }
  429. }
  430. auto custom_search_engine_action = GUI::Action::create_checkable("Custom...", [&](auto& action) {
  431. String search_engine;
  432. if (GUI::InputBox::show(this, search_engine, "Enter URL template:"sv, "Custom Search Engine"sv, "https://host/search?q={}"sv) != GUI::InputBox::ExecResult::OK || search_engine.is_empty()) {
  433. m_disable_search_engine_action->activate();
  434. return;
  435. }
  436. auto argument_count = search_engine.count("{}"sv);
  437. if (argument_count != 1) {
  438. GUI::MessageBox::show(this, "Invalid format, must contain '{}' once!"sv, "Error"sv, GUI::MessageBox::Type::Error);
  439. m_disable_search_engine_action->activate();
  440. return;
  441. }
  442. g_search_engine = search_engine;
  443. Config::write_string("Browser"sv, "Preferences"sv, "SearchEngine"sv, g_search_engine);
  444. action.set_status_tip(search_engine);
  445. });
  446. search_engine_menu.add_action(custom_search_engine_action);
  447. m_search_engine_actions.add_action(custom_search_engine_action);
  448. if (!search_engine_set && !g_search_engine.is_empty()) {
  449. custom_search_engine_action->set_checked(true);
  450. custom_search_engine_action->set_status_tip(g_search_engine);
  451. }
  452. return {};
  453. }
  454. GUI::TabWidget& BrowserWindow::tab_widget()
  455. {
  456. return *m_tab_widget;
  457. }
  458. Tab& BrowserWindow::active_tab()
  459. {
  460. return verify_cast<Tab>(*tab_widget().active_widget());
  461. }
  462. void BrowserWindow::set_window_title_for_tab(Tab const& tab)
  463. {
  464. auto& title = tab.title();
  465. auto url = tab.url();
  466. set_title(String::formatted("{} - Browser", title.is_empty() ? url.to_string() : title));
  467. }
  468. void BrowserWindow::create_new_tab(URL url, bool activate)
  469. {
  470. auto& new_tab = m_tab_widget->add_tab<Browser::Tab>("New tab", *this);
  471. m_tab_widget->set_bar_visible(!is_fullscreen() && m_tab_widget->children().size() > 1);
  472. new_tab.on_title_change = [this, &new_tab](auto& title) {
  473. m_tab_widget->set_tab_title(new_tab, title);
  474. if (m_tab_widget->active_widget() == &new_tab)
  475. set_window_title_for_tab(new_tab);
  476. };
  477. new_tab.on_favicon_change = [this, &new_tab](auto& bitmap) {
  478. m_tab_widget->set_tab_icon(new_tab, &bitmap);
  479. };
  480. new_tab.on_tab_open_request = [this](auto& url) {
  481. create_new_tab(url, true);
  482. };
  483. new_tab.on_tab_close_request = [this](auto& tab) {
  484. m_tab_widget->deferred_invoke([this, &tab] {
  485. m_tab_widget->remove_tab(tab);
  486. m_tab_widget->set_bar_visible(!is_fullscreen() && m_tab_widget->children().size() > 1);
  487. if (m_tab_widget->children().is_empty())
  488. close();
  489. });
  490. };
  491. new_tab.on_tab_close_other_request = [this](auto& tab) {
  492. m_tab_widget->deferred_invoke([this, &tab] {
  493. m_tab_widget->remove_all_tabs_except(tab);
  494. VERIFY(m_tab_widget->children().size() == 1);
  495. m_tab_widget->set_bar_visible(false);
  496. });
  497. };
  498. new_tab.on_get_cookie = [this](auto& url, auto source) -> String {
  499. return m_cookie_jar.get_cookie(url, source);
  500. };
  501. new_tab.on_set_cookie = [this](auto& url, auto& cookie, auto source) {
  502. m_cookie_jar.set_cookie(url, cookie, source);
  503. };
  504. new_tab.on_dump_cookies = [this]() {
  505. m_cookie_jar.dump_cookies();
  506. };
  507. new_tab.on_update_cookie = [this](auto const& url, auto cookie) {
  508. m_cookie_jar.update_cookie(url, move(cookie));
  509. };
  510. new_tab.on_get_cookies_entries = [this]() {
  511. return m_cookie_jar.get_all_cookies();
  512. };
  513. new_tab.on_get_local_storage_entries = [this]() {
  514. return active_tab().view().get_local_storage_entries();
  515. };
  516. new_tab.on_get_session_storage_entries = [this]() {
  517. return active_tab().view().get_session_storage_entries();
  518. };
  519. new_tab.on_take_screenshot = [this]() {
  520. return active_tab().view().take_screenshot();
  521. };
  522. new_tab.webdriver_endpoints().on_scroll_element_into_view = [this](i32 element_id) {
  523. active_tab().view().scroll_element_into_view(element_id);
  524. };
  525. new_tab.webdriver_endpoints().on_get_active_documents_type = [this]() {
  526. return active_tab().view().get_active_documents_type();
  527. };
  528. new_tab.webdriver_endpoints().on_get_computed_value_for_element = [this](i32 element_id, String const& property_name) {
  529. return active_tab().view().get_computed_value_for_element(element_id, property_name);
  530. };
  531. new_tab.webdriver_endpoints().on_get_element_text = [this](i32 element_id) {
  532. return active_tab().view().get_element_text(element_id);
  533. };
  534. new_tab.webdriver_endpoints().on_get_element_tag_name = [this](i32 element_id) {
  535. return active_tab().view().get_element_tag_name(element_id);
  536. };
  537. new_tab.webdriver_endpoints().on_get_element_rect = [this](i32 element_id) {
  538. return active_tab().view().get_element_rect(element_id);
  539. };
  540. new_tab.webdriver_endpoints().on_is_element_enabled = [this](i32 element_id) {
  541. return active_tab().view().is_element_enabled(element_id);
  542. };
  543. new_tab.webdriver_endpoints().on_serialize_source = [this]() {
  544. return active_tab().view().serialize_source();
  545. };
  546. new_tab.webdriver_endpoints().on_execute_script = [this](String const& body, Vector<String> const& json_arguments, Optional<u64> const& timeout, bool async) {
  547. return active_tab().view().webdriver_execute_script(body, json_arguments, timeout, async);
  548. };
  549. new_tab.webdriver_endpoints().on_take_element_screenshot = [this](i32 element_id) {
  550. return active_tab().view().take_element_screenshot(element_id);
  551. };
  552. new_tab.load(url);
  553. dbgln_if(SPAM_DEBUG, "Added new tab {:p}, loading {}", &new_tab, url);
  554. if (activate)
  555. m_tab_widget->set_active_widget(&new_tab);
  556. }
  557. void BrowserWindow::content_filters_changed()
  558. {
  559. tab_widget().for_each_child_of_type<Browser::Tab>([](auto& tab) {
  560. tab.content_filters_changed();
  561. return IterationDecision::Continue;
  562. });
  563. }
  564. void BrowserWindow::proxy_mappings_changed()
  565. {
  566. tab_widget().for_each_child_of_type<Browser::Tab>([](auto& tab) {
  567. tab.proxy_mappings_changed();
  568. return IterationDecision::Continue;
  569. });
  570. }
  571. void BrowserWindow::config_string_did_change(String const& domain, String const& group, String const& key, String const& value)
  572. {
  573. if (domain != "Browser")
  574. return;
  575. if (group == "Preferences") {
  576. if (key == "SearchEngine")
  577. Browser::g_search_engine = value;
  578. else if (key == "Home")
  579. Browser::g_home_url = value;
  580. else if (key == "NewTab")
  581. Browser::g_new_tab_url = value;
  582. } else if (group.starts_with("Proxy:"sv)) {
  583. dbgln("Proxy mapping changed: {}/{} = {}", group, key, value);
  584. auto proxy_spec = group.substring_view(6);
  585. auto existing_proxy = Browser::g_proxies.find(proxy_spec);
  586. if (existing_proxy.is_end())
  587. Browser::g_proxies.append(proxy_spec);
  588. Browser::g_proxy_mappings.set(key, existing_proxy.index());
  589. proxy_mappings_changed();
  590. }
  591. // TODO: ColorScheme
  592. }
  593. void BrowserWindow::config_bool_did_change(String const& domain, String const& group, String const& key, bool value)
  594. {
  595. dbgln("{} {} {} {}", domain, group, key, value);
  596. if (domain != "Browser" || group != "Preferences")
  597. return;
  598. if (key == "ShowBookmarksBar") {
  599. m_window_actions.show_bookmarks_bar_action().set_checked(value);
  600. Browser::BookmarksBarWidget::the().set_visible(value);
  601. } else if (key == "EnableContentFilters") {
  602. Browser::g_content_filters_enabled = value;
  603. content_filters_changed();
  604. }
  605. // NOTE: CloseDownloadWidgetOnFinish is read each time in DownloadWindow
  606. }
  607. void BrowserWindow::broadcast_window_position(Gfx::IntPoint const& position)
  608. {
  609. tab_widget().for_each_child_of_type<Browser::Tab>([&](auto& tab) {
  610. tab.window_position_changed(position);
  611. return IterationDecision::Continue;
  612. });
  613. }
  614. void BrowserWindow::broadcast_window_size(Gfx::IntSize const& size)
  615. {
  616. tab_widget().for_each_child_of_type<Browser::Tab>([&](auto& tab) {
  617. tab.window_size_changed(size);
  618. return IterationDecision::Continue;
  619. });
  620. }
  621. void BrowserWindow::event(Core::Event& event)
  622. {
  623. switch (event.type()) {
  624. case GUI::Event::Move:
  625. broadcast_window_position(static_cast<GUI::MoveEvent&>(event).position());
  626. break;
  627. case GUI::Event::Resize:
  628. broadcast_window_size(static_cast<GUI::ResizeEvent&>(event).size());
  629. break;
  630. default:
  631. break;
  632. }
  633. Window::event(event);
  634. }
  635. ErrorOr<void> BrowserWindow::take_screenshot(ScreenshotType type)
  636. {
  637. if (!active_tab().on_take_screenshot)
  638. return {};
  639. Gfx::ShareableBitmap bitmap;
  640. switch (type) {
  641. case ScreenshotType::Visible:
  642. bitmap = active_tab().on_take_screenshot();
  643. break;
  644. case ScreenshotType::Full:
  645. bitmap = active_tab().view().take_document_screenshot();
  646. break;
  647. }
  648. if (!bitmap.is_valid())
  649. return Error::from_string_view("Failed to take a screenshot of the current tab"sv);
  650. LexicalPath path { Core::StandardPaths::downloads_directory() };
  651. path = path.append(Core::DateTime::now().to_string("screenshot-%Y-%m-%d-%H-%M-%S.png"sv));
  652. auto encoded = Gfx::PNGWriter::encode(*bitmap.bitmap());
  653. auto screenshot_file = TRY(Core::Stream::File::open(path.string(), Core::Stream::OpenMode::Write));
  654. TRY(screenshot_file->write(encoded));
  655. return {};
  656. }
  657. }