Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

6 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Multithreaded Custom Browser Engine

A high-performance, custom web browser engine built natively in C++17. This engine features a fully multithreaded asynchronous fetching architecture, modular document parsing, custom CSS cascading logic, box layout calculations, and a high-fidelity native graphical user interface leveraging double-buffered Win32 graphics.


🏛️ System Architecture

The browser is designed with a decoupled, modular pipeline separating concurrency orchestration, networking, document modeling, and graphic display.

graph TD
    %% Main Architecture Flow
    Client["Main Application Entry<br>(URLs Input)"] --> Coordinator["Browser Coordinator<br>(Async Thread Pool)"]
    
    subgraph Engine Pipeline [Concurrent Subsystems per Tab]
        Coordinator -->|std::async| Fetcher["HTTP Client<br>(Winsock2 / BSD Sockets)"]
        Fetcher -->|Raw Response| Parser["HTML Parser Engine<br>(Gumbo / Fallback AST)"]
        Parser -->|Parsed DOM| UIGen["UI & CSS Generator<br>(Cascading Style Engine)"]
    end
    
    subgraph Output Interfaces [Presentation Layer]
        UIGen -->|Layout Tree| GUI["Native Win32 GUI Renderer<br>(Double-Buffered GDI)"]
        UIGen -->|Debug Info| CLI["Console Debug Renderer<br>(Thread-Safe Stream)"]
    end

    %% Styling
    classDef default fill:#1e1e2e,stroke:#cba6f7,stroke-width:2px,color:#cdd6f4;
    classDef engine fill:#313244,stroke:#89b4fa,stroke-width:2px,color:#cdd6f4;
    class Engine Pipeline engine;
Loading

⚙️ Detailed Workflow Lifecycle

Every requested URL goes through a highly coordinated state progression lifecycle from socket setup to graphical rendering:

sequenceDiagram
    autonumber
    actor User
    participant Main as Main Entry
    participant Browser as Browser Engine
    participant HTTP as HTTP Client
    participant Parser as HTML Parser
    participant CSS as UI/CSS Generator
    participant GUI as Win32 GUI Renderer

    User->>Main: Launch Browser with URLs
    Main->>Browser: open_many(urls)
    
    loop Concurrent Processing per URL
        Browser->>HTTP: get(url, timeout, max_redirects)
        activate HTTP
        HTTP->>HTTP: DNS Resolution & Socket Connect
        HTTP->>HTTP: Send HTTP/1.1 GET Request
        HTTP->>HTTP: Receive Headers & Chunked Body Decoder
        HTTP-->>Browser: HttpResponse Object
        deactivate HTTP

        alt HTTP Status 2xx
            Browser->>Parser: parse(response.body)
            activate Parser
            Parser->>Parser: Build AST (Gumbo or Native RegEx)
            Parser->>CSS: generate_ui(html_content)
            activate CSS
            CSS->>CSS: Extract Inline & Block Styles
            CSS->>CSS: Parse Custom CSS Rules
            CSS->>CSS: Apply Selector Cascading & Defaults
            CSS-->>Parser: UI Layout Shared Tree
            deactivate CSS
            Parser-->>Browser: ParsedPage Document Model
            deactivate Parser
        else HTTP Error / Redirect Exhausted
            Browser->>Browser: Capture Tab Error State
        end
    end

    Browser-->>Main: std::vector<TabResult>
    Main->>GUI: show_window(results)
    activate GUI
    GUI->>GUI: Initialize Native Window Class
    loop Double-Buffered Render Loop
        GUI->>GUI: Draw Custom Header Tabs & Active Borders
        GUI->>GUI: Recalculate Recursive Layout Bounds
        GUI->>GUI: BitBlt Memory Device Context to Screen
    end
    GUI-->>User: Fully Interactive Interface
    deactivate GUI
Loading

🧰 Core Services and Modules

1. Browser (Concurrency Coordinator)

  • Role: Coordinates multi-page retrieval workloads.
  • Implementation: Utilizes std::async with std::launch::async to assign dedicated hardware threads to individual webpage fetches. Protects CLI output channels via mutex locking (std::mutex) ensuring log streams do not interleave during parallel thread processing.

