foreseen

A text-based gemini browser with prefetching
git clone git://git.laack.co/foreseen.git
Log | Files | Refs | README | LICENSE

commit b1703740359d1b18192ff7bbe8363afd5cf9de94
parent bed7d0d09bc5f58a6f9d79235e16a821153e1b6e
Author: Andrew Laack <andrew@laack.co>
Date:   Sun,  4 Oct 2026 13:17:21 -0500

Format

Diffstat:
A.clang-format | 358+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
MMakefile | 9+++++++--
DTODO.txt | 8--------
Mdocs/TODO | 2--
Minclude/browser.hpp | 83+++++++++++++++++++++++++++++++++++++++++--------------------------------------
Minclude/cache.hpp | 23++++++++++++-----------
Minclude/errors.hpp | 8+++-----
Minclude/format-switch.hpp | 20+++++++++++---------
Minclude/gemini-client.hpp | 10++++++----
Minclude/heading.hpp | 20+++++++++++---------
Minclude/identity-manager.hpp | 5+++--
Minclude/line.hpp | 13++++++-------
Minclude/link.hpp | 33++++++++++++++++++---------------
Minclude/list-item.hpp | 20+++++++++++---------
Minclude/plaintext.hpp | 20+++++++++++---------
Minclude/preformatted.hpp | 20+++++++++++---------
Minclude/quote.hpp | 20+++++++++++---------
Minclude/render.hpp | 12+++++++-----
Minclude/shared.hpp | 37++++++++++++++++++++-----------------
Minclude/site.hpp | 27++++++++++++++-------------
Minclude/utils.hpp | 30+++++++++++++++---------------
Msrc/browser.cpp | 283+++++++++++++++++++++++++++++++++++++++++--------------------------------------
Msrc/cache.cpp | 8++++----
Msrc/format-switch.cpp | 24+++++++++---------------
Msrc/gemini-client.cpp | 95+++++++++++++++++++++++++++++++++++++++++++++++--------------------------------
Msrc/heading.cpp | 21++++++++++-----------
Msrc/identity-manager.cpp | 18++++++++++--------
Msrc/link.cpp | 80+++++++++++++++++++++++++++++++++++--------------------------------------------
Msrc/list-item.cpp | 30++++++++++++------------------
Msrc/main.cpp | 83++++++++++++++++++++++++++++++++++++++++++++-----------------------------------
Msrc/plaintext.cpp | 20+++++++-------------
Msrc/preformatted.cpp | 24+++++++++---------------
Msrc/quote.cpp | 23+++++++++--------------
Msrc/render.cpp | 266++++++++++++++++++++++++++++++++++++++++---------------------------------------
Msrc/shared.cpp | 2+-
Msrc/site.cpp | 22+++++++---------------
Msrc/utils.cpp | 240++++++++++++++++++++++++++++++++++++++++---------------------------------------
Mtests/browser-test.cpp | 138++++++++++++++++++++++++++++++++++++++++++++++---------------------------------
Atests/cgi-bin/000redirect.py | 4++++
Atests/cgi-bin/rnd.py | 4++++
Mtests/fetch-test.cpp | 33++++++++++++++++-----------------
Mtests/mem-leak-test.cpp | 53+++++++++++++++++++++++++++++------------------------
Mtests/puppet-test.cpp | 403++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------------------
Mtests/pure-test.cpp | 417+++++++++++++++++++++++++++++++++++++++++++------------------------------------
44 files changed, 1854 insertions(+), 1215 deletions(-)

diff --git a/.clang-format b/.clang-format @@ -0,0 +1,358 @@ +--- +Language: Cpp +AlignAfterOpenBracket: true +AccessModifierOffset: -1 +AlignArrayOfStructures: None +AlignConsecutiveAssignments: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + AlignFunctionDeclarations: false + AlignFunctionPointers: false + PadOperators: true +AlignConsecutiveBitFields: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + AlignFunctionDeclarations: false + AlignFunctionPointers: false + PadOperators: false +AlignConsecutiveDeclarations: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + AlignFunctionDeclarations: true + AlignFunctionPointers: false + PadOperators: false +AlignConsecutiveMacros: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + AlignFunctionDeclarations: false + AlignFunctionPointers: false + PadOperators: false +AlignConsecutiveShortCaseStatements: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCaseArrows: false + AlignCaseColons: false +AlignConsecutiveTableGenBreakingDAGArgColons: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + AlignFunctionDeclarations: false + AlignFunctionPointers: false + PadOperators: false +AlignConsecutiveTableGenCondOperatorColons: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + AlignFunctionDeclarations: false + AlignFunctionPointers: false + PadOperators: false +AlignConsecutiveTableGenDefinitionColons: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + AlignFunctionDeclarations: false + AlignFunctionPointers: false + PadOperators: false +AlignEscapedNewlines: Left +AlignOperands: Align +AlignTrailingComments: + AlignPPAndNotPP: true + Kind: Always + OverEmptyLines: 0 +AllowAllArgumentsOnNextLine: true +AllowAllParametersOfDeclarationOnNextLine: true +AllowBreakBeforeNoexceptSpecifier: Never +AllowBreakBeforeQtProperty: false +AllowShortBlocksOnASingleLine: Never +AllowShortCaseExpressionOnASingleLine: true +AllowShortCaseLabelsOnASingleLine: false +AllowShortCompoundRequirementOnASingleLine: true +AllowShortEnumsOnASingleLine: true +AllowShortFunctionsOnASingleLine: All +AllowShortIfStatementsOnASingleLine: WithoutElse +AllowShortLambdasOnASingleLine: All +AllowShortLoopsOnASingleLine: true +AllowShortNamespacesOnASingleLine: false +AlwaysBreakAfterDefinitionReturnType: None +AlwaysBreakBeforeMultilineStrings: true +AttributeMacros: + - __capability + - absl_nonnull + - absl_nullable + - absl_nullability_unknown +BinPackArguments: true +BinPackLongBracedList: true +BinPackParameters: BinPack +BitFieldColonSpacing: Both +BracedInitializerIndentWidth: -1 +BraceWrapping: + AfterCaseLabel: false + AfterClass: false + AfterControlStatement: Never + AfterEnum: false + AfterExternBlock: false + AfterFunction: false + AfterNamespace: false + AfterObjCDeclaration: false + AfterStruct: false + AfterUnion: false + BeforeCatch: false + BeforeElse: false + BeforeLambdaBody: false + BeforeWhile: false + IndentBraces: false + SplitEmptyFunction: true + SplitEmptyRecord: true + SplitEmptyNamespace: true +BreakAdjacentStringLiterals: true +BreakAfterAttributes: Leave +BreakAfterJavaFieldAnnotations: false +BreakAfterOpenBracketBracedList: false +BreakAfterOpenBracketFunction: false +BreakAfterOpenBracketIf: false +BreakAfterOpenBracketLoop: false +BreakAfterOpenBracketSwitch: false +BreakAfterReturnType: None +BreakArrays: true +BreakBeforeBinaryOperators: None +BreakBeforeCloseBracketBracedList: false +BreakBeforeCloseBracketFunction: false +BreakBeforeCloseBracketIf: false +BreakBeforeCloseBracketLoop: false +BreakBeforeCloseBracketSwitch: false +BreakBeforeConceptDeclarations: Always +BreakBeforeBraces: Attach +BreakBeforeInlineASMColon: OnlyMultiline +BreakBeforeTemplateCloser: false +BreakBeforeTernaryOperators: true +BreakBinaryOperations: Never +BreakConstructorInitializers: BeforeColon +BreakFunctionDefinitionParameters: false +BreakInheritanceList: BeforeColon +BreakStringLiterals: true +BreakTemplateDeclarations: Yes +ColumnLimit: 80 +CommentPragmas: '^ IWYU pragma:' +CompactNamespaces: false +ConstructorInitializerIndentWidth: 4 +ContinuationIndentWidth: 4 +Cpp11BracedListStyle: AlignFirstComment +DerivePointerAlignment: false +DisableFormat: false +EmptyLineAfterAccessModifier: Never +EmptyLineBeforeAccessModifier: LogicalBlock +EnumTrailingComma: Leave +ExperimentalAutoDetectBinPacking: false +FixNamespaceComments: true +ForEachMacros: + - foreach + - Q_FOREACH + - BOOST_FOREACH +IfMacros: + - KJ_IF_MAYBE +IncludeBlocks: Regroup +IncludeCategories: + - Regex: '^<ext/.*\.h>' + Priority: 2 + SortPriority: 0 + CaseSensitive: false + - Regex: '^<.*\.h>' + Priority: 1 + SortPriority: 0 + CaseSensitive: false + - Regex: '^<.*' + Priority: 2 + SortPriority: 0 + CaseSensitive: false + - Regex: '.*' + Priority: 3 + SortPriority: 0 + CaseSensitive: false +IncludeIsMainRegex: '([-_](test|unittest))?$' +IncludeIsMainSourceRegex: '' +IndentAccessModifiers: false +IndentCaseBlocks: false +IndentCaseLabels: true +IndentExportBlock: true +IndentExternBlock: AfterExternBlock +IndentGotoLabels: true +IndentPPDirectives: None +IndentRequiresClause: true +IndentWidth: 4 +IndentWrappedFunctionNames: false +InsertBraces: false +InsertNewlineAtEOF: false +InsertTrailingCommas: None +IntegerLiteralSeparator: + Binary: 0 + BinaryMinDigitsInsert: 0 + BinaryMaxDigitsRemove: 0 + Decimal: 0 + DecimalMinDigitsInsert: 0 + DecimalMaxDigitsRemove: 0 + Hex: 0 + HexMinDigitsInsert: 0 + HexMaxDigitsRemove: 0 + BinaryMinDigits: 0 + DecimalMinDigits: 0 + HexMinDigits: 0 +JavaScriptQuotes: Leave +JavaScriptWrapImports: true +KeepEmptyLines: + AtEndOfFile: false + AtStartOfBlock: false + AtStartOfFile: true +KeepFormFeed: false +LambdaBodyIndentation: Signature +LineEnding: DeriveLF +MacroBlockBegin: '' +MacroBlockEnd: '' +MainIncludeChar: Quote +MaxEmptyLinesToKeep: 1 +NamespaceIndentation: None +NumericLiteralCase: + ExponentLetter: Leave + HexDigit: Leave + Prefix: Leave + Suffix: Leave +ObjCBinPackProtocolList: Never +ObjCBlockIndentWidth: 2 +ObjCBreakBeforeNestedBlockParam: true +ObjCSpaceAfterProperty: false +ObjCSpaceBeforeProtocolList: true +OneLineFormatOffRegex: '' +PackConstructorInitializers: NextLine +PenaltyBreakAssignment: 2 +PenaltyBreakBeforeFirstCallParameter: 1 +PenaltyBreakBeforeMemberAccess: 150 +PenaltyBreakComment: 300 +PenaltyBreakFirstLessLess: 120 +PenaltyBreakOpenParenthesis: 0 +PenaltyBreakScopeResolution: 500 +PenaltyBreakString: 1000 +PenaltyBreakTemplateDeclaration: 10 +PenaltyExcessCharacter: 1000000 +PenaltyIndentedWhitespace: 0 +PenaltyReturnTypeOnItsOwnLine: 200 +PointerAlignment: Left +PPIndentWidth: -1 +QualifierAlignment: Leave +RawStringFormats: + - Language: Cpp + Delimiters: + - cc + - CC + - cpp + - Cpp + - CPP + - 'c++' + - 'C++' + CanonicalDelimiter: '' + BasedOnStyle: google + - Language: TextProto + Delimiters: + - pb + - PB + - proto + - PROTO + EnclosingFunctions: + - EqualsProto + - EquivToProto + - PARSE_PARTIAL_TEXT_PROTO + - PARSE_TEST_PROTO + - PARSE_TEXT_PROTO + - ParseTextOrDie + - ParseTextProtoOrDie + - ParseTestProto + - ParsePartialTestProto + CanonicalDelimiter: pb + BasedOnStyle: google +ReferenceAlignment: Pointer +ReflowComments: Always +RemoveBracesLLVM: false +RemoveEmptyLinesInUnwrappedLines: false +RemoveParentheses: Leave +RemoveSemicolon: false +RequiresClausePosition: OwnLine +RequiresExpressionIndentation: OuterScope +SeparateDefinitionBlocks: Leave +ShortNamespaceLines: 1 +SkipMacroDefinitionBody: false +SortIncludes: + Enabled: true + IgnoreCase: false + IgnoreExtension: false +SortJavaStaticImport: Before +SortUsingDeclarations: LexicographicNumeric +SpaceAfterCStyleCast: false +SpaceAfterLogicalNot: false +SpaceAfterOperatorKeyword: false +SpaceAfterTemplateKeyword: true +SpaceAroundPointerQualifiers: Default +SpaceBeforeAssignmentOperators: true +SpaceBeforeCaseColon: false +SpaceBeforeCpp11BracedList: false +SpaceBeforeCtorInitializerColon: true +SpaceBeforeInheritanceColon: true +SpaceBeforeJsonColon: false +SpaceBeforeParens: ControlStatements +SpaceBeforeParensOptions: + AfterControlStatements: true + AfterForeachMacros: true + AfterFunctionDefinitionName: false + AfterFunctionDeclarationName: false + AfterIfMacros: true + AfterNot: false + AfterOverloadedOperator: false + AfterPlacementOperator: true + AfterRequiresInClause: false + AfterRequiresInExpression: false + BeforeNonEmptyParentheses: false +SpaceBeforeRangeBasedForLoopColon: true +SpaceBeforeSquareBrackets: false +SpaceInEmptyBraces: Never +SpacesBeforeTrailingComments: 2 +SpacesInAngles: Never +SpacesInContainerLiterals: true +SpacesInLineCommentPrefix: + Minimum: 1 + Maximum: -1 +SpacesInParens: Never +SpacesInParensOptions: + ExceptDoubleParentheses: false + InCStyleCasts: false + InConditionalStatements: false + InEmptyParentheses: false + Other: false +SpacesInSquareBrackets: false +Standard: Auto +StatementAttributeLikeMacros: + - Q_EMIT +StatementMacros: + - Q_UNUSED + - QT_REQUIRE_VERSION +TableGenBreakInsideDAGArg: DontBreak +TabWidth: 8 +UseTab: Never +VerilogBreakBetweenInstancePorts: true +WhitespaceSensitiveMacros: + - BOOST_PP_STRINGIZE + - CF_SWIFT_NAME + - NS_SWIFT_NAME + - PP_STRINGIZE + - STRINGIZE +WrapNamespaceBodyWithEmptyLines: Leave +... + diff --git a/Makefile b/Makefile @@ -16,6 +16,11 @@ install: build cp docs/foreseen.1 ${MANPREFIX}/man1/foreseen.1 chmod 644 ${MANPREFIX}/man1/foreseen.1 +format: + clang-format -i include/*.hpp + clang-format -i src/*.cpp + clang-format -i tests/*.cpp + clean: rm -rf test*.out foreseen.out rm -rf bench*.out @@ -59,7 +64,7 @@ benchmark: perf record -g ./bench1.out rm bench1.out -test: pure-test browser-test fetch-test puppet-test +test: format pure-test browser-test fetch-test puppet-test lcov --capture --directory . --output-file coverage.info \ --no-external \ --rc geninfo_unexecuted_blocks=1 \ @@ -69,4 +74,4 @@ test: pure-test browser-test fetch-test puppet-test rm -rf *.gcda *.gcno rm -rf coverage.info -.PHONY: test pure-test browser-test fetch-test puppet-test benchmark mem-leak-test clean install build debug server +.PHONY: test pure-test browser-test fetch-test puppet-test benchmark mem-leak-test clean install build debug server format diff --git a/TODO.txt b/TODO.txt @@ -1,8 +0,0 @@ -- cleanups - - function signatures (const, noexcept) - - types - - ints - - imports - - tests - - remove useless ones - - formatter diff --git a/docs/TODO b/docs/TODO @@ -5,5 +5,3 @@ - imports - tests - remove useless ones - - formatter -- man pages diff --git a/include/browser.hpp b/include/browser.hpp @@ -5,64 +5,67 @@ #include <thread> #include <unordered_map> #include <vector> -#include "line.hpp" -#include "identity-manager.hpp" -#include "site.hpp" + #include "cache.hpp" +#include "identity-manager.hpp" +#include "line.hpp" #include "link.hpp" +#include "site.hpp" #include "utils.hpp" const std::string OPENED_EXT_TXT = "Externally opened"; enum SiteLoadResult { - SITE_LOADED, // These are valid status codes so 1X, 2X, and 3e + SITE_LOADED, // These are valid status codes so 1X, 2X, and 3e SITE_TEMPORARY_FAILURE, SITE_PERMANENT_FAILURE, SITE_REQUIRES_CERTIFICATE, SITE_REJECTED_CERTIFICATE, SITE_INVALID_CERTIFICATE, SITE_UNEXPECTED_STATUS_CODE, - LINK_DOES_NOT_EXIST // only for link following + LINK_DOES_NOT_EXIST // only for link following }; -struct SiteLoadPair { // TODO: Set this up. +struct SiteLoadPair { // TODO: Set this up. SiteLoadResult result; std::string metaLine; }; class Browser { - private: - IdentityManager identityManager = IdentityManager{}; - std::vector<std::thread> threads; - std::vector<std::atomic<bool>> done; - std::unordered_map<std::string, int> previousStatusCodes; - std::vector<Link*> siteHistory; - std::thread openThread; - int previousIdx = -1; - Cache* visitedCache; - Cache* preFetchCache; - Site* currentSite; - std::vector<Line*> lines; - std::vector<std::size_t> links; // these point to line indices - void tryCacheTargets(); - Site* findInCacheAndPromoteIfRelevant(std::string& urlString); - public: - Browser(); - void setLinksOfCurrentLines(); - ~Browser(); - SiteLoadPair goToSite(std::string url, bool addToHistory = true, bool refresh = false); - void setDone(int threadIdx); - void refresh(); - Site* getCurrentSite(); - std::string tryDownloadPage(std::string destinationDir = "") noexcept; - Link* getCurrentLink(); - std::optional<uri> getPriorUri(); - std::vector<std::pair<std::string, TextRender>> renderSite(); - std::vector<Line*> toLines(Site* site); - SiteLoadPair followLinkNumber(int linkToFollow); - std::vector<Link>* getLinkLines(); - Identity getIdentity(uri uriInput); - void justCacheSite(Link link); - void goBack(); - void goForward(); + private: + IdentityManager identityManager = IdentityManager{}; + std::vector<std::thread> threads; + std::vector<std::atomic<bool>> done; + std::unordered_map<std::string, int> previousStatusCodes; + std::vector<Link*> siteHistory; + std::thread openThread; + int previousIdx = -1; + Cache* visitedCache; + Cache* preFetchCache; + Site* currentSite; + std::vector<Line*> lines; + std::vector<std::size_t> links; // these point to line indices + void tryCacheTargets(); + Site* findInCacheAndPromoteIfRelevant(std::string& urlString); + + public: + Browser(); + void setLinksOfCurrentLines(); + ~Browser(); + SiteLoadPair goToSite(std::string url, bool addToHistory = true, + bool refresh = false); + void setDone(int threadIdx); + void refresh(); + Site* getCurrentSite(); + std::string tryDownloadPage(std::string destinationDir = "") noexcept; + Link* getCurrentLink(); + std::optional<uri> getPriorUri(); + std::vector<std::pair<std::string, TextRender>> renderSite(); + std::vector<Line*> toLines(Site* site); + SiteLoadPair followLinkNumber(int linkToFollow); + std::vector<Link>* getLinkLines(); + Identity getIdentity(uri uriInput); + void justCacheSite(Link link); + void goBack(); + void goForward(); }; diff --git a/include/cache.hpp b/include/cache.hpp @@ -1,18 +1,19 @@ -// cache for prior sites and such. -#include "site.hpp" -#include <mutex> +// cache for prior sites and such. #include <deque> +#include <mutex> #include <optional> #include <unordered_map> +#include "site.hpp" class Cache { - private: - void evict(); - std::unordered_map<std::string,Site> cache; - std::mutex mutex; - std::deque<std::string> evictionQueue; - public: - std::optional<Site> getSite(const std::string& site); - void addSite(std::string address, Site site); + private: + void evict(); + std::unordered_map<std::string, Site> cache; + std::mutex mutex; + std::deque<std::string> evictionQueue; + + public: + std::optional<Site> getSite(const std::string& site); + void addSite(std::string address, Site site); }; diff --git a/include/errors.hpp b/include/errors.hpp @@ -2,9 +2,7 @@ #include <stdexcept> -class FileReadError : public std::invalid_argument -{ -public: - FileReadError() : std::invalid_argument("Unable to read file") { }; +class FileReadError : public std::invalid_argument { + public: + FileReadError() : std::invalid_argument("Unable to read file") {}; }; - diff --git a/include/format-switch.hpp b/include/format-switch.hpp @@ -1,14 +1,16 @@ #pragma once -#include "line.hpp" #include <cstdint> +#include "line.hpp" + class FormatSwitch : public Line { - private: - std::string text = ""; - public: - FormatSwitch(std::string text); - std::string textToDraw() override; - uint8_t getColor() override; - LineType type() override; - bool isBold() override; + private: + std::string text = ""; + + public: + FormatSwitch(std::string text); + std::string textToDraw() override; + uint8_t getColor() override; + LineType type() override; + bool isBold() override; }; diff --git a/include/gemini-client.hpp b/include/gemini-client.hpp @@ -1,10 +1,12 @@ #pragma once -#include "site.hpp" #include "link.hpp" +#include "site.hpp" class GeminiClient { - Site* getNetworkedSite(Link link, std::string crtPath, std::string keyPath); - public: - Site* fetchSite(Link link, std::string crtPath = "", std::string keyPath = ""); + Site* getNetworkedSite(Link link, std::string crtPath, std::string keyPath); + + public: + Site* fetchSite(Link link, std::string crtPath = "", + std::string keyPath = ""); }; diff --git a/include/heading.hpp b/include/heading.hpp @@ -3,17 +3,19 @@ #include <cstdint> #include <optional> #include <string> + #include "../vendor/uri.hpp" #include "line.hpp" class Heading : public Line { - int headingLevel = 1; - std::string actualText; - std::string toDraw; - public: - Heading(std::string text); - std::string textToDraw() override; - uint8_t getColor() override; - LineType type() override; - bool isBold() override; + int headingLevel = 1; + std::string actualText; + std::string toDraw; + + public: + Heading(std::string text); + std::string textToDraw() override; + uint8_t getColor() override; + LineType type() override; + bool isBold() override; }; diff --git a/include/identity-manager.hpp b/include/identity-manager.hpp @@ -2,6 +2,7 @@ #include <string> #include <unordered_map> + #include "../vendor/uri.hpp" struct Identity { @@ -10,6 +11,6 @@ struct Identity { }; class IdentityManager { - public: - Identity getIdentityForURI(uri destination); + public: + Identity getIdentityForURI(uri destination); }; diff --git a/include/line.hpp b/include/line.hpp @@ -3,7 +3,6 @@ #include <cstdint> #include <string> - enum LineType { LINK, PLAINTEXT, @@ -17,10 +16,10 @@ enum LineType { }; class Line { - public: - virtual std::string textToDraw() = 0; - virtual uint8_t getColor() = 0; - virtual LineType type() = 0; - virtual ~Line() = default; - virtual bool isBold() = 0; + public: + virtual std::string textToDraw() = 0; + virtual uint8_t getColor() = 0; + virtual LineType type() = 0; + virtual ~Line() = default; + virtual bool isBold() = 0; }; diff --git a/include/link.hpp b/include/link.hpp @@ -3,23 +3,26 @@ #include <cstdint> #include <optional> #include <string> + #include "../vendor/uri.hpp" #include "line.hpp" class Link : public Line { - private: - bool invalid = false; - int linkNumber = -1; - std::string renderedText; - uri linkDestination = uri("gemini://example.com"); - std::optional<std::string> linkText; - uri parseDestination(std::string destination, std::optional<uri> prior); - public: - Link(std::string text, std::optional<uri> prior = std::nullopt, int linkNumber = -1); - uri getLinkDestination(); - std::optional<std::string> getLinkText(); - std::string textToDraw() override; - uint8_t getColor() override; - bool isBold() override; - LineType type() override; + private: + bool invalid = false; + int linkNumber = -1; + std::string renderedText; + uri linkDestination = uri("gemini://example.com"); + std::optional<std::string> linkText; + uri parseDestination(std::string destination, std::optional<uri> prior); + + public: + Link(std::string text, std::optional<uri> prior = std::nullopt, + int linkNumber = -1); + uri getLinkDestination(); + std::optional<std::string> getLinkText(); + std::string textToDraw() override; + uint8_t getColor() override; + bool isBold() override; + LineType type() override; }; diff --git a/include/list-item.hpp b/include/list-item.hpp @@ -1,14 +1,16 @@ #pragma once -#include "line.hpp" #include <cstdint> +#include "line.hpp" + class ListItem : public Line { - private: - std::string textToRender; - public: - ListItem(std::string text); - std::string textToDraw() override; - uint8_t getColor() override; - LineType type() override; - bool isBold() override; + private: + std::string textToRender; + + public: + ListItem(std::string text); + std::string textToDraw() override; + uint8_t getColor() override; + LineType type() override; + bool isBold() override; }; diff --git a/include/plaintext.hpp b/include/plaintext.hpp @@ -1,14 +1,16 @@ #pragma once -#include "line.hpp" #include <cstdint> +#include "line.hpp" + class Plaintext : public Line { - private: - std::string text = ""; - public: - Plaintext(std::string text); - std::string textToDraw() override; - uint8_t getColor() override; - LineType type() override; - bool isBold() override; + private: + std::string text = ""; + + public: + Plaintext(std::string text); + std::string textToDraw() override; + uint8_t getColor() override; + LineType type() override; + bool isBold() override; }; diff --git a/include/preformatted.hpp b/include/preformatted.hpp @@ -1,14 +1,16 @@ #pragma once -#include "line.hpp" #include <cstdint> +#include "line.hpp" + class Preformatted : public Line { - private: - std::string text = ""; - public: - Preformatted(std::string text); - std::string textToDraw() override; - uint8_t getColor() override; - LineType type() override; - bool isBold() override; + private: + std::string text = ""; + + public: + Preformatted(std::string text); + std::string textToDraw() override; + uint8_t getColor() override; + LineType type() override; + bool isBold() override; }; diff --git a/include/quote.hpp b/include/quote.hpp @@ -1,14 +1,16 @@ #pragma once -#include "line.hpp" #include <cstdint> +#include "line.hpp" + class Quote : public Line { - private: - std::string textToRender; - public: - Quote(std::string text); - std::string textToDraw() override; - uint8_t getColor() override; - LineType type() override; - bool isBold() override; + private: + std::string textToRender; + + public: + Quote(std::string text); + std::string textToDraw() override; + uint8_t getColor() override; + LineType type() override; + bool isBold() override; }; diff --git a/include/render.hpp b/include/render.hpp @@ -1,13 +1,15 @@ -#include "../include/browser.hpp" -#include "../include/utils.hpp" +#include <ncurses.h> +#include <unctrl.h> + #include <cassert> #include <cstdint> -#include <ncurses.h> #include <string> -#include <unctrl.h> #include <utility> #include <vector> +#include "../include/browser.hpp" +#include "../include/utils.hpp" + #pragma once struct DrawState { @@ -33,4 +35,4 @@ struct DrawState { }; bool mainLoop(DrawState& ds, Browser& b, int input, int cols, int lines); -void tryVisitSite(DrawState& ds , Browser& b, std::string site); +void tryVisitSite(DrawState& ds, Browser& b, std::string site); diff --git a/include/shared.hpp b/include/shared.hpp @@ -3,30 +3,33 @@ #include <cstdint> #include <string> -extern std::string DEFAULT_SEARCH_ENGINE; // default search option when search is inferred -extern int SITE_CACHE_LIMIT; // number of links to prefetch per page -extern int THREAD_NUM; // thread count in thread pool for pre-fetching -extern int MAX_WIDTH; // max text width -extern int CACHE_SIZE; // max elements in history cache and max in prefetch cache -extern uint8_t COLOR_LINK; // color used for links -extern uint8_t COLOR_PREFORMATTED; // color used for preformatted text regions -extern uint8_t COLOR_QUOTE; // color used for quote lines +extern std::string + DEFAULT_SEARCH_ENGINE; // default search option when search is inferred +extern int SITE_CACHE_LIMIT; // number of links to prefetch per page +extern int THREAD_NUM; // thread count in thread pool for pre-fetching +extern int MAX_WIDTH; // max text width +extern int + CACHE_SIZE; // max elements in history cache and max in prefetch cache +extern uint8_t COLOR_LINK; // color used for links +extern uint8_t COLOR_PREFORMATTED; // color used for preformatted text regions +extern uint8_t COLOR_QUOTE; // color used for quote lines -extern uint8_t COLOR_H3; // color used for H3 lines -extern uint8_t COLOR_H2; // color used for H2 lines -extern uint8_t COLOR_H1; // color used for H1 lines +extern uint8_t COLOR_H3; // color used for H3 lines +extern uint8_t COLOR_H2; // color used for H2 lines +extern uint8_t COLOR_H1; // color used for H1 lines -extern uint8_t COLOR_LIST_ITEM; // color used for list items -extern uint8_t COLOR_FORMAT_SWITCH; // color used for format switch lines -extern uint8_t COLOR_PLAINTEXT; // color used for plaintext lines +extern uint8_t COLOR_LIST_ITEM; // color used for list items +extern uint8_t COLOR_FORMAT_SWITCH; // color used for format switch lines +extern uint8_t COLOR_PLAINTEXT; // color used for plaintext lines - // We guarantee responses can be at least the size limit, and at most 4096 additional bytes +// We guarantee responses can be at least the size limit, and at most 4096 +// additional bytes extern int RESPONSE_SIZE_LIMIT_MB; // since the xdg-open stuff is in a seperate process nothing will go to stdout // even in the echo case. #ifdef DEBUG_MODE - const char openUnknownScheme[] = "echo"; +const char openUnknownScheme[] = "echo"; #else - const char openUnknownScheme[] = "xdg-open"; +const char openUnknownScheme[] = "xdg-open"; #endif diff --git a/include/site.hpp b/include/site.hpp @@ -3,17 +3,18 @@ #include <cstdint> #include <string> -class Site{ - private: - std::string body; - std::string header; - bool unreachable = false; - public: - Site(std::string header, std::string body); - std::string getBody(); - uint32_t getStatusCode(); - std::string getHeader(); - std::string getMeta(); - void setUnreachable(); - bool getUnreachable(); +class Site { + private: + std::string body; + std::string header; + bool unreachable = false; + + public: + Site(std::string header, std::string body); + std::string getBody(); + uint32_t getStatusCode(); + std::string getHeader(); + std::string getMeta(); + void setUnreachable(); + bool getUnreachable(); }; diff --git a/include/utils.hpp b/include/utils.hpp @@ -1,40 +1,40 @@ #pragma once #include <cstdint> -#include <optional> #include <filesystem> +#include <optional> #include <string> #include <vector> -#include "line.hpp" + #include "../vendor/uri.hpp" +#include "line.hpp" struct TextRender { uint8_t color; - bool isBold:1; - bool shouldFold:1 = true; // preformatted text doesn't need to be folded. + bool isBold : 1; + bool shouldFold : 1 = true; // preformatted text doesn't need to be folded. }; bool isPrefixed(std::string input, std::string prefix); std::string readFileToString(std::string filePath); bool isWhiteSpace(std::string& line, int idx); std::vector<std::string> stringToList(std::string input); -Line* lineToLine(std::string input, std::optional<uri> prior, int linkCount, bool isPreformatted); +Line* lineToLine(std::string input, std::optional<uri> prior, int linkCount, + bool isPreformatted); std::string urlEncode(const std::string& value); std::string getNewTab(); void openUrl(const std::string& url); -std::vector<std::pair<std::string, TextRender>> breakLines(std::vector<std::pair<std::string, TextRender>>& strLs, int width, int cols); +std::vector<std::pair<std::string, TextRender>> breakLines( + std::vector<std::pair<std::string, TextRender>>& strLs, int width, + int cols); std::string stripLeadingWhiteSpace(std::string& input); - -// This will over-write the existing file, if relevant. This will not create directories for you. +// This will over-write the existing file, if relevant. This will not create +// directories for you. void writeStringToFile(std::string toWrite, std::string filePath); std::string encodeAsFilename(uri link); std::filesystem::path getHome(); -enum ReturnType { - NUMBER_DESTINATION, - STRING_DESTINATION, - NO_DESTINATION -}; +enum ReturnType { NUMBER_DESTINATION, STRING_DESTINATION, NO_DESTINATION }; struct Destination { int linkNumber; @@ -44,8 +44,8 @@ struct Destination { Destination handleDestinationResolution(std::string destination, bool isCli); - -void sanitizeCharactersToDraw(std::vector<std::pair<std::string, TextRender>>& strLs); +void sanitizeCharactersToDraw( + std::vector<std::pair<std::string, TextRender>>& strLs); bool isSendableIfGeminiUrl(const uri& u); std::string getEditor(); diff --git a/src/browser.cpp b/src/browser.cpp @@ -1,32 +1,36 @@ #include "../include/browser.hpp" + +#include <unistd.h> + #include <cassert> +#include <cstddef> +#include <cstdlib> #include <filesystem> +#include <optional> #include <stdexcept> #include <string> #include <thread> -#include <unistd.h> -#include "../include/site.hpp" -#include "../include/shared.hpp" -#include "../include/errors.hpp" -#include "../include/gemini-client.hpp" -#include "../include/utils.hpp" -#include "../include/identity-manager.hpp" -#include <cstddef> -#include <cstdlib> -#include <optional> #include <utility> #include <vector> +#include "../include/errors.hpp" +#include "../include/gemini-client.hpp" +#include "../include/identity-manager.hpp" +#include "../include/shared.hpp" +#include "../include/site.hpp" +#include "../include/utils.hpp" std::string Browser::tryDownloadPage(std::string downloadDir) noexcept { std::string body = currentSite->getBody(); Link* current = getCurrentLink(); - assert(current != nullptr); // calling download page should always happen from a page... + assert( + current != + nullptr); // calling download page should always happen from a page... std::string destination = encodeAsFilename(current->getLinkDestination()); try { - if(downloadDir != "") { + if (downloadDir != "") { std::filesystem::path pth = std::filesystem::path(downloadDir); std::filesystem::create_directories(pth); destination = pth / destination; @@ -41,12 +45,13 @@ std::string Browser::tryDownloadPage(std::string downloadDir) noexcept { void dispatch(std::vector<Link>* targets, Browser& b, int threadIdx) { std::vector<Link>& refT = *targets; - for(int i = 0 ; i < (int)refT.size() && i < SITE_CACHE_LIMIT; ++i) { + for (int i = 0; i < (int)refT.size() && i < SITE_CACHE_LIMIT; ++i) { auto& target = refT[i]; auto id = b.getIdentity(target.getLinkDestination()); - if(id.crtPath != "" || id.keyPath != "") { - continue; // don't try to prefetch for domains we normally pass a cert to. + if (id.crtPath != "" || id.keyPath != "") { + continue; // don't try to prefetch for domains we normally pass a + // cert to. } b.justCacheSite(target); } @@ -54,15 +59,13 @@ void dispatch(std::vector<Link>* targets, Browser& b, int threadIdx) { delete targets; } -void Browser::setDone(int threadIdx) { - done[threadIdx] = true; -} +void Browser::setDone(int threadIdx) { done[threadIdx] = true; } void Browser::tryCacheTargets() { bool dispatched = false; - for(int i = 0; i < THREAD_NUM && dispatched == false; ++i) { - if(done[i]) { - if(threads[i].joinable()) { + for (int i = 0; i < THREAD_NUM && dispatched == false; ++i) { + if (done[i]) { + if (threads[i].joinable()) { threads[i].join(); } auto* lls = getLinkLines(); @@ -71,35 +74,34 @@ void Browser::tryCacheTargets() { dispatched = true; } } - } Site* Browser::findInCacheAndPromoteIfRelevant(std::string& urlString) { - Site* site = nullptr; - std::optional<Site> cachedSite = visitedCache->getSite(urlString); - if(cachedSite != std::nullopt) { - site = new Site(*cachedSite); - } - if(site == nullptr) { - std::optional<Site> cached = preFetchCache->getSite(urlString); - if(cached != std::nullopt) { - site = new Site(*cached); - visitedCache->addSite(urlString, *cached); - } + Site* site = nullptr; + std::optional<Site> cachedSite = visitedCache->getSite(urlString); + if (cachedSite != std::nullopt) { + site = new Site(*cachedSite); + } + if (site == nullptr) { + std::optional<Site> cached = preFetchCache->getSite(urlString); + if (cached != std::nullopt) { + site = new Site(*cached); + visitedCache->addSite(urlString, *cached); } + } - return site; + return site; } void Browser::refresh() { goToSite(getPriorUri().value().to_string(), false, true); } -SiteLoadPair Browser::goToSite(std::string url, bool addToHistory, bool refresh) { - +SiteLoadPair Browser::goToSite(std::string url, bool addToHistory, + bool refresh) { Link* prior = nullptr; - if((int)siteHistory.size() > previousIdx && previousIdx >= 0) { + if ((int)siteHistory.size() > previousIdx && previousIdx >= 0) { prior = siteHistory[previousIdx]; } @@ -107,52 +109,53 @@ SiteLoadPair Browser::goToSite(std::string url, bool addToHistory, bool refresh) Link* destination = nullptr; - if(prior == nullptr) { + if (prior == nullptr) { destination = new Link{url}; } else { - destination = new Link{url,prior->getLinkDestination()}; + destination = new Link{url, prior->getLinkDestination()}; } std::string urlString = destination->getLinkDestination().to_string(); - std::string scheme = destination->getLinkDestination().get_scheme(); - if(scheme != "gemini" && scheme != "file" && scheme != "about") { // TODO: Should I use about or just a fs file? - if(openThread.joinable()) { + std::string scheme = destination->getLinkDestination().get_scheme(); + if (scheme != "gemini" && scheme != "file" && + scheme != "about") { // TODO: Should I use about or just a fs file? + if (openThread.joinable()) { openThread.join(); } // this doesn't have to be blocking... // my browser hangs very often so yea. - openThread = std::thread(openUrl, urlString); + openThread = std::thread(openUrl, urlString); delete destination; return SiteLoadPair{SITE_LOADED, OPENED_EXT_TXT}; } - Site* site = nullptr; - Identity id = identityManager.getIdentityForURI(destination->getLinkDestination()); + Identity id = + identityManager.getIdentityForURI(destination->getLinkDestination()); - if(urlString.find("gemini://") != std::string::npos && !refresh) { - if(id.crtPath != "" && id.keyPath != "") { - if(!addToHistory) { + if (urlString.find("gemini://") != std::string::npos && !refresh) { + if (id.crtPath != "" && id.keyPath != "") { + if (!addToHistory) { site = findInCacheAndPromoteIfRelevant(urlString); } } else { site = findInCacheAndPromoteIfRelevant(urlString); } } - - if(site == nullptr) { + + if (site == nullptr) { site = client.fetchSite(*destination, id.crtPath, id.keyPath); } - if(site == nullptr || site->getUnreachable()) { - if(site != nullptr) { + if (site == nullptr || site->getUnreachable()) { + if (site != nullptr) { delete site; } delete destination; - if(site == nullptr) { + if (site == nullptr) { return SiteLoadPair{SITE_PERMANENT_FAILURE, "Connection error"}; } return SiteLoadPair{SITE_PERMANENT_FAILURE, site->getMeta()}; @@ -164,61 +167,61 @@ SiteLoadPair Browser::goToSite(std::string url, bool addToHistory, bool refresh) delete site; delete destination; - if(sc < 10 || sc > 69) { + if (sc < 10 || sc > 69) { return SiteLoadPair{SITE_UNEXPECTED_STATUS_CODE, meta}; } - if(sc < 50) { // 40 -> 49 + if (sc < 50) { // 40 -> 49 return SiteLoadPair{SITE_TEMPORARY_FAILURE, meta}; } - if(sc < 60) { // 50 -> 59 + if (sc < 60) { // 50 -> 59 return SiteLoadPair{SITE_PERMANENT_FAILURE, meta}; } - if(sc == 60) { + if (sc == 60) { return SiteLoadPair{SITE_REQUIRES_CERTIFICATE, meta}; } - - if(sc == 61) { + + if (sc == 61) { return SiteLoadPair{SITE_REJECTED_CERTIFICATE, meta}; } - if(sc == 62) { + if (sc == 62) { return SiteLoadPair{SITE_INVALID_CERTIFICATE, meta}; } return SiteLoadPair{SITE_REQUIRES_CERTIFICATE, meta}; - } - if(addToHistory) { - while((int)siteHistory.size() > previousIdx + 1) { - delete siteHistory[siteHistory.size() - 1]; + if (addToHistory) { + while ((int)siteHistory.size() > previousIdx + 1) { + delete siteHistory[siteHistory.size() - 1]; siteHistory.pop_back(); } siteHistory.push_back(destination); previousIdx = siteHistory.size() - 1; } - if(currentSite != nullptr) { + if (currentSite != nullptr) { delete currentSite; } currentSite = site; - if(urlString.find("gemini://") != std::string::npos) { + if (urlString.find("gemini://") != std::string::npos) { int sc = site->getStatusCode(); - if(sc >= 20 && sc <= 29) { + if (sc >= 20 && sc <= 29) { visitedCache->addSite(urlString, *site); } } - for(auto* line: lines) { + for (auto* line : lines) { delete line; } lines = toLines(site); setLinksOfCurrentLines(); - previousStatusCodes[destination->getLinkDestination().to_string()] = site->getStatusCode(); + previousStatusCodes[destination->getLinkDestination().to_string()] = + site->getStatusCode(); if (!addToHistory) { delete destination; } @@ -231,7 +234,6 @@ Identity Browser::getIdentity(uri uriInput) { return this->identityManager.getIdentityForURI(uriInput); } - void Browser::justCacheSite(Link link) { auto client = GeminiClient{}; @@ -243,13 +245,13 @@ void Browser::justCacheSite(Link link) { Site* site = nullptr; - if(urlString.find("gemini://") != std::string::npos) { + if (urlString.find("gemini://") != std::string::npos) { site = client.fetchSite(link); - } + } - if(site != nullptr) { + if (site != nullptr) { int sc = site->getStatusCode(); - if(sc >= 20 && sc <= 29) { + if (sc >= 20 && sc <= 29) { preFetchCache->addSite(urlString, *site); } delete site; @@ -258,20 +260,17 @@ void Browser::justCacheSite(Link link) { return; } - void Browser::setLinksOfCurrentLines() { - links = std::vector<std::size_t> {}; - for(std::size_t i = 0; i < lines.size(); ++i) { - if(lines[i]->type() == LINK) { + links = std::vector<std::size_t>{}; + for (std::size_t i = 0; i < lines.size(); ++i) { + if (lines[i]->type() == LINK) { links.push_back(i); } } } - // TODO: This is a pure function. std::vector<Line*> Browser::toLines(Site* site) { - auto lines = stringToList(site->getBody()); std::vector<Line*> res{}; @@ -279,20 +278,19 @@ std::vector<Line*> Browser::toLines(Site* site) { int lc = 1; bool isPreformatted = false; - for(auto line: lines) { + for (auto line : lines) { res.push_back(lineToLine(line, getPriorUri(), lc, isPreformatted)); - if (res[res.size()-1]->type() == FORMAT_SWITCH) { + if (res[res.size() - 1]->type() == FORMAT_SWITCH) { isPreformatted = !isPreformatted; } - if(res[res.size() - 1]->type() == LINK) { + if (res[res.size() - 1]->type() == LINK) { lc += 1; } } return res; } - -Browser::Browser() : threads(THREAD_NUM), done(THREAD_NUM){ +Browser::Browser() : threads(THREAD_NUM), done(THREAD_NUM) { currentSite = nullptr; visitedCache = new Cache{}; preFetchCache = new Cache{}; @@ -300,16 +298,16 @@ Browser::Browser() : threads(THREAD_NUM), done(THREAD_NUM){ d = true; } - // this ensures some nice invariants about the browser, like always having at least one valid page. + // this ensures some nice invariants about the browser, like always having + // at least one valid page. SiteLoadPair start = goToSite("about://newtab"); - if(start.result != SITE_LOADED) { + if (start.result != SITE_LOADED) { throw std::runtime_error("Browser unexpectedly failed to start."); } } // TODO: SHould add more stuff here too, like the links stuff. Browser::~Browser() { - for (auto& t : threads) { if (t.joinable()) { t.join(); @@ -333,54 +331,52 @@ Browser::~Browser() { } } - -Site* Browser::getCurrentSite() { - return currentSite; -} +Site* Browser::getCurrentSite() { return currentSite; } std::vector<std::pair<std::string, TextRender>> Browser::renderSite() { - std::vector<std::pair<std::string, TextRender>> res{}; res.reserve(lines.size()); - for(auto* line: lines) { + for (auto* line : lines) { // TODO: Don't special case this; define an interface. - if(line->type() == PREFORMATTED) { - std::pair<std::string,TextRender> cp {line->textToDraw(), TextRender {line->getColor(), line->isBold(), false}}; + if (line->type() == PREFORMATTED) { + std::pair<std::string, TextRender> cp{ + line->textToDraw(), + TextRender{line->getColor(), line->isBold(), false}}; res.push_back(cp); } else { - std::pair<std::string,TextRender> cp {line->textToDraw(), TextRender {line->getColor(), line->isBold()}}; + std::pair<std::string, TextRender> cp{ + line->textToDraw(), + TextRender{line->getColor(), line->isBold()}}; res.push_back(cp); } } return res; } - std::optional<uri> Browser::getPriorUri() { - if(previousIdx < (int)siteHistory.size() && previousIdx >= 0) { + if (previousIdx < (int)siteHistory.size() && previousIdx >= 0) { return siteHistory[previousIdx]->getLinkDestination(); } return std::nullopt; - } std::vector<Link>* Browser::getLinkLines() { - std::vector<Link>* res = new std::vector<Link> {}; - for(auto& ln : links) { + std::vector<Link>* res = new std::vector<Link>{}; + for (auto& ln : links) { res->push_back(*dynamic_cast<Link*>(lines[ln])); } return res; } - SiteLoadPair Browser::followLinkNumber(int linkToFollow) { - if((int)links.size() > linkToFollow-1 && linkToFollow-1 >= 0) { - std::size_t pos = links[linkToFollow-1]; - if(lines.size() > pos) { + if ((int)links.size() > linkToFollow - 1 && linkToFollow - 1 >= 0) { + std::size_t pos = links[linkToFollow - 1]; + if (lines.size() > pos) { Line* ptr = lines[pos]; Link* ptrLnk = dynamic_cast<Link*>(ptr); - SiteLoadPair res = goToSite(ptrLnk->getLinkDestination().to_string(), true); + SiteLoadPair res = + goToSite(ptrLnk->getLinkDestination().to_string(), true); return res; } } @@ -388,36 +384,43 @@ SiteLoadPair Browser::followLinkNumber(int linkToFollow) { } void Browser::goBack() { - int original = previousIdx; // we track this because sometimes sites do this: - // start site - // input something - // redirect back to start site - // and in such cases, I'd expect back and forward to treat the same site as one site, - // but only in cases where they are right next to each other without any other 2X status code sites - // between them. + // start site + // input something + // redirect back to start site + // and in such cases, I'd expect back and forward to treat the same site as + // one site, but only in cases where they are right next to each other + // without any other 2X status code sites between them. std::string starting = getCurrentLink()->getLinkDestination().to_string(); previousIdx -= 1; - if((int)siteHistory.size() > previousIdx && previousIdx >= 0) { - - int prSC = previousStatusCodes[siteHistory[previousIdx]->getLinkDestination().to_string()]; - std::string current = siteHistory[previousIdx]->getLinkDestination().to_string(); - while(!(prSC >= 20 && prSC <= 29) || starting == current) { + if ((int)siteHistory.size() > previousIdx && previousIdx >= 0) { + int prSC = previousStatusCodes + [siteHistory[previousIdx]->getLinkDestination().to_string()]; + std::string current = + siteHistory[previousIdx]->getLinkDestination().to_string(); + while (!(prSC >= 20 && prSC <= 29) || starting == current) { previousIdx -= 1; - if((int)siteHistory.size() > previousIdx && previousIdx >= 0) { - prSC = previousStatusCodes[siteHistory[previousIdx]->getLinkDestination().to_string()]; - current = siteHistory[previousIdx]->getLinkDestination().to_string(); + if ((int)siteHistory.size() > previousIdx && previousIdx >= 0) { + prSC = previousStatusCodes[siteHistory[previousIdx] + ->getLinkDestination() + .to_string()]; + current = + siteHistory[previousIdx]->getLinkDestination().to_string(); } else { previousIdx = original; - return; // safely fail with rollback + return; // safely fail with rollback } } - if(!(goToSite(this->siteHistory[previousIdx]->getLinkDestination().to_string(), false).result == SITE_LOADED)) { + if (!(goToSite(this->siteHistory[previousIdx] + ->getLinkDestination() + .to_string(), + false) + .result == SITE_LOADED)) { previousIdx = original; } @@ -427,30 +430,37 @@ void Browser::goBack() { } void Browser::goForward() { - int original = previousIdx; std::string starting = getCurrentLink()->getLinkDestination().to_string(); previousIdx += 1; - if((int)siteHistory.size() > previousIdx && previousIdx >= 0) { - - int prSC = previousStatusCodes[siteHistory[previousIdx]->getLinkDestination().to_string()]; - std::string current = siteHistory[previousIdx]->getLinkDestination().to_string(); + if ((int)siteHistory.size() > previousIdx && previousIdx >= 0) { + int prSC = previousStatusCodes + [siteHistory[previousIdx]->getLinkDestination().to_string()]; + std::string current = + siteHistory[previousIdx]->getLinkDestination().to_string(); - while(!(prSC >= 20 && prSC <= 29) || starting == current) { + while (!(prSC >= 20 && prSC <= 29) || starting == current) { previousIdx += 1; - if((int)siteHistory.size() > previousIdx && previousIdx >= 0) { - prSC = previousStatusCodes[siteHistory[previousIdx]->getLinkDestination().to_string()]; - current = siteHistory[previousIdx]->getLinkDestination().to_string(); + if ((int)siteHistory.size() > previousIdx && previousIdx >= 0) { + prSC = previousStatusCodes[siteHistory[previousIdx] + ->getLinkDestination() + .to_string()]; + current = + siteHistory[previousIdx]->getLinkDestination().to_string(); } else { - previousIdx = original; // fail safely + previousIdx = original; // fail safely return; } } - if(!(goToSite(this->siteHistory[previousIdx]->getLinkDestination().to_string(), false).result == SITE_LOADED)) { + if (!(goToSite(this->siteHistory[previousIdx] + ->getLinkDestination() + .to_string(), + false) + .result == SITE_LOADED)) { previousIdx = original; } } else { @@ -459,9 +469,8 @@ void Browser::goForward() { } Link* Browser::getCurrentLink() { - if(previousIdx >= 0 && previousIdx < (int)siteHistory.size()) { + if (previousIdx >= 0 && previousIdx < (int)siteHistory.size()) { return this->siteHistory[previousIdx]; } return nullptr; } - diff --git a/src/cache.cpp b/src/cache.cpp @@ -1,16 +1,16 @@ #include "../include/cache.hpp" -#include "../include/site.hpp" -#include "../include/shared.hpp" + #include <cassert> #include <mutex> #include <optional> +#include "../include/shared.hpp" +#include "../include/site.hpp" std::optional<Site> Cache::getSite(const std::string& site) { - std::lock_guard<std::mutex> lock(mutex); auto it = cache.find(site); - + if (it != cache.end()) { return it->second; } diff --git a/src/format-switch.cpp b/src/format-switch.cpp @@ -1,23 +1,17 @@ #include "../include/format-switch.hpp" -#include "../include/shared.hpp" -#include <cstdint> + #include <ncurses.h> -FormatSwitch::FormatSwitch(std::string input) : text(input) {} +#include <cstdint> + +#include "../include/shared.hpp" -std::string FormatSwitch::textToDraw() { - return ""; -} +FormatSwitch::FormatSwitch(std::string input) : text(input) {} -uint8_t FormatSwitch::getColor() { - return COLOR_FORMAT_SWITCH; -} +std::string FormatSwitch::textToDraw() { return ""; } -LineType FormatSwitch::type() { - return FORMAT_SWITCH; -} +uint8_t FormatSwitch::getColor() { return COLOR_FORMAT_SWITCH; } -bool FormatSwitch::isBold() { - return false; -} +LineType FormatSwitch::type() { return FORMAT_SWITCH; } +bool FormatSwitch::isBold() { return false; } diff --git a/src/gemini-client.cpp b/src/gemini-client.cpp @@ -1,49 +1,59 @@ -#include <cassert> -#include <cstddef> -#include <stdexcept> +#include "../include/gemini-client.hpp" + +#include <openssl/ssl.h> +#include <poll.h> #include <sys/socket.h> #include <sys/time.h> -#include "../include/gemini-client.hpp" -#include "../include/site.hpp" -#include "../include/shared.hpp" + +#include <cassert> #include <chrono> -#include "../include/utils.hpp" -#include "../include/errors.hpp" -#include <openssl/ssl.h> +#include <cstddef> +#include <stdexcept> #include <string> -#include <poll.h> -Site* GeminiClient::getNetworkedSite(Link link, std::string crtPath, std::string keyPath) { +#include "../include/errors.hpp" +#include "../include/shared.hpp" +#include "../include/site.hpp" +#include "../include/utils.hpp" +Site* GeminiClient::getNetworkedSite(Link link, std::string crtPath, + std::string keyPath) { if (!isSendableIfGeminiUrl(link.getLinkDestination())) { return nullptr; } std::string host = link.getLinkDestination().get_host(); - std::string req = link.getLinkDestination().to_string() + "\r\n"; + std::string req = link.getLinkDestination().to_string() + "\r\n"; std::string conn = host + ":1965"; - if(link.getLinkDestination().get_port()) { - conn = host + ":" + std::to_string(link.getLinkDestination().get_port()); + if (link.getLinkDestination().get_port()) { + conn = + host + ":" + std::to_string(link.getLinkDestination().get_port()); } - std::unique_ptr<SSL_CTX, decltype(&SSL_CTX_free)> ctx(SSL_CTX_new(TLS_client_method()), SSL_CTX_free); + std::unique_ptr<SSL_CTX, decltype(&SSL_CTX_free)> ctx( + SSL_CTX_new(TLS_client_method()), SSL_CTX_free); if (!ctx) { return nullptr; } - if(crtPath != "" && keyPath != "") { - if (SSL_CTX_use_certificate_file(ctx.get(), crtPath.c_str(), SSL_FILETYPE_PEM) <= 0 || SSL_CTX_use_PrivateKey_file(ctx.get(), keyPath.c_str(), SSL_FILETYPE_PEM) <= 0 || !SSL_CTX_check_private_key(ctx.get())) { + if (crtPath != "" && keyPath != "") { + if (SSL_CTX_use_certificate_file(ctx.get(), crtPath.c_str(), + SSL_FILETYPE_PEM) <= 0 || + SSL_CTX_use_PrivateKey_file(ctx.get(), keyPath.c_str(), + SSL_FILETYPE_PEM) <= 0 || + !SSL_CTX_check_private_key(ctx.get())) { return nullptr; } } - std::unique_ptr<BIO, decltype(&BIO_free_all)> bio(BIO_new_ssl_connect(ctx.get()), BIO_free_all); + std::unique_ptr<BIO, decltype(&BIO_free_all)> bio( + BIO_new_ssl_connect(ctx.get()), BIO_free_all); if (!bio) { return nullptr; - } + } SSL* ssl; BIO_get_ssl(bio.get(), &ssl); @@ -54,14 +64,18 @@ Site* GeminiClient::getNetworkedSite(Link link, std::string crtPath, std::string auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(5); while (BIO_do_connect(bio.get()) <= 0) { - int fd = -1; - long ms = std::chrono::duration_cast<std::chrono::milliseconds>(deadline - std::chrono::steady_clock::now()).count(); + long ms = std::chrono::duration_cast<std::chrono::milliseconds>( + deadline - std::chrono::steady_clock::now()) + .count(); pollfd p{}; // yikes. - if (!BIO_should_retry(bio.get()) || BIO_get_fd(bio.get(), &fd) < 0 || fd < 0 || ms <= 0 || (p = {fd, short(BIO_should_read(bio.get()) ? POLLIN : POLLOUT), 0}, poll(&p, 1, int(ms)) <= 0)) { + if (!BIO_should_retry(bio.get()) || BIO_get_fd(bio.get(), &fd) < 0 || + fd < 0 || ms <= 0 || + (p = {fd, short(BIO_should_read(bio.get()) ? POLLIN : POLLOUT), 0}, + poll(&p, 1, int(ms)) <= 0)) { return nullptr; } } @@ -87,7 +101,7 @@ Site* GeminiClient::getNetworkedSite(Link link, std::string crtPath, std::string response.append(buf, n); sizeRemaining -= n; - if(sizeRemaining <= 0) { + if (sizeRemaining <= 0) { break; } } @@ -105,16 +119,16 @@ Site* GeminiClient::getNetworkedSite(Link link, std::string crtPath, std::string } std::string status = response.substr(0, end); - std::string body = response.substr(nl + 1); + std::string body = response.substr(nl + 1); return new Site(status, body); } - -Site* GeminiClient::fetchSite(Link link, std::string crtPath, std::string keyPath) { +Site* GeminiClient::fetchSite(Link link, std::string crtPath, + std::string keyPath) { std::string destination = link.getLinkDestination().to_string(); - if(isPrefixed(destination, "gemini://")) { + if (isPrefixed(destination, "gemini://")) { try { return getNetworkedSite(link, crtPath, keyPath); } catch (...) { @@ -122,10 +136,13 @@ Site* GeminiClient::fetchSite(Link link, std::string crtPath, std::string keyPat unreach->setUnreachable(); return unreach; } - } else if (isPrefixed(destination, "file://")){ // TODO: This seems wrong; it should probably be fullpath with that prefix. + } else if (isPrefixed( + destination, + "file://")) { // TODO: This seems wrong; it should probably + // be fullpath with that prefix. // TODO: this is messy and perhaps not necessary - + std::string rest = destination.substr(7); std::string host; std::string path; @@ -147,22 +164,24 @@ Site* GeminiClient::fetchSite(Link link, std::string crtPath, std::string keyPat std::string fsPath; - if(host == "localhost") { + if (host == "localhost") { fsPath = path; - } else { - throw std::invalid_argument("The requested file appears to exist on another system."); + } else { + throw std::invalid_argument( + "The requested file appears to exist on another system."); } try { fileStr = readFileToString(fsPath); - } catch (FileReadError& e ) { - return new Site {"51 file not found", ""}; + } catch (FileReadError& e) { + return new Site{"51 file not found", ""}; } // TODO: how should I discern file types? - return new Site {"20 text/gemini", fileStr}; - } else if(isPrefixed(destination, "about://")){ - return new Site {"20 text/gemini", getNewTab()}; + return new Site{"20 text/gemini", fileStr}; + } else if (isPrefixed(destination, "about://")) { + return new Site{"20 text/gemini", getNewTab()}; } else { - throw std::runtime_error("An invalid argument was passed to fetchsite, " + destination); + throw std::runtime_error( + "An invalid argument was passed to fetchsite, " + destination); } } diff --git a/src/heading.cpp b/src/heading.cpp @@ -1,23 +1,24 @@ #include "../include/heading.hpp" -#include "../include/utils.hpp" -#include "../include/shared.hpp" -#include <cstdint> + #include <ncurses.h> + +#include <cstdint> #include <stdexcept> -Heading::Heading(std::string text) : actualText(text) { +#include "../include/shared.hpp" +#include "../include/utils.hpp" +Heading::Heading(std::string text) : actualText(text) { // TODO: Actually handle whitespace correctly here. - if(text.substr(0,3) == "###") { + if (text.substr(0, 3) == "###") { headingLevel = 3; toDraw = actualText.substr(3); } - else if(text.substr(0,2) == "##") { + else if (text.substr(0, 2) == "##") { headingLevel = 2; toDraw = actualText.substr(2); - } - else if(text.substr(0,1) == "#") { + } else if (text.substr(0, 1) == "#") { headingLevel = 1; toDraw = actualText.substr(1); } @@ -58,6 +59,4 @@ LineType Heading::type() { } throw std::runtime_error("This is an invalid program state."); } -bool Heading::isBold() { - return true; -} +bool Heading::isBold() { return true; } diff --git a/src/identity-manager.cpp b/src/identity-manager.cpp @@ -1,17 +1,19 @@ +#include "../include/identity-manager.hpp" + +#include <unistd.h> + #include <algorithm> #include <cstdlib> #include <filesystem> #include <iostream> #include <stdexcept> #include <string> -#include <unistd.h> -#include "../vendor/uri.hpp" -#include "../include/identity-manager.hpp" + #include "../include/utils.hpp" +#include "../vendor/uri.hpp" Identity IdentityManager::getIdentityForURI(uri destination) { - - if(destination.get_scheme() != "gemini") { + if (destination.get_scheme() != "gemini") { return Identity{"", ""}; } @@ -26,10 +28,10 @@ Identity IdentityManager::getIdentityForURI(uri destination) { try { if (fs::exists(dir / "client.crt") && fs::exists(dir / "client.key")) { - return Identity{(dir / "client.key").string(), (dir / "client.crt").string()}; + return Identity{(dir / "client.key").string(), + (dir / "client.crt").string()}; } - } - catch (const fs::filesystem_error& e){ + } catch (const fs::filesystem_error& e) { // this can happen if the domain is stupidly long. // in such cases, there are bigger issues. } diff --git a/src/link.cpp b/src/link.cpp @@ -1,15 +1,16 @@ #include "../include/link.hpp" + +#include <ncurses.h> + #include <cstdint> #include <optional> #include <string> -#include "../include/utils.hpp" + #include "../include/shared.hpp" +#include "../include/utils.hpp" #include "../vendor/uri.hpp" -#include <ncurses.h> - Link::Link(std::string text, std::optional<uri> prior, int linkNumber) { - this->linkNumber = linkNumber; if (text.substr(0, 2) != "=>") { @@ -19,25 +20,25 @@ Link::Link(std::string text, std::optional<uri> prior, int linkNumber) { std::string afterPrefix = text; - afterPrefix = text.substr(2,text.size()); + afterPrefix = text.substr(2, text.size()); int highest = -1; - for(int i = 0; i < (int)afterPrefix.size(); ++i) { - if(!(isWhiteSpace(afterPrefix, i))) { + for (int i = 0; i < (int)afterPrefix.size(); ++i) { + if (!(isWhiteSpace(afterPrefix, i))) { break; } highest = i; } - std::string afterWhite = afterPrefix.substr(highest+1, afterPrefix.size()); + std::string afterWhite = + afterPrefix.substr(highest + 1, afterPrefix.size()); int nextWhite = std::min(afterWhite.find(' '), afterWhite.find('\t')); - if(nextWhite != -1) { + if (nextWhite != -1) { + linkText = afterWhite.substr(nextWhite + 1); - linkText = afterWhite.substr(nextWhite+1); - std::string destination = afterWhite.substr(0, nextWhite); linkDestination = parseDestination(destination, prior); @@ -46,7 +47,7 @@ Link::Link(std::string text, std::optional<uri> prior, int linkNumber) { linkDestination = parseDestination(afterWhite, prior); } - if(linkText != std::nullopt) { + if (linkText != std::nullopt) { std::string tmp = linkText.value(); std::string rdlt = stripLeadingWhiteSpace(tmp); @@ -54,21 +55,23 @@ Link::Link(std::string text, std::optional<uri> prior, int linkNumber) { } else { std::string tmp = linkDestination.to_string(); std::string rdlt = stripLeadingWhiteSpace(tmp); - renderedText = "[" + std::to_string(linkNumber) + "] " + linkDestination.to_string(); + renderedText = "[" + std::to_string(linkNumber) + "] " + + linkDestination.to_string(); } } uri Link::parseDestination(std::string destination, std::optional<uri> prior) { - // TODO: Not sure if this is right w/ how file paths work. - - // TODO: There's a mess here to untangle. Like I think there might be some relative links that'll get fucked by this. - // despite that, this is a requirement to get search parameters working correctly which are probably more important. - if(destination.find(":") == std::string::npos || destination[0] == '?') { - if(prior != std::nullopt) { + // TODO: There's a mess here to untangle. Like I think there might be some + // relative links that'll get fucked by this. despite that, this is a + // requirement to get search parameters working correctly which are probably + // more important. + + if (destination.find(":") == std::string::npos || destination[0] == '?') { + if (prior != std::nullopt) { // query parameter special casing - if(destination.substr(0,1) == "?") { + if (destination.substr(0, 1) == "?") { std::string encoded = urlEncode(destination.substr(1)); return uri{prior.value().to_string() + "?" + encoded}; } @@ -78,43 +81,30 @@ uri Link::parseDestination(std::string destination, std::optional<uri> prior) { if (destination[0] == '/') { destination = base + destination; } else { - std::string path = prior->get_path(); if (path[0] != '/') { path = "/" + path; } - destination = base + path.substr(0, path.rfind('/') + 1) + destination; + destination = + base + path.substr(0, path.rfind('/') + 1) + destination; } - } + } } try { - return uri{destination}; - } catch(...) { + return uri{destination}; + } catch (...) { invalid = true; - return uri{"gemini://broken-link.com"}; // TODO: Handle this better + return uri{"gemini://broken-link.com"}; // TODO: Handle this better } } -uri Link::getLinkDestination() { - return linkDestination; -} -std::optional<std::string> Link::getLinkText() { - return linkText; -} - -std::string Link::textToDraw() { - return renderedText + "\n"; -} +uri Link::getLinkDestination() { return linkDestination; } +std::optional<std::string> Link::getLinkText() { return linkText; } -uint8_t Link::getColor() { - return COLOR_LINK; -} +std::string Link::textToDraw() { return renderedText + "\n"; } -LineType Link::type() { - return LINK; -} +uint8_t Link::getColor() { return COLOR_LINK; } -bool Link::isBold() { - return false; -} +LineType Link::type() { return LINK; } +bool Link::isBold() { return false; } diff --git a/src/list-item.cpp b/src/list-item.cpp @@ -1,29 +1,23 @@ #include "../include/list-item.hpp" -#include "../include/utils.hpp" -#include "../include/shared.hpp" + #include <cstdint> -ListItem::ListItem(std::string input) { +#include "../include/shared.hpp" +#include "../include/utils.hpp" -// list-item = "*" SP text-line -// notice that a space is required along with a *. There'd be no reason to remove -// them and then add them back here, so we just pass everything through. +ListItem::ListItem(std::string input) { + // list-item = "*" SP text-line + // notice that a space is required along with a *. There'd be no reason to + // remove them and then add them back here, so we just pass everything + // through. textToRender = input; } -std::string ListItem::textToDraw() { - return textToRender + "\n"; -} +std::string ListItem::textToDraw() { return textToRender + "\n"; } -uint8_t ListItem::getColor() { - return COLOR_LIST_ITEM; -} +uint8_t ListItem::getColor() { return COLOR_LIST_ITEM; } -LineType ListItem::type() { - return LIST_ITEM; -} +LineType ListItem::type() { return LIST_ITEM; } -bool ListItem::isBold() { - return false; -} +bool ListItem::isBold() { return false; } diff --git a/src/main.cpp b/src/main.cpp @@ -1,47 +1,49 @@ -#include "../include/browser.hpp" -#include "../include/utils.hpp" -#include "../include/render.hpp" -#include "../include/shared.hpp" +#include <locale.h> +#include <ncurses.h> +#include <unctrl.h> + #include <cassert> #include <csignal> #include <iostream> -#include <ncurses.h> -#include <locale.h> #include <string> -#include <unctrl.h> + +#include "../include/browser.hpp" +#include "../include/render.hpp" +#include "../include/shared.hpp" +#include "../include/utils.hpp" #include "../vendor/argparse.hpp" void initColors() { - if(has_colors()) { + if (has_colors()) { start_color(); use_default_colors(); - for (int c = 0; c < COLORS && c+1 < COLOR_PAIRS; ++c) { + for (int c = 0; c < COLORS && c + 1 < COLOR_PAIRS; ++c) { init_pair(c + 1, c, -1); } } } int main(int argc, char** argv) { - argparse::ArgumentParser program("foreseen", "0.0.1"); program.add_argument("-c", "--cache-pages") - .help("max number of pages for each cache (history, prefetch)") - .default_value(CACHE_SIZE) - .scan<'i', int>(); + .help("max number of pages for each cache (history, prefetch)") + .default_value(CACHE_SIZE) + .scan<'i', int>(); program.add_argument("-p", "--prefetch-links") - .help("max number of links to prefetch per page (0 disables prefetching)") - .default_value(SITE_CACHE_LIMIT) - .scan<'i', int>(); + .help( + "max number of links to prefetch per page (0 disables prefetching)") + .default_value(SITE_CACHE_LIMIT) + .scan<'i', int>(); program.add_argument("-e", "--search-engine") - .help("default search engine") - .default_value(DEFAULT_SEARCH_ENGINE); + .help("default search engine") + .default_value(DEFAULT_SEARCH_ENGINE); program.add_argument("destination") - .help("page to open") - .nargs(argparse::nargs_pattern::optional); + .help("page to open") + .nargs(argparse::nargs_pattern::optional); try { program.parse_args(argc, argv); @@ -55,48 +57,55 @@ int main(int argc, char** argv) { CACHE_SIZE = program.get<int>("--cache-pages"); DEFAULT_SEARCH_ENGINE = program.get<std::string>("--search-engine"); - if(DEFAULT_SEARCH_ENGINE.find("gemini://") != 0) { - std::cout << "Search engine must be prefixed with \"gemini://\": " + DEFAULT_SEARCH_ENGINE << std::endl; + if (DEFAULT_SEARCH_ENGINE.find("gemini://") != 0) { + std::cout << "Search engine must be prefixed with \"gemini://\": " + + DEFAULT_SEARCH_ENGINE + << std::endl; return -1; } - if(DEFAULT_SEARCH_ENGINE.substr(DEFAULT_SEARCH_ENGINE.size()-1) != "?") { + if (DEFAULT_SEARCH_ENGINE.substr(DEFAULT_SEARCH_ENGINE.size() - 1) != "?") { DEFAULT_SEARCH_ENGINE += "?"; } - std::string destination = program.present<std::string>("destination").value_or(""); + std::string destination = + program.present<std::string>("destination").value_or(""); - std::signal(SIGPIPE, SIG_IGN); // need this in case of swapping network connections bc that shouldn't kill the whole process. + std::signal(SIGPIPE, + SIG_IGN); // need this in case of swapping network connections + // bc that shouldn't kill the whole process. Browser* bPtr = new Browser{}; Browser& b = *bPtr; - DrawState ds {}; + DrawState ds{}; ds.bPtr = bPtr; - setlocale(LC_CTYPE, ""); // emojis and such + setlocale(LC_CTYPE, ""); // emojis and such initscr(); set_escdelay(25); - noecho(); // don't echo user inputs - cbreak(); // make C-c and C-z work - curs_set(0); // hide cursor - keypad(stdscr,TRUE); + noecho(); // don't echo user inputs + cbreak(); // make C-c and C-z work + curs_set(0); // hide cursor + keypad(stdscr, TRUE); initColors(); Destination cliDestination = handleDestinationResolution(destination, true); - if(cliDestination.t != NO_DESTINATION) { - assert(cliDestination.t == STRING_DESTINATION); // we don't allow numeric link following on startup. - tryVisitSite(ds,b, cliDestination.destination); + if (cliDestination.t != NO_DESTINATION) { + assert(cliDestination.t == + STRING_DESTINATION); // we don't allow numeric link following on + // startup. + tryVisitSite(ds, b, cliDestination.destination); } int input = 0; - while(true) { - bool continueExecution = mainLoop(ds,b,input, COLS,LINES); - if(!continueExecution) { + while (true) { + bool continueExecution = mainLoop(ds, b, input, COLS, LINES); + if (!continueExecution) { break; } input = getch(); diff --git a/src/plaintext.cpp b/src/plaintext.cpp @@ -1,21 +1,15 @@ #include "../include/plaintext.hpp" -#include "../include/shared.hpp" + #include <cstdint> +#include "../include/shared.hpp" + Plaintext::Plaintext(std::string input) : text(input) {} -std::string Plaintext::textToDraw() { - return text + "\n"; -} +std::string Plaintext::textToDraw() { return text + "\n"; } -uint8_t Plaintext::getColor() { - return COLOR_PLAINTEXT; -} +uint8_t Plaintext::getColor() { return COLOR_PLAINTEXT; } -LineType Plaintext::type() { - return PLAINTEXT; -} +LineType Plaintext::type() { return PLAINTEXT; } -bool Plaintext::isBold() { - return false; -} +bool Plaintext::isBold() { return false; } diff --git a/src/preformatted.cpp b/src/preformatted.cpp @@ -1,23 +1,17 @@ #include "../include/preformatted.hpp" -#include "../include/shared.hpp" -#include <cstdint> + #include <ncurses.h> -Preformatted::Preformatted(std::string input) : text(input) {} +#include <cstdint> + +#include "../include/shared.hpp" -std::string Preformatted::textToDraw() { - return text + "\n"; -} +Preformatted::Preformatted(std::string input) : text(input) {} -uint8_t Preformatted::getColor() { - return COLOR_PREFORMATTED; -} +std::string Preformatted::textToDraw() { return text + "\n"; } -LineType Preformatted::type() { - return PREFORMATTED; -} +uint8_t Preformatted::getColor() { return COLOR_PREFORMATTED; } -bool Preformatted::isBold() { - return false; -} +LineType Preformatted::type() { return PREFORMATTED; } +bool Preformatted::isBold() { return false; } diff --git a/src/quote.cpp b/src/quote.cpp @@ -1,8 +1,11 @@ #include "../include/quote.hpp" + +#include <ncurses.h> + +#include <cstdint> + #include "../include/shared.hpp" #include "../include/utils.hpp" -#include <cstdint> -#include <ncurses.h> Quote::Quote(std::string input) { textToRender = input.substr(1); @@ -10,18 +13,10 @@ Quote::Quote(std::string input) { textToRender = "> " + textToRender; } -std::string Quote::textToDraw() { - return textToRender + "\n"; -} +std::string Quote::textToDraw() { return textToRender + "\n"; } -uint8_t Quote::getColor() { - return COLOR_QUOTE; -} +uint8_t Quote::getColor() { return COLOR_QUOTE; } -LineType Quote::type() { - return QUOTE; -} +LineType Quote::type() { return QUOTE; } -bool Quote::isBold() { - return false; -} +bool Quote::isBold() { return false; } diff --git a/src/render.cpp b/src/render.cpp @@ -1,33 +1,37 @@ -#include "../include/browser.hpp" -#include "../include/utils.hpp" #include "../include/render.hpp" -#include "../include/shared.hpp" + +#include <ncurses.h> +#include <unctrl.h> + #include <algorithm> #include <cassert> #include <cctype> #include <chrono> #include <cstdint> #include <cstdlib> -#include <ncurses.h> #include <string> -#include <unctrl.h> #include <utility> #include <vector> +#include "../include/browser.hpp" +#include "../include/shared.hpp" +#include "../include/utils.hpp" + #ifndef CTRL #define CTRL(c) ((c) & 037) #endif #ifdef DEBUG_MODE - const char* OUT_LOCATION = "/tmp/foreseen"; +const char* OUT_LOCATION = "/tmp/foreseen"; #else - const char* OUT_LOCATION = ""; +const char* OUT_LOCATION = ""; #endif - - -int lowestPos(std::vector<std::pair<std::string, TextRender>>& strLs, DrawState& ds) { - return (strLs.size() - (ds.lines - 2)) + 1; // this gives us two new lines at the end because the last line should contain a \n. +int lowestPos(std::vector<std::pair<std::string, TextRender>>& strLs, + DrawState& ds) { + return (strLs.size() - (ds.lines - 2)) + + 1; // this gives us two new lines at the end because the last line + // should contain a \n. } bool isValidUserInput(int uinput) { @@ -37,25 +41,24 @@ bool isValidUserInput(int uinput) { return false; } void drawInputBox(std::string text, std::string userInput, DrawState& ds) { + move(ds.lines / 2 - 1, ds.columns / 4); - move(ds.lines/2-1, ds.columns/4); - - attron(COLOR_PAIR(COLOR_CYAN+1)); - for(int i = 0; i < ds.columns/2; ++i) { + attron(COLOR_PAIR(COLOR_CYAN + 1)); + for (int i = 0; i < ds.columns / 2; ++i) { addstr("-"); } - move(ds.lines/2 + 1, ds.columns/4); - for(int i = 0; i < ds.columns/2; ++i) { + move(ds.lines / 2 + 1, ds.columns / 4); + for (int i = 0; i < ds.columns / 2; ++i) { addstr("-"); } - attroff(COLOR_PAIR(COLOR_CYAN+1)); + attroff(COLOR_PAIR(COLOR_CYAN + 1)); int userInputSize = userInput.size(); - int width = ds.columns/2; + int width = ds.columns / 2; - if((int)text.size() >= width) { - text = text.substr(0,width-6) + "...: "; + if ((int)text.size() >= width) { + text = text.substr(0, width - 6) + "...: "; } int textSize = text.size(); @@ -66,32 +69,34 @@ void drawInputBox(std::string text, std::string userInput, DrawState& ds) { int delta = width - (textSize + userInputSize); - if(delta < 0) { - userTextToRender = userInput.substr(delta*-1, userInput.size()); + if (delta < 0) { + userTextToRender = userInput.substr(delta * -1, userInput.size()); } else { - while(delta != 0) { - userTextToRender.append(" "); // this makes sure the background doesn't leak through. + while (delta != 0) { + userTextToRender.append( + " "); // this makes sure the background doesn't leak through. delta -= 1; } } - move(ds.lines/2, ds.columns/4); + move(ds.lines / 2, ds.columns / 4); addstr(text.c_str()); addstr(userTextToRender.c_str()); - } uint64_t getCurrentTime() { - return std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now().time_since_epoch()).count(); + return std::chrono::duration_cast<std::chrono::milliseconds>( + std::chrono::steady_clock::now().time_since_epoch()) + .count(); } void draw(DrawState& ds) { - if(ds.columns < 20) { + if (ds.columns < 20) { erase(); addstr("Screen width too small."); refresh(); return; } - if(ds.lines < 3) { + if (ds.lines < 3) { erase(); addstr("Screen height too small."); refresh(); @@ -101,8 +106,9 @@ void draw(DrawState& ds) { auto* cs = ds.bPtr->getCurrentSite(); // CS is null or has status 2X - if (!(cs != nullptr && (cs->getStatusCode() < 20 || cs->getStatusCode() > 29))) { - if(ds.mustReRender) { + if (!(cs != nullptr && + (cs->getStatusCode() < 20 || cs->getStatusCode() > 29))) { + if (ds.mustReRender) { ds.prior = ds.bPtr->renderSite(); sanitizeCharactersToDraw(ds.prior); ds.mustReRender = false; @@ -110,42 +116,43 @@ void draw(DrawState& ds) { } } - if(ds.reBreak) { - ds.broken = breakLines(ds.prior, std::min(ds.columns, MAX_WIDTH), ds.columns); + if (ds.reBreak) { + ds.broken = + breakLines(ds.prior, std::min(ds.columns, MAX_WIDTH), ds.columns); ds.reBreak = false; } - if(ds.toLowest) { + if (ds.toLowest) { ds.y = lowestPos(ds.broken, ds); ds.toLowest = false; } - ds.y = std::max(0,std::min(ds.y,lowestPos(ds.broken,ds))); + ds.y = std::max(0, std::min(ds.y, lowestPos(ds.broken, ds))); erase(); - move(0,(ds.columns / 2) - ((int)ds.header.size() / 2) ); + move(0, (ds.columns / 2) - ((int)ds.header.size() / 2)); attron(A_BOLD); - if((int)ds.header.size() < ds.columns) { + if ((int)ds.header.size() < ds.columns) { addstr(ds.header.c_str()); - } else { - addstr((ds.header.substr(0,ds.columns-3) + "...").c_str()); + } else { + addstr((ds.header.substr(0, ds.columns - 3) + "...").c_str()); } attroff(A_BOLD); addstr(std::string(ds.columns, ' ').c_str()); - for(int i = ds.y; i - ds.y < ds.lines - 2 && i < (int)ds.broken.size(); ++i) { + for (int i = ds.y; i - ds.y < ds.lines - 2 && i < (int)ds.broken.size(); + ++i) { move(i - ds.y + 2, 0); attron(COLOR_PAIR(ds.broken[i].second.color + 1)); - if(ds.broken[i].second.isBold) { + if (ds.broken[i].second.isBold) { attron(A_BOLD); addstr(ds.broken[i].first.c_str()); attroff(A_BOLD); - } - else { + } else { addstr(ds.broken[i].first.c_str()); } attroff(COLOR_PAIR(ds.broken[i].second.color + 1)); @@ -156,12 +163,11 @@ void draw(DrawState& ds) { drawInputBox(toShow, ds.redirInput, ds); } - if(ds.handleInput) { - if(ds.metaLine != "") { + if (ds.handleInput) { + if (ds.metaLine != "") { drawInputBox(ds.metaLine + ": ", ds.userInput, ds); } else { drawInputBox("Input: ", ds.userInput, ds); - } } @@ -169,69 +175,67 @@ void draw(DrawState& ds) { drawInputBox("Destination / Link Number: ", ds.openOtherInput, ds); } - if(ds.issueText != "") { + if (ds.issueText != "") { uint64_t now = getCurrentTime(); - if(ds.timeToClearIssueText <= now) { + if (ds.timeToClearIssueText <= now) { ds.issueText = ""; } else { - move(0,0); + move(0, 0); attron(A_BOLD); - attron(COLOR_PAIR(COLOR_RED+1)); + attron(COLOR_PAIR(COLOR_RED + 1)); std::string tr = ds.issueText; std::string truncated; - for(auto& ch : tr) { + for (auto& ch : tr) { truncated += (char)toascii(ch); } - if((int)ds.issueText.size() > ds.columns) { - truncated = truncated.substr(0,ds.columns - 3) + "..."; + if ((int)ds.issueText.size() > ds.columns) { + truncated = truncated.substr(0, ds.columns - 3) + "..."; } addstr(truncated.c_str()); - attroff(COLOR_PAIR(COLOR_RED+1)); + attroff(COLOR_PAIR(COLOR_RED + 1)); attroff(A_BOLD); } - } refresh(); } void openPageHandler(DrawState& ds, int sel) { - - if(sel == KEY_BACKSPACE || sel == 127 || sel == 8) { - if(ds.openOtherInput.size() > 0) { - ds.openOtherInput = ds.openOtherInput.substr(0,ds.openOtherInput.size() - 1); + if (sel == KEY_BACKSPACE || sel == 127 || sel == 8) { + if (ds.openOtherInput.size() > 0) { + ds.openOtherInput = + ds.openOtherInput.substr(0, ds.openOtherInput.size() - 1); } } - if(sel == 27) { + if (sel == 27) { ds.openOtherInput = ""; ds.handleOpenOther = false; return; } - if(sel == '\n' || sel == KEY_ENTER) { + if (sel == '\n' || sel == KEY_ENTER) { ds.handleOpenOther = false; return; } - if(isValidUserInput(sel)) { - ds.openOtherInput += std::string {(char)sel}; + if (isValidUserInput(sel)) { + ds.openOtherInput += std::string{(char)sel}; } - } void handleRedir(DrawState& ds, int input, Browser& b) { - if(input == 'y') { + if (input == 'y') { ds.redirInput = "y"; draw(ds); ds.handleRedirect = false; tryVisitSite(ds, b, b.getCurrentSite()->getMeta()); ds.mustReRender = true; } - if(input == 'n') { + if (input == 'n') { ds.redirInput = "n"; draw(ds); ds.handleRedirect = false; @@ -241,55 +245,54 @@ void handleRedir(DrawState& ds, int input, Browser& b) { } void handleUserInput(DrawState& ds, Browser& b, int sel) { - if(sel == '\n' || sel == KEY_ENTER) { - + if (sel == '\n' || sel == KEY_ENTER) { ds.handleInput = false; - if(ds.userInput != "") { - tryVisitSite(ds, b, "?"+ds.userInput); + if (ds.userInput != "") { + tryVisitSite(ds, b, "?" + ds.userInput); } else { b.goBack(); ds.mustReRender = true; } return; } - if(sel == 27) { + if (sel == 27) { ds.handleInput = false; - draw(ds); // this might not be totally necessary because back is generally fast, but it's not strictly - // guaranteed. + draw(ds); // this might not be totally necessary because back is + // generally fast, but it's not strictly guaranteed. b.goBack(); ds.mustReRender = true; return; } - if(sel == KEY_BACKSPACE || sel == 127 || sel == 8) { - if(ds.userInput.size() > 0) { - ds.userInput = ds.userInput.substr(0,ds.userInput.size() - 1); + if (sel == KEY_BACKSPACE || sel == 127 || sel == 8) { + if (ds.userInput.size() > 0) { + ds.userInput = ds.userInput.substr(0, ds.userInput.size() - 1); } return; } - if(isValidUserInput(sel)) { - ds.userInput += std::string {(char)sel}; + if (isValidUserInput(sel)) { + ds.userInput += std::string{(char)sel}; } } void handleResult(DrawState& ds, SiteLoadPair result) { switch (result.result) { case SITE_LOADED: - if(result.metaLine != OPENED_EXT_TXT) { + if (result.metaLine != OPENED_EXT_TXT) { ds.y = 0; ds.mustReRender = true; } break; case SITE_TEMPORARY_FAILURE: - if(result.metaLine != "") { + if (result.metaLine != "") { ds.issueText = "Temporary site failure: " + result.metaLine; } else { ds.issueText = "Temporary site failure"; } break; case SITE_PERMANENT_FAILURE: - if(result.metaLine != "") { + if (result.metaLine != "") { ds.issueText = "Permanent site failure: " + result.metaLine; } else { ds.issueText = "Permanent site failure"; @@ -297,26 +300,29 @@ void handleResult(DrawState& ds, SiteLoadPair result) { break; case SITE_REQUIRES_CERTIFICATE: - if(result.metaLine != "") { - ds.issueText = "Site requires a certificate: " + result.metaLine; + if (result.metaLine != "") { + ds.issueText = + "Site requires a certificate: " + result.metaLine; } else { ds.issueText = "Site requires a certificate"; } break; case SITE_REJECTED_CERTIFICATE: - if(result.metaLine != "") { - ds.issueText = "Your certificate is not authorized: " + result.metaLine; - } - else { + if (result.metaLine != "") { + ds.issueText = + "Your certificate is not authorized: " + result.metaLine; + } else { ds.issueText = "Your certificate is not authorized"; } break; case SITE_INVALID_CERTIFICATE: - if(result.metaLine != "") { - ds.issueText = "Your certificate has been rejected as invalid: " + result.metaLine; + if (result.metaLine != "") { + ds.issueText = + "Your certificate has been rejected as invalid: " + + result.metaLine; } else { ds.issueText = "Your certificate has been rejected as invalid"; } @@ -332,32 +338,31 @@ void handleResult(DrawState& ds, SiteLoadPair result) { ds.timeToClearIssueText = getCurrentTime() + 1000; } - -void tryVisitSite(DrawState& ds , Browser& b, std::string site) { +void tryVisitSite(DrawState& ds, Browser& b, std::string site) { SiteLoadPair result = b.goToSite(site); - handleResult(ds,result); + handleResult(ds, result); } -bool mainLoop(DrawState& ds, Browser& b, int input, int cols, int lines) { - - if(lines != ds.lines || cols != ds.columns) { +bool mainLoop(DrawState& ds, Browser& b, int input, int cols, int lines) { + if (lines != ds.lines || cols != ds.columns) { ds.reBreak = true; } ds.lines = lines; ds.columns = cols; - if(ds.handleOpenOther) { - openPageHandler(ds,input); - if(!ds.handleOpenOther) { + if (ds.handleOpenOther) { + openPageHandler(ds, input); + if (!ds.handleOpenOther) { draw(ds); - if(ds.openOtherInput != "") { - Destination destination = handleDestinationResolution(ds.openOtherInput , false); + if (ds.openOtherInput != "") { + Destination destination = + handleDestinationResolution(ds.openOtherInput, false); SiteLoadPair res; - switch(destination.t) { + switch (destination.t) { case NUMBER_DESTINATION: res = b.followLinkNumber(destination.linkNumber); - handleResult(ds,res); + handleResult(ds, res); break; case STRING_DESTINATION: tryVisitSite(ds, b, destination.destination); @@ -373,19 +378,18 @@ bool mainLoop(DrawState& ds, Browser& b, int input, int cols, int lines) { } return true; } else if (ds.handleRedirect) { - handleRedir(ds, input, b); - if(!ds.handleRedirect) { + if (!ds.handleRedirect) { mainLoop(ds, b, KEY_RESIZE, ds.columns, ds.lines); - } else { + } else { draw(ds); } return true; } else if (ds.handleInput) { handleUserInput(ds, b, input); - if(!ds.handleInput) { + if (!ds.handleInput) { mainLoop(ds, b, KEY_RESIZE, ds.columns, ds.lines); } else { draw(ds); @@ -393,57 +397,56 @@ bool mainLoop(DrawState& ds, Browser& b, int input, int cols, int lines) { return true; } - - if(input == 'q') { + if (input == 'q') { return false; } - if(input == KEY_DOWN) { + if (input == KEY_DOWN) { ds.y += 1; - } else if (input == KEY_UP){ + } else if (input == KEY_UP) { ds.y -= 1; - } else if (input == 'g'){ + } else if (input == 'g') { ds.y = 0; - } else if (input == 'G'){ + } else if (input == 'G') { ds.toLowest = true; - } else if (input == CTRL('d')){ + } else if (input == CTRL('d')) { ds.y += ds.lines / 2; } else if (input == CTRL('u')) { ds.y -= ds.lines / 2; - } else if (input == 'r' || input == CTRL('r')){ + } else if (input == 'r' || input == CTRL('r')) { b.refresh(); ds.mustReRender = true; - } else if(input == 'f') { + } else if (input == 'f') { b.goForward(); ds.mustReRender = true; ds.y = 0; - } else if(input == 'd') { + } else if (input == 'd') { std::string outLocation = b.tryDownloadPage(OUT_LOCATION); - if(outLocation == "") { + if (outLocation == "") { ds.issueText = "Failed to download file"; ds.timeToClearIssueText = getCurrentTime() + 1000; } else { ds.issueText = "File downloaded to " + outLocation; ds.timeToClearIssueText = getCurrentTime() + 1000; } - } else if(input == 'b') { + } else if (input == 'b') { b.goBack(); ds.mustReRender = true; ds.y = 0; - } else if(input == 'o') { + } else if (input == 'o') { ds.handleOpenOther = true; - } else if (input == 'e'){ + } else if (input == 'e') { std::string editor = getEditor(); std::string dl = b.tryDownloadPage(OUT_LOCATION); - if(dl != "") { + if (dl != "") { def_prog_mode(); endwin(); std::string quoted = "'"; for (char c : dl) { - if(c == '\'') { + if (c == '\'') { quoted += std::string("'\\''"); } else { - quoted += std::string(1, c); + quoted += std::string(1, c); } } quoted += "'"; @@ -455,9 +458,11 @@ bool mainLoop(DrawState& ds, Browser& b, int input, int cols, int lines) { } } - if( (b.getCurrentSite()->getStatusCode() < 20 || b.getCurrentSite()->getStatusCode() > 29) && !ds.handleRedirect && !ds.handleInput) { - if(b.getCurrentSite()->getStatusCode() >= 10 && b.getCurrentSite()->getStatusCode() <= 19) { - + if ((b.getCurrentSite()->getStatusCode() < 20 || + b.getCurrentSite()->getStatusCode() > 29) && + !ds.handleRedirect && !ds.handleInput) { + if (b.getCurrentSite()->getStatusCode() >= 10 && + b.getCurrentSite()->getStatusCode() <= 19) { auto* st = b.getCurrentSite(); assert(st != nullptr); ds.metaLine = st->getMeta(); @@ -465,9 +470,11 @@ bool mainLoop(DrawState& ds, Browser& b, int input, int cols, int lines) { ds.handleInput = true; ds.userInput = ""; - } else if (b.getCurrentSite()->getStatusCode() >= 30 && b.getCurrentSite()->getStatusCode() <= 39 && !ds.handleRedirect){ + } else if (b.getCurrentSite()->getStatusCode() >= 30 && + b.getCurrentSite()->getStatusCode() <= 39 && + !ds.handleRedirect) { auto* st = b.getCurrentSite(); - if(st != nullptr) { + if (st != nullptr) { ds.metaLine = st->getMeta(); } @@ -483,7 +490,6 @@ bool mainLoop(DrawState& ds, Browser& b, int input, int cols, int lines) { auto* st = b.getCurrentSite(); assert(st != nullptr); ds.metaLine = st->getMeta(); - draw(ds); return true; diff --git a/src/shared.cpp b/src/shared.cpp @@ -18,4 +18,4 @@ uint8_t COLOR_LIST_ITEM = 15; uint8_t COLOR_FORMAT_SWITCH = 7; uint8_t COLOR_PLAINTEXT = 15; -int RESPONSE_SIZE_LIMIT_MB = 5; // This will truncate at the specified size. +int RESPONSE_SIZE_LIMIT_MB = 5; // This will truncate at the specified size. diff --git a/src/site.cpp b/src/site.cpp @@ -1,23 +1,20 @@ #include "../include/site.hpp" + #include <algorithm> #include <cstdint> #include <string> Site::Site(std::string h, std::string b) : body(b), header(h) {} -std::string Site::getHeader() { - return header; -} +std::string Site::getHeader() { return header; } -std::string Site::getBody() { - return body; -} +std::string Site::getBody() { return body; } uint32_t Site::getStatusCode() { try { - uint32_t statusCode = std::stoi(header.substr(0,2)); + uint32_t statusCode = std::stoi(header.substr(0, 2)); return statusCode; } catch (...) { - return uint32_t {41}; + return uint32_t{41}; } } @@ -27,11 +24,6 @@ std::string Site::getMeta() { return meta; } +void Site::setUnreachable() { unreachable = true; } -void Site::setUnreachable() { - unreachable = true; -} - -bool Site::getUnreachable() { - return unreachable; -} +bool Site::getUnreachable() { return unreachable; } diff --git a/src/utils.cpp b/src/utils.cpp @@ -1,19 +1,15 @@ #include "../include/utils.hpp" -#include "../include/list-item.hpp" -#include "../include/quote.hpp" -#include "../include/heading.hpp" -#include "../include/link.hpp" -#include "../include/shared.hpp" -#include "../include/format-switch.hpp" -#include "../include/errors.hpp" -#include "../include/plaintext.hpp" -#include "../include/preformatted.hpp" -#include <thread> + +#include <fcntl.h> +#include <spawn.h> +#include <sys/wait.h> #include <threads.h> + #include <algorithm> #include <cassert> #include <cstddef> #include <cstdlib> +#include <filesystem> #include <fstream> #include <iomanip> #include <ios> @@ -22,17 +18,23 @@ #include <sstream> #include <stdexcept> #include <string> +#include <thread> #include <utility> -#include <filesystem> #include <vector> -#include <spawn.h> -#include <sys/wait.h> -#include <fcntl.h> + +#include "../include/errors.hpp" +#include "../include/format-switch.hpp" +#include "../include/heading.hpp" +#include "../include/link.hpp" +#include "../include/list-item.hpp" +#include "../include/plaintext.hpp" +#include "../include/preformatted.hpp" +#include "../include/quote.hpp" +#include "../include/shared.hpp" extern char** environ; void openUrl(const std::string& url) { - posix_spawn_file_actions_t fa; posix_spawn_file_actions_init(&fa); // we don't want the stdout mucking up our terminal. @@ -41,7 +43,8 @@ void openUrl(const std::string& url) { pid_t pid; char* argv[] = {(char*)openUnknownScheme, (char*)url.c_str(), nullptr}; - if (posix_spawnp(&pid, openUnknownScheme, &fa, nullptr, argv, environ) == 0) { + if (posix_spawnp(&pid, openUnknownScheme, &fa, nullptr, argv, environ) == + 0) { waitpid(pid, nullptr, 0); } posix_spawn_file_actions_destroy(&fa); @@ -53,7 +56,7 @@ bool isPrefixed(std::string input, std::string prefix) { std::string readFileToString(std::string filePath) { auto in = std::ifstream(filePath); - if(in.fail()) { + if (in.fail()) { throw FileReadError{}; } std::ostringstream sstr; @@ -64,21 +67,20 @@ std::string readFileToString(std::string filePath) { std::string stripLeadingWhiteSpace(std::string& input) { std::size_t x = 0; - while(x < input.size() && isWhiteSpace(input, x)) { + while (x < input.size() && isWhiteSpace(input, x)) { x += 1; } return input.substr(x); } bool isWhiteSpace(std::string& line, int idx) { - if(idx < (int)line.size() && idx >= 0) { + if (idx < (int)line.size() && idx >= 0) { return line[idx] == ' ' || line[idx] == '\t'; - } + } return false; } -std::vector<std::string> stringToList(std::string input) -{ +std::vector<std::string> stringToList(std::string input) { std::vector<std::string> res; if (!input.empty()) { int start = 0; @@ -98,51 +100,47 @@ std::vector<std::string> stringToList(std::string input) return res; } -Line* lineToLine(std::string input, std::optional<uri> prior, int linkCount, bool isPreformatted) { - - if(input.substr(0,3) == "```") { +Line* lineToLine(std::string input, std::optional<uri> prior, int linkCount, + bool isPreformatted) { + if (input.substr(0, 3) == "```") { FormatSwitch* fs = new FormatSwitch{input}; return fs; } - if(!isPreformatted) { - if(input.substr(0,2) == "=>") { + if (!isPreformatted) { + if (input.substr(0, 2) == "=>") { Link* ln = new Link{input, prior, linkCount}; return ln; } - if( (input.substr(0,1) == "#" ) || - (input.substr(0,2) == "##") || - (input.substr(0,3) == "###")) { - + if ((input.substr(0, 1) == "#") || (input.substr(0, 2) == "##") || + (input.substr(0, 3) == "###")) { Heading* hd = new Heading{input}; return hd; } - if(input.substr(0,1) == ">") { - Quote* qt= new Quote{input}; + if (input.substr(0, 1) == ">") { + Quote* qt = new Quote{input}; return qt; } - if(input.substr(0,2) == "* ") { - ListItem* li= new ListItem{input}; + if (input.substr(0, 2) == "* ") { + ListItem* li = new ListItem{input}; return li; } - return new Plaintext{input}; } else { return new Preformatted{input}; } return new Plaintext{input}; - } - std::string urlEncode(const std::string& value) { std::ostringstream escaped; escaped.fill('0'); escaped << std::hex; - for (std::string::const_iterator i = value.begin(), n = value.end(); i != n; ++i) { + for (std::string::const_iterator i = value.begin(), n = value.end(); i != n; + ++i) { std::string::value_type c = (*i); // Keep alphanumeric and other accepted characters intact @@ -153,7 +151,7 @@ std::string urlEncode(const std::string& value) { // Any other characters are percent-encoded escaped << std::uppercase; - escaped << '%' << std::setw(2) << int((unsigned char) c); + escaped << '%' << std::setw(2) << int((unsigned char)c); escaped << std::nouppercase; } @@ -161,7 +159,7 @@ std::string urlEncode(const std::string& value) { } std::string getNewTab() { - std::string st = + std::string st = "# New Tab\n" "\n" "This is a new tab. We have a few keybindings around here:\n" @@ -170,8 +168,7 @@ std::string getNewTab() { "* f -> forward a page\n" "* o -> show url entry / link selection\n" "* e -> open current page in your preferred text editor\n" - "* (r | C-r) -> refresh page\n" - ; + "* (r | C-r) -> refresh page\n"; return st; } @@ -190,15 +187,14 @@ int u8len(unsigned char c) { } return 1; } - -int u8width(const std::string& s, std::size_t i, int len) { +int u8width(const std::string& s, std::size_t i, int len) { unsigned char c = static_cast<unsigned char>(s[i]); if (len == 1 && c < 0x80) { return (c >= 0x20 && c != 0x7F) ? 1 : 0; } - std::mbstate_t st {}; + std::mbstate_t st{}; wchar_t wc; if (std::mbrtowc(&wc, s.data() + i, len, &st) != (std::size_t)len) { return 1; @@ -210,95 +206,98 @@ int u8width(const std::string& s, std::size_t i, int len) { return w; } - - // WIDTH IS INCLUSIVE // WE ASSUME NO WIDER CHARS (E.G. replace tabs with spaces.) -std::vector<std::pair<std::string, TextRender>> breakLines(std::vector<std::pair<std::string, TextRender>>& strLs, int width, int cols) { - - std::vector<std::pair<std::string, TextRender>> res {}; - +std::vector<std::pair<std::string, TextRender>> breakLines( + std::vector<std::pair<std::string, TextRender>>& strLs, int width, + int cols) { + std::vector<std::pair<std::string, TextRender>> res{}; + int leftPadAmount = std::max(0, (cols - width) / 2); - std::string leftPadStr (leftPadAmount, ' '); - - if(width <= 0) { + std::string leftPadStr(leftPadAmount, ' '); + + if (width <= 0) { return res; } res.reserve(strLs.size()); - for(std::size_t i = 0; i < strLs.size(); ++i) { - + for (std::size_t i = 0; i < strLs.size(); ++i) { const std::string& cstr = strLs[i].first; - - if(!strLs[i].second.shouldFold) { + + if (!strLs[i].second.shouldFold) { int limit = cols - leftPadAmount; int w = 0; std::size_t end = 0; - while(end < cstr.size()) { + while (end < cstr.size()) { int len = std::min(u8len(cstr[end]), (int)(cstr.size() - end)); int cw = u8width(cstr, end, len); - if(w + cw > limit) { + if (w + cw > limit) { break; } w += cw; end += len; } - std::string rs = cstr.substr(0, end); // otherwise there's some funkiness at the end due to how ncurses renders stuff. - res.push_back(std::pair<std::string,TextRender> {leftPadStr + rs, strLs[i].second}); + std::string rs = + cstr.substr(0, end); // otherwise there's some funkiness at the + // end due to how ncurses renders stuff. + res.push_back(std::pair<std::string, TextRender>{leftPadStr + rs, + strLs[i].second}); continue; } - + std::string current = ""; int curWidth = 0; int lastSpace = -1; int lastSpaceWidth = 0; - - for(int x = 0; x < (int)cstr.size(); ) { - if(cstr[x] == '\n') { - res.push_back(std::pair<std::string,TextRender> {leftPadStr + current, strLs[i].second}); + + for (int x = 0; x < (int)cstr.size();) { + if (cstr[x] == '\n') { + res.push_back(std::pair<std::string, TextRender>{ + leftPadStr + current, strLs[i].second}); current = ""; curWidth = 0; lastSpace = -1; ++x; continue; } - + int len = std::min(u8len(cstr[x]), (int)cstr.size() - x); int w = u8width(cstr, x, len); - - if(w > 0 && curWidth > 0 && curWidth + w > width) { - + + if (w > 0 && curWidth > 0 && curWidth + w > width) { std::string toPush = current; - - if(lastSpace != -1) { - toPush = current.substr(0,lastSpace+1); - current = current.substr(lastSpace+1); + + if (lastSpace != -1) { + toPush = current.substr(0, lastSpace + 1); + current = current.substr(lastSpace + 1); curWidth = curWidth - lastSpaceWidth; } else { current = ""; curWidth = 0; } - - res.push_back(std::pair<std::string,TextRender> {leftPadStr + toPush,strLs[i].second}); + + res.push_back(std::pair<std::string, TextRender>{ + leftPadStr + toPush, strLs[i].second}); lastSpace = -1; } - + current.append(cstr, x, len); curWidth += w; - if(cstr[x] == ' ') { + if (cstr[x] == ' ') { lastSpace = current.size() - 1; lastSpaceWidth = curWidth; } x += len; } - if(current.size() > 0) { - res.push_back(std::pair<std::string,TextRender> {leftPadStr + current,strLs[i].second}); + if (current.size() > 0) { + res.push_back(std::pair<std::string, TextRender>{ + leftPadStr + current, strLs[i].second}); current = ""; } } - + return res; } @@ -307,27 +306,27 @@ void writeStringToFile(std::string toWrite, std::string filePath) { std::ofstream ofs(path); ofs << toWrite; } -std::string encodeAsFilename(uri link) { - +std::string encodeAsFilename(uri link) { std::string base = link.to_string(); assert(base.find(':') != std::string::npos); - base = base.substr(base.find(':')+1); // works for file:/// and gemini:/// + base = + base.substr(base.find(':') + 1); // works for file:/// and gemini:/// - while(base.size() > 0 && base[0] == '/') { + while (base.size() > 0 && base[0] == '/') { base = base.substr(1); } - std::string cleaned = std::regex_replace(base, std::regex("[^[:alnum:]._-]"), "_"); + std::string cleaned = + std::regex_replace(base, std::regex("[^[:alnum:]._-]"), "_"); return cleaned; } -std::filesystem::path getHome() -{ +std::filesystem::path getHome() { std::string home = std::getenv("HOME"); if (home == "") { throw std::runtime_error{"$HOME not set."}; } - if(!std::filesystem::exists(home)) { + if (!std::filesystem::exists(home)) { throw std::runtime_error{"$HOME directory doesn't exist..."}; } @@ -335,19 +334,20 @@ std::filesystem::path getHome() } Destination handleDestinationResolution(std::string destination, bool isCli) { + Destination ret{}; - Destination ret {}; - - if(destination == "") { + if (destination == "") { ret.t = NO_DESTINATION; return ret; } - if(isCli) { - if(std::filesystem::exists(destination)) { - std::string path = "file://" + std::filesystem::current_path().string() + "/" + destination; + if (isCli) { + if (std::filesystem::exists(destination)) { + std::string path = "file://" + + std::filesystem::current_path().string() + "/" + + destination; - if(destination.find('/') == std::size_t(0)) { + if (destination.find('/') == std::size_t(0)) { path = "file://" + destination; } @@ -355,14 +355,14 @@ Destination handleDestinationResolution(std::string destination, bool isCli) { ret.t = STRING_DESTINATION; return ret; - } else { + } else { std::string inputString = destination; - if(inputString.find("gemini://") == 0) { + if (inputString.find("gemini://") == 0) { ret.destination = destination; ret.t = STRING_DESTINATION; return ret; - } else if (inputString.find(':') == std::string::npos){ - ret.destination = std::string {"gemini://"} + destination; + } else if (inputString.find(':') == std::string::npos) { + ret.destination = std::string{"gemini://"} + destination; ret.t = STRING_DESTINATION; return ret; @@ -370,14 +370,13 @@ Destination handleDestinationResolution(std::string destination, bool isCli) { ret.destination = destination; ret.t = STRING_DESTINATION; return ret; - } } } else { try { std::size_t pos = 0; - int dest = std::stoi(destination,&pos); - if(pos == destination.size() && dest >= 0) { + int dest = std::stoi(destination, &pos); + if (pos == destination.size() && dest >= 0) { ret.linkNumber = dest; ret.t = NUMBER_DESTINATION; return ret; @@ -385,15 +384,19 @@ Destination handleDestinationResolution(std::string destination, bool isCli) { throw std::invalid_argument("Unable to convert fully"); } } catch (...) { - - if (destination.find(' ') == std::string::npos && (destination.rfind("localhost:", 0) == 0 || destination.rfind("localhost/", 0) == 0 || destination == "localhost")) { + if (destination.find(' ') == std::string::npos && + (destination.rfind("localhost:", 0) == 0 || + destination.rfind("localhost/", 0) == 0 || + destination == "localhost")) { destination = "gemini://" + destination; - } - else if(destination.find("://") == std::string::npos || destination.find(' ') != std::string::npos) { - if(destination.find('.') != std::string::npos && destination.find(' ') == std::string::npos) { + } else if (destination.find("://") == std::string::npos || + destination.find(' ') != std::string::npos) { + if (destination.find('.') != std::string::npos && + destination.find(' ') == std::string::npos) { destination = "gemini://" + destination; } else { - destination = DEFAULT_SEARCH_ENGINE + urlEncode(destination); + destination = + DEFAULT_SEARCH_ENGINE + urlEncode(destination); } } @@ -401,25 +404,26 @@ Destination handleDestinationResolution(std::string destination, bool isCli) { ret.t = STRING_DESTINATION; return ret; } - } throw std::logic_error("Unexpected input."); } -void sanitizeCharactersToDraw(std::vector<std::pair<std::string, TextRender>>& strLs) { +void sanitizeCharactersToDraw( + std::vector<std::pair<std::string, TextRender>>& strLs) { std::vector<std::thread> threads{}; - for(std::size_t i = 0; i < strLs.size(); ++i) { - + for (std::size_t i = 0; i < strLs.size(); ++i) { std::string& s = strLs[i].first; std::string out; out.reserve(s.size()); for (int c : s) - if (c == '\r' || c == '\v' || c == '\b' || c == '\f' || c == '\a' || c == '\0') { + if (c == '\r' || c == '\v' || c == '\b' || c == '\f' || c == '\a' || + c == '\0') { continue; } else if (c == '\t') { - out += " "; // \t is a larger character and fucks with breaklines. + out += " "; // \t is a larger character and fucks with + // breaklines. } else { out += c; } @@ -435,7 +439,7 @@ bool isSendableIfGeminiUrl(const uri& u) { std::string getEditor() { const char* editor = std::getenv("EDITOR"); - if(editor) { + if (editor) { return std::string{editor}; } else { // if editor isn't set, default to nano diff --git a/tests/browser-test.cpp b/tests/browser-test.cpp @@ -1,10 +1,13 @@ -#include <catch2/catch_test_macros.hpp> +#include "../include/browser.hpp" + #include <rapidcheck.h> +#include <rapidcheck/Assertions.h> + +#include <catch2/catch_test_macros.hpp> #include <cstdlib> #include <filesystem> -#include <rapidcheck/Assertions.h> #include <utility> -#include "../include/browser.hpp" + #include "../include/utils.hpp" std::string genRandom(const int len) { @@ -18,91 +21,98 @@ std::string genRandom(const int len) { for (int i = 0; i < len; ++i) { tmp_s += alphanum[rand() % (sizeof(alphanum) - 1)]; } - + return tmp_s; } - -TEST_CASE( "Basic rendering of all line types" ) { +TEST_CASE("Basic rendering of all line types") { Browser b{}; std::string cwd = std::filesystem::current_path(); std::string st = "file://" + cwd + "/tests/sites/all_line_types.gmi"; b.goToSite(st, true); - REQUIRE(b.getCurrentSite()->getBody() == readFileToString("tests/sites/all_line_types.gmi")); + REQUIRE(b.getCurrentSite()->getBody() == + readFileToString("tests/sites/all_line_types.gmi")); auto strLs = b.renderSite(); - auto res = breakLines(strLs, 80,200); - for(auto& st: res) { - if(st.second.shouldFold) { + auto res = breakLines(strLs, 80, 200); + for (auto& st : res) { + if (st.second.shouldFold) { REQUIRE(st.first.size() <= 200); } } } - -TEST_CASE( "Basic navigation" ) { +TEST_CASE("Basic navigation") { Browser b{}; std::string cwd = std::filesystem::current_path(); std::string st = "file://" + cwd + "/tests/sites/basic.gmi"; std::string st2 = "file://" + cwd + "/tests/sites/basic_2.gmi"; b.goToSite(st, true); - REQUIRE(b.getCurrentSite()->getBody() == readFileToString("tests/sites/basic.gmi")); + REQUIRE(b.getCurrentSite()->getBody() == + readFileToString("tests/sites/basic.gmi")); b.goToSite(st2, true); - REQUIRE(b.getCurrentSite()->getBody() == readFileToString("tests/sites/basic_2.gmi")); + REQUIRE(b.getCurrentSite()->getBody() == + readFileToString("tests/sites/basic_2.gmi")); } - -TEST_CASE( "Local filesystem relative navigation" ) { - +TEST_CASE("Local filesystem relative navigation") { Browser b{}; std::string cwd = std::filesystem::current_path(); std::string st = "file://" + cwd + "/tests/sites/basic.gmi"; b.goToSite(st, true); - REQUIRE(b.getCurrentSite()->getBody() == readFileToString("tests/sites/basic.gmi")); + REQUIRE(b.getCurrentSite()->getBody() == + readFileToString("tests/sites/basic.gmi")); b.goToSite("basic_2.gmi", true); - REQUIRE(b.getCurrentSite()->getBody() == readFileToString("tests/sites/basic_2.gmi")); + REQUIRE(b.getCurrentSite()->getBody() == + readFileToString("tests/sites/basic_2.gmi")); } -TEST_CASE ("Local filesystems navigation via links") { +TEST_CASE("Local filesystems navigation via links") { Browser b{}; std::string cwd = std::filesystem::current_path(); std::string st = "file://" + cwd + "/tests/sites/basic.gmi"; b.goToSite(st, true); - REQUIRE(b.getCurrentSite()->getBody() == readFileToString("tests/sites/basic.gmi")); + REQUIRE(b.getCurrentSite()->getBody() == + readFileToString("tests/sites/basic.gmi")); b.followLinkNumber(1); - REQUIRE(b.getCurrentSite()->getBody() == readFileToString("tests/sites/basic_2.gmi")); + REQUIRE(b.getCurrentSite()->getBody() == + readFileToString("tests/sites/basic_2.gmi")); } TEST_CASE("Test browser doesn't crash on invalid sites.") { Browser b{}; b.goToSite("gemini://this_site_doesn_t_exsist"); - REQUIRE(b.getCurrentLink()->getLinkDestination().to_string() == "about://newtab"); + REQUIRE(b.getCurrentLink()->getLinkDestination().to_string() == + "about://newtab"); b.goBack(); - REQUIRE(b.getCurrentLink()->getLinkDestination().to_string() == "about://newtab"); + REQUIRE(b.getCurrentLink()->getLinkDestination().to_string() == + "about://newtab"); } - -TEST_CASE("Test browser doesn't crash when accessing sites with specified port number that is not responsive.") { +TEST_CASE( + "Test browser doesn't crash when accessing sites with specified port " + "number that is not responsive.") { Browser b{}; SiteLoadPair res = b.goToSite("gemini://localhost:3847"); REQUIRE(res.result == SITE_PERMANENT_FAILURE); b.goForward(); b.goBack(); - REQUIRE(b.getCurrentLink()->getLinkDestination().to_string() == "about://newtab"); + REQUIRE(b.getCurrentLink()->getLinkDestination().to_string() == + "about://newtab"); } - -TEST_CASE("Test browser can access sites with specified (default) port number.") { +TEST_CASE( + "Test browser can access sites with specified (default) port number.") { Browser b{}; b.goToSite("gemini://localhost:1965"); REQUIRE(b.getCurrentSite()->getMeta() == "text/gemini"); } - -// TODO: Test invalid meta lines (like the case where weird stuff is sent from server) +// TODO: Test invalid meta lines (like the case where weird stuff is sent from +// server) TEST_CASE("Test browser returns proper meta for visited sites.") { Browser b{}; b.goToSite("gemini://localhost"); @@ -110,45 +120,52 @@ TEST_CASE("Test browser returns proper meta for visited sites.") { REQUIRE(b.getCurrentSite()->getMeta() == "text/gemini"); } - -TEST_CASE("Test browser doesn't crash on invalid link number following, excessive back, and excessive forwards.") { - +TEST_CASE( + "Test browser doesn't crash on invalid link number following, excessive " + "back, and excessive forwards.") { Browser b{}; b.goToSite("gemini://localhost/sites/feed.xml"); - REQUIRE(b.getCurrentLink()->getLinkDestination().to_string() == "gemini://localhost/sites/feed.xml"); - for(int i = 0; i < 1000; ++i) { + REQUIRE(b.getCurrentLink()->getLinkDestination().to_string() == + "gemini://localhost/sites/feed.xml"); + for (int i = 0; i < 1000; ++i) { b.followLinkNumber(i); } - REQUIRE(b.getCurrentLink()->getLinkDestination().to_string() == "gemini://localhost/sites/feed.xml"); + REQUIRE(b.getCurrentLink()->getLinkDestination().to_string() == + "gemini://localhost/sites/feed.xml"); b.goBack(); - REQUIRE(b.getCurrentLink()->getLinkDestination().to_string() == "about://newtab"); + REQUIRE(b.getCurrentLink()->getLinkDestination().to_string() == + "about://newtab"); b.goForward(); - REQUIRE(b.getCurrentLink()->getLinkDestination().to_string() == "gemini://localhost/sites/feed.xml"); + REQUIRE(b.getCurrentLink()->getLinkDestination().to_string() == + "gemini://localhost/sites/feed.xml"); b.goBack(); b.goBack(); - REQUIRE(b.getCurrentLink()->getLinkDestination().to_string() == "about://newtab"); + REQUIRE(b.getCurrentLink()->getLinkDestination().to_string() == + "about://newtab"); b.goForward(); b.goForward(); - REQUIRE(b.getCurrentLink()->getLinkDestination().to_string() == "gemini://localhost/sites/feed.xml"); + REQUIRE(b.getCurrentLink()->getLinkDestination().to_string() == + "gemini://localhost/sites/feed.xml"); } TEST_CASE("Test page downloading.") { Browser b{}; b.goToSite("gemini://localhost/sites/"); - REQUIRE(b.getCurrentLink()->getLinkDestination().to_string() == "gemini://localhost/sites/"); + REQUIRE(b.getCurrentLink()->getLinkDestination().to_string() == + "gemini://localhost/sites/"); std::string destination = b.tryDownloadPage(); std::string out = readFileToString(destination); REQUIRE(out == b.getCurrentSite()->getBody()); REQUIRE(std::filesystem::remove(destination)); } - TEST_CASE("Test downloading to specific directory") { std::filesystem::path cwd = std::filesystem::current_path(); Browser b{}; b.goToSite("gemini://localhost/sites/"); - REQUIRE(b.getCurrentLink()->getLinkDestination().to_string() == "gemini://localhost/sites/"); + REQUIRE(b.getCurrentLink()->getLinkDestination().to_string() == + "gemini://localhost/sites/"); std::string destination = b.tryDownloadPage(cwd); std::string out = readFileToString(destination); REQUIRE(out == b.getCurrentSite()->getBody()); @@ -156,15 +173,17 @@ TEST_CASE("Test downloading to specific directory") { REQUIRE(std::filesystem::remove(destination)); } - -TEST_CASE("Test going forwards doesn't break when accessing an invalid site prior.") { +TEST_CASE( + "Test going forwards doesn't break when accessing an invalid site prior.") { Browser b{}; SiteLoadPair res = b.goToSite("gemini://aroisetnatsr.aoirseaorstie"); REQUIRE(res.result == SITE_PERMANENT_FAILURE); b.goForward(); } -TEST_CASE("Test going backwards doesn't break when accessing an invalid site prior.") { +TEST_CASE( + "Test going backwards doesn't break when accessing an invalid site " + "prior.") { Browser b{}; SiteLoadPair res = b.goToSite("gemini://aroisetnatsr.aoirseaorstie"); REQUIRE(res.result == SITE_PERMANENT_FAILURE); @@ -174,13 +193,15 @@ TEST_CASE("Test going backwards doesn't break when accessing an invalid site pri TEST_CASE("Test encoding allows relative linking with : in parameter") { Browser b{}; b.goToSite("gemini://localhost/cgi-bin/search.py"); - REQUIRE(b.getCurrentLink()->getLinkDestination().to_string() == "gemini://localhost/cgi-bin/search.py"); + REQUIRE(b.getCurrentLink()->getLinkDestination().to_string() == + "gemini://localhost/cgi-bin/search.py"); b.goToSite("?https://test.com"); - REQUIRE(b.getCurrentLink()->getLinkDestination().to_string() == "gemini://localhost/cgi-bin/search.py?https%3A%2F%2Ftest.com"); + REQUIRE(b.getCurrentLink()->getLinkDestination().to_string() == + "gemini://localhost/cgi-bin/search.py?https%3A%2F%2Ftest.com"); } TEST_CASE("Sanitize characters to draw tests") { - Browser b {}; + Browser b{}; std::string cwd = std::filesystem::current_path(); std::string st = "file://" + cwd + "/tests/sites/line-return.gmi"; SiteLoadPair res = b.goToSite(st); @@ -191,30 +212,31 @@ TEST_CASE("Sanitize characters to draw tests") { auto ls = b.renderSite(); sanitizeCharactersToDraw(ls); - for(auto& line : ls) { + for (auto& line : ls) { REQUIRE(line.first.find('\r') == std::string::npos); } } TEST_CASE("Never crash from weird user inputs") { - for(int i = 0; i < 5; ++i) { - Browser b {}; + for (int i = 0; i < 5; ++i) { + Browser b{}; - std::vector<std::string> ls {}; - for(int x = 0; x < 10; ++x) { + std::vector<std::string> ls{}; + for (int x = 0; x < 10; ++x) { ls.push_back(genRandom(rand() % 5000)); } - for(auto& str : ls) { + for (auto& str : ls) { auto res = handleDestinationResolution("?" + str, false); - if(res.t == STRING_DESTINATION) { + if (res.t == STRING_DESTINATION) { b.goToSite(res.destination); } else if (res.t == NUMBER_DESTINATION) { b.followLinkNumber(res.linkNumber); } b.refresh(); b.goBack(); - REQUIRE(b.getCurrentLink()->getLinkDestination().to_string() == "about://newtab"); + REQUIRE(b.getCurrentLink()->getLinkDestination().to_string() == + "about://newtab"); } } } diff --git a/tests/cgi-bin/000redirect.py b/tests/cgi-bin/000redirect.py @@ -0,0 +1,4 @@ +#!/usr/bin/env python3 +import random + +print(f"31 gemini://localhost", end="\r\n") diff --git a/tests/cgi-bin/rnd.py b/tests/cgi-bin/rnd.py @@ -0,0 +1,4 @@ +#!/usr/bin/env python3 +import random + +print(str(random.randint(0,100)) + " text/gemini", end="\r\n") diff --git a/tests/fetch-test.cpp b/tests/fetch-test.cpp @@ -1,28 +1,29 @@ #include <catch2/catch_test_macros.hpp> -#include "../include/utils.hpp" #include <filesystem> #include "../include/gemini-client.hpp" #include "../include/link.hpp" +#include "../include/utils.hpp" TEST_CASE("Link constructors") { + auto l2 = Link{"=> basic_2.gmi Other Page!", + uri{"file:///tests/sites/basic.gmi"}}; - auto l2 = Link{"=> basic_2.gmi Other Page!", uri{"file:///tests/sites/basic.gmi"}}; - - REQUIRE("file:///tests/sites/basic_2.gmi" == l2.getLinkDestination().to_string()); + REQUIRE("file:///tests/sites/basic_2.gmi" == + l2.getLinkDestination().to_string()); REQUIRE("Other Page!" == l2.getLinkText()); } // this mostly exists in case utils.cpp is busted in some very obvious way. TEST_CASE("Local Sanity Client") { - auto client = GeminiClient {}; + auto client = GeminiClient{}; std::string cwd = std::filesystem::current_path(); std::string st = "=> file://" + cwd + "/tests/sites/basic_2.gmi"; auto ln = Link{st}; Site* s = client.fetchSite(ln); - std::string expectedSite = + std::string expectedSite = "# Hello World 2\n" "\n" "This is basic_2.gmi!\n" @@ -31,11 +32,11 @@ TEST_CASE("Local Sanity Client") { REQUIRE(s->getBody() == expectedSite); delete s; - } TEST_CASE("Match on all .gmi file headers in tests/sites") { - auto client = GeminiClient {}; - for(const auto& current: std::filesystem::directory_iterator("tests/sites")) { + auto client = GeminiClient{}; + for (const auto& current : + std::filesystem::directory_iterator("tests/sites")) { std::string cwd = std::filesystem::current_path(); std::string st = "=> file://" + cwd + "/"; @@ -47,10 +48,10 @@ TEST_CASE("Match on all .gmi file headers in tests/sites") { } } - TEST_CASE("Match on all .gmi files in tests/sites") { - auto client = GeminiClient {}; - for(const auto& current: std::filesystem::directory_iterator("tests/sites")) { + auto client = GeminiClient{}; + for (const auto& current : + std::filesystem::directory_iterator("tests/sites")) { std::string cwd = std::filesystem::current_path(); std::string st = "=> file://" + cwd + "/"; std::string full = st + current.path().string(); @@ -63,16 +64,15 @@ TEST_CASE("Match on all .gmi files in tests/sites") { } TEST_CASE("Match status code on missing .gmi files") { - auto client = GeminiClient {}; + auto client = GeminiClient{}; auto ln = Link{"=> file:///tests/sites/this_file_doesnt_exist.gmi"}; Site* s = client.fetchSite(ln); REQUIRE(s->getStatusCode() == 51); delete s; } - TEST_CASE("Send basic gemini requests") { - auto client = GeminiClient {}; + auto client = GeminiClient{}; auto ln = Link{"=> gemini://localhost"}; Site* s = client.fetchSite(ln); REQUIRE(s->getStatusCode() == 20); @@ -80,9 +80,8 @@ TEST_CASE("Send basic gemini requests") { delete s; } - TEST_CASE("Send request to non-existent gemini server") { - auto client = GeminiClient {}; + auto client = GeminiClient{}; auto ln = Link{"=> gemini://this.cant.be.a.site123"}; Site* s = client.fetchSite(ln); REQUIRE(s == nullptr); diff --git a/tests/mem-leak-test.cpp b/tests/mem-leak-test.cpp @@ -1,11 +1,13 @@ -#include "../include/browser.hpp" +#include <unistd.h> + #include <csignal> #include <cstdlib> +#include <ctime> #include <iostream> #include <thread> #include <vector> -#include <ctime> -#include <unistd.h> + +#include "../include/browser.hpp" std::string genRandom(const int len) { static const char alphanum[] = @@ -18,7 +20,7 @@ std::string genRandom(const int len) { for (int i = 0; i < len; ++i) { tmp_s += alphanum[rand() % (sizeof(alphanum) - 1)]; } - + return tmp_s; } @@ -26,38 +28,40 @@ void traversal() { Browser b{}; b.goToSite("gemini://localhost", true); - for(int i = 0; i < 100; ++i) { - + for (int i = 0; i < 100; ++i) { auto* lls = b.getLinkLines(); std::size_t count = lls->size(); delete lls; - if(b.getCurrentLink() != nullptr) { - std::cout << "CURRENTLY AT: " << b.getCurrentLink()->getLinkDestination().to_string() << std::endl; + if (b.getCurrentLink() != nullptr) { + std::cout << "CURRENTLY AT: " + << b.getCurrentLink()->getLinkDestination().to_string() + << std::endl; } - if(count == 0 && rand() % 10 == 0) { + if (count == 0 && rand() % 10 == 0) { std::cout << "GOING BACK" << std::endl; b.goBack(); - } else if(rand() % 5 == 0) { + } else if (rand() % 5 == 0) { std::cout << "GOING FORWARD" << std::endl; b.goForward(); - } else if(rand() % 10 == 0) { + } else if (rand() % 10 == 0) { std::cout << "GOING BACK" << std::endl; b.goBack(); - } else if (rand() % 5 == 0){ - if(rand() % 5 == 0) { - std::string dst = std::string{"gemini://"} + genRandom(rand() % 5000) + ".com"; + } else if (rand() % 5 == 0) { + if (rand() % 5 == 0) { + std::string dst = std::string{"gemini://"} + + genRandom(rand() % 5000) + ".com"; std::cout << "TRAVELLING TO: " << dst << std::endl; b.goToSite(dst); } else { - std::string dst = std::string{"gemini://"} + genRandom(rand() % 15) + ".com"; + std::string dst = + std::string{"gemini://"} + genRandom(rand() % 15) + ".com"; std::cout << "TRAVELLING TO: " << dst << std::endl; b.goToSite(dst); } - } - else { - if(count == 0) { + } else { + if (count == 0) { count = 10; } int num = ((rand() % count) + 1) + (rand() % 5); @@ -69,16 +73,17 @@ void traversal() { // NOTE: When running this you probably want to run something like: // `watch pkill {browser}` -// because it'll probably try to follow http links that are found. +// because it'll probably try to follow http links that are found. int main() { - std::signal(SIGPIPE, SIG_IGN); // this is also done in main for the actual executable, this is for consistency. - std::vector<std::thread*> vec {}; - for(int x = 0; x < 5; ++x) { - auto* t = new std::thread (&traversal); + std::signal(SIGPIPE, SIG_IGN); // this is also done in main for the actual + // executable, this is for consistency. + std::vector<std::thread*> vec{}; + for (int x = 0; x < 5; ++x) { + auto* t = new std::thread(&traversal); vec.push_back(t); } - for(auto& th : vec) { + for (auto& th : vec) { th->join(); delete th; } diff --git a/tests/puppet-test.cpp b/tests/puppet-test.cpp @@ -1,17 +1,18 @@ -#include <catch2/catch_test_macros.hpp> -#include <cstdlib> -#include <filesystem> -#include <rapidcheck.h> -#include "../include/render.hpp" #include <ncurses.h> +#include <rapidcheck.h> #include <rapidcheck/Check.h> #include <rapidcheck/Log.h> + +#include <catch2/catch_test_macros.hpp> +#include <cstdlib> +#include <filesystem> #include <string> + +#include "../include/render.hpp" #ifndef CTRL #define CTRL(c) ((c) & 037) #endif - std::string genRandom(const int len) { static const char alpha[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" @@ -22,7 +23,7 @@ std::string genRandom(const int len) { for (int i = 0; i < len; ++i) { tmp_s += alpha[rand() % (sizeof(alpha) - 1)]; } - + return tmp_s; } @@ -37,198 +38,388 @@ std::string genAlNumNlSp(const int len) { for (int i = 0; i < len; ++i) { tmp_s += alphanum[rand() % (sizeof(alphanum) - 1)]; } - + return tmp_s; } - // Puppet entire browser TEST_CASE("q quits session immediately") { - Browser* bPtr = new Browser {}; + Browser* bPtr = new Browser{}; Browser& b = *bPtr; - DrawState ds {}; + DrawState ds{}; ds.bPtr = bPtr; - REQUIRE_FALSE(mainLoop(ds, b, 'q',0,0)); + REQUIRE_FALSE(mainLoop(ds, b, 'q', 0, 0)); delete bPtr; } TEST_CASE("RESIZE falls through and returns") { - Browser* bPtr = new Browser {}; + Browser* bPtr = new Browser{}; Browser& b = *bPtr; - DrawState ds {}; + DrawState ds{}; ds.bPtr = bPtr; - REQUIRE(mainLoop(ds, b, KEY_RESIZE,0,0)); + REQUIRE(mainLoop(ds, b, KEY_RESIZE, 0, 0)); delete bPtr; } TEST_CASE("Redirect to broken doesn't deadlock") { - Browser* bPtr = new Browser {}; + Browser* bPtr = new Browser{}; Browser& b = *bPtr; - DrawState ds {}; + DrawState ds{}; ds.bPtr = bPtr; - std::string dest = "ogemini://localhost/cgi-bin/redirect-to-broken.py"; - for(auto& ch : dest) { - REQUIRE(mainLoop(ds, b, ch,100,100)); + std::string dest = "ogemini://localhost/cgi-bin/redirect-to-broken.py"; + for (auto& ch : dest) { + REQUIRE(mainLoop(ds, b, ch, 100, 100)); } - for(int i = 0; i < 100; ++i) { - REQUIRE(mainLoop(ds, b, 'y',100,100)); + for (int i = 0; i < 100; ++i) { + REQUIRE(mainLoop(ds, b, 'y', 100, 100)); } - REQUIRE(mainLoop(ds, b, 'n',100,100)); - REQUIRE(b.getCurrentLink()->getLinkDestination().to_string() == "about://newtab"); + REQUIRE(mainLoop(ds, b, 'n', 100, 100)); + REQUIRE(b.getCurrentLink()->getLinkDestination().to_string() == + "about://newtab"); delete bPtr; } - - - TEST_CASE("Open page handler returns") { - Browser* bPtr = new Browser {}; + Browser* bPtr = new Browser{}; Browser& b = *bPtr; - DrawState ds {}; + DrawState ds{}; ds.bPtr = bPtr; - REQUIRE(mainLoop(ds, b, 'o',0,0)); + REQUIRE(mainLoop(ds, b, 'o', 0, 0)); delete bPtr; } TEST_CASE("Cancel 'o' menu by pressing escape") { - Browser* bPtr = new Browser {}; + Browser* bPtr = new Browser{}; Browser& b = *bPtr; - DrawState ds {}; + DrawState ds{}; ds.bPtr = bPtr; - REQUIRE(mainLoop(ds, b, 'o',0,0)); - REQUIRE(mainLoop(ds, b, 'l',0,0)); - REQUIRE(mainLoop(ds, b, 'a',0,0)); - REQUIRE(mainLoop(ds, b, 'a',0,0)); - REQUIRE(mainLoop(ds, b, 'a',0,0)); - REQUIRE(mainLoop(ds, b, KEY_BACKSPACE,0,0)); - REQUIRE(mainLoop(ds, b, 'c',0,0)); - REQUIRE(mainLoop(ds, b, 'k',0,0)); - REQUIRE(mainLoop(ds, b, '.',0,0)); - REQUIRE(mainLoop(ds, b, 'c',0,0)); - REQUIRE(mainLoop(ds, b, 'o',0,0)); - REQUIRE(mainLoop(ds, b, 27,0,0)); // escape - REQUIRE(b.getCurrentLink()->getLinkDestination().to_string() == "about://newtab"); + REQUIRE(mainLoop(ds, b, 'o', 0, 0)); + REQUIRE(mainLoop(ds, b, 'l', 0, 0)); + REQUIRE(mainLoop(ds, b, 'a', 0, 0)); + REQUIRE(mainLoop(ds, b, 'a', 0, 0)); + REQUIRE(mainLoop(ds, b, 'a', 0, 0)); + REQUIRE(mainLoop(ds, b, KEY_BACKSPACE, 0, 0)); + REQUIRE(mainLoop(ds, b, 'c', 0, 0)); + REQUIRE(mainLoop(ds, b, 'k', 0, 0)); + REQUIRE(mainLoop(ds, b, '.', 0, 0)); + REQUIRE(mainLoop(ds, b, 'c', 0, 0)); + REQUIRE(mainLoop(ds, b, 'o', 0, 0)); + REQUIRE(mainLoop(ds, b, 27, 0, 0)); // escape + REQUIRE(b.getCurrentLink()->getLinkDestination().to_string() == + "about://newtab"); delete bPtr; } TEST_CASE("Handle redirects") { - Browser* bPtr = new Browser {}; + Browser* bPtr = new Browser{}; Browser& b = *bPtr; - DrawState ds {}; + DrawState ds{}; ds.bPtr = bPtr; std::string st = "ogemini://localhost/cgi-bin/redirect.py"; - for(auto& ch: st) { - REQUIRE(mainLoop(ds, b, ch,0,0)); + for (auto& ch : st) { + REQUIRE(mainLoop(ds, b, ch, 0, 0)); } - - REQUIRE(mainLoop(ds, b, '\n',0,0)); - REQUIRE(b.getCurrentLink()->getLinkDestination().to_string() == "gemini://localhost/cgi-bin/redirect.py"); + REQUIRE(mainLoop(ds, b, '\n', 0, 0)); - REQUIRE(mainLoop(ds, b, 'y',0,0)); // follow redirect - REQUIRE(b.getCurrentLink()->getLinkDestination().to_string() == "gemini://localhost"); - delete bPtr; + REQUIRE(b.getCurrentLink()->getLinkDestination().to_string() == + "gemini://localhost/cgi-bin/redirect.py"); + REQUIRE(mainLoop(ds, b, 'y', 0, 0)); // follow redirect + REQUIRE(b.getCurrentLink()->getLinkDestination().to_string() == + "gemini://localhost"); + delete bPtr; } -TEST_CASE("Handle redirect rejection") { - Browser* bPtr = new Browser {}; + +TEST_CASE("Cancel input") { + Browser* bPtr = new Browser{}; Browser& b = *bPtr; - DrawState ds {}; + DrawState ds{}; ds.bPtr = bPtr; - std::string st = "ogemini://localhost/cgi-bin/redirect.py"; - for(auto& ch: st) { - REQUIRE(mainLoop(ds, b, ch,0,0)); + std::string st = "ogemini://localhost/cgi-bin/search.py"; + for (auto& ch : st) { + REQUIRE(mainLoop(ds, b, ch, 0, 0)); } - REQUIRE(mainLoop(ds, b, '\n',0,0)); + REQUIRE(mainLoop(ds, b, '\n', 0, 0)); - REQUIRE(b.getCurrentLink()->getLinkDestination().to_string() == "gemini://localhost/cgi-bin/redirect.py"); + REQUIRE(b.getCurrentLink()->getLinkDestination().to_string() == + "gemini://localhost/cgi-bin/search.py"); + + std::string s2 = "test search query"; + for (auto& ch : s2) { + REQUIRE(mainLoop(ds, b, ch, 0, 0)); + } - REQUIRE(mainLoop(ds, b, 'n',0,0)); // don't follow redirect - REQUIRE(b.getCurrentLink()->getLinkDestination().to_string() == "about://newtab"); + REQUIRE(mainLoop(ds, b, 27, 0, 0)); // escape + + REQUIRE(b.getCurrentLink()->getLinkDestination().to_string() == + "about://newtab"); delete bPtr; } -TEST_CASE("Only return false on 'q' entry when not using input boxes, never crash, junk inputs") { - setenv("EDITOR", "test" , 1); - - rc::check("Never return false / fail except with input 'q'", [] (std::string st) { - Browser* bPtr = new Browser {}; +TEST_CASE("Handle random status codes") { + for (int i = 0; i < 100; ++i) { + Browser* bPtr = new Browser{}; Browser& b = *bPtr; - DrawState ds {}; + DrawState ds{}; ds.bPtr = bPtr; - RC_LOG(st); - for(auto& cur : st) { - if(cur == 'q') { - if(!ds.handleInput && !ds.handleOpenOther && !ds.handleRedirect) { - REQUIRE_FALSE(mainLoop(ds,b,cur,0,0)); - } else { - REQUIRE(mainLoop(ds,b,cur,0,0)); - } - } else { - REQUIRE(mainLoop(ds,b,cur,0,0)); - } + + std::string st = "ogemini://localhost/cgi-bin/rnd.py"; + for (auto& ch : st) { + REQUIRE(mainLoop(ds, b, ch, 0, 0)); } + REQUIRE(mainLoop(ds, b, '\n', 0, 0)); delete bPtr; - }); + } +} + +TEST_CASE("Follow non-existent link") { + Browser* bPtr = new Browser{}; + Browser& b = *bPtr; + DrawState ds{}; + ds.bPtr = bPtr; + + std::string st = "ogemini://localhost/cgi-bin/"; + for (auto& ch : st) { + REQUIRE(mainLoop(ds, b, ch, 0, 0)); + } + REQUIRE(mainLoop(ds, b, '\n', 0, 0)); + + REQUIRE(mainLoop(ds, b, 'o', 0, 0)); + REQUIRE(mainLoop(ds, b, '9', 0, 0)); + REQUIRE(mainLoop(ds, b, '9', 0, 0)); + REQUIRE(mainLoop(ds, b, '9', 0, 0)); + REQUIRE(mainLoop(ds, b, '\n', 0, 0)); + + REQUIRE(b.getCurrentLink()->getLinkDestination().to_string() == + "gemini://localhost/cgi-bin/"); + + delete bPtr; +} + +TEST_CASE("Handle input status codes") { + Browser* bPtr = new Browser{}; + Browser& b = *bPtr; + DrawState ds{}; + ds.bPtr = bPtr; + + std::string st = "ogemini://localhost/cgi-bin/search.py"; + for (auto& ch : st) { + REQUIRE(mainLoop(ds, b, ch, 0, 0)); + } + + REQUIRE(mainLoop(ds, b, '\n', 0, 0)); + + REQUIRE(b.getCurrentLink()->getLinkDestination().to_string() == + "gemini://localhost/cgi-bin/search.py"); + + std::string s2 = "test search query"; + for (auto& ch : s2) { + REQUIRE(mainLoop(ds, b, ch, 0, 0)); + } + + REQUIRE(mainLoop(ds, b, 127, 0, 0)); + REQUIRE(mainLoop(ds, b, 'y', 0, 0)); + + REQUIRE(mainLoop(ds, b, '\n', 0, 0)); + + REQUIRE(mainLoop(ds, b, 'n', 0, 0)); // don't follow redirect + REQUIRE(b.getCurrentLink()->getLinkDestination().to_string() == + "gemini://localhost/cgi-bin/search.py?" + urlEncode(s2)); + delete bPtr; } -TEST_CASE("Only return false on 'q' entry when not using input boxes, alphanumeric inputs") { - setenv("EDITOR", "test" , 1); +TEST_CASE("Handle redirect rejection") { + Browser* bPtr = new Browser{}; + Browser& b = *bPtr; + DrawState ds{}; + ds.bPtr = bPtr; + + std::string st = "ogemini://localhost/cgi-bin/redirect.py"; + for (auto& ch : st) { + REQUIRE(mainLoop(ds, b, ch, 0, 0)); + } + + REQUIRE(mainLoop(ds, b, '\n', 0, 0)); + + REQUIRE(b.getCurrentLink()->getLinkDestination().to_string() == + "gemini://localhost/cgi-bin/redirect.py"); + + REQUIRE(mainLoop(ds, b, 'n', 0, 0)); // don't follow redirect + REQUIRE(b.getCurrentLink()->getLinkDestination().to_string() == + "about://newtab"); + delete bPtr; +} + +TEST_CASE("Handle g and G navigation") { + Browser* bPtr = new Browser{}; + Browser& b = *bPtr; + DrawState ds{}; + ds.bPtr = bPtr; - for(int i = 0; i < 10; ++i) { - Browser* bPtr = new Browser {}; + std::string st = "ogemini://localhost/cgi-bin/redirect.py"; + for (auto& ch : st) { + REQUIRE(mainLoop(ds, b, ch, 100, 100)); + } + + REQUIRE(mainLoop(ds, b, '\n', 100, 100)); + + REQUIRE(b.getCurrentLink()->getLinkDestination().to_string() == + "gemini://localhost/cgi-bin/redirect.py"); + + REQUIRE(mainLoop(ds, b, 'n', 100, 100)); // don't follow redirect + REQUIRE(b.getCurrentLink()->getLinkDestination().to_string() == + "about://newtab"); + + REQUIRE(mainLoop(ds, b, 'g', 0, 0)); + REQUIRE(mainLoop(ds, b, 'G', 0, 0)); + + REQUIRE(mainLoop(ds, b, 'g', 100, 0)); + REQUIRE(mainLoop(ds, b, 'G', 100, 0)); + + REQUIRE(mainLoop(ds, b, 'g', 100, 100)); + REQUIRE(mainLoop(ds, b, 'G', 100, 100)); + + REQUIRE(mainLoop(ds, b, 'g', 100, 0)); + REQUIRE(mainLoop(ds, b, 'G', 100, 0)); + + delete bPtr; +} + +TEST_CASE("Show issue text on non-existent resource request") { + Browser* bPtr = new Browser{}; + Browser& b = *bPtr; + DrawState ds{}; + ds.bPtr = bPtr; + + std::string st = + "ogemini://localhost/cgi-bin/this-straight-up-cant-exist.py"; + for (auto& ch : st) { + REQUIRE(mainLoop(ds, b, ch, 100, 100)); + } + + REQUIRE(mainLoop(ds, b, '\n', 100, 100)); + + REQUIRE(b.getCurrentLink()->getLinkDestination().to_string() == + "about://newtab"); + + REQUIRE(ds.issueText != ""); + + REQUIRE(mainLoop(ds, b, 'o', 100, 100)); + + delete bPtr; +} + +TEST_CASE("Redirect on navigation by link number") { + Browser* bPtr = new Browser{}; + Browser& b = *bPtr; + DrawState ds{}; + ds.bPtr = bPtr; + + std::string st = "ogemini://localhost/cgi-bin/"; + for (auto& ch : st) { + REQUIRE(mainLoop(ds, b, ch, 100, 100)); + } + + REQUIRE(mainLoop(ds, b, '\n', 100, 100)); + + REQUIRE(mainLoop(ds, b, 'o', 100, 100)); + REQUIRE(mainLoop(ds, b, '2', 100, 100)); + REQUIRE(mainLoop(ds, b, '\n', 100, 100)); + + REQUIRE(mainLoop(ds, b, 'y', 100, 100)); + REQUIRE(ds.issueText == ""); + REQUIRE(b.getCurrentLink()->getLinkDestination().to_string() == + "gemini://localhost"); + + delete bPtr; +} + +TEST_CASE( + "Only return false on 'q' entry when not using input boxes, never crash, " + "junk inputs") { + setenv("EDITOR", "test", 1); + + rc::check("Never return false / fail except with input 'q'", + [](std::string st) { + Browser* bPtr = new Browser{}; + Browser& b = *bPtr; + DrawState ds{}; + ds.bPtr = bPtr; + RC_LOG(st); + for (auto& cur : st) { + if (cur == 'q') { + if (!ds.handleInput && !ds.handleOpenOther && + !ds.handleRedirect) { + REQUIRE_FALSE(mainLoop(ds, b, cur, 0, 0)); + } else { + REQUIRE(mainLoop(ds, b, cur, 0, 0)); + } + } else { + REQUIRE(mainLoop(ds, b, cur, 0, 0)); + } + } + delete bPtr; + }); +} + +TEST_CASE( + "Only return false on 'q' entry when not using input boxes, alphanumeric " + "inputs") { + setenv("EDITOR", "test", 1); + + for (int i = 0; i < 10; ++i) { + Browser* bPtr = new Browser{}; Browser& b = *bPtr; - DrawState ds {}; + DrawState ds{}; ds.bPtr = bPtr; - std::string st = genAlNumNlSp(rand()%100); + std::string st = genAlNumNlSp(rand() % 100); INFO(st); - for(auto& cur : st) { - if(cur == 'q') { - if(!ds.handleInput && !ds.handleOpenOther && !ds.handleRedirect) { - REQUIRE_FALSE(mainLoop(ds,b,cur,0,0)); + for (auto& cur : st) { + if (cur == 'q') { + if (!ds.handleInput && !ds.handleOpenOther && + !ds.handleRedirect) { + REQUIRE_FALSE(mainLoop(ds, b, cur, 0, 0)); } else { - REQUIRE(mainLoop(ds,b,cur,0,0)); + REQUIRE(mainLoop(ds, b, cur, 0, 0)); } } else { - REQUIRE(mainLoop(ds,b,cur,0,0)); + REQUIRE(mainLoop(ds, b, cur, 0, 0)); } } delete bPtr; - } } TEST_CASE("Basic usage with small screen sizes") { + setenv("EDITOR", "test", 1); - setenv("EDITOR", "test" , 1); - - for(int i = 0; i < 10; ++i) { + for (int i = 0; i < 10; ++i) { int x = rand() % 25; int y = rand() % 10; - Browser* bPtr = new Browser {}; + Browser* bPtr = new Browser{}; Browser& b = *bPtr; - DrawState ds {}; + DrawState ds{}; ds.bPtr = bPtr; std::string cwd = std::filesystem::current_path(); std::string st = "file://" + cwd + "/tests/sites/all_line_types.gmi"; - REQUIRE(mainLoop(ds, b, 'o',x,y)); + REQUIRE(mainLoop(ds, b, 'o', x, y)); - for(auto& ch: st) { - REQUIRE(mainLoop(ds, b, ch,x,y)); + for (auto& ch : st) { + REQUIRE(mainLoop(ds, b, ch, x, y)); } - REQUIRE(mainLoop(ds, b, '\n',x,y)); + REQUIRE(mainLoop(ds, b, '\n', x, y)); REQUIRE(b.getCurrentLink()->getLinkDestination().to_string() == st); delete bPtr; } } - diff --git a/tests/pure-test.cpp b/tests/pure-test.cpp @@ -1,44 +1,54 @@ // Testing pure functions #include <rapidcheck.h> +#include <rapidcheck/Check.h> + #include <catch2/catch_test_macros.hpp> #include <catch2/generators/catch_generators.hpp> #include <cstdlib> #include <ctime> #include <filesystem> #include <optional> -#include <rapidcheck/Check.h> #include <utility> + #include "../include/browser.hpp" #include "../include/shared.hpp" #include "../include/utils.hpp" TEST_CASE("Test cli input handling") { - SECTION("CLI inputs maintain arbitrary schemas") { std::unordered_map<std::string, std::string> expectations; - expectations["https://github.com"] = "https://github.com"; - expectations["whatever://github.com"] = "whatever://github.com"; - expectations["about://github.com"] = "about://github.com"; + expectations["https://github.com"] = "https://github.com"; + expectations["whatever://github.com"] = "whatever://github.com"; + expectations["about://github.com"] = "about://github.com"; expectations["gopher://github.com"] = "gopher://github.com"; expectations["gemini://github.com"] = "gemini://github.com"; expectations["file:///home/whatever"] = "file:///home/whatever"; expectations["localhost"] = "gemini://localhost"; - for(auto& expect : expectations) { - REQUIRE(handleDestinationResolution(expect.first, true).destination == expect.second); - REQUIRE(handleDestinationResolution(expect.first, true).t == STRING_DESTINATION); + for (auto& expect : expectations) { + REQUIRE( + handleDestinationResolution(expect.first, true).destination == + expect.second); + REQUIRE(handleDestinationResolution(expect.first, true).t == + STRING_DESTINATION); } } SECTION("Resolve relative file paths via the CLI if they exist") { std::unordered_map<std::string, std::string> expectations; std::string cwd = std::filesystem::current_path(); - expectations["tests/sites/basic.gmi"] = "file://" + cwd + "/tests/sites/basic.gmi"; - expectations["tests/sites/basic_2.gmi"] = "file://" + cwd + "/tests/sites/basic_2.gmi"; - expectations[cwd + "/tests/sites/basic_2.gmi"] = "file://" + cwd + "/tests/sites/basic_2.gmi"; - for(auto& expect : expectations) { - REQUIRE(handleDestinationResolution(expect.first, true).destination == expect.second); - REQUIRE(handleDestinationResolution(expect.first, true).t == STRING_DESTINATION); + expectations["tests/sites/basic.gmi"] = + "file://" + cwd + "/tests/sites/basic.gmi"; + expectations["tests/sites/basic_2.gmi"] = + "file://" + cwd + "/tests/sites/basic_2.gmi"; + expectations[cwd + "/tests/sites/basic_2.gmi"] = + "file://" + cwd + "/tests/sites/basic_2.gmi"; + for (auto& expect : expectations) { + REQUIRE( + handleDestinationResolution(expect.first, true).destination == + expect.second); + REQUIRE(handleDestinationResolution(expect.first, true).t == + STRING_DESTINATION); } } @@ -46,79 +56,101 @@ TEST_CASE("Test cli input handling") { std::unordered_map<std::string, std::string> expectations; expectations["tlgs.one"] = "gemini://tlgs.one"; expectations["laack.co"] = "gemini://laack.co"; - expectations["blog.laack.co/pygame-vs-raylib.gmi"] = "gemini://blog.laack.co/pygame-vs-raylib.gmi"; - for(auto& expect : expectations) { - REQUIRE(handleDestinationResolution(expect.first, true).destination == expect.second); - REQUIRE(handleDestinationResolution(expect.first, true).t == STRING_DESTINATION); + expectations["blog.laack.co/pygame-vs-raylib.gmi"] = + "gemini://blog.laack.co/pygame-vs-raylib.gmi"; + for (auto& expect : expectations) { + REQUIRE( + handleDestinationResolution(expect.first, true).destination == + expect.second); + REQUIRE(handleDestinationResolution(expect.first, true).t == + STRING_DESTINATION); } } - - } TEST_CASE("Verify urls with numeric prefix are resolved correctly") { - REQUIRE(handleDestinationResolution("123movies.com",false).t == STRING_DESTINATION); - REQUIRE(handleDestinationResolution("123movies.com",false).destination == "gemini://123movies.com"); + REQUIRE(handleDestinationResolution("123movies.com", false).t == + STRING_DESTINATION); + REQUIRE(handleDestinationResolution("123movies.com", false).destination == + "gemini://123movies.com"); } TEST_CASE("Inputs with spaces outside of the cli are always searched") { - - if(DEFAULT_SEARCH_ENGINE.substr(DEFAULT_SEARCH_ENGINE.size()-1) != "?") { + if (DEFAULT_SEARCH_ENGINE.substr(DEFAULT_SEARCH_ENGINE.size() - 1) != "?") { DEFAULT_SEARCH_ENGINE += "?"; } auto d1 = handleDestinationResolution("what :// :// test", false); - REQUIRE(d1.destination == "gemini://tlgs.one/search?what%20%3A%2F%2F%20%3A%2F%2F%20test"); - rc::check("Inputs with spaces outside of the cli are always searched", - [](const std::string& st) { - auto dest = handleDestinationResolution(st, false); - if(st.find(' ') != std::string::npos) { - RC_ASSERT(dest.destination.find("tlgs.one") != std::string::npos); - REQUIRE(dest.destination.find("tlgs.one") != std::string::npos); - } - }); + REQUIRE(d1.destination == + "gemini://tlgs.one/search?what%20%3A%2F%2F%20%3A%2F%2F%20test"); + rc::check( + "Inputs with spaces outside of the cli are always searched", + [](const std::string& st) { + auto dest = handleDestinationResolution(st, false); + if (st.find(' ') != std::string::npos) { + RC_ASSERT(dest.destination.find("tlgs.one") != + std::string::npos); + REQUIRE(dest.destination.find("tlgs.one") != std::string::npos); + } + }); } - TEST_CASE("Test user input handling for destinations") { - - if(DEFAULT_SEARCH_ENGINE.substr(DEFAULT_SEARCH_ENGINE.size()-1) != "?") { + if (DEFAULT_SEARCH_ENGINE.substr(DEFAULT_SEARCH_ENGINE.size() - 1) != "?") { DEFAULT_SEARCH_ENGINE += "?"; } SECTION("Convert numbers to link numbers") { - for(int i = 0; i < 10000; ++i) { - REQUIRE(handleDestinationResolution(std::to_string(i), false).linkNumber == i); - REQUIRE(handleDestinationResolution(std::to_string(i), false).t == NUMBER_DESTINATION); + for (int i = 0; i < 10000; ++i) { + REQUIRE(handleDestinationResolution(std::to_string(i), false) + .linkNumber == i); + REQUIRE(handleDestinationResolution(std::to_string(i), false).t == + NUMBER_DESTINATION); } } SECTION("Transparently resolve gemini:// prefixed urls") { - REQUIRE(handleDestinationResolution("gemini://test.com", false).t == STRING_DESTINATION); - REQUIRE(handleDestinationResolution("gemini://test.com", false).destination == "gemini://test.com"); + REQUIRE(handleDestinationResolution("gemini://test.com", false).t == + STRING_DESTINATION); + REQUIRE(handleDestinationResolution("gemini://test.com", false) + .destination == "gemini://test.com"); } SECTION("Convert input with spaces into query") { - REQUIRE(handleDestinationResolution("what is the capital of scotland?", false).t == STRING_DESTINATION); - REQUIRE(handleDestinationResolution("what is the capital of scotland?", false).destination == "gemini://tlgs.one/search?" + urlEncode("what is the capital of scotland?")); + REQUIRE(handleDestinationResolution("what is the capital of scotland?", + false) + .t == STRING_DESTINATION); + REQUIRE(handleDestinationResolution("what is the capital of scotland?", + false) + .destination == + "gemini://tlgs.one/search?" + + urlEncode("what is the capital of scotland?")); } SECTION("Convert {domain} without scheme -> gemini://{domain}") { - REQUIRE(handleDestinationResolution("laack.co", false).t == STRING_DESTINATION); - REQUIRE(handleDestinationResolution("laack.co", false).destination == "gemini://laack.co"); + REQUIRE(handleDestinationResolution("laack.co", false).t == + STRING_DESTINATION); + REQUIRE(handleDestinationResolution("laack.co", false).destination == + "gemini://laack.co"); } SECTION("Support localhost") { - REQUIRE(handleDestinationResolution("localhost", false).destination == "gemini://localhost"); - REQUIRE(handleDestinationResolution("gemini://localhost", false).destination == "gemini://localhost"); - REQUIRE(handleDestinationResolution("gemini://localhost:1965", false).destination == "gemini://localhost:1965"); - REQUIRE(handleDestinationResolution("localhost:1965", false).destination == "gemini://localhost:1965"); - + REQUIRE(handleDestinationResolution("localhost", false).destination == + "gemini://localhost"); + REQUIRE(handleDestinationResolution("gemini://localhost", false) + .destination == "gemini://localhost"); + REQUIRE(handleDestinationResolution("gemini://localhost:1965", false) + .destination == "gemini://localhost:1965"); + REQUIRE( + handleDestinationResolution("localhost:1965", false).destination == + "gemini://localhost:1965"); } SECTION("Transparently resolve file names") { - REQUIRE(handleDestinationResolution("file:///test/whatever", false).t == STRING_DESTINATION); - REQUIRE(handleDestinationResolution("file:///test/whatever", false).destination == "file:///test/whatever"); + REQUIRE(handleDestinationResolution("file:///test/whatever", false).t == + STRING_DESTINATION); + REQUIRE(handleDestinationResolution("file:///test/whatever", false) + .destination == "file:///test/whatever"); } SECTION("Convert empty string to no-destination") { @@ -127,167 +159,164 @@ TEST_CASE("Test user input handling for destinations") { SECTION("Handle arbitrary string inputs for CLI input") { rc::check("Handle arbitrary string inputs for CLI input", - [](const std::string& st) { - auto dest = handleDestinationResolution(st, true); - RC_ASSERT(dest.t != NUMBER_DESTINATION); - REQUIRE(dest.t != NUMBER_DESTINATION); - switch (dest.t) { - case NO_DESTINATION: - break; - case STRING_DESTINATION: - break; - case NUMBER_DESTINATION: - break; - } - }); + [](const std::string& st) { + auto dest = handleDestinationResolution(st, true); + RC_ASSERT(dest.t != NUMBER_DESTINATION); + REQUIRE(dest.t != NUMBER_DESTINATION); + switch (dest.t) { + case NO_DESTINATION: + break; + case STRING_DESTINATION: + break; + case NUMBER_DESTINATION: + break; + } + }); } SECTION("Handle arbitrary string inputs for non-CLI input") { rc::check("Handle arbitrary string inputs for non-CLI input", - [](const std::string& st) { - auto dest = handleDestinationResolution(st, false); + [](const std::string& st) { + auto dest = handleDestinationResolution(st, false); - if(dest.t == STRING_DESTINATION) { - RC_ASSERT(dest.destination != ""); - REQUIRE(dest.destination != ""); - } - }); + if (dest.t == STRING_DESTINATION) { + RC_ASSERT(dest.destination != ""); + REQUIRE(dest.destination != ""); + } + }); } - - } - TEST_CASE("Test width == 0 doesn't crash program") { - std::vector<std::pair<std::string, TextRender>> strLs {}; - for(int i = 0; i < 10; ++i) { - std::pair<std::string, TextRender> current {"this is a simple test line", TextRender{10,false}}; + std::vector<std::pair<std::string, TextRender>> strLs{}; + for (int i = 0; i < 10; ++i) { + std::pair<std::string, TextRender> current{"this is a simple test line", + TextRender{10, false}}; strLs.push_back(current); } - REQUIRE_NOTHROW(breakLines(strLs, 0,80)); + REQUIRE_NOTHROW(breakLines(strLs, 0, 80)); } TEST_CASE("Don't fold doesn't fold lines") { - std::vector<std::pair<std::string, TextRender>> strLs {}; - for(int i = 0; i < 10; ++i) { - std::pair<std::string, TextRender> current {"this is a simple test line", TextRender{10,true,false}}; + std::vector<std::pair<std::string, TextRender>> strLs{}; + for (int i = 0; i < 10; ++i) { + std::pair<std::string, TextRender> current{"this is a simple test line", + TextRender{10, true, false}}; strLs.push_back(current); } - auto result = breakLines(strLs, 10,80); - REQUIRE(result.size() == strLs.size()); + auto result = breakLines(strLs, 10, 80); + REQUIRE(result.size() == strLs.size()); } TEST_CASE("Test trivial line breaking") { - std::vector<std::pair<std::string, TextRender>> strLs {}; - for(int i = 0; i < 10; ++i) { - std::pair<std::string, TextRender> current {"this is a simple test line", TextRender{10,false}}; + std::vector<std::pair<std::string, TextRender>> strLs{}; + for (int i = 0; i < 10; ++i) { + std::pair<std::string, TextRender> current{"this is a simple test line", + TextRender{10, false}}; strLs.push_back(current); } - auto result = breakLines(strLs, 10,80); - REQUIRE(result.size() == 30); + auto result = breakLines(strLs, 10, 80); + REQUIRE(result.size() == 30); } -static std::string charset = "abc defghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; +static std::string charset = + "abc defghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; TEST_CASE("Test width invariant") { - - std::vector<std::pair<std::string, TextRender>> strLs {}; + std::vector<std::pair<std::string, TextRender>> strLs{}; srand(std::time(NULL)); - for(int i = 0; i < 100; ++i) { + for (int i = 0; i < 100; ++i) { std::string strRnd; int ub = rand() % 100; - for(int x = 0; x < ub; ++x) { + for (int x = 0; x < ub; ++x) { strRnd += charset[rand() % charset.length()]; } - std::pair<std::string, TextRender> current {strRnd, TextRender{10, false}}; + std::pair<std::string, TextRender> current{strRnd, + TextRender{10, false}}; strLs.push_back(current); } - auto result = breakLines(strLs, 80,80); + auto result = breakLines(strLs, 80, 80); - for(auto& res: result) { + for (auto& res : result) { REQUIRE(res.first.size() <= 80); } } TEST_CASE("Test lots of spaces") { - - std::vector<std::pair<std::string, TextRender>> strLs {}; + std::vector<std::pair<std::string, TextRender>> strLs{}; srand(std::time(NULL)); - for(int i = 0; i < 10; ++i) { + for (int i = 0; i < 10; ++i) { std::string strRnd; int ub = rand() % 100; - for(int x = 0; x < ub; ++x) { + for (int x = 0; x < ub; ++x) { strRnd += ' '; } - std::pair<std::string, TextRender> current {strRnd, TextRender{10, false}}; + std::pair<std::string, TextRender> current{strRnd, + TextRender{10, false}}; strLs.push_back(current); } - auto result = breakLines(strLs, 80,80); + auto result = breakLines(strLs, 80, 80); - for(auto& res: result) { + for (auto& res : result) { REQUIRE(res.first.size() <= 80); } - } TEST_CASE("Test normal line classification") { SECTION("Plaintext classification") { - auto res1 = lineToLine("", std::nullopt, -1, false); + auto res1 = lineToLine("", std::nullopt, -1, false); REQUIRE(res1->type() == PLAINTEXT); } SECTION("Preformatted classification") { - auto res2 = lineToLine("", std::nullopt, -1, true); + auto res2 = lineToLine("", std::nullopt, -1, true); REQUIRE(res2->type() == PREFORMATTED); } SECTION("Link classification") { - auto res3 = lineToLine("=> gemini://laack.co", std::nullopt, 1, false); + auto res3 = lineToLine("=> gemini://laack.co", std::nullopt, 1, false); REQUIRE(res3->type() == LINK); } SECTION("Format switch classification") { - auto res4 = lineToLine("```", std::nullopt, 1, false); + auto res4 = lineToLine("```", std::nullopt, 1, false); REQUIRE(res4->type() == FORMAT_SWITCH); } SECTION("H1 classification") { - auto res5 = lineToLine("# H1 Heading", std::nullopt, 1, false); + auto res5 = lineToLine("# H1 Heading", std::nullopt, 1, false); REQUIRE(res5->type() == H1); } SECTION("H2 classification") { - auto res6 = lineToLine("## H2 Heading", std::nullopt, 1, false); + auto res6 = lineToLine("## H2 Heading", std::nullopt, 1, false); REQUIRE(res6->type() == H2); } SECTION("H3 classification") { - auto res7 = lineToLine("### H3 Heading", std::nullopt, 1, false); + auto res7 = lineToLine("### H3 Heading", std::nullopt, 1, false); REQUIRE(res7->type() == H3); } SECTION("Quote classification") { - auto res8 = lineToLine("> test quote", std::nullopt, 1, false); + auto res8 = lineToLine("> test quote", std::nullopt, 1, false); REQUIRE(res8->type() == QUOTE); } SECTION("List item classification") { - auto res9 = lineToLine("* test li", std::nullopt, 1, false); + auto res9 = lineToLine("* test li", std::nullopt, 1, false); REQUIRE(res9->type() == LIST_ITEM); } - - } TEST_CASE("Test line parsing handles whitespace correctly") { - - std::unordered_map<std::string, LineType> prefixes {}; + std::unordered_map<std::string, LineType> prefixes{}; prefixes[">"] = QUOTE; prefixes["#"] = H1; @@ -296,16 +325,16 @@ TEST_CASE("Test line parsing handles whitespace correctly") { std::vector<std::string> options{" ", "\t"}; - for(auto& prefix: prefixes) { - for(int x = 0; x < 100; ++x) { - + for (auto& prefix : prefixes) { + for (int x = 0; x < 100; ++x) { std::string acc = options[rand() % 2]; - for(int i = 0; i < 1000; ++i) { - std::string check = prefix.first + acc + "test line content"; - auto ln = lineToLine(check, std::nullopt, 1, false); + for (int i = 0; i < 1000; ++i) { + std::string check = prefix.first + acc + "test line content"; + auto ln = lineToLine(check, std::nullopt, 1, false); REQUIRE(ln->type() == prefix.second); - REQUIRE(ln->textToDraw() == prefix.first + " test line content\n"); + REQUIRE(ln->textToDraw() == + prefix.first + " test line content\n"); acc += options[rand() % 2]; } } @@ -313,144 +342,148 @@ TEST_CASE("Test line parsing handles whitespace correctly") { std::string acc = options[rand() % 2]; - rc::check("any non-zero number of whitespaces results in the same link text", - [](const std::vector<bool> &l0) { - std::string acc = ""; - if(l0.size() == 0) { - if(rand() % 2 == 0) { - acc = " "; - } else { - acc = "\t"; - } + rc::check( + "any non-zero number of whitespaces results in the same link text", + [](const std::vector<bool>& l0) { + std::string acc = ""; + if (l0.size() == 0) { + if (rand() % 2 == 0) { + acc = " "; + } else { + acc = "\t"; } - for(bool i : l0) { - if(i) { - acc += '\t'; - } else { - acc += ' '; - } + } + for (bool i : l0) { + if (i) { + acc += '\t'; + } else { + acc += ' '; } - std::string check = "=>" + acc + "gemini://laack.co" + acc + "link human text"; - auto ln = lineToLine(check, std::nullopt, 1, false); - RC_ASSERT(ln->type() == LINK); - RC_ASSERT(ln->textToDraw() == "[1] link human text\n"); - REQUIRE(ln->type() == LINK); - REQUIRE(ln->textToDraw() == "[1] link human text\n"); - }); + } + std::string check = + "=>" + acc + "gemini://laack.co" + acc + "link human text"; + auto ln = lineToLine(check, std::nullopt, 1, false); + RC_ASSERT(ln->type() == LINK); + RC_ASSERT(ln->textToDraw() == "[1] link human text\n"); + REQUIRE(ln->type() == LINK); + REQUIRE(ln->textToDraw() == "[1] link human text\n"); + }); } - TEST_CASE("Proper whitespace compliance") { SECTION("Line types without white spacing") { - auto res1 = lineToLine("", std::nullopt, -1, false); + auto res1 = lineToLine("", std::nullopt, -1, false); REQUIRE(res1->type() == PLAINTEXT); - auto res3 = lineToLine("=>gemini://laack.co", std::nullopt, 1, false); + auto res3 = lineToLine("=>gemini://laack.co", std::nullopt, 1, false); REQUIRE(res3->type() == LINK); - auto res5 = lineToLine("#H1 Heading", std::nullopt, 1, false); + auto res5 = lineToLine("#H1 Heading", std::nullopt, 1, false); REQUIRE(res5->type() == H1); - auto res6 = lineToLine("##H2 Heading", std::nullopt, 1, false); + auto res6 = lineToLine("##H2 Heading", std::nullopt, 1, false); REQUIRE(res6->type() == H2); - auto res7 = lineToLine("###H3 Heading", std::nullopt, 1, false); + auto res7 = lineToLine("###H3 Heading", std::nullopt, 1, false); REQUIRE(res7->type() == H3); - auto res8 = lineToLine(">test quote", std::nullopt, 1, false); + auto res8 = lineToLine(">test quote", std::nullopt, 1, false); REQUIRE(res8->type() == QUOTE); - // the only one that requires a whitespace, and it must be a space, not tab - auto res9 = lineToLine("*test li", std::nullopt, 1, false); + // the only one that requires a whitespace, and it must be a space, not + // tab + auto res9 = lineToLine("*test li", std::nullopt, 1, false); REQUIRE(res9->type() == PLAINTEXT); - auto res10 = lineToLine("*\ttest li", std::nullopt, 1, false); + auto res10 = lineToLine("*\ttest li", std::nullopt, 1, false); REQUIRE(res10->type() == PLAINTEXT); - auto res11 = lineToLine("* test li", std::nullopt, 1, false); + auto res11 = lineToLine("* test li", std::nullopt, 1, false); REQUIRE(res11->type() == LIST_ITEM); REQUIRE(res11->textToDraw() == "* test li\n"); } SECTION("Non-whitespace based line types don't require whitespace") { - auto res2 = lineToLine("", std::nullopt, -1, true); + auto res2 = lineToLine("", std::nullopt, -1, true); REQUIRE(res2->type() == PREFORMATTED); - auto res4 = lineToLine("```", std::nullopt, 1, false); + auto res4 = lineToLine("```", std::nullopt, 1, false); REQUIRE(res4->type() == FORMAT_SWITCH); } - - } - -TEST_CASE("Line parser handles lines that are only format characters with whitespaces") { - auto res1 = lineToLine(" ", std::nullopt, -1, false); +TEST_CASE( + "Line parser handles lines that are only format characters with " + "whitespaces") { + auto res1 = lineToLine(" ", std::nullopt, -1, false); REQUIRE(res1->type() == PLAINTEXT); - auto res2 = lineToLine(" ", std::nullopt, -1, true); + auto res2 = lineToLine(" ", std::nullopt, -1, true); REQUIRE(res2->type() == PREFORMATTED); - auto res3 = lineToLine("=> ", std::nullopt, 1, false); + auto res3 = lineToLine("=> ", std::nullopt, 1, false); REQUIRE(res3->type() == LINK); - auto res4 = lineToLine("``` ", std::nullopt, 1, false); + auto res4 = lineToLine("``` ", std::nullopt, 1, false); REQUIRE(res4->type() == FORMAT_SWITCH); - auto res5 = lineToLine("# ", std::nullopt, 1, false); + auto res5 = lineToLine("# ", std::nullopt, 1, false); REQUIRE(res5->type() == H1); - auto res6 = lineToLine("## ", std::nullopt, 1, false); + auto res6 = lineToLine("## ", std::nullopt, 1, false); REQUIRE(res6->type() == H2); - auto res7 = lineToLine("### ", std::nullopt, 1, false); + auto res7 = lineToLine("### ", std::nullopt, 1, false); REQUIRE(res7->type() == H3); - auto res8 = lineToLine("> ", std::nullopt, 1, false); + auto res8 = lineToLine("> ", std::nullopt, 1, false); REQUIRE(res8->type() == QUOTE); - auto res9 = lineToLine("* ", std::nullopt, 1, false); + auto res9 = lineToLine("* ", std::nullopt, 1, false); REQUIRE(res9->type() == LIST_ITEM); } // I was wrong on this originally bc the spec states whitespaces are optional. -TEST_CASE("Line parser handles lines that are only format characters without whitespaces") { - auto res1 = lineToLine("", std::nullopt, -1, false); +TEST_CASE( + "Line parser handles lines that are only format characters without " + "whitespaces") { + auto res1 = lineToLine("", std::nullopt, -1, false); REQUIRE(res1->type() == PLAINTEXT); - auto res2 = lineToLine("", std::nullopt, -1, true); + auto res2 = lineToLine("", std::nullopt, -1, true); REQUIRE(res2->type() == PREFORMATTED); - auto res3 = lineToLine("=>", std::nullopt, 1, false); + auto res3 = lineToLine("=>", std::nullopt, 1, false); REQUIRE(res3->type() == LINK); - auto res4 = lineToLine("```", std::nullopt, 1, false); + auto res4 = lineToLine("```", std::nullopt, 1, false); REQUIRE(res4->type() == FORMAT_SWITCH); - auto res5 = lineToLine("#", std::nullopt, 1, false); + auto res5 = lineToLine("#", std::nullopt, 1, false); REQUIRE(res5->type() == H1); - auto res6 = lineToLine("##", std::nullopt, 1, false); + auto res6 = lineToLine("##", std::nullopt, 1, false); REQUIRE(res6->type() == H2); - auto res7 = lineToLine("###", std::nullopt, 1, false); + auto res7 = lineToLine("###", std::nullopt, 1, false); REQUIRE(res7->type() == H3); - auto res8 = lineToLine(">", std::nullopt, 1, false); + auto res8 = lineToLine(">", std::nullopt, 1, false); REQUIRE(res8->type() == QUOTE); - auto res9 = lineToLine("*", std::nullopt, 1, false); + auto res9 = lineToLine("*", std::nullopt, 1, false); REQUIRE(res9->type() == PLAINTEXT); } -static std::string linecharset = "#>=abc## de_-><0193248$#)(&@)(*&$#^*&#^%^&*&fghijklmnopqrstuvwxyz #````ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; +static std::string linecharset = + "#>=abc## de_-><0193248$#)(&@)(*&$#^*&#^%^&*&fghijklmnopqrstuvwxyz " + "#````ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; TEST_CASE("Crash test random line strings") { - rc::check("Crash test random line strings", - [](const std::string& st) { - auto* ln = lineToLine(st, std::nullopt, 1, false); - delete ln; - }); + rc::check("Crash test random line strings", [](const std::string& st) { + auto* ln = lineToLine(st, std::nullopt, 1, false); + delete ln; + }); } TEST_CASE("Test cache never exceeds CACHE_SIZE") { @@ -460,9 +493,11 @@ TEST_CASE("Test cache never exceeds CACHE_SIZE") { for (int i = 0; i < 10000; ++i) { c.addSite("gemini://" + std::to_string(i), Site("header", "body")); if (i >= size) { - REQUIRE(c.getSite("gemini://" + std::to_string(i - size)) == std::nullopt); + REQUIRE(c.getSite("gemini://" + std::to_string(i - size)) == + std::nullopt); } int oldest = std::max(0, i - size + 1); - REQUIRE(c.getSite("gemini://" + std::to_string(oldest)) != std::nullopt); + REQUIRE(c.getSite("gemini://" + std::to_string(oldest)) != + std::nullopt); } }