diff options
| author | Akshay Nair <phenax5@gmail.com> | 2025-03-23 19:48:53 +0530 |
|---|---|---|
| committer | Akshay Nair <phenax5@gmail.com> | 2025-03-23 21:47:03 +0530 |
| commit | 346c16b4e2ea26f47e0e370a490b7794492a9ebb (patch) | |
| tree | 277a30ac8b0c82a9c9736985385d0d150a55fcb5 | |
| parent | 9cc72e8ea9f59f9a9627d05528d54a559ebd412c (diff) | |
| download | null-browser-346c16b4e2ea26f47e0e370a490b7794492a9ebb.tar.gz null-browser-346c16b4e2ea26f47e0e370a490b7794492a9ebb.zip | |
Apply clang-tidy suggestions
33 files changed, 666 insertions, 686 deletions
diff --git a/.clang-tidy b/.clang-tidy index d948960..b4cca2b 100644 --- a/.clang-tidy +++ b/.clang-tidy @@ -1,24 +1,33 @@ --- +UseColor: true + Checks: > - bugprone-* - clang-analyzer-* - cppcoreguidelines-* - modernize-* - performance-* - readability-* - misc-* - -modernize-use-trailing-return-type - -cppcoreguidelines-pro-bounds-pointer-arithmetic - -cppcoreguidelines-avoid-magic-numbers + -* + , readability-* + , bugprone-* + , clang-analyzer-* + , performance-* + , modernize-* + , misc-const-correctness + , -modernize-use-trailing-return-type + , -readability-magic-numbers + , -readability-braces-around-statements + , -readability-convert-member-functions-to-static + , -readability-implicit-bool-conversion + , -bugprone-easily-swappable-parameters + +# , cppcoreguidelines-owning-memory +# , cppcoreguidelines-* +# , misc-* WarningsAsErrors: > bugprone-* - clang-analyzer-* - cppcoreguidelines-* - modernize-* - performance-* + , clang-analyzer-* + , modernize-* + , performance-* + +HeaderFilterRegex: '^src/.*$' -HeaderFilterRegex: '' HeaderFileExtensions: - h - hpp @@ -27,10 +36,15 @@ ImplementationFileExtensions: - cpp CheckOptions: + readability-identifier-naming.VariableCase: lower_case + readability-identifier-naming.FunctionCase: lower_case + readability-identifier-naming.MemberCase: lower_case + readability-identifier-naming.MethodCase: lower_case + readability-identifier-naming.ParameterCase: lower_case modernize-use-nullptr.CheckSmartPointers: true modernize-use-nullptr.IgnoreMacros: false # Use 'auto' when it improves readability - modernize-use-auto.MinTypeNameLength: 5 + modernize-use-auto.MinTypeNameLength: 8 readability-container-size-empty.IgnoreQtContainers: true # Performance optimizations performance-noexcept-move-constructor.StrictMode: true @@ -28,5 +28,5 @@ build-release: check: clang-format -i ./src/**/*.{hpp,cpp} - clang-tidy ./src/**/*.{hpp,cpp} + clang-tidy --config-file=.clang-tidy ./src/**/*.{hpp,cpp} @@ -3,14 +3,14 @@ - [X] Keybindings (lua api) - [X] Modal keys - [X] event loop for async work -- [ ] example: trigger dmenu for simple selection -- [ ] Config loading and runtime path +- [X] example: trigger dmenu for simple selection +- [X] Fix segfault on quit - [ ] Tab history navigation - [ ] Tab next/prev - [ ] Get tab list api - [ ] Assign ID to each tab (reference in lua api) - [ ] Tab select by id -- [ ] Fix segfault on quit +- [ ] Config loading and runtime path - [ ] Multi-window ** Next diff --git a/spec/InputMediatorSpec.cpp b/spec/InputMediatorSpec.cpp index b48b008..9052cc6 100644 --- a/spec/InputMediatorSpec.cpp +++ b/spec/InputMediatorSpec.cpp @@ -1,8 +1,6 @@ -#include "InputMediator.hpp" -#include "LuaRuntime.hpp" #include "testUtils.h" -#include "widgets/WebViewStack.hpp" +// NOLINTBEGIN class InputMediatorSpec : public QObject { Q_OBJECT @@ -11,3 +9,4 @@ private slots: QTEST_REGISTER(InputMediatorSpec) #include "InputMediatorSpec.moc" +// NOLINTEND diff --git a/spec/KeySeqParserSpec.cpp b/spec/KeySeqParserSpec.cpp index 7ce2a4a..dcf6140 100644 --- a/spec/KeySeqParserSpec.cpp +++ b/spec/KeySeqParserSpec.cpp @@ -4,6 +4,7 @@ #include "keymap/KeySeqParser.hpp" +// NOLINTBEGIN class KeySeqParserSpec : public QObject { Q_OBJECT @@ -15,12 +16,12 @@ private slots: QList<KeyChord> keys = parser.parse("<C-tab><c-tAb><c-Tab>"); - QList<KeyChord> expectedKeys = { + QList<KeyChord> expected_keys = { {.mod = Qt::ControlModifier, .key = Qt::Key_Tab}, {.mod = Qt::ControlModifier, .key = Qt::Key_Tab}, {.mod = Qt::ControlModifier, .key = Qt::Key_Tab}, }; - QCOMPARE(keys, expectedKeys); + QCOMPARE(keys, expected_keys); } context("when input contains individual keys"); @@ -29,7 +30,7 @@ private slots: QList<KeyChord> keys = parser.parse("ab<c><s><sPace><tab><esC>z"); - QList<KeyChord> expectedKeys = { + QList<KeyChord> expected_keys = { {.mod = Qt::NoModifier, .key = Qt::Key_A}, {.mod = Qt::NoModifier, .key = Qt::Key_B}, {.mod = Qt::NoModifier, .key = Qt::Key_C}, @@ -39,10 +40,11 @@ private slots: {.mod = Qt::NoModifier, .key = Qt::Key_Escape}, {.mod = Qt::NoModifier, .key = Qt::Key_Z}, }; - QCOMPARE(keys, expectedKeys); + QCOMPARE(keys, expected_keys); } } }; QTEST_REGISTER(KeySeqParserSpec) #include "KeySeqParserSpec.moc" +// NOLINTEND diff --git a/spec/KeymapEvaluatorSpec.cpp b/spec/KeymapEvaluatorSpec.cpp index 8e8ba87..0483e99 100644 --- a/spec/KeymapEvaluatorSpec.cpp +++ b/spec/KeymapEvaluatorSpec.cpp @@ -3,6 +3,7 @@ #include "keymap/KeymapEvaluator.hpp" +// NOLINTBEGIN class KeymapEvaluatorSpec : public QObject { Q_OBJECT @@ -10,112 +11,121 @@ private slots: void test_evaluate_single_key_chord() { context("when the key sequence is mapped"); it("calls mapping") { - int keymapWasCalled = false; + auto keymap_was_called = false; KeymapEvaluator evaluator; - evaluator.addKeymap(KeyMode::Normal, "<c-t>", - [&keymapWasCalled]() { keymapWasCalled = true; }); + evaluator.add_keymap(KeyMode::Normal, "<c-t>", [&keymap_was_called]() { + keymap_was_called = true; + }); evaluator.evaluate(Qt::ControlModifier, Qt::Key_T); - QVERIFY(keymapWasCalled); + QVERIFY(keymap_was_called); } context("when the key sequence is not mapped"); it("does not call mapping") { - int keymapWasCalled = false; + auto keymap_was_called = false; KeymapEvaluator evaluator; - evaluator.addKeymap(KeyMode::Normal, "<c-t>", - [&keymapWasCalled]() { keymapWasCalled = true; }); + evaluator.add_keymap(KeyMode::Normal, "<c-t>", [&keymap_was_called]() { + keymap_was_called = true; + }); evaluator.evaluate(Qt::ControlModifier, Qt::Key_K); - QVERIFY(NOT keymapWasCalled); + QVERIFY(NOT keymap_was_called); } } void test_evaluate_multi_key_sequence() { context("when the full key sequence is mapped"); it("calls mapping") { - int keymapWasCalled = false; + auto keymap_was_called = false; KeymapEvaluator evaluator; - evaluator.addKeymap(KeyMode::Normal, "<c-t>a", - [&keymapWasCalled]() { keymapWasCalled = true; }); + evaluator.add_keymap(KeyMode::Normal, "<c-t>a", [&keymap_was_called]() { + keymap_was_called = true; + }); evaluator.evaluate(Qt::ControlModifier, Qt::Key_T); evaluator.evaluate(Qt::NoModifier, Qt::Key_A); - QVERIFY(keymapWasCalled); + QVERIFY(keymap_was_called); } context("when only part of a mapped key sequence is entered"); it("does not call mapping") { - int keymapWasCalled = false; + auto keymap_was_called = false; KeymapEvaluator evaluator; - evaluator.addKeymap(KeyMode::Normal, "<c-t>a", - [&keymapWasCalled]() { keymapWasCalled = true; }); + evaluator.add_keymap(KeyMode::Normal, "<c-t>a", [&keymap_was_called]() { + keymap_was_called = true; + }); evaluator.evaluate(Qt::ControlModifier, Qt::Key_T); - QVERIFY(NOT keymapWasCalled); + QVERIFY(NOT keymap_was_called); } context("when the key sequence is not mapped"); it("does not call mapping") { - int keymapWasCalled = false; + auto keymap_was_called = false; KeymapEvaluator evaluator; - evaluator.addKeymap(KeyMode::Normal, "<c-t>a", - [&keymapWasCalled]() { keymapWasCalled = true; }); + evaluator.add_keymap(KeyMode::Normal, "<c-t>a", [&keymap_was_called]() { + keymap_was_called = true; + }); evaluator.evaluate(Qt::ControlModifier, Qt::Key_K); - QVERIFY(NOT keymapWasCalled); + QVERIFY(NOT keymap_was_called); } context("when the key sequence is not mapped"); it("does not call mapping") { - int keymapWasCalled = false; + auto keymap_was_called = false; KeymapEvaluator evaluator; - evaluator.addKeymap(KeyMode::Normal, "<c-t>a", - [&keymapWasCalled]() { keymapWasCalled = true; }); + evaluator.add_keymap(KeyMode::Normal, "<c-t>a", [&keymap_was_called]() { + keymap_was_called = true; + }); evaluator.evaluate(Qt::ControlModifier, Qt::Key_T); evaluator.evaluate(Qt::NoModifier, Qt::Key_B); - QVERIFY(NOT keymapWasCalled); + QVERIFY(NOT keymap_was_called); } context("when an incorrect sequence is entered before the correct one"); it("calls mapping") { - int keymapWasCalled = false; + auto keymap_was_called = false; KeymapEvaluator evaluator; - evaluator.addKeymap(KeyMode::Normal, "<c-t>a", - [&keymapWasCalled]() { keymapWasCalled = true; }); + evaluator.add_keymap(KeyMode::Normal, "<c-t>a", [&keymap_was_called]() { + keymap_was_called = true; + }); evaluator.evaluate(Qt::ControlModifier, Qt::Key_T); evaluator.evaluate(Qt::NoModifier, Qt::Key_B); evaluator.evaluate(Qt::ControlModifier, Qt::Key_T); evaluator.evaluate(Qt::NoModifier, Qt::Key_A); - QVERIFY(keymapWasCalled); + QVERIFY(keymap_was_called); } // TODO: maybe fix this behavior context( "when partial mapped sequence is entered before an entire sequence"); it("does not call mapping") { - int keymapWasCalled = false; + auto keymap_was_called = false; KeymapEvaluator evaluator; - evaluator.addKeymap(KeyMode::Normal, "<c-t>a", - [&keymapWasCalled]() { keymapWasCalled = true; }); + evaluator.add_keymap(KeyMode::Normal, "<c-t>a", [&keymap_was_called]() { + keymap_was_called = true; + }); evaluator.evaluate(Qt::ControlModifier, Qt::Key_T); evaluator.evaluate(Qt::ControlModifier, Qt::Key_T); evaluator.evaluate(Qt::NoModifier, Qt::Key_A); - QVERIFY(NOT keymapWasCalled); + QVERIFY(NOT keymap_was_called); } } }; QTEST_REGISTER(KeymapEvaluatorSpec) #include "KeymapEvaluatorSpec.moc" +// NOLINTEND diff --git a/spec/LuaRuntimeSpec.cpp b/spec/LuaRuntimeSpec.cpp index 3b4be70..4d89f30 100644 --- a/spec/LuaRuntimeSpec.cpp +++ b/spec/LuaRuntimeSpec.cpp @@ -4,67 +4,72 @@ #include "LuaRuntime.hpp" #include "testUtils.h" +// NOLINTBEGIN class LuaRuntimeSpec : public QObject { Q_OBJECT private slots: - void beforeTestCase() { LuaRuntime::instance()->startEventLoop(); } + void beforeTestCase() { LuaRuntime::instance()->start_event_loop(); } void cleanupTestCase() { - LuaRuntime::instance()->stopEventLoop(); + LuaRuntime::instance()->stop_event_loop(); uv_library_shutdown(); } void test_evaluate() { context("when given an expression returning a number"); - it("emits evaluationCompleted with the result") { - auto lua = LuaRuntime::instance(); - QSignalSpy evaluationCompletedSpy(lua, &LuaRuntime::evaluationCompleted); + it("emits evaluation_completed with the result") { + auto *lua = LuaRuntime::instance(); + QSignalSpy evaluation_completed_spy(lua, + &LuaRuntime::evaluation_completed); lua->evaluate("return 20 + 1 * 5"); - evaluationCompletedSpy.wait(); - QCOMPARE(evaluationCompletedSpy.count(), 1); - QVariant result = evaluationCompletedSpy.takeFirst().at(0); + evaluation_completed_spy.wait(); + QCOMPARE(evaluation_completed_spy.count(), 1); + QVariant result = evaluation_completed_spy.takeFirst().at(0); QCOMPARE(result, 25); } context("when given an expression returning a string"); - it("emits evaluationCompleted with the result") { - auto lua = LuaRuntime::instance(); - QSignalSpy evaluationCompletedSpy(lua, &LuaRuntime::evaluationCompleted); + it("emits evaluation_completed with the result") { + auto *lua = LuaRuntime::instance(); + QSignalSpy evaluation_completed_spy(lua, + &LuaRuntime::evaluation_completed); lua->evaluate("local name = 'world'; return 'hello ' .. name"); - evaluationCompletedSpy.wait(); - QCOMPARE(evaluationCompletedSpy.count(), 1); - QVariant result = evaluationCompletedSpy.takeFirst().at(0); + evaluation_completed_spy.wait(); + QCOMPARE(evaluation_completed_spy.count(), 1); + QVariant result = evaluation_completed_spy.takeFirst().at(0); QCOMPARE(result, "hello world"); } context("when given an expression returning a boolean"); - it("emits evaluationCompleted with the result") { - auto lua = LuaRuntime::instance(); - QSignalSpy evaluationCompletedSpy(lua, &LuaRuntime::evaluationCompleted); + it("emits evaluation_completed with the result") { + auto *lua = LuaRuntime::instance(); + QSignalSpy evaluation_completed_spy(lua, + &LuaRuntime::evaluation_completed); lua->evaluate("local num = 5; return 5 == num"); - evaluationCompletedSpy.wait(); - QCOMPARE(evaluationCompletedSpy.count(), 1); - QVariant result = evaluationCompletedSpy.takeFirst().at(0); + evaluation_completed_spy.wait(); + QCOMPARE(evaluation_completed_spy.count(), 1); + QVariant result = evaluation_completed_spy.takeFirst().at(0); QCOMPARE(result, true); } context("when given an expression returning nil"); - it("emits evaluationCompleted with the result") { - auto lua = LuaRuntime::instance(); - QSignalSpy evaluationCompletedSpy(lua, &LuaRuntime::evaluationCompleted); + it("emits evaluation_completed with the result") { + auto *lua = LuaRuntime::instance(); + QSignalSpy evaluation_completed_spy(lua, + &LuaRuntime::evaluation_completed); lua->evaluate("return nil"); - QVERIFY(evaluationCompletedSpy.wait()); - QCOMPARE(evaluationCompletedSpy.count(), 1); - QVariant result = evaluationCompletedSpy.takeFirst().at(0); + QVERIFY(evaluation_completed_spy.wait()); + QCOMPARE(evaluation_completed_spy.count(), 1); + QVariant result = evaluation_completed_spy.takeFirst().at(0); QCOMPARE(result, 0); } } @@ -72,22 +77,24 @@ private slots: void test_queue_task() { context("when task is queued"); it("evaluates task asynchronously") { - auto lua = LuaRuntime::instance(); - bool wasTaskCalled = false; + auto *lua = LuaRuntime::instance(); + bool was_task_called = false; - lua->queueTask([&wasTaskCalled]() { wasTaskCalled = true; }); - QVERIFY(NOT wasTaskCalled); + lua->queue_task([&was_task_called]() { was_task_called = true; }); + QVERIFY(NOT was_task_called); - QVERIFY(QTest::qWaitFor([&wasTaskCalled]() { return wasTaskCalled; })); - QVERIFY(wasTaskCalled); + QVERIFY( + QTest::qWaitFor([&was_task_called]() { return was_task_called; })); + QVERIFY(was_task_called); } } void test_sanity_check_uv_timer() { context("when a 1 second timer is set"); it("calls callback after 1 second") { - auto lua = LuaRuntime::instance(); - QSignalSpy evaluationCompletedSpy(lua, &LuaRuntime::evaluationCompleted); + auto *lua = LuaRuntime::instance(); + QSignalSpy evaluation_completed_spy(lua, + &LuaRuntime::evaluation_completed); lua->evaluate(R"( _G.was_timer_called = false; @@ -97,19 +104,20 @@ private slots: timer:close() end) )"); - QVERIFY(evaluationCompletedSpy.wait()); - QVERIFY(NOT lua->evaluateSync("return _G.was_timer_called").toBool()); + QVERIFY(evaluation_completed_spy.wait()); + QVERIFY(NOT lua->evaluate_sync("return _G.was_timer_called").toBool()); QVERIFY(QTest::qWaitFor([&lua]() { - return lua->evaluateSync("return _G.was_timer_called").toBool(); + return lua->evaluate_sync("return _G.was_timer_called").toBool(); })); } } void test_sanity_check_uv_spawn() { it("calls exit callback when process exists") { - auto lua = LuaRuntime::instance(); - QSignalSpy evaluationCompletedSpy(lua, &LuaRuntime::evaluationCompleted); + auto *lua = LuaRuntime::instance(); + QSignalSpy evaluation_completed_spy(lua, + &LuaRuntime::evaluation_completed); lua->evaluate(R"( _G.spawn_exit_code = -1; @@ -117,11 +125,11 @@ private slots: _G.spawn_exit_code = code; end) )"); - QVERIFY(evaluationCompletedSpy.wait()); - QCOMPARE(lua->evaluateSync("return _G.spawn_exit_code").toInt(), -1); + QVERIFY(evaluation_completed_spy.wait()); + QCOMPARE(lua->evaluate_sync("return _G.spawn_exit_code").toInt(), -1); QVERIFY(QTest::qWaitFor([&lua]() { - return 0 == lua->evaluateSync("return _G.spawn_exit_code").toInt(); + return 0 == lua->evaluate_sync("return _G.spawn_exit_code").toInt(); })); } } @@ -129,3 +137,4 @@ private slots: QTEST_REGISTER(LuaRuntimeSpec) #include "LuaRuntimeSpec.moc" +// NOLINTEND diff --git a/spec/WebViewStackSpec.cpp b/spec/WebViewStackSpec.cpp index 0cd58ed..134c250 100644 --- a/spec/WebViewStackSpec.cpp +++ b/spec/WebViewStackSpec.cpp @@ -7,6 +7,7 @@ #include "widgets/WebView.hpp" #include "widgets/WebViewStack.hpp" +// NOLINTBEGIN class WebViewStackSpec : public QObject { Q_OBJECT @@ -22,11 +23,11 @@ private slots: context("when initialized"); it("opens a single tab") { Configuration configuration; - WebViewStack webViewStack(&configuration); + WebViewStack web_view_stack(&configuration); - QCOMPARE(webViewStack.count(), 1); - QCOMPARE(webViewStack.currentUrl(), configuration.newTabUrl); - webViewStack.deleteLater(); + QCOMPARE(web_view_stack.count(), 1); + QCOMPARE(web_view_stack.current_url(), configuration.new_tab_url); + web_view_stack.deleteLater(); } } @@ -34,48 +35,48 @@ private slots: context("when openUrl is called without an open type"); it("replaces current tab url with newtab url") { Configuration configuration; - WebViewStack webViewStack(&configuration); - webViewStack.openUrl(QUrl("http://a.com"), OpenType::OpenUrl); + WebViewStack web_view_stack(&configuration); + web_view_stack.open_url(QUrl("http://a.com"), OpenType::OpenUrl); - webViewStack.openUrl(QUrl(configuration.newTabUrl)); + web_view_stack.open_url(QUrl(configuration.new_tab_url)); - QCOMPARE(webViewStack.count(), 1); - std::vector<QUrl> urls = {QUrl(configuration.newTabUrl)}; - QCOMPARE(webViewStack.urls(), urls); - QCOMPARE(webViewStack.currentWebViewIndex(), 0); - QCOMPARE(webViewStack.currentUrl(), configuration.newTabUrl); + QCOMPARE(web_view_stack.count(), 1); + std::vector<QUrl> urls = {QUrl(configuration.new_tab_url)}; + QCOMPARE(web_view_stack.urls(), urls); + QCOMPARE(web_view_stack.current_web_view_index(), 0); + QCOMPARE(web_view_stack.current_url(), configuration.new_tab_url); } context("when creating a new webview with a url and focus is false"); it("opens the given url in background") { Configuration configuration; - WebViewStack webViewStack(&configuration); + WebViewStack web_view_stack(&configuration); - webViewStack.openUrl(QUrl("https://duckduckgo.com"), - OpenType::OpenUrlInBgTab); + web_view_stack.open_url(QUrl("https://duckduckgo.com"), + OpenType::OpenUrlInBgTab); - QCOMPARE(webViewStack.count(), 2); - std::vector<QUrl> urls = {QUrl(configuration.newTabUrl), + QCOMPARE(web_view_stack.count(), 2); + std::vector<QUrl> urls = {QUrl(configuration.new_tab_url), QUrl("https://duckduckgo.com")}; - QCOMPARE(webViewStack.urls(), urls); - QCOMPARE(webViewStack.currentWebViewIndex(), 0); - QCOMPARE(webViewStack.currentUrl(), configuration.newTabUrl); + QCOMPARE(web_view_stack.urls(), urls); + QCOMPARE(web_view_stack.current_web_view_index(), 0); + QCOMPARE(web_view_stack.current_url(), configuration.new_tab_url); } context("when creating a new webview with a url and focus is true"); it("opens the given url as current view") { Configuration configuration; - WebViewStack webViewStack(&configuration); + WebViewStack web_view_stack(&configuration); - webViewStack.openUrl(QUrl("https://duckduckgo.com"), - OpenType::OpenUrlInTab); + web_view_stack.open_url(QUrl("https://duckduckgo.com"), + OpenType::OpenUrlInTab); - QCOMPARE(webViewStack.count(), 2); - std::vector<QUrl> urls = {QUrl(configuration.newTabUrl), + QCOMPARE(web_view_stack.count(), 2); + std::vector<QUrl> urls = {QUrl(configuration.new_tab_url), QUrl("https://duckduckgo.com")}; - QCOMPARE(webViewStack.urls(), urls); - QCOMPARE(webViewStack.currentWebViewIndex(), 1); - QCOMPARE(webViewStack.currentUrl(), QUrl("https://duckduckgo.com")); + QCOMPARE(web_view_stack.urls(), urls); + QCOMPARE(web_view_stack.current_web_view_index(), 1); + QCOMPARE(web_view_stack.current_url(), QUrl("https://duckduckgo.com")); } } @@ -84,41 +85,41 @@ private slots: context("- and there is only 1 tab"); it("does nothing") { Configuration configuration; - WebViewStack webViewStack(&configuration); + WebViewStack web_view_stack(&configuration); - webViewStack.next(); + web_view_stack.next(); - QCOMPARE(webViewStack.currentWebViewIndex(), 0); - QCOMPARE(webViewStack.currentUrl(), configuration.newTabUrl); + QCOMPARE(web_view_stack.current_web_view_index(), 0); + QCOMPARE(web_view_stack.current_url(), configuration.new_tab_url); } context("when nextWebView is called"); context("- and there are tabs after the current tab"); it("goes to the next tab") { Configuration configuration; - WebViewStack webViewStack(&configuration); - webViewStack.openUrl(QUrl("http://a1.com"), OpenType::OpenUrlInBgTab); - webViewStack.openUrl(QUrl("http://a2.com"), OpenType::OpenUrlInBgTab); + WebViewStack web_view_stack(&configuration); + web_view_stack.open_url(QUrl("http://a1.com"), OpenType::OpenUrlInBgTab); + web_view_stack.open_url(QUrl("http://a2.com"), OpenType::OpenUrlInBgTab); - webViewStack.next(); + web_view_stack.next(); - QCOMPARE(webViewStack.currentWebViewIndex(), 1); - QCOMPARE(webViewStack.currentUrl(), QUrl("http://a1.com")); + QCOMPARE(web_view_stack.current_web_view_index(), 1); + QCOMPARE(web_view_stack.current_url(), QUrl("http://a1.com")); } context("when nextWebView is called"); context("- and current tab is the last tab"); it("jumps to the first tab") { Configuration configuration; - WebViewStack webViewStack(&configuration); - webViewStack.openUrl(QUrl("http://a1.com"), OpenType::OpenUrlInBgTab); - webViewStack.openUrl(QUrl("http://a2.com"), OpenType::OpenUrlInTab); - QCOMPARE(webViewStack.currentWebViewIndex(), 2); + WebViewStack web_view_stack(&configuration); + web_view_stack.open_url(QUrl("http://a1.com"), OpenType::OpenUrlInBgTab); + web_view_stack.open_url(QUrl("http://a2.com"), OpenType::OpenUrlInTab); + QCOMPARE(web_view_stack.current_web_view_index(), 2); - webViewStack.next(); + web_view_stack.next(); - QCOMPARE(webViewStack.currentWebViewIndex(), 0); - QCOMPARE(webViewStack.currentUrl(), configuration.newTabUrl); + QCOMPARE(web_view_stack.current_web_view_index(), 0); + QCOMPARE(web_view_stack.current_url(), configuration.new_tab_url); } } @@ -127,41 +128,41 @@ private slots: context("- and there is only 1 tab"); it("does nothing") { Configuration configuration; - WebViewStack webViewStack(&configuration); + WebViewStack web_view_stack(&configuration); - webViewStack.previous(); + web_view_stack.previous(); - QCOMPARE(webViewStack.currentWebViewIndex(), 0); - QCOMPARE(webViewStack.currentUrl(), configuration.newTabUrl); + QCOMPARE(web_view_stack.current_web_view_index(), 0); + QCOMPARE(web_view_stack.current_url(), configuration.new_tab_url); } context("when previousWebView is called"); context("- and there are tabs before the current tab"); it("goes to the next tab") { Configuration configuration; - WebViewStack webViewStack(&configuration); - webViewStack.openUrl(QUrl("http://a1.com"), OpenType::OpenUrlInBgTab); - webViewStack.openUrl(QUrl("http://a2.com"), OpenType::OpenUrlInTab); - QCOMPARE(webViewStack.currentWebViewIndex(), 2); + WebViewStack web_view_stack(&configuration); + web_view_stack.open_url(QUrl("http://a1.com"), OpenType::OpenUrlInBgTab); + web_view_stack.open_url(QUrl("http://a2.com"), OpenType::OpenUrlInTab); + QCOMPARE(web_view_stack.current_web_view_index(), 2); - webViewStack.previous(); + web_view_stack.previous(); - QCOMPARE(webViewStack.currentWebViewIndex(), 1); - QCOMPARE(webViewStack.currentUrl(), QUrl("http://a1.com")); + QCOMPARE(web_view_stack.current_web_view_index(), 1); + QCOMPARE(web_view_stack.current_url(), QUrl("http://a1.com")); } context("when previousWebView is called"); context("- and current tab is the last tab"); it("jumps to the last tab") { Configuration configuration; - WebViewStack webViewStack(&configuration); - webViewStack.openUrl(QUrl("http://a1.com"), OpenType::OpenUrlInBgTab); - webViewStack.openUrl(QUrl("http://a2.com"), OpenType::OpenUrlInBgTab); + WebViewStack web_view_stack(&configuration); + web_view_stack.open_url(QUrl("http://a1.com"), OpenType::OpenUrlInBgTab); + web_view_stack.open_url(QUrl("http://a2.com"), OpenType::OpenUrlInBgTab); - webViewStack.previous(); + web_view_stack.previous(); - QCOMPARE(webViewStack.currentWebViewIndex(), 2); - QCOMPARE(webViewStack.currentUrl(), QUrl("http://a2.com")); + QCOMPARE(web_view_stack.current_web_view_index(), 2); + QCOMPARE(web_view_stack.current_url(), QUrl("http://a2.com")); } } @@ -170,32 +171,33 @@ private slots: context("- with out of bounds index"); it("does nothing") { Configuration configuration; - WebViewStack webViewStack(&configuration); - webViewStack.openUrl(QUrl("https://a.com"), OpenType::OpenUrl); + WebViewStack web_view_stack(&configuration); + web_view_stack.open_url(QUrl("https://a.com"), OpenType::OpenUrl); - webViewStack.close(1); + web_view_stack.close(1); - QCOMPARE(webViewStack.count(), 1); - QCOMPARE(webViewStack.urls(), (std::vector<QUrl>{QUrl("https://a.com")})); - QCOMPARE(webViewStack.currentWebViewIndex(), 0); - QCOMPARE(webViewStack.currentUrl(), QUrl("https://a.com")); + QCOMPARE(web_view_stack.count(), 1); + QCOMPARE(web_view_stack.urls(), + (std::vector<QUrl>{QUrl("https://a.com")})); + QCOMPARE(web_view_stack.current_web_view_index(), 0); + QCOMPARE(web_view_stack.current_url(), QUrl("https://a.com")); } context("when closeWebView is called"); context("- and there is only 1 tab"); it("closes the tab and opens empty tab in its place") { Configuration configuration; - WebViewStack webViewStack(&configuration); - webViewStack.openUrl(QUrl("https://a.com"), OpenType::OpenUrl); - QCOMPARE(webViewStack.count(), 1); + WebViewStack web_view_stack(&configuration); + web_view_stack.open_url(QUrl("https://a.com"), OpenType::OpenUrl); + QCOMPARE(web_view_stack.count(), 1); - webViewStack.close(0); + web_view_stack.close(0); - QCOMPARE(webViewStack.count(), 1); - QCOMPARE(webViewStack.urls(), - (std::vector<QUrl>{configuration.newTabUrl})); - QCOMPARE(webViewStack.currentWebViewIndex(), 0); - QCOMPARE(webViewStack.currentUrl(), configuration.newTabUrl); + QCOMPARE(web_view_stack.count(), 1); + QCOMPARE(web_view_stack.urls(), + (std::vector<QUrl>{configuration.new_tab_url})); + QCOMPARE(web_view_stack.current_web_view_index(), 0); + QCOMPARE(web_view_stack.current_url(), configuration.new_tab_url); } context("when closeWebView is called"); @@ -203,20 +205,20 @@ private slots: context("- and there are some tabs after"); it("closes the tab and focuses the next tab") { Configuration configuration; - WebViewStack webViewStack(&configuration); - webViewStack.openUrl(QUrl("https://a1.com"), OpenType::OpenUrlInTab); - webViewStack.openUrl(QUrl("https://a2.com"), OpenType::OpenUrlInBgTab); - QCOMPARE(webViewStack.count(), 3); - QCOMPARE(webViewStack.currentWebViewIndex(), 1); + WebViewStack web_view_stack(&configuration); + web_view_stack.open_url(QUrl("https://a1.com"), OpenType::OpenUrlInTab); + web_view_stack.open_url(QUrl("https://a2.com"), OpenType::OpenUrlInBgTab); + QCOMPARE(web_view_stack.count(), 3); + QCOMPARE(web_view_stack.current_web_view_index(), 1); - webViewStack.close(1); + web_view_stack.close(1); - QCOMPARE(webViewStack.count(), 2); - QCOMPARE( - webViewStack.urls(), - (std::vector<QUrl>{configuration.newTabUrl, QUrl("https://a2.com")})); - QCOMPARE(webViewStack.currentWebViewIndex(), 1); - QCOMPARE(webViewStack.currentUrl(), QUrl("https://a2.com")); + QCOMPARE(web_view_stack.count(), 2); + QCOMPARE(web_view_stack.urls(), + (std::vector<QUrl>{configuration.new_tab_url, + QUrl("https://a2.com")})); + QCOMPARE(web_view_stack.current_web_view_index(), 1); + QCOMPARE(web_view_stack.current_url(), QUrl("https://a2.com")); } context("when closeWebView is called"); @@ -224,20 +226,20 @@ private slots: context("- which is the last tab"); it("closes the tab and focusses previous tab") { Configuration configuration; - WebViewStack webViewStack(&configuration); - webViewStack.openUrl(QUrl("https://a1.com"), OpenType::OpenUrlInBgTab); - webViewStack.openUrl(QUrl("https://a2.com"), OpenType::OpenUrlInTab); - QCOMPARE(webViewStack.count(), 3); - QCOMPARE(webViewStack.currentWebViewIndex(), 2); + WebViewStack web_view_stack(&configuration); + web_view_stack.open_url(QUrl("https://a1.com"), OpenType::OpenUrlInBgTab); + web_view_stack.open_url(QUrl("https://a2.com"), OpenType::OpenUrlInTab); + QCOMPARE(web_view_stack.count(), 3); + QCOMPARE(web_view_stack.current_web_view_index(), 2); - webViewStack.close(2); + web_view_stack.close(2); - QCOMPARE(webViewStack.count(), 2); - QCOMPARE( - webViewStack.urls(), - (std::vector<QUrl>{configuration.newTabUrl, QUrl("https://a1.com")})); - QCOMPARE(webViewStack.currentWebViewIndex(), 1); - QCOMPARE(webViewStack.currentUrl(), QUrl("https://a1.com")); + QCOMPARE(web_view_stack.count(), 2); + QCOMPARE(web_view_stack.urls(), + (std::vector<QUrl>{configuration.new_tab_url, + QUrl("https://a1.com")})); + QCOMPARE(web_view_stack.current_web_view_index(), 1); + QCOMPARE(web_view_stack.current_url(), QUrl("https://a1.com")); } } @@ -246,46 +248,47 @@ private slots: context("- of type new tab"); it("opens a new web view and focusses it") { Configuration configuration; - WebViewStack webViewStack(&configuration); - webViewStack.openUrl(QUrl("https://a.com"), OpenType::OpenUrl); - auto webview = webViewStack.findChild<WebView *>(); - QCOMPARE(webViewStack.count(), 1); + WebViewStack web_view_stack(&configuration); + web_view_stack.open_url(QUrl("https://a.com"), OpenType::OpenUrl); + auto *webview = web_view_stack.findChild<WebView *>(); + QCOMPARE(web_view_stack.count(), 1); - FakeNewWindowRequest windowRequest( + FakeNewWindowRequest window_request( FakeNewWindowRequest::DestinationType::InNewTab, QRect(0, 0, 0, 0), QUrl("https://new.com"), true); - emit webview->page()->newWindowRequested(windowRequest); + emit webview->page()->newWindowRequested(window_request); - QCOMPARE(webViewStack.count(), 2); + QCOMPARE(web_view_stack.count(), 2); QCOMPARE( - webViewStack.urls(), + web_view_stack.urls(), (std::vector<QUrl>{QUrl("https://a.com"), QUrl("https://new.com")})); - QCOMPARE(webViewStack.currentWebViewIndex(), 1); - QCOMPARE(webViewStack.currentUrl(), QUrl("https://new.com")); + QCOMPARE(web_view_stack.current_web_view_index(), 1); + QCOMPARE(web_view_stack.current_url(), QUrl("https://new.com")); } context("when webview emits a newWindowRequested signal"); context("- of type new background tab"); it("opens a new web view in the background") { Configuration configuration; - WebViewStack webViewStack(&configuration); - webViewStack.openUrl(QUrl("https://a.com"), OpenType::OpenUrl); - auto webview = webViewStack.findChild<WebView *>(); + WebViewStack web_view_stack(&configuration); + web_view_stack.open_url(QUrl("https://a.com"), OpenType::OpenUrl); + auto *webview = web_view_stack.findChild<WebView *>(); - FakeNewWindowRequest windowRequest( + FakeNewWindowRequest window_request( FakeNewWindowRequest::DestinationType::InNewBackgroundTab, QRect(0, 0, 0, 0), QUrl("https://new.com"), true); - emit webview->page()->newWindowRequested(windowRequest); + emit webview->page()->newWindowRequested(window_request); - QCOMPARE(webViewStack.count(), 2); + QCOMPARE(web_view_stack.count(), 2); QCOMPARE( - webViewStack.urls(), + web_view_stack.urls(), (std::vector<QUrl>{QUrl("https://a.com"), QUrl("https://new.com")})); - QCOMPARE(webViewStack.currentWebViewIndex(), 0); - QCOMPARE(webViewStack.currentUrl(), QUrl("https://a.com")); + QCOMPARE(web_view_stack.current_web_view_index(), 0); + QCOMPARE(web_view_stack.current_url(), QUrl("https://a.com")); } } }; QTEST_REGISTER(WebViewStackSpec) #include "WebViewStackSpec.moc" +// NOLINTEND diff --git a/spec/main.cpp b/spec/main.cpp index 352ecba..15d0b60 100644 --- a/spec/main.cpp +++ b/spec/main.cpp @@ -4,5 +4,5 @@ int main(int argc, char **argv) { QApplication app(argc, argv); - return runAllTests(); + return run_all_tests(); } diff --git a/spec/testUtils.cpp b/spec/testUtils.cpp index 0fc5e2b..cea7a3d 100644 --- a/spec/testUtils.cpp +++ b/spec/testUtils.cpp @@ -2,23 +2,23 @@ #include <QtTest/qtestcase.h> #include <cstdio> -std::vector<std::function<QObject *()>> &getQTestRegistry() { +std::vector<std::function<QObject *()>> &get_qtest_registry() { static std::vector<std::function<QObject *()>> registry; return registry; } -int runAllTests() { - int exitCode = 0; +int run_all_tests() { + int exit_code = 0; - QString testName = getenv("TEST_NAME"); + QString test_name = getenv("TEST_NAME"); - for (const auto &runTest : getQTestRegistry()) { - auto test = runTest(); - if (testName.isEmpty() || test->objectName().contains(testName)) - exitCode |= QTest::qExec(test); + for (const auto &run_test : get_qtest_registry()) { + auto *test = run_test(); + if (test_name.isEmpty() || test->objectName().contains(test_name)) + exit_code |= QTest::qExec(test); delete test; } - getQTestRegistry().clear(); - return exitCode; + get_qtest_registry().clear(); + return exit_code; } diff --git a/spec/testUtils.h b/spec/testUtils.h index fd0c30b..f6cdebb 100644 --- a/spec/testUtils.h +++ b/spec/testUtils.h @@ -26,16 +26,16 @@ #define STRINGIFY(x) #x -std::vector<std::function<QObject *()>> &getQTestRegistry(); -int runAllTests(); +std::vector<std::function<QObject *()>> &get_qtest_registry(); +int run_all_tests(); #define QTEST_REGISTER(klass) \ namespace { \ const bool registered__##klass = []() { \ - getQTestRegistry().push_back([]() { \ - auto t = new klass; \ - t->setObjectName(#klass); \ - return t; \ + get_qtest_registry().push_back([]() { \ + auto test = new (klass); \ + test->setObjectName(#klass); \ + return test; \ }); \ return true; \ }(); \ diff --git a/src/AsyncEventLoop.cpp b/src/AsyncEventLoop.cpp index 230d891..3acbc41 100644 --- a/src/AsyncEventLoop.cpp +++ b/src/AsyncEventLoop.cpp @@ -1,8 +1,10 @@ #include <QtCore> +#include <chrono> #include <functional> #include <mutex> #include <queue> #include <thread> +#include <utility> #include <uv.h> #include "AsyncEventLoop.hpp" @@ -12,24 +14,24 @@ AsyncEventLoop::AsyncEventLoop() { loop = (uv_loop_t *)malloc(sizeof(uv_loop_t)); uv_loop_init(loop); - uv_async_init(loop, &asyncHandle, AsyncEventLoop::asyncHandleCallback); - asyncHandle.data = this; + uv_async_init(loop, &async_handle, AsyncEventLoop::async_handle_callback); + async_handle.data = this; - loopThread = std::thread(&AsyncEventLoop::runLoop, this); + loop_thread = std::thread(&AsyncEventLoop::run_loop, this); // Wait for thread to start - while (!isLoopRunning) + while (!is_loop_running) std::this_thread::sleep_for(std::chrono::milliseconds(50)); } -void AsyncEventLoop::wake() { uv_async_send(&asyncHandle); } +void AsyncEventLoop::wake() { uv_async_send(&async_handle); } -void AsyncEventLoop::processTasks() { +void AsyncEventLoop::process_tasks() { std::queue<std::function<void()>> tasks; { - std::lock_guard<std::mutex> lock(tasksQueueMutex); - tasksQueue.swap(tasks); + const std::lock_guard<std::mutex> lock(tasks_queue_mutex); + tasks_queue.swap(tasks); } while (!tasks.empty()) { @@ -39,9 +41,9 @@ void AsyncEventLoop::processTasks() { } } -void AsyncEventLoop::runLoop() { - isLoopRunning = true; - while (isLoopRunning) { +void AsyncEventLoop::run_loop() { + is_loop_running = true; + while (is_loop_running) { // qDebug() << "loop iteration" << uv_loop_alive(loop); uv_run(loop, UV_RUN_NOWAIT); // qDebug() << "uv_run() returned: " << result; @@ -50,48 +52,49 @@ void AsyncEventLoop::runLoop() { } AsyncEventLoop::~AsyncEventLoop() { - if (!isLoopRunning) + if (!is_loop_running) return; - isLoopRunning = false; + is_loop_running = false; - flushTasks(); + flush_tasks(); std::this_thread::sleep_for(std::chrono::milliseconds(50)); uv_stop(loop); // Close all handles - AsyncEventLoop::closeHandle(reinterpret_cast<uv_handle_t *>(&asyncHandle)); - uv_walk(loop, AsyncEventLoop::closeHandle, nullptr); + AsyncEventLoop::close_handle(reinterpret_cast<uv_handle_t *>(&async_handle)); + uv_walk(loop, AsyncEventLoop::close_handle, nullptr); - if (loopThread.joinable()) - loopThread.join(); + if (loop_thread.joinable()) + loop_thread.join(); // Close loop - while (uv_loop_close(loop) == EBUSY) - std::this_thread::sleep_for(std::chrono::milliseconds(100)); + uv_loop_close(loop); uv_run(loop, UV_RUN_DEFAULT); - if (uv_loop_alive(loop)) + if (uv_loop_alive(loop) > 0) qDebug() << "WARNING: Loop still has active handles!"; free(loop); loop = nullptr; } -void AsyncEventLoop::flushTasks() { - std::lock_guard<std::mutex> lock(tasksQueueMutex); - std::queue<std::function<void()>>().swap(tasksQueue); +void AsyncEventLoop::flush_tasks() { + { + const std::lock_guard<std::mutex> lock(tasks_queue_mutex); + std::queue<std::function<void()>>().swap(tasks_queue); + } wake(); } -void AsyncEventLoop::asyncHandleCallback(uv_async_t *handle) { +void AsyncEventLoop::async_handle_callback(uv_async_t *handle) { auto *runtime = static_cast<AsyncEventLoop *>(handle->data); - runtime->processTasks(); + runtime->process_tasks(); } -void AsyncEventLoop::closeHandle(uv_handle_t *handle, void *) { +void AsyncEventLoop::close_handle(uv_handle_t *handle, void * /*unused*/) { if (!uv_is_closing(handle)) { - uv_close(handle, [](uv_handle_t *h) { h->data = nullptr; }); + uv_close(handle, [](uv_handle_t *handle) { handle->data = nullptr; }); uv_unref(handle); } } diff --git a/src/AsyncEventLoop.hpp b/src/AsyncEventLoop.hpp index 8082dfa..7a3ed69 100644 --- a/src/AsyncEventLoop.hpp +++ b/src/AsyncEventLoop.hpp @@ -16,30 +16,28 @@ public: ~AsyncEventLoop(); void wake(); - DEFINE_GETTER(getUVLoop, loop) + DEFINE_GETTER(get_uv_loop, loop) - template <typename F> void queueTask(F &&task) { + template <typename F> void queue_task(F &&task) { { - std::lock_guard<std::mutex> lock(tasksQueueMutex); - tasksQueue.push(std::forward<F>(task)); + const std::lock_guard<std::mutex> lock(tasks_queue_mutex); + tasks_queue.push(std::forward<F>(task)); } wake(); } protected: - void runLoop(); - void processTasks(); - static void asyncHandleCallback(uv_async_t *handle); - static void closeHandle(uv_handle_t *handle, void *arg = nullptr); - -private: - void flushTasks(); + void run_loop(); + void process_tasks(); + void flush_tasks(); + static void async_handle_callback(uv_async_t *handle); + static void close_handle(uv_handle_t *handle, void *arg = nullptr); private: uv_loop_t *loop; - std::thread loopThread; - uv_async_t asyncHandle; - std::atomic<bool> isLoopRunning = false; - std::queue<std::function<void()>> tasksQueue; - std::mutex tasksQueueMutex; + std::thread loop_thread; + uv_async_t async_handle; + std::atomic<bool> is_loop_running = false; + std::queue<std::function<void()>> tasks_queue; + std::mutex tasks_queue_mutex; }; diff --git a/src/CommandParser.cpp b/src/CommandParser.cpp deleted file mode 100644 index 2b9b422..0000000 --- a/src/CommandParser.cpp +++ /dev/null @@ -1,37 +0,0 @@ -#include <QtCore/qnamespace.h> -#include <QtCore> - -#include "CommandParser.hpp" - -CommandParser::CommandParser() {} - -Cmd CommandParser::parse(QString input) { - // TODO: simplify this to only parse the command - auto parts = input.split(QRegularExpression("\\s+"), Qt::SkipEmptyParts); - - if (parts.isEmpty()) - return {.command = Noop, .argsString = "", .rawInput = input}; - - auto cmdStr = parts.first(); - auto cmd = toCommandType(cmdStr); - auto rawArgs = input.slice(cmdStr.length()).trimmed(); - - return {.command = cmd, .argsString = rawArgs, .rawInput = input}; -} - -CommandType CommandParser::toCommandType(QString cmd) { - if (cmd == "lua") - return LuaEval; - if (cmd == "open") - return Open; - if (cmd == "tabopen") - return TabOpen; - if (cmd == "tn" || cmd == "tabnext") - return TabNext; - if (cmd == "tp" || cmd == "tabprev") - return TabPrev; - if (cmd == "tabs") - return TabSelect; - - return Noop; -} diff --git a/src/CommandParser.hpp b/src/CommandParser.hpp deleted file mode 100644 index 9197df5..0000000 --- a/src/CommandParser.hpp +++ /dev/null @@ -1,29 +0,0 @@ -#pragma once - -#include <QtCore/qcontainerfwd.h> -#include <QtCore> - -enum CommandType { - Noop, - LuaEval, - Open, - TabOpen, - TabNext, - TabPrev, - TabSelect, -}; - -struct Cmd { - CommandType command; - QString argsString; - QString rawInput; -}; - -class CommandParser { -public: - CommandParser(); - Cmd parse(QString command); - -private: - CommandType toCommandType(QString cmd); -}; diff --git a/src/Configuration.hpp b/src/Configuration.hpp index cc68803..032d12e 100644 --- a/src/Configuration.hpp +++ b/src/Configuration.hpp @@ -1,7 +1,6 @@ #pragma once #include <QtCore> -#include <cstdio> class Configuration : public QObject { Q_OBJECT @@ -9,5 +8,5 @@ class Configuration : public QObject { public: using QObject::QObject; - QUrl newTabUrl = QUrl("https://lite.duckduckgo.com"); + QUrl new_tab_url = QUrl("https://lite.duckduckgo.com"); }; diff --git a/src/InputMediator.cpp b/src/InputMediator.cpp index 61ef125..aeb352b 100644 --- a/src/InputMediator.cpp +++ b/src/InputMediator.cpp @@ -2,55 +2,56 @@ #include <QWidget> #include <QtCore> -#include "CommandParser.hpp" #include "InputMediator.hpp" #include "LuaRuntime.hpp" #include "keymap/KeymapEvaluator.hpp" #include "widgets/WebViewStack.hpp" // TODO: Rename this -InputMediator::InputMediator(WebViewStack *webViewStack, LuaRuntime *luaRuntime, - KeymapEvaluator *keymapEvaluator) - : QObject(), webViewStack(webViewStack), luaRuntime(luaRuntime), - keymapEvaluator(keymapEvaluator) { - connect(luaRuntime, &LuaRuntime::urlOpened, webViewStack, - &WebViewStack::openUrl); - connect(luaRuntime, &LuaRuntime::keymapAddRequested, this, - &InputMediator::addKeymap); +InputMediator::InputMediator(WebViewStack *web_view_stack, + LuaRuntime *lua_runtime, + KeymapEvaluator *keymap_evaluator) + : web_view_stack(web_view_stack), lua_runtime(lua_runtime), + keymap_evaluator(keymap_evaluator) { + connect(lua_runtime, &LuaRuntime::url_opened, web_view_stack, + &WebViewStack::open_url); + connect(lua_runtime, &LuaRuntime::keymap_add_requested, this, + &InputMediator::add_keymap); } -void InputMediator::addKeymap(QString modeString, QString keyseq, - std::function<void()> action) { - KeyMode mode = keymapEvaluator->modeFromString(modeString); - keymapEvaluator->addKeymap(mode, keyseq, action); +void InputMediator::add_keymap(const QString &mode_string, + const QString &keyseq, + std::function<void()> action) { + const KeyMode mode = keymap_evaluator->mode_from_string(mode_string); + keymap_evaluator->add_keymap(mode, keyseq, std::move(action)); } -void InputMediator::evaluateCommand(QString command) { - CommandParser parser; - auto cmd = parser.parse(command); +// void InputMediator::evaluate_command(QString command) { +// CommandParser parser; +// auto cmd = parser.parse(command); +// +// switch (cmd.command) { +// case CommandType::LuaEval: +// lua_runtime->evaluate(cmd.argsString); +// break; +// case CommandType::Open: +// open_url(cmd.argsString, OpenType::OpenUrl); +// break; +// case CommandType::TabOpen: +// open_url(cmd.argsString, OpenType::OpenUrlInTab); +// break; +// case CommandType::TabNext: +// next_web_view(); +// break; +// case CommandType::TabPrev: +// previous_web_view(); +// break; +// case CommandType::TabSelect: +// web_view_stack->focus_web_view(cmd.argsString.toLong()); +// break; +// case CommandType::Noop: +// break; +// } +// } - switch (cmd.command) { - case CommandType::LuaEval: - luaRuntime->evaluate(cmd.argsString); - break; - case CommandType::Open: - openUrl(cmd.argsString, OpenType::OpenUrl); - break; - case CommandType::TabOpen: - openUrl(cmd.argsString, OpenType::OpenUrlInTab); - break; - case CommandType::TabNext: - nextWebView(); - break; - case CommandType::TabPrev: - previousWebView(); - break; - case CommandType::TabSelect: - webViewStack->focusWebView(cmd.argsString.toLong()); - break; - case CommandType::Noop: - break; - } -} - -InputMediator::~InputMediator() { delete webViewStack; } +InputMediator::~InputMediator() { delete web_view_stack; } diff --git a/src/InputMediator.hpp b/src/InputMediator.hpp index 87395d5..2cd34f2 100644 --- a/src/InputMediator.hpp +++ b/src/InputMediator.hpp @@ -12,23 +12,23 @@ class InputMediator : public QObject { Q_OBJECT public: - InputMediator(WebViewStack *webViewStack, LuaRuntime *luaRuntime, - KeymapEvaluator *keymapEvaluator); - ~InputMediator(); + InputMediator(WebViewStack *web_view_stack, LuaRuntime *lua_runtime, + KeymapEvaluator *keymap_evaluator); + ~InputMediator() override; - DELEGATE(webViewStack, openUrl, openUrl) - DELEGATE(webViewStack, currentUrl, currentUrl) - DELEGATE(webViewStack, next, nextWebView) - DELEGATE(webViewStack, previous, previousWebView) - DELEGATE(webViewStack, closeCurrent, closeCurrentWebView) - DELEGATE(keymapEvaluator, evaluate, evaluateKeymap) + DELEGATE(web_view_stack, open_url, open_url) + DELEGATE(web_view_stack, current_url, current_url) + DELEGATE(web_view_stack, next, next_web_view) + DELEGATE(web_view_stack, previous, previous_web_view) + DELEGATE(web_view_stack, close_current, close_current_web_view) + DELEGATE(keymap_evaluator, evaluate, evaluate_keymap) protected: - void evaluateCommand(QString command); - void addKeymap(QString mode, QString keyseq, std::function<void()> action); + void add_keymap(const QString &mode_string, const QString &keyseq, + std::function<void()> action); private: - WebViewStack *webViewStack; - LuaRuntime *luaRuntime; - KeymapEvaluator *keymapEvaluator; + WebViewStack *web_view_stack; + LuaRuntime *lua_runtime; + KeymapEvaluator *keymap_evaluator; }; diff --git a/src/LuaRuntime.cpp b/src/LuaRuntime.cpp index 274ec29..eb61a19 100644 --- a/src/LuaRuntime.cpp +++ b/src/LuaRuntime.cpp @@ -7,32 +7,29 @@ extern "C" { #include "AsyncEventLoop.hpp" #include "LuaRuntime.hpp" -const char *uv_global_name = "uv"; -const char *web_global_name = "web"; - LuaRuntime::LuaRuntime() { state = luaL_newstate(); luaL_openlibs(state); - preserveTop(state, { initWebLib(); }) + preserve_top(state, { init_web_lib(); }) } -void LuaRuntime::startEventLoop() { - if (eventLoop != nullptr) - stopEventLoop(); +void LuaRuntime::start_event_loop() { + if (event_loop != nullptr) + stop_event_loop(); // Init event loop - eventLoop = new AsyncEventLoop(); + event_loop = new AsyncEventLoop(); // Load `uv` (luv) - luv_set_loop(state, eventLoop->getUVLoop()); + luv_set_loop(state, event_loop->get_uv_loop()); luaopen_luv(state); lua_setglobal(state, uv_global_name); } -void LuaRuntime::stopEventLoop() { - if (eventLoop != nullptr) { - delete eventLoop; - eventLoop = nullptr; +void LuaRuntime::stop_event_loop() { + if (event_loop != nullptr) { + delete event_loop; + event_loop = nullptr; } // Clear the uv global @@ -41,28 +38,28 @@ void LuaRuntime::stopEventLoop() { lua_gc(state, LUA_GCCOLLECT, 0); } -void LuaRuntime::evaluate(QString code) { - eventLoop->queueTask([this, code]() { - preserveTop(state, { +void LuaRuntime::evaluate(const QString &code) { + event_loop->queue_task([this, code]() { + preserve_top(state, { if (luaL_dostring(state, code.toStdString().c_str()) != LUA_OK) { const char *value = lua_tostring(state, -1); qDebug() << "Lua Error: " << value; - emit evaluationFailed(value); + emit evaluation_failed(value); } else { - QVariant value = getLuaValue(-1); + const QVariant value = get_lua_value(-1); qDebug() << "result: " << value; - emit evaluationCompleted(value); + emit evaluation_completed(value); } }) }); } -QVariant LuaRuntime::evaluateSync(QString code) { +QVariant LuaRuntime::evaluate_sync(const QString &code) { luaL_dostring(state, code.toStdString().c_str()); - return getLuaValue(-1); // TODO: error handling + return get_lua_value(-1); // TODO: error handling } -QVariant LuaRuntime::getLuaValue(int idx) { +QVariant LuaRuntime::get_lua_value(int idx) { if (lua_isstring(state, idx)) return lua_tostring(state, idx); @@ -78,29 +75,29 @@ QVariant LuaRuntime::getLuaValue(int idx) { return lua_tostring(state, idx); } -int LuaRuntime::lua_onUrlOpen(lua_State *state) { +int LuaRuntime::lua_on_url_open(lua_State *state) { const char *url = luaL_optstring(state, 1, ""); - auto runtime = LuaRuntime::instance(); - emit runtime->urlOpened(url, OpenType::OpenUrl); + auto *runtime = LuaRuntime::instance(); + emit runtime->url_opened(url, OpenType::OpenUrl); return 1; } -int LuaRuntime::lua_onUrlTabOpen(lua_State *state) { +int LuaRuntime::lua_on_url_tab_open(lua_State *state) { const char *url = luaL_optstring(state, 1, ""); - auto runtime = LuaRuntime::instance(); - emit runtime->urlOpened(url, OpenType::OpenUrlInTab); + auto *runtime = LuaRuntime::instance(); + emit runtime->url_opened(url, OpenType::OpenUrlInTab); return 1; } -int LuaRuntime::lua_addKeymap(lua_State *state) { +int LuaRuntime::lua_add_keymap(lua_State *state) { const char *mode = lua_tostring(state, 1); const char *keyseq = lua_tostring(state, 2); lua_pushvalue(state, 3); - int functionRef = luaL_ref(state, LUA_REGISTRYINDEX); - auto action = [state, functionRef]() { - preserveTop(state, { - lua_rawgeti(state, LUA_REGISTRYINDEX, functionRef); + const int function_ref = luaL_ref(state, LUA_REGISTRYINDEX); + auto action = [state, function_ref]() { + preserve_top(state, { + lua_rawgeti(state, LUA_REGISTRYINDEX, function_ref); if (lua_pcall(state, 0, 0, 0) != LUA_OK) { const char *error = lua_tostring(state, -1); qDebug() << "Error calling Lua function:" << error; @@ -109,15 +106,15 @@ int LuaRuntime::lua_addKeymap(lua_State *state) { }; // TODO: Cleanup function ref on after keymap clear - auto runtime = LuaRuntime::instance(); - emit runtime->keymapAddRequested(mode, keyseq, action); + auto *runtime = LuaRuntime::instance(); + emit runtime->keymap_add_requested(mode, keyseq, action); return 1; } -void LuaRuntime::loadFile(QString path) { - queueTask([this, path]() { - preserveTop(state, { +void LuaRuntime::load_file(const QString &path) { + queue_task([this, path]() { + preserve_top(state, { qDebug() << "Loading: " << path; if (luaL_dofile(state, path.toStdString().c_str()) != LUA_OK) { qDebug() << "Load file error:" << lua_tostring(state, -1); @@ -126,28 +123,32 @@ void LuaRuntime::loadFile(QString path) { }); } -void LuaRuntime::initWebLib() { +void LuaRuntime::init_web_lib() { + // NOLINTBEGIN(modernize-avoid-c-arrays) + // web luaL_Reg weblib[] = { - {"open", &LuaRuntime::lua_onUrlOpen}, - {"tabopen", &LuaRuntime::lua_onUrlTabOpen}, + {"open", &LuaRuntime::lua_on_url_open}, + {"tabopen", &LuaRuntime::lua_on_url_tab_open}, {nullptr, nullptr}, }; - luaL_newlib(state, weblib); + luaL_newlib(state, weblib); // NOLINT(readability-math-missing-parentheses) lua_setglobal(state, web_global_name); // web.keymap lua_getglobal(state, web_global_name); luaL_Reg keymaplib[] = { - {"set", &LuaRuntime::lua_addKeymap}, + {"set", &LuaRuntime::lua_add_keymap}, }; - luaL_newlib(state, keymaplib); + luaL_newlib(state, keymaplib); // NOLINT(readability-math-missing-parentheses) lua_setfield(state, -2, "keymap"); // lua_pop(state, 1); + + // NOLINTEND(modernize-avoid-c-arrays) } LuaRuntime::~LuaRuntime() { - stopEventLoop(); + stop_event_loop(); lua_close(state); state = nullptr; } diff --git a/src/LuaRuntime.hpp b/src/LuaRuntime.hpp index 3d44282..94d24d8 100644 --- a/src/LuaRuntime.hpp +++ b/src/LuaRuntime.hpp @@ -7,47 +7,51 @@ #include "AsyncEventLoop.hpp" #include "widgets/WebViewStack.hpp" -#define preserveTop(STATE, BODY) \ - int __top = lua_gettop(STATE); \ +#define preserve_top(STATE, BODY) \ + const int __top = lua_gettop(STATE); \ BODY; \ lua_settop(STATE, __top); class LuaRuntime : public QObject { Q_OBJECT + const char *uv_global_name = "uv"; + const char *web_global_name = "web"; + public: static LuaRuntime *instance() { static LuaRuntime inst; return &inst; } - void evaluate(QString code); - void loadFile(QString path); - QVariant evaluateSync(QString code); + void evaluate(const QString &code); + void load_file(const QString &path); + QVariant evaluate_sync(const QString &code); - void stopEventLoop(); - void startEventLoop(); - DELEGATE(eventLoop, queueTask, queueTask) + void stop_event_loop(); + void start_event_loop(); + DELEGATE(event_loop, queue_task, queue_task) - QVariant getLuaValue(int idx); - DEFINE_GETTER(getState, state) + QVariant get_lua_value(int idx); + DEFINE_GETTER(get_state, state) signals: - void urlOpened(QString url, OpenType openType); - void evaluationCompleted(QVariant value); - void evaluationFailed(QString value); - void keymapAddRequested(QString mode, QString keyseq, std::function<void()>); - // void outputProduced(QVariant value); + void url_opened(QString url, OpenType open_type); + void evaluation_completed(QVariant value); + void evaluation_failed(QString value); + void keymap_add_requested(QString mode, QString keyseq, + std::function<void()>); + // void output_produced(QVariant value); protected: LuaRuntime(); - ~LuaRuntime(); - void initWebLib(); - static int lua_onUrlOpen(lua_State *state); - static int lua_onUrlTabOpen(lua_State *state); - static int lua_addKeymap(lua_State *state); + ~LuaRuntime() override; + void init_web_lib(); + static int lua_on_url_open(lua_State *state); + static int lua_on_url_tab_open(lua_State *state); + static int lua_add_keymap(lua_State *state); private: lua_State *state; - AsyncEventLoop *eventLoop = nullptr; + AsyncEventLoop *event_loop = nullptr; }; diff --git a/src/keymap/KeySeqParser.cpp b/src/keymap/KeySeqParser.cpp index c5534eb..f81ba2a 100644 --- a/src/keymap/KeySeqParser.cpp +++ b/src/keymap/KeySeqParser.cpp @@ -1,78 +1,78 @@ #include <QWidget> #include <QtCore> #include <algorithm> +#include <cstdint> #include "keymap/KeySeqParser.hpp" -bool operator==(const KeyChord a, const KeyChord b) { - return a.mod == b.mod && a.key == b.key; +bool operator==(const KeyChord chord1, const KeyChord chord2) { + return chord1.mod == chord2.mod && chord1.key == chord2.key; } -KeySeqParser::KeySeqParser() {} - -QList<KeyChord> KeySeqParser::parse(QString keySequence) { - QList<KeyChord> keyChords; - KeyChord lastKey; +QList<KeyChord> KeySeqParser::parse(QString key_sequence) { + QList<KeyChord> key_chords; + KeyChord last_key; // TODO: Refactor // TODO: Support <C-S-t> - keySequence = keySequence.toLower(); - while (!keySequence.isEmpty()) { - int skipCount = 1; - if (keySequence.startsWith("<c-")) { - int nextClosing = keySequence.indexOf('>'); - auto keyName = keySequence.sliced(3, nextClosing - 3); - lastKey.mod = lastKey.mod | Qt::KeyboardModifier::ControlModifier; - lastKey.key = parseKey(keyName); - skipCount = nextClosing + 1; - } else if (keySequence.startsWith("<s-")) { - int nextClosing = keySequence.indexOf('>'); - auto keyName = keySequence.sliced(3, nextClosing - 3); - lastKey.mod = lastKey.mod | Qt::KeyboardModifier::ShiftModifier; - lastKey.key = parseKey(keyName); - skipCount = nextClosing + 1; - } else if (keySequence.startsWith("<")) { - int nextClosing = keySequence.indexOf('>'); - auto keyName = keySequence.sliced(1, nextClosing - 1); - lastKey.mod = Qt::KeyboardModifier::NoModifier; - lastKey.key = parseKey(keyName); - skipCount = nextClosing + 1; + key_sequence = key_sequence.toLower(); + while (!key_sequence.isEmpty()) { + int skip_count = 1; + uint16_t next_closing; + if (key_sequence.startsWith("<c-")) { + next_closing = key_sequence.indexOf('>'); + auto key_name = key_sequence.sliced(3, next_closing - 3); + last_key.mod = last_key.mod | Qt::KeyboardModifier::ControlModifier; + last_key.key = parse_key(key_name); + skip_count = next_closing + 1; + } else if (key_sequence.startsWith("<s-")) { + next_closing = key_sequence.indexOf('>'); + auto key_name = key_sequence.sliced(3, next_closing - 3); + last_key.mod = last_key.mod | Qt::KeyboardModifier::ShiftModifier; + last_key.key = parse_key(key_name); + skip_count = next_closing + 1; + } else if (key_sequence.startsWith("<")) { + next_closing = key_sequence.indexOf('>'); + auto key_name = key_sequence.sliced(1, next_closing - 1); + last_key.mod = Qt::KeyboardModifier::NoModifier; + last_key.key = parse_key(key_name); + skip_count = next_closing + 1; } else { - auto keyName = keySequence.first(1); - lastKey.mod = Qt::KeyboardModifier::NoModifier; - lastKey.key = parseKey(keyName); + auto key_name = key_sequence.first(1); + last_key.mod = Qt::KeyboardModifier::NoModifier; + last_key.key = parse_key(key_name); } - keySequence.slice(std::max(1, skipCount)); - keyChords.push_back(lastKey); - lastKey = KeyChord(); + key_sequence.slice(std::max(1, skip_count)); + key_chords.push_back(last_key); + last_key = KeyChord(); } - return keyChords; + return key_chords; } -Qt::Key KeySeqParser::parseKey(QString keyName) { - if (keyName.length() == 0) +Qt::Key KeySeqParser::parse_key(const QString &key_name) { + if (key_name.length() == 0) return Qt::Key_T; // TODO: tmp - if (keyName.length() == 1) { - char c = keyName.toStdString().at(0); - return Qt::Key(Qt::Key_A + (c - 'a')); + if (key_name.length() == 1) { + const char key_char = key_name.toStdString().at(0); + return Qt::Key(Qt::Key_A + (key_char - 'a')); } - if (keyName == "space") + if (key_name == "space") return Qt::Key_Space; - if (keyName == "cr") + if (key_name == "cr") return Qt::Key_Return; - if (keyName == "esc") + if (key_name == "esc") return Qt::Key_Escape; - if (keyName == "bs") + if (key_name == "bs") return Qt::Key_Backspace; - if (keyName == "tab") + if (key_name == "tab") return Qt::Key_Tab; return Qt::Key_T; diff --git a/src/keymap/KeySeqParser.hpp b/src/keymap/KeySeqParser.hpp index 2dad0c7..eb878ab 100644 --- a/src/keymap/KeySeqParser.hpp +++ b/src/keymap/KeySeqParser.hpp @@ -1,18 +1,17 @@ #pragma once -#include <QtCore/qnamespace.h> #include <QtCore> -#include <cmath> +#include <cstdint> struct KeyChord { Qt::KeyboardModifiers mod; Qt::Key key; }; -bool operator==(const KeyChord a, const KeyChord b); +bool operator==(KeyChord chord1, KeyChord chord2); -typedef QList<KeyChord> KeySequence; +using KeySequence = QList<KeyChord>; -enum KeyMatchType { +enum KeyMatchType : uint8_t { NoMatch, Match, Pending, @@ -20,8 +19,8 @@ enum KeyMatchType { class KeySeqParser { public: - static KeyMatchType keySequenceMatch(const KeySequence target, - const KeySequence current) { + static KeyMatchType key_sequence_match(const KeySequence &target, + const KeySequence ¤t) { for (int i = 0; i < target.length(); i++) { if (current.length() <= i) return KeyMatchType::Pending; @@ -34,11 +33,9 @@ public: return KeyMatchType::Match; } -public: - KeySeqParser(); - - KeySequence parse(QString keySequence); + KeySeqParser() = default; + KeySequence parse(QString key_sequence); private: - Qt::Key parseKey(QString keyName); + Qt::Key parse_key(const QString &key_name); }; diff --git a/src/keymap/KeymapEvaluator.cpp b/src/keymap/KeymapEvaluator.cpp index 692317b..912c84d 100644 --- a/src/keymap/KeymapEvaluator.cpp +++ b/src/keymap/KeymapEvaluator.cpp @@ -1,20 +1,22 @@ #include <QWidget> #include <QtCore> +#include <utility> +#include "keymap/KeySeqParser.hpp" #include "keymap/KeymapEvaluator.hpp" -KeymapEvaluator::KeymapEvaluator() : QObject() {} - // TODO: Clear mapping after some time -void KeymapEvaluator::addKeymap(KeyMode mode, QString key, KeyAction action) { - if (!modalKeys.contains(mode)) - modalKeys.insert(mode, {}); +void KeymapEvaluator::add_keymap(KeyMode mode, const QString &key, + KeyAction action) { + if (!modal_keys.contains(mode)) + modal_keys.insert(mode, {}); qDebug() << " " << mode << key; - auto keySeq = keySeqParser.parse(key); - modalKeys[mode].append(KeyMap{.keySequence = keySeq, .action = action}); + auto key_seq = key_seq_parser.parse(key); + modal_keys[mode].append( + KeyMap{.key_sequence = key_seq, .action = std::move(action)}); } bool KeymapEvaluator::evaluate(Qt::KeyboardModifiers modifiers, Qt::Key key) { @@ -22,48 +24,49 @@ bool KeymapEvaluator::evaluate(Qt::KeyboardModifiers modifiers, Qt::Key key) { key == Qt::Key_Alt) return true; - auto keymaps = currentModeKeys(); - auto foundPendingMatches = false; + const auto *keymaps = current_mode_keys(); + auto found_pending_matches = false; - activeKeySequence.append(KeyChord{.mod = modifiers, .key = key}); + active_key_sequence.append(KeyChord{.mod = modifiers, .key = key}); - for (auto &keymap : *keymaps) { - auto matchType = - KeySeqParser::keySequenceMatch(keymap.keySequence, activeKeySequence); + for (const auto &keymap : *keymaps) { + auto match_type = KeySeqParser::key_sequence_match(keymap.key_sequence, + active_key_sequence); - if (matchType == KeyMatchType::Match) { + if (match_type == KeyMatchType::Match) { keymap.action(); - activeKeySequence.clear(); + active_key_sequence.clear(); return true; - } else if (matchType == KeyMatchType::Pending) { - foundPendingMatches = true; + } + if (match_type == KeyMatchType::Pending) { + found_pending_matches = true; } } - if (!foundPendingMatches) - activeKeySequence.clear(); + if (!found_pending_matches) + active_key_sequence.clear(); - if (isInsertableMode()) - return foundPendingMatches; + if (is_insertable_mode()) + return found_pending_matches; return true; } -bool KeymapEvaluator::isInsertableMode() { - return currentMode == KeyMode::Insert; +bool KeymapEvaluator::is_insertable_mode() { + return current_mode == KeyMode::Insert; } -const QList<KeyMap> *KeymapEvaluator::currentModeKeys() { - if (!modalKeys.contains(currentMode)) +const QList<KeyMap> *KeymapEvaluator::current_mode_keys() { + if (!modal_keys.contains(current_mode)) return new QList<KeyMap>(); - return &modalKeys[currentMode]; + return &modal_keys[current_mode]; } -KeyMode KeymapEvaluator::modeFromString(QString modeString) { - if (modeString == "n") +KeyMode KeymapEvaluator::mode_from_string(const QString &mode_string) { + if (mode_string == "n") return KeyMode::Normal; - if (modeString == "i") + if (mode_string == "i") return KeyMode::Insert; return KeyMode::Normal; } diff --git a/src/keymap/KeymapEvaluator.hpp b/src/keymap/KeymapEvaluator.hpp index b98a881..4f8184b 100644 --- a/src/keymap/KeymapEvaluator.hpp +++ b/src/keymap/KeymapEvaluator.hpp @@ -1,43 +1,42 @@ #pragma once #include <QWidget> -#include <QtCore/qmap.h> -#include <QtCore/qnamespace.h> #include <QtCore> +#include <cstdint> #include <functional> #include "keymap/KeySeqParser.hpp" #include "utils.hpp" -typedef std::function<void()> KeyAction; +using KeyAction = std::function<void()>; struct KeyMap { - KeySequence keySequence; + KeySequence key_sequence; KeyAction action; }; -enum KeyMode { Normal, Insert }; +enum KeyMode : uint8_t { Normal, Insert }; class KeymapEvaluator : public QObject { Q_OBJECT public: - KeymapEvaluator(); + KeymapEvaluator() = default; - void addKeymap(KeyMode mode, QString key, KeyAction action); + void add_keymap(KeyMode mode, const QString &key, KeyAction action); bool evaluate(Qt::KeyboardModifiers modifiers, Qt::Key key); - KeyMode modeFromString(QString modeString); + KeyMode mode_from_string(const QString &mode_string); - DEFINE_SETTER(setCurrentMode, currentMode) - DEFINE_GETTER(getCurrentMode, currentMode) + DEFINE_SETTER(set_current_mode, current_mode) + DEFINE_GETTER(get_current_mode, current_mode) -private: - const QList<KeyMap> *currentModeKeys(); - bool isInsertableMode(); +protected: + const QList<KeyMap> *current_mode_keys(); + bool is_insertable_mode(); private: - QMap<KeyMode, QList<KeyMap>> modalKeys; - KeySeqParser keySeqParser; - KeyMode currentMode = KeyMode::Normal; - KeySequence activeKeySequence; + QMap<KeyMode, QList<KeyMap>> modal_keys; + KeySeqParser key_seq_parser; + KeyMode current_mode = KeyMode::Normal; + KeySequence active_key_sequence; }; diff --git a/src/main.cpp b/src/main.cpp index d86b484..4a30628 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -5,14 +5,14 @@ #include "widgets/MainWindow.hpp" int main(int argc, char *argv[]) { - QApplication app(argc, argv); + const QApplication app(argc, argv); - auto lua = LuaRuntime::instance(); - lua->startEventLoop(); + auto *lua = LuaRuntime::instance(); + lua->start_event_loop(); - MainWindow mainWindow; - mainWindow.setWindowTitle("null-browser"); - mainWindow.show(); + MainWindow main_window; + main_window.setWindowTitle("null-browser"); + main_window.show(); - return app.exec(); + return QApplication::exec(); } diff --git a/src/utils.hpp b/src/utils.hpp index fbe5597..d5d4fc5 100644 --- a/src/utils.hpp +++ b/src/utils.hpp @@ -1,3 +1,4 @@ +#pragma once #define DELEGATE(OBJ, METHOD, METHOD_AS) \ template <typename... Args> decltype(auto) METHOD_AS(Args &&...args) { \ diff --git a/src/widgets/MainWindow.cpp b/src/widgets/MainWindow.cpp index df8da53..c3c392e 100644 --- a/src/widgets/MainWindow.cpp +++ b/src/widgets/MainWindow.cpp @@ -1,10 +1,9 @@ #include <QKeyEvent> #include <QStackedLayout> #include <QVBoxLayout> -#include <QtCore/qcoreevent.h> -#include <QtCore/qnamespace.h> -#include <QtWidgets/qapplication.h> +#include <QtCore> +#include "Configuration.hpp" #include "InputMediator.hpp" #include "keymap/KeymapEvaluator.hpp" #include "widgets/MainWindow.hpp" @@ -18,50 +17,51 @@ MainWindow::MainWindow() { qApp->installEventFilter(this); // Root stacked layout - auto layout = new QStackedLayout(); + auto *layout = new QStackedLayout(); layout->setContentsMargins(0, 0, 0, 0); layout->setSpacing(0); layout->setStackingMode(QStackedLayout::StackAll); centralWidget()->setLayout(layout); // Web engine - auto webViewStack = new WebViewStack((const Configuration *)&configuration, - new QWebEngineProfile("null-browser")); - layout->addWidget(webViewStack); + auto *web_view_stack = + new WebViewStack((const Configuration *)&configuration, + new QWebEngineProfile("null-browser")); + layout->addWidget(web_view_stack); // TODO: remoev - webViewStack->openUrl(QUrl("https://duckduckgo.com"), OpenType::OpenUrl); - webViewStack->openUrl(QUrl("https://ediblemonad.dev"), - OpenType::OpenUrlInBgTab); - webViewStack->openUrl(QUrl("https://github.com/trending"), - OpenType::OpenUrlInBgTab); + web_view_stack->open_url(QUrl("https://duckduckgo.com"), OpenType::OpenUrl); + web_view_stack->open_url(QUrl("https://ediblemonad.dev"), + OpenType::OpenUrlInBgTab); + web_view_stack->open_url(QUrl("https://github.com/trending"), + OpenType::OpenUrlInBgTab); - auto keymapEvaluator = new KeymapEvaluator; + auto *keymap_evaluator = new KeymapEvaluator; - inputMediator = - new InputMediator(webViewStack, LuaRuntime::instance(), keymapEvaluator); + input_mediator = new InputMediator(web_view_stack, LuaRuntime::instance(), + keymap_evaluator); // NOTE: TMP - LuaRuntime::instance()->loadFile("./config.lua"); + LuaRuntime::instance()->load_file("./config.lua"); // TODO: remove - keymapEvaluator->addKeymap(KeyMode::Normal, "i", [keymapEvaluator]() { - keymapEvaluator->setCurrentMode(KeyMode::Insert); + keymap_evaluator->add_keymap(KeyMode::Normal, "i", [keymap_evaluator]() { + keymap_evaluator->set_current_mode(KeyMode::Insert); }); - keymapEvaluator->addKeymap(KeyMode::Insert, "<esc>", [keymapEvaluator]() { - keymapEvaluator->setCurrentMode(KeyMode::Normal); + keymap_evaluator->add_keymap(KeyMode::Insert, "<esc>", [keymap_evaluator]() { + keymap_evaluator->set_current_mode(KeyMode::Normal); }); - keymapEvaluator->addKeymap(KeyMode::Normal, "<c-t>a", - []() { qDebug() << "Stuff"; }); + keymap_evaluator->add_keymap(KeyMode::Normal, "<c-t>a", + []() { qDebug() << "Stuff"; }); } -bool MainWindow::eventFilter(QObject *, QEvent *event) { +bool MainWindow::eventFilter(QObject * /*watched*/, QEvent *event) { if (event->type() != QEvent::KeyPress) return false; - auto keyEvent = static_cast<QKeyEvent *>(event); - bool shouldSkip = inputMediator->evaluateKeymap(keyEvent->modifiers(), - (Qt::Key)keyEvent->key()); + auto *key_event = static_cast<QKeyEvent *>(event); + const bool should_skip = input_mediator->evaluate_keymap( + key_event->modifiers(), (Qt::Key)key_event->key()); - return shouldSkip; + return should_skip; } diff --git a/src/widgets/MainWindow.hpp b/src/widgets/MainWindow.hpp index c3118fc..26bd15b 100644 --- a/src/widgets/MainWindow.hpp +++ b/src/widgets/MainWindow.hpp @@ -9,10 +9,10 @@ class MainWindow : public QMainWindow { public: MainWindow(); -private: +protected: bool eventFilter(QObject *object, QEvent *event) override; private: - InputMediator *inputMediator; + InputMediator *input_mediator; Configuration configuration; }; diff --git a/src/widgets/WebView.cpp b/src/widgets/WebView.cpp index e00be1f..9c542f8 100644 --- a/src/widgets/WebView.cpp +++ b/src/widgets/WebView.cpp @@ -1,6 +1,7 @@ -#include <QWidget> +#include <QWebEngineView> #include <QtCore> #include "widgets/WebView.hpp" -WebView::WebView(QWebEngineProfile *profile) : QWebEngineView(profile) {} +WebView::WebView(QWebEngineProfile *profile, QWidget *parent_node) + : QWebEngineView(profile, parent_node) {} diff --git a/src/widgets/WebView.hpp b/src/widgets/WebView.hpp index 8a95139..f0457fd 100644 --- a/src/widgets/WebView.hpp +++ b/src/widgets/WebView.hpp @@ -1,13 +1,11 @@ #pragma once -#include <QKeyEvent> #include <QWebEngineView> -#include <QWidget> #include <QtCore> class WebView : public QWebEngineView { Q_OBJECT public: - WebView(QWebEngineProfile *profile); + WebView(QWebEngineProfile *profile, QWidget *parent_node = nullptr); }; diff --git a/src/widgets/WebViewStack.cpp b/src/widgets/WebViewStack.cpp index fa5d3ab..19e472e 100644 --- a/src/widgets/WebViewStack.cpp +++ b/src/widgets/WebViewStack.cpp @@ -1,6 +1,6 @@ #include <QStackedLayout> #include <QWebEngineNewWindowRequest> -#include <algorithm> +#include <QWebEngineProfile> #include <vector> #include "widgets/WebViewStack.hpp" @@ -12,135 +12,134 @@ WebViewStack::WebViewStack(const Configuration *configuration, layout->setContentsMargins(0, 0, 0, 0); layout->setStackingMode(QStackedLayout::StackOne); - createNewWebView(configuration->newTabUrl, true); + create_new_web_view(configuration->new_tab_url, true); } -void WebViewStack::openUrl(QUrl url, OpenType openType) { - switch (openType) { +void WebViewStack::open_url(const QUrl &url, OpenType open_type) { + switch (open_type) { case OpenType::OpenUrl: - setCurrentUrl(url); + set_current_url(url); break; case OpenType::OpenUrlInTab: - createNewWebView(url, true); + create_new_web_view(url, true); break; case OpenType::OpenUrlInBgTab: - createNewWebView(url, false); + create_new_web_view(url, false); break; case OpenType::OpenUrlInWindow: - createNewWebView(url, true); + create_new_web_view(url, true); break; } } -WebView *WebViewStack::createNewWebView(QUrl url, bool focus) { - auto webview = new WebView(profile); +WebView *WebViewStack::create_new_web_view(const QUrl &url, bool focus) { + auto *webview = new WebView(profile); webview->setUrl(url); layout->addWidget(webview); - webViewList.append(webview); + web_view_list.append(webview); connect(webview->page(), &QWebEnginePage::newWindowRequested, this, - &WebViewStack::onNewWebViewRequest); + &WebViewStack::on_new_web_view_request); if (focus) - focusWebView(webViewList.length() - 1); + focus_web_view(web_view_list.length() - 1); return webview; } -QList<Tab> WebViewStack::getTabList() { +QList<Tab> WebViewStack::get_tab_list() { QList<Tab> urls; - for (auto &view : webViewList) + for (auto &view : web_view_list) urls.append(Tab{.url = view->url().toString(), .title = view->title()}); return urls; } -void WebViewStack::onNewWebViewRequest( +void WebViewStack::on_new_web_view_request( const QWebEngineNewWindowRequest &request) { switch (request.destination()) { case QWebEngineNewWindowRequest::InNewTab: - createNewWebView(request.requestedUrl(), true); + create_new_web_view(request.requestedUrl(), true); break; case QWebEngineNewWindowRequest::InNewBackgroundTab: - createNewWebView(request.requestedUrl(), false); + create_new_web_view(request.requestedUrl(), false); break; case QWebEngineNewWindowRequest::InNewWindow: - // TODO: Impl - createNewWebView(request.requestedUrl(), true); - break; case QWebEngineNewWindowRequest::InNewDialog: // TODO: Impl - createNewWebView(request.requestedUrl(), true); + create_new_web_view(request.requestedUrl(), true); break; } } void WebViewStack::next() { - if (webViewList.isEmpty()) + if (web_view_list.isEmpty()) return; - auto index = currentWebViewIndex() + 1; - auto total = webViewList.length(); + auto index = current_web_view_index() + 1; + auto total = web_view_list.length(); index = index >= total ? index % total : index; - focusWebView(index); + focus_web_view(index); } void WebViewStack::previous() { - if (webViewList.isEmpty()) + if (web_view_list.isEmpty()) return; - int index = ((int)currentWebViewIndex()) - 1; - qsizetype total = webViewList.length(); + auto index = current_web_view_index() - 1; + auto total = web_view_list.length(); index = index < 0 ? total + index : index; - focusWebView(index); + focus_web_view(index); } -void WebViewStack::closeCurrent() { close(currentWebViewIndex()); } +void WebViewStack::close_current() { close(current_web_view_index()); } -void WebViewStack::close(int32_t index) { - if (index < 0 || index >= webViewList.length()) +void WebViewStack::close(qsizetype index) { + if (index < 0 || index >= web_view_list.length()) return; - auto webview = webViewList.at(index); + auto *webview = web_view_list.at(index); layout->removeWidget(webview); - webViewList.removeAt(index); + web_view_list.removeAt(index); disconnect(webview->page()); webview->deleteLater(); - focusWebView(currentWebViewIndex()); + focus_web_view(current_web_view_index()); - if (webViewList.isEmpty()) { - createNewWebView(configuration->newTabUrl, true); + if (web_view_list.isEmpty()) { + create_new_web_view(configuration->new_tab_url, true); } } std::vector<QUrl> WebViewStack::urls() { std::vector<QUrl> urls; - for (auto &view : webViewList) + for (auto &view : web_view_list) urls.push_back(view->url()); return urls; } -u_int32_t WebViewStack::currentWebViewIndex() { return layout->currentIndex(); } +uint32_t WebViewStack::current_web_view_index() { + return layout->currentIndex(); +} -u_int32_t WebViewStack::count() { return webViewList.length(); } +uint32_t WebViewStack::count() { return web_view_list.length(); } -void WebViewStack::focusWebView(int32_t index) { - if (webViewList.isEmpty()) +void WebViewStack::focus_web_view(qsizetype index) { + if (web_view_list.isEmpty()) return; index = std::max((long long)0, - std::min((long long)index, webViewList.length() - 1)); - layout->setCurrentIndex(index); + std::min((long long)index, web_view_list.length() - 1)); + layout->setCurrentIndex((int)index); } -QUrl WebViewStack::currentUrl() { - if (currentWebViewIndex() >= webViewList.length()) - return QUrl(""); +QUrl WebViewStack::current_url() { + if (current_web_view_index() >= web_view_list.length()) + return QUrl{}; - return webViewList.at(currentWebViewIndex())->url(); + return web_view_list.at(current_web_view_index())->url(); } -void WebViewStack::setCurrentUrl(QUrl url) { - if (currentWebViewIndex() >= webViewList.length()) +void WebViewStack::set_current_url(const QUrl &url) { + if (current_web_view_index() >= web_view_list.length()) return; - webViewList.at(currentWebViewIndex())->setUrl(url); + web_view_list.at(current_web_view_index())->setUrl(url); } diff --git a/src/widgets/WebViewStack.hpp b/src/widgets/WebViewStack.hpp index 473f699..aa463cc 100644 --- a/src/widgets/WebViewStack.hpp +++ b/src/widgets/WebViewStack.hpp @@ -2,12 +2,18 @@ #include <QStackedLayout> #include <QWebEngineProfile> +#include <cstdint> #include <vector> #include "Configuration.hpp" #include "widgets/WebView.hpp" -enum OpenType { OpenUrl, OpenUrlInTab, OpenUrlInBgTab, OpenUrlInWindow }; +enum OpenType : uint8_t { + OpenUrl, + OpenUrlInTab, + OpenUrlInBgTab, + OpenUrlInWindow +}; struct Tab { QString url; @@ -18,38 +24,35 @@ class WebViewStack : public QWidget { Q_OBJECT public: - inline static const QUrl NewtabURL = QUrl("about:blank"); - -public: WebViewStack(const Configuration *configuration, QWebEngineProfile *profile = new QWebEngineProfile, QWidget *parent = nullptr); - void openUrl(QUrl url, OpenType openType = OpenType::OpenUrl); + void open_url(const QUrl &url, OpenType open_type = OpenType::OpenUrl); std::vector<QUrl> urls(); - QList<Tab> getTabList(); - u_int32_t currentWebViewIndex(); - u_int32_t count(); - QUrl currentUrl(); + QList<Tab> get_tab_list(); + uint32_t current_web_view_index(); + uint32_t count(); + QUrl current_url(); - void focusWebView(int32_t index); + void focus_web_view(qsizetype index); void next(); void previous(); - void close(int32_t index); - void closeCurrent(); - -private: - void setCurrentUrl(QUrl url); - WebView *createNewWebView(QUrl url, bool focus = false); + void close(qsizetype index); + void close_current(); private slots: - void onNewWebViewRequest(const QWebEngineNewWindowRequest &request); + void on_new_web_view_request(const QWebEngineNewWindowRequest &request); + +protected: + void set_current_url(const QUrl &url); + WebView *create_new_web_view(const QUrl &url, bool focus = false); private: const Configuration *configuration; QWebEngineProfile *profile; QStackedLayout *layout; - QList<WebView *> webViewList; + QList<WebView *> web_view_list; }; diff --git a/templates/qtest.sh b/templates/qtest.sh index 48a9f7d..50d288c 100755 --- a/templates/qtest.sh +++ b/templates/qtest.sh @@ -10,6 +10,7 @@ echo "#include <QtCore> #include \"$class_name.hpp\" +// NOLINTBEGIN class ${class_name}Spec : public QObject { Q_OBJECT @@ -26,5 +27,6 @@ private slots: QTEST_REGISTER(${class_name}Spec) #include \"${class_name}Spec.moc\" +// NOLINTEND " > "./spec/${class_name}Spec.cpp" |