2. HttpClient (Network Service)

  • Role: Manages TCP stream transport layer transactions.
  • Implementation: Platform-agnostic raw socket design wrapping Winsock2 (ws2_32) on Windows platforms.
  • Features:
    • Automatically resolves DNS addresses via getaddrinfo.
    • Configurable redirection loop execution supporting status codes 301, 302, 307, and 308 with accurate root-relative and absolute URL joiners.
    • Native de-chunking engine for transparently handling HTTP servers returning Transfer-Encoding: chunked binary frames.

3. HtmlParser (Document Parsing Engine)

  • Role: Interprets raw textual tags into structured semantic layouts.
  • Implementation: Supports standard conditional preprocessor compilation leveraging Google Gumbo when available, or switching safely to an internal lightweight fallback AST engine.
  • Features: Extracts title string definitions, header lists (<h1>), anchor hyperlink structures (<a href>), and cleans HTML layout code into pristine content blocks.

4. UIGenerator (Style and Layout Processor)

  • Role: Translates document models into visual elements equipped with geometric metadata.
  • Implementation: Fully autonomous custom CSS parser capable of splitting composite selectors, extracting inline tag styles, computing user-agent fallbacks, and calculating dimensional properties.
  • Features: Produces a unified, parent-child linked UIElement hierarchy containing finalized display styling matrices and box geometry coordinates.

5. GUIRenderer (High-Fidelity Graphical Desktop Interface)

  • Role: Renders visual representation models onto application screens.
  • Implementation: Implemented natively over standard Win32 GDI interfaces without bloated graphical framework dependencies.
  • Features:
    • Double Buffering: Utilizes in-memory virtual drawing surfaces (CreateCompatibleDC) copied atomically to client frames (BitBlt), completely eliminating screen tearing and refresh flicker.
    • Custom Tab Management: Tab switching mechanisms displaying active/hovered indicators driven by an aesthetic slate-dark design interface.
    • Interactive Dynamics: Tracks window pointer matrices dynamically altering cursor types (IDC_HAND vs IDC_ARROW) over hyperlink targets and processes native mouse hook events.

6. Renderer (Console Debug Tooling)

  • Role: Secondary presentation interface formatting AST parameters for CLI debug inspection.
  • Implementation: Dumps heading definitions, index mappings, string snippet previews, and recursive UI node paths cleanly using standard output streams.

📚 Libraries and Dependencies Used

Library / Module Source / Type Role & Purpose
C++17 STL Native Standard Core thread scheduling (<future>, <thread>, <mutex>), dynamic strings, smart pointer lifetime tracking (<memory>), and regex text parsers.
Winsock2 (ws2_32) Windows System Low-level network socket interface facilitating robust TCP handshakes, socket timeouts, and stream payloads.
Win32 GDI (gdi32) Windows System Graphics Device Interface handling vector rectangles, custom font weights (CreateFontA), solid color brushes, and pixel blitting operations.
User32 (user32) Windows System Native OS windowing engine capturing keyboard/mouse hardware messages, tracking coordinates, rendering cursor states, and instantiating message dialog loops.
Google Gumbo Optional Third-Party Pure C99 HTML5 standards-compliant parsing library converting unformatted HTML markup strings into deep structural node trees.

🚀 Getting Started & Execution Instructions

Prerequisites

  • A modern C++ compiler supporting C++17 (e.g., MSVC, GCC, or Clang).
  • CMake (version 3.10 or higher).

Compilation Steps

  1. Clone or Open the Workspace Directory: Ensure you are in the source workspace root containing CMakeLists.txt.

  2. Generate Build Configurations:

    mkdir build
    cd build
    cmake ..
  3. Build the Engine Executable:

    cmake --build . --config Release
  4. Launch the Multithreaded Browser: Run the output executable directly from the terminal. You can optionally supply custom URLs as execution arguments:

    # Run default embedded demo tabs
    .\Release\browser.exe
    
    # Run with custom explicit HTTP targets
    .\Release\browser.exe "http://example.com/" "http://neverssl.com/"

Built to showcase highly concurrent systems programming paired with rich interactive graphic pipelines.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages