diff --git a/.github/linters/actionlint.yml b/.github/linters/actionlint.yml new file mode 100644 index 00000000..3061c96e --- /dev/null +++ b/.github/linters/actionlint.yml @@ -0,0 +1,10 @@ +--- +# Configuration for actionlint as run by the Lint Code Base workflow. +# +# The actionlint bundled with the linter image predates these GitHub-hosted +# runner images and reports them as unknown labels. Listing them here only +# teaches it the names; every actionlint check stays enabled. +self-hosted-runner: + labels: + - macos-15 + - macos-15-intel diff --git a/.github/workflows/aptitude-package.yml b/.github/workflows/aptitude-package.yml index b98e2c0f..13a951b9 100644 --- a/.github/workflows/aptitude-package.yml +++ b/.github/workflows/aptitude-package.yml @@ -8,217 +8,101 @@ on: jobs: build-apt-package: - runs-on: ubuntu-latest + # One package per supported Ubuntu release, each built on that release so + # its dependencies match. + runs-on: ubuntu-${{ matrix.ubuntu_version }} strategy: + fail-fast: false matrix: ubuntu_version: ['22.04', '24.04'] - + permissions: + contents: write + steps: - - name: Checkout code - uses: actions/checkout@v4 - - - name: Set up build environment - run: | - sudo apt-get update - sudo apt-get install -y \ - build-essential \ - cmake \ - pkg-config \ - libssl-dev \ - libcurl4-openssl-dev \ - libglfw3-dev \ - libgl1-mesa-dev \ - libglu1-mesa-dev \ - zlib1g-dev \ - libjsoncpp-dev \ - git \ - debhelper \ - devscripts \ - dh-make \ - reprepro \ - gnupg - - - name: Build project - run: | - mkdir -p build - cd build - cmake -DCMAKE_BUILD_TYPE=Release \ - -DCMAKE_INSTALL_PREFIX=/usr \ - -DBUILD_SHARED_LIBS=ON .. - make -j$(nproc) - - - name: Create Debian package - run: | - VERSION=$(git describe --tags --always 2>/dev/null | sed 's/^v//' || echo "0.1.0") - PACKAGE_NAME="bolt-cppml" - ARCH="amd64" - UBUNTU_VERSION="${{ matrix.ubuntu_version }}" - - mkdir -p debian-package/DEBIAN - mkdir -p debian-package/usr/bin - mkdir -p debian-package/usr/lib/bolt-cppml - mkdir -p debian-package/usr/share/applications - mkdir -p debian-package/usr/share/doc/${PACKAGE_NAME} - mkdir -p debian-package/usr/share/pixmaps - - # Copy main binary - if [ -f build/bolt ]; then - cp build/bolt debian-package/usr/bin/ - else - echo "Warning: bolt binary not found, creating placeholder" - echo '#!/bin/bash' > debian-package/usr/bin/bolt - echo 'echo "Bolt C++ IDE"' >> debian-package/usr/bin/bolt - fi - - # Copy bolt library - if [ -f build/libbolt_lib.so ]; then - cp build/libbolt_lib.so* debian-package/usr/lib/bolt-cppml/ - fi - - # Copy GGML/llama libraries from bin directory - if [ -d build/bin ]; then - for lib in build/bin/*.so*; do - if [ -f "$lib" ]; then - cp "$lib" debian-package/usr/lib/bolt-cppml/ 2>/dev/null || true - fi - done - fi - - # Create ldconfig file - mkdir -p debian-package/etc/ld.so.conf.d - echo "/usr/lib/bolt-cppml" > debian-package/etc/ld.so.conf.d/bolt-cppml.conf - - # Create control file - cat > debian-package/DEBIAN/control << EOF - Package: ${PACKAGE_NAME} - Version: ${VERSION} - Section: devel - Priority: optional - Architecture: ${ARCH} - Depends: libssl3 | libssl1.1, libcurl4, libglfw3, libgl1, libglu1-mesa, zlib1g, libjsoncpp25 | libjsoncpp24 - Maintainer: Bolt C++ Team - Description: Modern C++ implementation of Bolt IDE with AI integration - Bolt C++ is a modern C++ implementation of the Bolt IDE core components - with AI integration and real-time collaborative features. - . - Features include: - - GGML integration for AI model inference - - RWKV implementation for RNN capabilities - - Multi-cursor support and syntax highlighting - - Integrated debugger with breakpoints - - WebSocket server for real-time collaboration - - Comprehensive ImGui dark-mode interface - Homepage: https://github.com/cogpy/bolt-cppml - EOF - - # Create postinst script to run ldconfig - cat > debian-package/DEBIAN/postinst << 'EOF' - #!/bin/bash - ldconfig - EOF - chmod 755 debian-package/DEBIAN/postinst - - # Create postrm script - cat > debian-package/DEBIAN/postrm << 'EOF' - #!/bin/bash - ldconfig - EOF - chmod 755 debian-package/DEBIAN/postrm - - # Create desktop entry - cat > debian-package/usr/share/applications/bolt-cppml.desktop << EOF - [Desktop Entry] - Type=Application - Name=Bolt C++ - Comment=Modern C++ IDE with AI integration - Exec=/usr/bin/bolt - Icon=bolt-cppml - Terminal=false - Categories=Development;IDE; - EOF - - # Copy documentation - cp README.md debian-package/usr/share/doc/${PACKAGE_NAME}/ - if [ -f LICENSE ]; then - cp LICENSE debian-package/usr/share/doc/${PACKAGE_NAME}/copyright - elif [ -f LICENSE.md ]; then - cp LICENSE.md debian-package/usr/share/doc/${PACKAGE_NAME}/copyright - else - echo "MIT License" > debian-package/usr/share/doc/${PACKAGE_NAME}/copyright - echo "Copyright (c) 2025 Bolt C++ Team" >> debian-package/usr/share/doc/${PACKAGE_NAME}/copyright - fi - - # Copy icon if exists - if [ -f generated-icon.png ]; then - cp generated-icon.png debian-package/usr/share/pixmaps/bolt-cppml.png - fi - - # Set permissions - chmod 755 debian-package/DEBIAN - chmod 755 debian-package/usr/bin/bolt - find debian-package/usr/lib -name "*.so*" -exec chmod 644 {} \; 2>/dev/null || true - - # Build .deb package - dpkg-deb --build debian-package ${PACKAGE_NAME}_${VERSION}_${ARCH}_ubuntu${UBUNTU_VERSION}.deb - - - name: Create APT repository structure - run: | - VERSION=$(git describe --tags --always 2>/dev/null | sed 's/^v//' || echo "0.1.0") - PACKAGE_NAME="bolt-cppml" - ARCH="amd64" - UBUNTU_VERSION="${{ matrix.ubuntu_version }}" - - mkdir -p apt-repo/conf - mkdir -p apt-repo/dists/ubuntu-${UBUNTU_VERSION}/main/binary-amd64 - mkdir -p apt-repo/pool/main - - # Create repository configuration - cat > apt-repo/conf/distributions << EOF - Origin: Bolt C++ - Label: Bolt C++ Repository - Codename: ubuntu-${UBUNTU_VERSION} - Architectures: amd64 - Components: main - Description: Bolt C++ IDE packages for Ubuntu ${UBUNTU_VERSION} - EOF - - # Copy .deb to pool - cp ${PACKAGE_NAME}_${VERSION}_${ARCH}_ubuntu${UBUNTU_VERSION}.deb apt-repo/pool/main/ - - # Create Packages file - cd apt-repo - dpkg-scanpackages pool/main /dev/null > dists/ubuntu-${UBUNTU_VERSION}/main/binary-amd64/Packages - gzip -9c dists/ubuntu-${UBUNTU_VERSION}/main/binary-amd64/Packages > dists/ubuntu-${UBUNTU_VERSION}/main/binary-amd64/Packages.gz - - # Create Release file - cat > dists/ubuntu-${UBUNTU_VERSION}/Release << EOF - Origin: Bolt C++ - Label: Bolt C++ Repository - Suite: ubuntu-${UBUNTU_VERSION} - Codename: ubuntu-${UBUNTU_VERSION} - Version: ${VERSION} - Architectures: amd64 - Components: main - Description: Bolt C++ IDE packages for Ubuntu ${UBUNTU_VERSION} - Date: $(date -R) - EOF - - - name: Upload Debian package - uses: actions/upload-artifact@v4 - with: - name: debian-package-ubuntu-${{ matrix.ubuntu_version }} - path: '*.deb' - - - name: Upload APT repository - uses: actions/upload-artifact@v4 - with: - name: apt-repo-ubuntu-${{ matrix.ubuntu_version }} - path: 'apt-repo/**' - - - name: Create Release - if: startsWith(github.ref, 'refs/tags/') - uses: softprops/action-gh-release@v1 - with: - files: '*.deb' - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + - name: Checkout code + uses: actions/checkout@v4 + + - name: Set up build environment + run: | + sudo apt-get update + sudo apt-get install -y \ + build-essential cmake pkg-config git dpkg-dev \ + libssl-dev libcurl4-openssl-dev libglfw3-dev \ + libgl1-mesa-dev libglu1-mesa-dev zlib1g-dev libjsoncpp-dev + + - name: Build project + run: | + cmake -B build -DCMAKE_BUILD_TYPE=Release \ + -DCMAKE_INSTALL_PREFIX=/usr -DBUILD_SHARED_LIBS=ON + cmake --build build -j "$(nproc)" + + - name: Determine version + id: version + # A tag v1.2.3 gives 1.2.3. Any other run gives the project version + # plus the commit, for example 1.2.3+git0a1b2c3. + run: | + if [[ "$GITHUB_REF" == refs/tags/v* ]]; then + VERSION="${GITHUB_REF_NAME#v}" + else + BASE="$(sed -n 's/^project(bolt VERSION \([0-9.]*\).*/\1/p' CMakeLists.txt)" + VERSION="${BASE}+git$(git rev-parse --short HEAD)" + fi + echo "version=$VERSION" >> "$GITHUB_OUTPUT" + echo "deb=bolt-cppml_${VERSION}_ubuntu${{ matrix.ubuntu_version }}_amd64.deb" >> "$GITHUB_OUTPUT" + + - name: Build Debian package + run: scripts/build-deb.sh build "${{ steps.version.outputs.version }}" "${{ steps.version.outputs.deb }}" + + - name: Install the package and run bolt from it + run: | + sudo apt-get install -y "./${{ steps.version.outputs.deb }}" + /usr/bin/bolt --version + printf 'hello\n/exit\n' | /usr/bin/bolt | grep -q 'Echo: hello' + sudo apt-get remove -y bolt-cppml + + - name: Create APT repository + # A flat repository for this Ubuntu release. It is unsigned; sign it + # before publishing it anywhere apt will fetch it from. + run: | + VERSION="${{ steps.version.outputs.version }}" + DEB="${{ steps.version.outputs.deb }}" + SUITE="ubuntu-${{ matrix.ubuntu_version }}" + + mkdir -p "apt-repo/dists/$SUITE/main/binary-amd64" apt-repo/pool/main + cp "$DEB" apt-repo/pool/main/ + + ( + cd apt-repo + dpkg-scanpackages pool/main /dev/null > "dists/$SUITE/main/binary-amd64/Packages" + gzip -9c "dists/$SUITE/main/binary-amd64/Packages" > "dists/$SUITE/main/binary-amd64/Packages.gz" + + { + echo "Origin: Bolt C++" + echo "Label: Bolt C++ Repository" + echo "Suite: $SUITE" + echo "Codename: $SUITE" + echo "Version: $VERSION" + echo "Architectures: amd64" + echo "Components: main" + echo "Description: Bolt C++ IDE packages for Ubuntu ${{ matrix.ubuntu_version }}" + echo "Date: $(date -R)" + } > "dists/$SUITE/Release" + ) + + grep -q '^Package: bolt-cppml$' "apt-repo/dists/$SUITE/main/binary-amd64/Packages" + tar -czf "bolt-cppml-apt-repo-${SUITE}.tar.gz" apt-repo + + - name: Upload APT repository + uses: actions/upload-artifact@v4 + with: + name: apt-repo-ubuntu-${{ matrix.ubuntu_version }} + path: 'apt-repo/**' + + - name: Attach repository archive to the release + # The .deb itself is attached by the Debian Package Build workflow. + if: startsWith(github.ref, 'refs/tags/') + uses: softprops/action-gh-release@v2 + with: + files: 'bolt-cppml-apt-repo-*.tar.gz' + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/cross-platform.yml b/.github/workflows/cross-platform.yml index c15952cc..9de8cb02 100644 --- a/.github/workflows/cross-platform.yml +++ b/.github/workflows/cross-platform.yml @@ -177,7 +177,7 @@ jobs: - name: Upload packages to release if: github.event_name == 'release' - uses: softprops/action-gh-release@v1 + uses: softprops/action-gh-release@v2 with: files: | build/*.exe diff --git a/.github/workflows/debian-package.yml b/.github/workflows/debian-package.yml index b214a766..e4755b41 100644 --- a/.github/workflows/debian-package.yml +++ b/.github/workflows/debian-package.yml @@ -8,166 +8,68 @@ on: jobs: build-deb: - runs-on: ubuntu-latest + # One package per supported Ubuntu release, each built on that release so + # its dependencies match. + runs-on: ubuntu-${{ matrix.ubuntu_version }} strategy: + fail-fast: false matrix: ubuntu_version: ['22.04', '24.04'] - + permissions: + contents: write + steps: - - name: Checkout code - uses: actions/checkout@v4 - - - name: Set up build environment - run: | - sudo apt-get update - sudo apt-get install -y \ - build-essential \ - cmake \ - pkg-config \ - libssl-dev \ - libcurl4-openssl-dev \ - libglfw3-dev \ - libgl1-mesa-dev \ - libglu1-mesa-dev \ - zlib1g-dev \ - libjsoncpp-dev \ - git \ - debhelper \ - devscripts \ - dh-make - - - name: Build project - run: | - mkdir -p build - cd build - cmake -DCMAKE_BUILD_TYPE=Release \ - -DCMAKE_INSTALL_PREFIX=/usr \ - -DBUILD_SHARED_LIBS=ON .. - make -j$(nproc) - - - name: Create Debian package structure - run: | - VERSION=$(git describe --tags --always 2>/dev/null | sed 's/^v//' || echo "0.1.0") - PACKAGE_NAME="bolt-cppml" - ARCH="amd64" - - mkdir -p debian-package/DEBIAN - mkdir -p debian-package/usr/bin - mkdir -p debian-package/usr/lib/bolt-cppml - mkdir -p debian-package/usr/share/applications - mkdir -p debian-package/usr/share/doc/${PACKAGE_NAME} - mkdir -p debian-package/usr/share/pixmaps - - # Copy main binary - if [ -f build/bolt ]; then - cp build/bolt debian-package/usr/bin/ - else - echo "Warning: bolt binary not found, creating placeholder" - echo '#!/bin/bash' > debian-package/usr/bin/bolt - echo 'echo "Bolt C++ IDE"' >> debian-package/usr/bin/bolt - fi - - # Copy bolt library - if [ -f build/libbolt_lib.so ]; then - cp build/libbolt_lib.so* debian-package/usr/lib/bolt-cppml/ - fi - - # Copy GGML/llama libraries from bin directory - if [ -d build/bin ]; then - for lib in build/bin/*.so*; do - if [ -f "$lib" ]; then - cp "$lib" debian-package/usr/lib/bolt-cppml/ 2>/dev/null || true - fi - done - fi - - # Create ldconfig file - mkdir -p debian-package/etc/ld.so.conf.d - echo "/usr/lib/bolt-cppml" > debian-package/etc/ld.so.conf.d/bolt-cppml.conf - - # Create control file - cat > debian-package/DEBIAN/control << EOF - Package: ${PACKAGE_NAME} - Version: ${VERSION} - Section: devel - Priority: optional - Architecture: ${ARCH} - Depends: libssl3 | libssl1.1, libcurl4, libglfw3, libgl1, libglu1-mesa, zlib1g, libjsoncpp25 | libjsoncpp24 - Maintainer: Bolt C++ Team - Description: Modern C++ implementation of Bolt IDE with AI integration - Bolt C++ is a modern C++ implementation of the Bolt IDE core components - with AI integration and real-time collaborative features. - . - Features include: - - GGML integration for AI model inference - - RWKV implementation for RNN capabilities - - Multi-cursor support and syntax highlighting - - Integrated debugger - - WebSocket server for real-time collaboration - - Comprehensive ImGui dark-mode interface - Homepage: https://github.com/cogpy/bolt-cppml - EOF - - # Create postinst script to run ldconfig - cat > debian-package/DEBIAN/postinst << 'EOF' - #!/bin/bash - ldconfig - EOF - chmod 755 debian-package/DEBIAN/postinst - - # Create postrm script - cat > debian-package/DEBIAN/postrm << 'EOF' - #!/bin/bash - ldconfig - EOF - chmod 755 debian-package/DEBIAN/postrm - - # Create desktop entry - cat > debian-package/usr/share/applications/bolt-cppml.desktop << EOF - [Desktop Entry] - Type=Application - Name=Bolt C++ - Comment=Modern C++ IDE with AI integration - Exec=/usr/bin/bolt - Icon=bolt-cppml - Terminal=false - Categories=Development;IDE; - EOF - - # Copy documentation - cp README.md debian-package/usr/share/doc/${PACKAGE_NAME}/ - if [ -f LICENSE ]; then - cp LICENSE debian-package/usr/share/doc/${PACKAGE_NAME}/copyright - elif [ -f LICENSE.md ]; then - cp LICENSE.md debian-package/usr/share/doc/${PACKAGE_NAME}/copyright - else - echo "MIT License" > debian-package/usr/share/doc/${PACKAGE_NAME}/copyright - echo "Copyright (c) 2025 Bolt C++ Team" >> debian-package/usr/share/doc/${PACKAGE_NAME}/copyright - fi - - # Copy icon if exists - if [ -f generated-icon.png ]; then - cp generated-icon.png debian-package/usr/share/pixmaps/bolt-cppml.png - fi - - # Set permissions - chmod 755 debian-package/DEBIAN - chmod 755 debian-package/usr/bin/bolt - find debian-package/usr/lib -name "*.so*" -exec chmod 644 {} \; 2>/dev/null || true - - # Build .deb package - dpkg-deb --build debian-package ${PACKAGE_NAME}_${VERSION}_${ARCH}.deb - - - name: Upload Debian package - uses: actions/upload-artifact@v4 - with: - name: debian-package-ubuntu-${{ matrix.ubuntu_version }} - path: '*.deb' - - - name: Create Release - if: startsWith(github.ref, 'refs/tags/') - uses: softprops/action-gh-release@v1 - with: - files: '*.deb' - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + - name: Checkout code + uses: actions/checkout@v4 + + - name: Set up build environment + run: | + sudo apt-get update + sudo apt-get install -y \ + build-essential cmake pkg-config git dpkg-dev \ + libssl-dev libcurl4-openssl-dev libglfw3-dev \ + libgl1-mesa-dev libglu1-mesa-dev zlib1g-dev libjsoncpp-dev + + - name: Build project + run: | + cmake -B build -DCMAKE_BUILD_TYPE=Release \ + -DCMAKE_INSTALL_PREFIX=/usr -DBUILD_SHARED_LIBS=ON + cmake --build build -j "$(nproc)" + + - name: Determine version + id: version + # A tag v1.2.3 gives 1.2.3. Any other run gives the project version + # plus the commit, for example 1.2.3+git0a1b2c3. + run: | + if [[ "$GITHUB_REF" == refs/tags/v* ]]; then + VERSION="${GITHUB_REF_NAME#v}" + else + BASE="$(sed -n 's/^project(bolt VERSION \([0-9.]*\).*/\1/p' CMakeLists.txt)" + VERSION="${BASE}+git$(git rev-parse --short HEAD)" + fi + echo "version=$VERSION" >> "$GITHUB_OUTPUT" + echo "deb=bolt-cppml_${VERSION}_ubuntu${{ matrix.ubuntu_version }}_amd64.deb" >> "$GITHUB_OUTPUT" + + - name: Build Debian package + run: scripts/build-deb.sh build "${{ steps.version.outputs.version }}" "${{ steps.version.outputs.deb }}" + + - name: Install the package and run bolt from it + run: | + sudo apt-get install -y "./${{ steps.version.outputs.deb }}" + /usr/bin/bolt --version + printf 'hello\n/exit\n' | /usr/bin/bolt | grep -q 'Echo: hello' + sudo apt-get remove -y bolt-cppml + + - name: Upload Debian package + uses: actions/upload-artifact@v4 + with: + name: debian-package-ubuntu-${{ matrix.ubuntu_version }} + path: '*.deb' + + - name: Attach package to the release + if: startsWith(github.ref, 'refs/tags/') + uses: softprops/action-gh-release@v2 + with: + files: '*.deb' + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/e2e-ci.yml b/.github/workflows/e2e-ci.yml index 08a3d557..423cfedd 100644 --- a/.github/workflows/e2e-ci.yml +++ b/.github/workflows/e2e-ci.yml @@ -249,20 +249,22 @@ jobs: if: matrix.compiler == 'mingw' uses: msys2/setup-msys2@v2 with: - msystem: MINGW64 + # UCRT64 is the environment MSYS2 maintains. The older MINGW64 + # repository no longer carries glfw and most other libraries. + msystem: UCRT64 update: true # git is needed at test time: the GitRepository tests shell out # to it, and the MSYS2 shell does not inherit the Windows PATH. install: >- git - mingw-w64-x86_64-gcc - mingw-w64-x86_64-cmake - mingw-w64-x86_64-ninja - mingw-w64-x86_64-curl - mingw-w64-x86_64-jsoncpp - mingw-w64-x86_64-glfw - mingw-w64-x86_64-openssl - mingw-w64-x86_64-zlib + mingw-w64-ucrt-x86_64-gcc + mingw-w64-ucrt-x86_64-cmake + mingw-w64-ucrt-x86_64-ninja + mingw-w64-ucrt-x86_64-curl + mingw-w64-ucrt-x86_64-jsoncpp + mingw-w64-ucrt-x86_64-glfw + mingw-w64-ucrt-x86_64-openssl + mingw-w64-ucrt-x86_64-zlib - name: Configure CMake (MSVC) if: matrix.compiler == 'msvc' diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index df0b4cc2..c2a8ff4d 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -734,6 +734,7 @@ jobs: ### Linux - \`bolt-${VERSION}-linux-x64.tar.gz\` - Linux x64 binary - \`bolt_${VERSION}_amd64.deb\` - Debian/Ubuntu package + - \`bolt-${VERSION}-1.x86_64.rpm\` - Fedora/RHEL package ### Windows - \`bolt-${VERSION}-windows-x64.zip\` - Windows x64 binary @@ -752,9 +753,10 @@ jobs: sudo dpkg -i bolt_${VERSION}_amd64.deb \`\`\` - ### macOS - 1. Download the DMG file - 2. Open the DMG and drag Bolt to Applications + ### Linux (RPM) + \`\`\`bash + sudo rpm -i bolt-${VERSION}-1.x86_64.rpm + \`\`\` ### Windows Run the MSI installer or extract the ZIP to your preferred location. diff --git a/.github/workflows/rpm-package.yml b/.github/workflows/rpm-package.yml index 2a9b7f12..a180cba1 100644 --- a/.github/workflows/rpm-package.yml +++ b/.github/workflows/rpm-package.yml @@ -11,6 +11,8 @@ jobs: runs-on: ubuntu-latest container: image: fedora:latest + permissions: + contents: write steps: - name: Install build dependencies @@ -40,12 +42,24 @@ jobs: cmake -DCMAKE_BUILD_TYPE=Release \ -DCMAKE_INSTALL_PREFIX=/usr \ -DBUILD_SHARED_LIBS=ON .. - make -j$(nproc) + make -j"$(nproc)" - name: Create RPM package run: | - VERSION=$(git describe --tags --always 2>/dev/null | sed 's/^v//' || echo "0.1.0") + # A tag v1.2.3 gives 1.2.3. Any other run gives the project version + # plus the commit, for example 1.2.3+git0a1b2c3. + if [[ "$GITHUB_REF" == refs/tags/v* ]]; then + VERSION="${GITHUB_REF_NAME#v}" + else + BASE="$(sed -n 's/^project(bolt VERSION \([0-9.]*\).*/\1/p' CMakeLists.txt)" + VERSION="${BASE}+git${GITHUB_SHA:0:7}" + fi PACKAGE_NAME="bolt-cppml" + + if [ ! -x build/bolt ]; then + echo "error: build/bolt not found; nothing to package" >&2 + exit 1 + fi # Setup RPM build environment rpmdev-setuptree @@ -98,13 +112,7 @@ jobs: mkdir -p %{buildroot}/usr/share/doc/%{name} # Copy binary - if [ -f ${GITHUB_WORKSPACE}/build/bolt ]; then install -m 755 ${GITHUB_WORKSPACE}/build/bolt %{buildroot}/usr/bin/ - else - echo '#!/bin/bash' > %{buildroot}/usr/bin/bolt - echo 'echo "Bolt C++ IDE"' >> %{buildroot}/usr/bin/bolt - chmod 755 %{buildroot}/usr/bin/bolt - fi # Copy libraries if [ -f ${GITHUB_WORKSPACE}/build/libbolt_lib.so ]; then @@ -161,9 +169,15 @@ jobs: rpmbuild -bb ~/rpmbuild/SPECS/${PACKAGE_NAME}.spec # Copy RPM to workspace - cp ~/rpmbuild/RPMS/*/${PACKAGE_NAME}-${VERSION}-*.rpm . 2>/dev/null || \ - cp ~/rpmbuild/RPMS/*/${PACKAGE_NAME}*.rpm . 2>/dev/null || \ - echo "Warning: RPM not found in expected location" + cp ~/rpmbuild/RPMS/*/"${PACKAGE_NAME}"-*.rpm . + ls -l ./*.rpm + + - name: Install the package and run bolt from it + run: | + dnf install -y ./bolt-cppml-*.rpm + /usr/bin/bolt --version + printf 'hello\n/exit\n' | /usr/bin/bolt | grep -q 'Echo: hello' + dnf remove -y bolt-cppml - name: Upload RPM package uses: actions/upload-artifact@v4 @@ -173,7 +187,7 @@ jobs: - name: Create Release if: startsWith(github.ref, 'refs/tags/') - uses: softprops/action-gh-release@v1 + uses: softprops/action-gh-release@v2 with: files: '*.rpm' env: diff --git a/CMakeLists.txt b/CMakeLists.txt index 71369123..83f932df 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,5 +1,5 @@ cmake_minimum_required(VERSION 3.15) -project(bolt VERSION 1.0.0 LANGUAGES CXX) +project(bolt VERSION 1.1.0 LANGUAGES CXX) set(CMAKE_CXX_STANDARD 20) set(CMAKE_CXX_STANDARD_REQUIRED ON) @@ -274,8 +274,8 @@ add_library(bolt_lib # Set library type based on BUILD_SHARED_LIBS option if(BUILD_SHARED_LIBS) set_target_properties(bolt_lib PROPERTIES - VERSION 1.0.0 - SOVERSION 1 + VERSION ${PROJECT_VERSION} + SOVERSION ${PROJECT_VERSION_MAJOR} ) endif() @@ -398,6 +398,8 @@ endif() add_executable(bolt src/bolt/main.cpp) target_link_libraries(bolt PRIVATE bolt_lib) target_compile_definitions(bolt PRIVATE BOLT_VERSION="${PROJECT_VERSION}") +# The GUI's About window shows the same version. +target_compile_definitions(bolt_lib PRIVATE BOLT_VERSION="${PROJECT_VERSION}") if(WIN32) target_sources(bolt PRIVATE ${BOLT_WIN32_RESOURCES}) endif() diff --git a/benchmark_tool.cpp b/benchmark_tool.cpp index 543c2c63..9aeecce3 100644 --- a/benchmark_tool.cpp +++ b/benchmark_tool.cpp @@ -1,13 +1,14 @@ -#include "include/bolt/core/benchmark_suite.hpp" -#include "include/bolt/core/logging.hpp" -#include -#include -#include #include #include #include +#include +#include +#include + +#include "include/bolt/core/benchmark_suite.hpp" +#include "include/bolt/core/logging.hpp" -using namespace bolt; +using namespace bolt; // NOLINT(build/namespaces) void printUsage(const char* programName) { std::cout << "Usage: " << programName << " [options]\n\n"; @@ -36,34 +37,29 @@ void printUsage(const char* programName) { void printBenchmarkSummary(const std::vector& results) { std::cout << "\n=== Benchmark Summary ===\n"; - std::cout << std::left << std::setw(30) << "Benchmark" - << std::setw(12) << "Category" - << std::setw(15) << "Avg Time (ms)" - << std::setw(15) << "Min Time (ms)" - << std::setw(15) << "Max Time (ms)" + std::cout << std::left << std::setw(30) << "Benchmark" << std::setw(12) << "Category" << std::setw(15) + << "Avg Time (ms)" << std::setw(15) << "Min Time (ms)" << std::setw(15) << "Max Time (ms)" << std::setw(12) << "Success Rate" << "Status\n"; std::cout << std::string(110, '-') << "\n"; - + for (const auto& result : results) { std::string status = result.isValid() ? "SUCCESS" : "FAILED"; - std::cout << std::left << std::setw(30) << result.name.substr(0, 29) - << std::setw(12) << result.category - << std::setw(15) << std::fixed << std::setprecision(3) << result.averageDurationMs - << std::setw(15) << std::fixed << std::setprecision(3) << result.minDurationMs - << std::setw(15) << std::fixed << std::setprecision(3) << result.maxDurationMs - << std::setw(12) << std::fixed << std::setprecision(1) << (result.getSuccessRate() * 100) << "%" - << status << "\n"; - + std::cout << std::left << std::setw(30) << result.name.substr(0, 29) << std::setw(12) << result.category + << std::setw(15) << std::fixed << std::setprecision(3) << result.averageDurationMs << std::setw(15) + << std::fixed << std::setprecision(3) << result.minDurationMs << std::setw(15) << std::fixed + << std::setprecision(3) << result.maxDurationMs << std::setw(12) << std::fixed << std::setprecision(1) + << (result.getSuccessRate() * 100) << "%" << status << "\n"; + if (!result.errorMessage.empty()) { std::cout << " Error: " << result.errorMessage << "\n"; } } - + // Calculate summary statistics int totalSuccessful = 0, totalFailed = 0; double totalTime = 0.0; - + for (const auto& result : results) { if (result.isValid()) { totalSuccessful++; @@ -72,28 +68,25 @@ void printBenchmarkSummary(const std::vector& results) { totalFailed++; } } - + std::cout << "\n"; std::cout << "Total Benchmarks: " << results.size() << "\n"; std::cout << "Successful: " << totalSuccessful << "\n"; std::cout << "Failed: " << totalFailed << "\n"; if (totalSuccessful > 0) { - std::cout << "Average Time: " << std::fixed << std::setprecision(3) - << (totalTime / totalSuccessful) << " ms\n"; + std::cout << "Average Time: " << std::fixed << std::setprecision(3) << (totalTime / totalSuccessful) << " ms\n"; } } void printComparisonSummary(const std::vector& comparisons) { std::cout << "\n=== Baseline Comparison ===\n"; - std::cout << std::left << std::setw(30) << "Benchmark" - << std::setw(15) << "Current (ms)" - << std::setw(15) << "Baseline (ms)" - << std::setw(12) << "Change (%)" + std::cout << std::left << std::setw(30) << "Benchmark" << std::setw(15) << "Current (ms)" << std::setw(15) + << "Baseline (ms)" << std::setw(12) << "Change (%)" << "Status\n"; std::cout << std::string(80, '-') << "\n"; - + int improvements = 0, regressions = 0, stable = 0; - + for (const auto& comp : comparisons) { std::string statusStr; switch (comp.performanceStatus) { @@ -113,19 +106,18 @@ void printComparisonSummary(const std::vector& comparisons) statusStr = "INCONCLUSIVE"; break; } - - std::cout << std::left << std::setw(30) << comp.benchmarkName.substr(0, 29) - << std::setw(15) << std::fixed << std::setprecision(3) << comp.current.averageDurationMs - << std::setw(15) << std::fixed << std::setprecision(3) << comp.baseline.averageDurationMs - << std::setw(12) << std::fixed << std::setprecision(1) << comp.durationChangePercent - << statusStr << "\n"; + + std::cout << std::left << std::setw(30) << comp.benchmarkName.substr(0, 29) << std::setw(15) << std::fixed + << std::setprecision(3) << comp.current.averageDurationMs << std::setw(15) << std::fixed + << std::setprecision(3) << comp.baseline.averageDurationMs << std::setw(12) << std::fixed + << std::setprecision(1) << comp.durationChangePercent << statusStr << "\n"; } - + std::cout << "\nComparison Summary:\n"; std::cout << "Improvements: " << improvements << "\n"; std::cout << "Regressions: " << regressions << "\n"; std::cout << "Stable: " << stable << "\n"; - + if (regressions > 0) { std::cout << "\nโš ๏ธ Performance regressions detected!\n"; } else if (improvements > 0) { @@ -136,9 +128,9 @@ void printComparisonSummary(const std::vector& comparisons) int main(int argc, char* argv[]) { // Initialize logging LogManager::configureConsoleLogging(LogLevel::INFO, false); - + auto& suite = BenchmarkSuite::getInstance(); - + // Command line argument parsing std::string command; std::string specificBenchmark; @@ -152,10 +144,10 @@ int main(int argc, char* argv[]) { int warmup = 3; int timeout = 30000; bool verbose = false; - + for (int i = 1; i < argc; ++i) { std::string arg = argv[i]; - + if (arg == "--help" || arg == "-h") { printUsage(argv[0]); return 0; @@ -195,24 +187,24 @@ int main(int argc, char* argv[]) { return 1; } } - + if (command.empty()) { command = "run-all"; // Default action } - + // Configure benchmark suite suite.setDefaultIterations(iterations); suite.setDefaultWarmupRuns(warmup); suite.setDefaultTimeout(std::chrono::milliseconds(timeout)); suite.enableVerboseOutput(verbose); - + // Load core benchmarks by including the source // This ensures the benchmarks are registered - extern void register_core_benchmarks(); // Forward declaration - + extern void register_core_benchmarks(); // Forward declaration + std::cout << "Bolt Performance Benchmark Suite\n"; std::cout << "================================\n\n"; - + try { if (command == "list") { auto benchmarks = suite.getAvailableBenchmarks(); @@ -221,7 +213,7 @@ int main(int argc, char* argv[]) { std::cout << " " << name << "\n"; } std::cout << "\nTotal: " << benchmarks.size() << " benchmarks\n"; - + } else if (command == "categories") { auto categories = suite.getAvailableCategories(); std::cout << "Available Categories:\n"; @@ -229,12 +221,12 @@ int main(int argc, char* argv[]) { std::cout << " " << category << "\n"; } std::cout << "\nTotal: " << categories.size() << " categories\n"; - + } else if (command == "run-all") { std::cout << "Running all benchmarks...\n"; auto results = suite.runAllBenchmarks(); printBenchmarkSummary(results); - + // Handle baseline comparison if (!baselineFile.empty()) { auto baseline = suite.loadBaselineResults(baselineFile); @@ -243,7 +235,7 @@ int main(int argc, char* argv[]) { printComparisonSummary(comparisons); } } - + // Generate reports if (!jsonOutput.empty()) { suite.generateJsonReport(results, jsonOutput); @@ -257,7 +249,7 @@ int main(int argc, char* argv[]) { if (!saveBaselineFile.empty()) { suite.saveBaselineResults(results, saveBaselineFile); } - + } else if (command == "category") { std::cout << "Running benchmarks in category: " << specificCategory << "\n"; auto results = suite.runBenchmarksByCategory(specificCategory); @@ -266,23 +258,22 @@ int main(int argc, char* argv[]) { return 1; } printBenchmarkSummary(results); - + } else if (command == "benchmark") { std::cout << "Running benchmark: " << specificBenchmark << "\n"; auto result = suite.runBenchmark(specificBenchmark); std::vector results = {result}; printBenchmarkSummary(results); - + if (!result.isValid()) { return 1; } } - } catch (const std::exception& e) { std::cerr << "Error: " << e.what() << std::endl; return 1; } - + std::cout << "\nBenchmark execution completed.\n"; return 0; -} \ No newline at end of file +} diff --git a/benchmark_tool_standalone.cpp b/benchmark_tool_standalone.cpp index fc9d50ce..b1d836e1 100644 --- a/benchmark_tool_standalone.cpp +++ b/benchmark_tool_standalone.cpp @@ -1,27 +1,28 @@ -#include "include/bolt/core/benchmark_suite.hpp" -#include "include/bolt/core/performance_profiler.hpp" -#include "include/bolt/core/memory_manager.hpp" -#include "include/bolt/core/memory_pool.hpp" -#include "include/bolt/core/logging.hpp" -#include -#include -#include #include #include +#include #include -#include +#include #include +#include +#include #include -#include +#include + +#include "include/bolt/core/benchmark_suite.hpp" +#include "include/bolt/core/logging.hpp" +#include "include/bolt/core/memory_manager.hpp" +#include "include/bolt/core/memory_pool.hpp" +#include "include/bolt/core/performance_profiler.hpp" -using namespace bolt; +using namespace bolt; // NOLINT(build/namespaces) // Simple test benchmarks for standalone demo void benchmark_memory_allocation_demo(const BenchmarkConfig& config) { std::vector allocations; const size_t numAllocations = 1000; const size_t allocationSize = 1024; - + // Allocate for (size_t i = 0; i < numAllocations; ++i) { void* ptr = malloc(allocationSize); @@ -29,7 +30,7 @@ void benchmark_memory_allocation_demo(const BenchmarkConfig& config) { allocations.push_back(ptr); } } - + // Deallocate for (void* ptr : allocations) { if (ptr) { @@ -41,19 +42,19 @@ void benchmark_memory_allocation_demo(const BenchmarkConfig& config) { void benchmark_string_operations_demo(const BenchmarkConfig& config) { const int numStrings = 500; std::vector strings; - + // String creation for (int i = 0; i < numStrings; ++i) { strings.emplace_back("Demo string " + std::to_string(i) + " with content"); } - + // String manipulation for (auto& str : strings) { str += " modified"; str = str.substr(0, str.length() / 2); std::transform(str.begin(), str.end(), str.begin(), ::toupper); } - + // String searching int found = 0; for (const auto& str : strings) { @@ -66,22 +67,22 @@ void benchmark_string_operations_demo(const BenchmarkConfig& config) { void benchmark_vector_operations_demo(const BenchmarkConfig& config) { std::vector vec; const int numElements = 5000; - + // Push back for (int i = 0; i < numElements; ++i) { vec.push_back(i); } - + // Random access std::random_device rd; std::mt19937 gen(rd()); std::uniform_int_distribution<> dis(0, numElements - 1); - + int sum = 0; for (int i = 0; i < 1000; ++i) { sum += vec[dis(gen)]; } - + // Erase elements while (!vec.empty() && vec.size() > numElements / 2) { vec.erase(vec.begin() + vec.size() / 2); @@ -93,9 +94,9 @@ void benchmark_threading_demo(const BenchmarkConfig& config) { const int operationsPerThread = 500; std::mutex testMutex; int sharedCounter = 0; - + std::vector threads; - + for (int i = 0; i < numThreads; ++i) { threads.emplace_back([&]() { for (int j = 0; j < operationsPerThread; ++j) { @@ -104,7 +105,7 @@ void benchmark_threading_demo(const BenchmarkConfig& config) { } }); } - + for (auto& thread : threads) { if (thread.joinable()) { thread.join(); @@ -116,7 +117,7 @@ void benchmark_file_io_demo(const BenchmarkConfig& config) { const std::string filename = "/tmp/benchmark_demo_file.txt"; const std::string content = "Demo content for file I/O benchmark. "; const int numLines = 500; - + // Write file { std::ofstream file(filename); @@ -124,7 +125,7 @@ void benchmark_file_io_demo(const BenchmarkConfig& config) { file << content << "Line " << i << std::endl; } } - + // Read file { std::ifstream file(filename); @@ -134,34 +135,34 @@ void benchmark_file_io_demo(const BenchmarkConfig& config) { lineCount++; } } - + // Clean up std::remove(filename.c_str()); } void registerDemoBenchmarks() { auto& suite = BenchmarkSuite::getInstance(); - + BenchmarkConfig config1("memory_allocation_demo", "Basic memory allocation and deallocation performance"); config1.category = "DEMO"; config1.iterations = 50; suite.registerBenchmark(config1, benchmark_memory_allocation_demo); - + BenchmarkConfig config2("string_operations_demo", "String creation, manipulation, and destruction"); config2.category = "DEMO"; config2.iterations = 30; suite.registerBenchmark(config2, benchmark_string_operations_demo); - + BenchmarkConfig config3("vector_operations_demo", "Vector operations performance"); config3.category = "DEMO"; config3.iterations = 20; suite.registerBenchmark(config3, benchmark_vector_operations_demo); - + BenchmarkConfig config4("threading_demo", "Thread creation and synchronization"); config4.category = "DEMO"; config4.iterations = 10; suite.registerBenchmark(config4, benchmark_threading_demo); - + BenchmarkConfig config5("file_io_demo", "File I/O operations"); config5.category = "DEMO"; config5.iterations = 5; @@ -190,34 +191,29 @@ void printUsage(const char* programName) { void printBenchmarkSummary(const std::vector& results) { std::cout << "\n=== Benchmark Summary ===\n"; - std::cout << std::left << std::setw(25) << "Benchmark" - << std::setw(10) << "Category" - << std::setw(15) << "Avg Time (ms)" - << std::setw(15) << "Min Time (ms)" - << std::setw(15) << "Max Time (ms)" + std::cout << std::left << std::setw(25) << "Benchmark" << std::setw(10) << "Category" << std::setw(15) + << "Avg Time (ms)" << std::setw(15) << "Min Time (ms)" << std::setw(15) << "Max Time (ms)" << std::setw(12) << "Success Rate" << "Status\n"; std::cout << std::string(95, '-') << "\n"; - + for (const auto& result : results) { std::string status = result.isValid() ? "SUCCESS" : "FAILED"; - std::cout << std::left << std::setw(25) << result.name.substr(0, 24) - << std::setw(10) << result.category - << std::setw(15) << std::fixed << std::setprecision(3) << result.averageDurationMs - << std::setw(15) << std::fixed << std::setprecision(3) << result.minDurationMs - << std::setw(15) << std::fixed << std::setprecision(3) << result.maxDurationMs - << std::setw(12) << std::fixed << std::setprecision(1) << (result.getSuccessRate() * 100) << "%" - << status << "\n"; - + std::cout << std::left << std::setw(25) << result.name.substr(0, 24) << std::setw(10) << result.category + << std::setw(15) << std::fixed << std::setprecision(3) << result.averageDurationMs << std::setw(15) + << std::fixed << std::setprecision(3) << result.minDurationMs << std::setw(15) << std::fixed + << std::setprecision(3) << result.maxDurationMs << std::setw(12) << std::fixed << std::setprecision(1) + << (result.getSuccessRate() * 100) << "%" << status << "\n"; + if (!result.errorMessage.empty()) { std::cout << " Error: " << result.errorMessage << "\n"; } } - + // Calculate summary statistics int totalSuccessful = 0, totalFailed = 0; double totalTime = 0.0; - + for (const auto& result : results) { if (result.isValid()) { totalSuccessful++; @@ -226,23 +222,22 @@ void printBenchmarkSummary(const std::vector& results) { totalFailed++; } } - + std::cout << "\n"; std::cout << "Total Benchmarks: " << results.size() << "\n"; std::cout << "Successful: " << totalSuccessful << "\n"; std::cout << "Failed: " << totalFailed << "\n"; if (totalSuccessful > 0) { - std::cout << "Average Time: " << std::fixed << std::setprecision(3) - << (totalTime / totalSuccessful) << " ms\n"; + std::cout << "Average Time: " << std::fixed << std::setprecision(3) << (totalTime / totalSuccessful) << " ms\n"; } } int main(int argc, char* argv[]) { // Initialize logging LogManager::configureConsoleLogging(LogLevel::INFO, false); - + auto& suite = BenchmarkSuite::getInstance(); - + // Command line argument parsing std::string command; std::string specificBenchmark; @@ -252,10 +247,10 @@ int main(int argc, char* argv[]) { std::string htmlOutput; int iterations = 10; bool verbose = false; - + for (int i = 1; i < argc; ++i) { std::string arg = argv[i]; - + if (arg == "--help" || arg == "-h") { printUsage(argv[0]); return 0; @@ -287,21 +282,21 @@ int main(int argc, char* argv[]) { return 1; } } - + if (command.empty()) { command = "run-all"; // Default action } - + // Configure benchmark suite suite.setDefaultIterations(iterations); suite.enableVerboseOutput(verbose); - + // Register demo benchmarks registerDemoBenchmarks(); - + std::cout << "Bolt Performance Benchmark Suite (Standalone)\n"; std::cout << "=============================================\n\n"; - + try { if (command == "list") { auto benchmarks = suite.getAvailableBenchmarks(); @@ -310,7 +305,7 @@ int main(int argc, char* argv[]) { std::cout << " " << name << "\n"; } std::cout << "\nTotal: " << benchmarks.size() << " benchmarks\n"; - + } else if (command == "categories") { auto categories = suite.getAvailableCategories(); std::cout << "Available Categories:\n"; @@ -318,12 +313,12 @@ int main(int argc, char* argv[]) { std::cout << " " << category << "\n"; } std::cout << "\nTotal: " << categories.size() << " categories\n"; - + } else if (command == "run-all") { std::cout << "Running all benchmarks...\n"; auto results = suite.runAllBenchmarks(); printBenchmarkSummary(results); - + // Generate reports if (!jsonOutput.empty()) { suite.generateJsonReport(results, jsonOutput); @@ -337,7 +332,7 @@ int main(int argc, char* argv[]) { suite.generateHtmlReport(results, htmlOutput); std::cout << "HTML report saved to: " << htmlOutput << "\n"; } - + } else if (command == "category") { std::cout << "Running benchmarks in category: " << specificCategory << "\n"; auto results = suite.runBenchmarksByCategory(specificCategory); @@ -346,23 +341,22 @@ int main(int argc, char* argv[]) { return 1; } printBenchmarkSummary(results); - + } else if (command == "benchmark") { std::cout << "Running benchmark: " << specificBenchmark << "\n"; auto result = suite.runBenchmark(specificBenchmark); std::vector results = {result}; printBenchmarkSummary(results); - + if (!result.isValid()) { return 1; } } - } catch (const std::exception& e) { std::cerr << "Error: " << e.what() << std::endl; return 1; } - + std::cout << "\nBenchmark execution completed.\n"; return 0; -} \ No newline at end of file +} diff --git a/bolt_ai_terminal.cpp b/bolt_ai_terminal.cpp index fae85fb7..90d8ffc1 100644 --- a/bolt_ai_terminal.cpp +++ b/bolt_ai_terminal.cpp @@ -8,15 +8,15 @@ int main() { std::cout << "๐Ÿฆ™ Bolt TinyLlama Chat Terminal" << std::endl; std::cout << "==============================" << std::endl; - + // Create our AI manager bolt::ai::EnhancedAIManager ai_manager; std::cout << "โœ… AI Manager initialized" << std::endl; - + // Try to auto-detect and load GGUF models std::cout << "๐Ÿ” Looking for TinyLlama models..." << std::endl; bool model_found = ai_manager.auto_detect_models(); - + if (model_found) { std::cout << "โœ… GGUF model loaded!" << std::endl; std::cout << "๐Ÿ“‹ Model info: " << ai_manager.get_model_info() << std::endl; @@ -24,28 +24,28 @@ int main() { std::cout << "โš ๏ธ No GGUF models found, but intelligent fallback responses available!" << std::endl; std::cout << "๐Ÿ’ก To use a real model, place a .gguf file in the ./models/ directory" << std::endl; } - + std::cout << "\n๐Ÿ’ฌ Chat with AI (type 'quit' to exit, 'info' for model details):" << std::endl; std::cout << "โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€" << std::endl; - + std::string input; std::string session_id = "terminal_chat"; - + // Create a session ai_manager.create_session(session_id); - + while (true) { std::cout << "\n๐Ÿ‘ค You: "; - + if (!std::getline(std::cin, input)) { - break; // EOF or error + break; // EOF or error } - + if (input == "quit" || input == "exit") { std::cout << "๐Ÿ‘‹ Goodbye!" << std::endl; break; } - + if (input == "info") { if (ai_manager.has_direct_model()) { std::cout << "๐Ÿ“‹ " << ai_manager.get_model_info() << std::endl; @@ -55,7 +55,7 @@ int main() { } continue; } - + if (input == "stats") { auto stats = ai_manager.get_statistics(); std::cout << "๐Ÿ“Š Statistics:" << std::endl; @@ -65,17 +65,17 @@ int main() { std::cout << " Avg response time: " << stats.average_inference_time_ms << "ms" << std::endl; continue; } - + if (input.empty()) { continue; } - + std::cout << "\n๐Ÿค– AI: "; std::cout.flush(); - + // Get AI response auto response = ai_manager.chat(input, session_id); - + if (response.success) { std::cout << response.response << std::endl; std::cout << "โฑ๏ธ Response time: " << response.inference_time_ms << "ms" << std::endl; @@ -85,9 +85,9 @@ int main() { } else { std::cout << "โŒ Error: " << response.error << std::endl; } - + std::cout << "โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€" << std::endl; } - + return 0; } diff --git a/bolt_chat.cpp b/bolt_chat.cpp index 5042450b..010e758f 100644 --- a/bolt_chat.cpp +++ b/bolt_chat.cpp @@ -1,60 +1,63 @@ -#include "bolt/ai/direct_gguf_inference.hpp" #include #include #include +#include "bolt/ai/direct_gguf_inference.hpp" + class BoltTerminalChat { -private: + private: bolt::ai::DirectGGUFInference ai_; std::vector conversation_history_; - -public: + + public: bool initialize() { std::cout << "๐Ÿš€ Bolt Terminal Chat - Direct GGUF Access\n"; std::cout << "=========================================\n\n"; - + // Load the TinyLlama model - std::string model_path = "/workspaces/bolt-cppml/models/TinyLlama-1.1B-Chat-v1.0-GGUF/tinyllama-1.1b-chat-v1.0.Q3_K_M.gguf"; - + std::string model_path = + "/workspaces/bolt-cppml/models/TinyLlama-1.1B-Chat-v1.0-GGUF/tinyllama-1.1b-chat-v1.0.Q3_K_M.gguf"; + std::cout << "๐Ÿ“ฅ Loading AI model...\n"; bool loaded = ai_.load_model(model_path); - + if (!loaded) { std::cout << "โŒ Failed to load model\n"; return false; } - + std::cout << "โœ… AI model loaded successfully!\n"; std::cout << ai_.get_model_info() << "\n"; return true; } - + void run_chat() { std::cout << "\n๐Ÿ’ฌ Chat ready! Commands:\n"; std::cout << " Type your message and press Enter\n"; std::cout << " /help - Show help\n"; std::cout << " /clear - Clear conversation history\n"; std::cout << " /quit, /exit, quit, exit - End chat\n\n"; - + std::string input; while (true) { std::cout << "You> "; std::getline(std::cin, input); - - if (input.empty()) continue; - + + if (input.empty()) + continue; + // Handle commands if (input == "/quit" || input == "/exit" || input == "quit" || input == "exit") { std::cout << "๐Ÿ‘‹ Goodbye!\n"; break; } - + if (input == "/clear") { conversation_history_.clear(); std::cout << "๐Ÿงน Conversation history cleared\n"; continue; } - + if (input == "/help") { std::cout << "Available commands:\n"; std::cout << " /help - Show this help\n"; @@ -63,28 +66,28 @@ class BoltTerminalChat { std::cout << " Just type your message for AI chat\n"; continue; } - + // Generate AI response std::cout << "AI> ๐Ÿค” Thinking...\r" << std::flush; - + auto response = ai_.chat(input, conversation_history_); - + if (response.success) { std::cout << "AI> " << response.response << "\n\n"; - + // Update conversation history conversation_history_.push_back(input); conversation_history_.push_back(response.response); - + // Keep history manageable (last 10 exchanges = 20 messages) if (conversation_history_.size() > 20) { conversation_history_.erase(conversation_history_.begin(), conversation_history_.begin() + 2); } - + // Show some stats std::cout << "โฑ๏ธ Response time: " << static_cast(response.inference_time_ms / 1000) << "s | "; std::cout << "Tokens: " << response.tokens_generated << "\n\n"; - + } else { std::cout << "AI> โŒ Error: " << response.error << "\n\n"; } @@ -94,11 +97,11 @@ class BoltTerminalChat { int main(int argc, char* argv[]) { BoltTerminalChat chat; - + if (!chat.initialize()) { return 1; } - + chat.run_chat(); return 0; } diff --git a/bolt_terminal_ai_fixed.cpp b/bolt_terminal_ai_fixed.cpp index 701fe381..f5ff33a7 100644 --- a/bolt_terminal_ai_fixed.cpp +++ b/bolt_terminal_ai_fixed.cpp @@ -1,42 +1,46 @@ -#include "include/bolt/ai/enhanced_ai_manager.hpp" +#include // For isatty + #include -#include #include -#include // For isatty +#include + +#include "include/bolt/ai/enhanced_ai_manager.hpp" class BoltTerminalAI { -private: + private: std::unique_ptr ai_manager_; std::string session_id_; - -public: + + public: BoltTerminalAI() { ai_manager_ = std::make_unique(); session_id_ = "terminal_session"; ai_manager_->create_session(session_id_); } - + void show_status() { std::cout << "\n๐Ÿ“Š AI Status:\n"; std::cout << " Current Provider: " << ai_manager_->get_current_provider() << "\n"; std::cout << " Ready: " << (ai_manager_->is_ready() ? "โœ…" : "โŒ") << "\n"; - std::cout << " Direct Model: " << (ai_manager_->has_direct_model() ? "โœ… " + ai_manager_->get_model_info() : "โŒ Using fallback") << "\n"; - + std::cout << " Direct Model: " + << (ai_manager_->has_direct_model() ? "โœ… " + ai_manager_->get_model_info() : "โŒ Using fallback") + << "\n"; + auto stats = ai_manager_->get_statistics(); std::cout << " Total Requests: " << stats.total_requests << "\n"; std::cout << " Successful: " << stats.successful_requests << "\n"; std::cout << " Failed: " << stats.failed_requests << "\n\n"; } - + void chat_loop() { std::cout << "๐Ÿค– Bolt AI Terminal Chat\n"; std::cout << "========================\n\n"; - + show_status(); - + // Check if input is from a pipe or terminal bool is_piped = !isatty(fileno(stdin)); - + if (!is_piped) { std::cout << "Commands:\n"; std::cout << " /status - Show AI status\n"; @@ -44,56 +48,65 @@ class BoltTerminalAI { std::cout << " /clear - Clear chat history\n"; std::cout << " /load - Try to load a GGUF model\n"; std::cout << " /quit - Exit the application\n\n"; - + std::cout << "๐Ÿ’ฌ Start chatting (type your message and press Enter):\n\n"; } - + std::string input; while (std::getline(std::cin, input)) { if (input.empty()) { - if (is_piped) break; // Exit on empty line when piped + if (is_piped) + break; // Exit on empty line when piped continue; } - + if (!is_piped) { std::cout << "You: " << input << "\n"; } - + // Handle commands if (input == "/quit" || input == "/exit") { std::cout << "\n๐Ÿ‘‹ Goodbye!\n"; break; } - + if (input == "/status") { show_status(); - if (!is_piped) continue; - else break; + if (!is_piped) + continue; + else + break; } - + if (input == "/history") { show_history(); - if (!is_piped) continue; - else break; + if (!is_piped) + continue; + else + break; } - + if (input == "/clear") { ai_manager_->clear_session_history(session_id_); std::cout << "๐Ÿ—‘๏ธ Chat history cleared.\n\n"; - if (!is_piped) continue; - else break; + if (!is_piped) + continue; + else + break; } - + if (input == "/load") { try_load_model(); - if (!is_piped) continue; - else break; + if (!is_piped) + continue; + else + break; } - + // Send to AI std::cout << "AI: "; auto response = ai_manager_->chat(input, session_id_); - + if (response.success) { std::cout << response.response << "\n"; if (response.inference_time_ms > 0) { @@ -106,9 +119,9 @@ class BoltTerminalAI { } else { std::cout << "โŒ Error: " << response.error << "\n"; } - + std::cout << "\n"; - + // For piped input, process one question and exit if (is_piped) { break; @@ -116,14 +129,14 @@ class BoltTerminalAI { } } -private: + private: void show_history() { auto history = ai_manager_->get_session_history(session_id_); if (history.empty()) { std::cout << "๐Ÿ“ No chat history yet.\n\n"; return; } - + std::cout << "\n๐Ÿ“œ Chat History:\n"; std::cout << "================\n"; for (const auto& entry : history) { @@ -131,7 +144,7 @@ class BoltTerminalAI { } std::cout << "\n"; } - + void try_load_model() { std::cout << "๐Ÿ” Attempting to auto-detect GGUF models...\n"; if (ai_manager_->auto_detect_models()) { @@ -140,7 +153,8 @@ class BoltTerminalAI { } else { std::cout << "โŒ No GGUF models found. You can:\n"; std::cout << " 1. Download a small model:\n"; - std::cout << " wget -P ./models/ https://huggingface.co/microsoft/DialoGPT-small/resolve/main/model.gguf\n"; + std::cout + << " wget -P ./models/ https://huggingface.co/microsoft/DialoGPT-small/resolve/main/model.gguf\n"; std::cout << " 2. Or continue using intelligent fallback responses\n\n"; } } @@ -154,6 +168,6 @@ int main() { std::cerr << "โŒ Error: " << e.what() << std::endl; return 1; } - + return 0; } diff --git a/bolt_terminal_chat.cpp b/bolt_terminal_chat.cpp index 293b03a4..0deab430 100644 --- a/bolt_terminal_chat.cpp +++ b/bolt_terminal_chat.cpp @@ -1,117 +1,118 @@ +#include #include #include -#include -#include #include +#include // Simple terminal chat that calls KoboldCpp as a subprocess class KoboldTerminal { -private: + private: std::string kobold_path; std::string model_path; std::vector conversation; - -public: - KoboldTerminal(const std::string& kobold, const std::string& model) - : kobold_path(kobold), model_path(model) {} - + + public: + KoboldTerminal(const std::string& kobold, const std::string& model) : kobold_path(kobold), model_path(model) {} + bool initialize() { std::cout << "๐Ÿš€ Initializing Bolt Terminal Chat with KoboldCpp\n"; std::cout << "Model: " << model_path << std::endl; - + // Check if files exist std::ifstream kobold_file(kobold_path); std::ifstream model_file(model_path); - + if (!kobold_file.good()) { std::cout << "โŒ KoboldCpp not found: " << kobold_path << std::endl; return false; } - + if (!model_file.good()) { std::cout << "โŒ Model not found: " << model_path << std::endl; return false; } - + std::cout << "โœ… Files found successfully" << std::endl; return true; } - + std::string chat(const std::string& message) { conversation.push_back("Human: " + message); - + // Format prompt with conversation history std::string prompt = "You are a helpful AI assistant specialized in programming.\n\n"; - + // Add recent conversation (keep it manageable) int start_idx = std::max(0, static_cast(conversation.size()) - 6); for (int i = start_idx; i < static_cast(conversation.size()); i++) { prompt += conversation[i] + "\n"; } prompt += "Assistant: "; - + // Write prompt to temp file std::ofstream temp_file("/tmp/prompt.txt"); temp_file << prompt; temp_file.close(); - + // Call KoboldCpp with the prompt - std::string command = "cd " + kobold_path + " && echo \"" + message + "\" | python koboldcpp.py --model \"" + model_path + "\" --cli --promptlimit 150 2>/dev/null | tail -1"; - + std::string command = "cd " + kobold_path + " && echo \"" + message + "\" | python koboldcpp.py --model \"" + + model_path + "\" --cli --promptlimit 150 2>/dev/null | tail -1"; + FILE* pipe = popen(command.c_str(), "r"); if (!pipe) { return "โŒ Failed to execute KoboldCpp"; } - + std::string result; char buffer[1024]; while (fgets(buffer, sizeof(buffer), pipe) != nullptr) { result += buffer; } pclose(pipe); - + // Clean up the response if (result.empty()) { return "โŒ No response from AI"; } - + // Remove any trailing newlines while (!result.empty() && (result.back() == '\n' || result.back() == '\r')) { result.pop_back(); } - + conversation.push_back("Assistant: " + result); - + // Keep conversation history manageable if (conversation.size() > 12) { conversation.erase(conversation.begin(), conversation.begin() + 2); } - + return result; } - + void run_interactive() { std::cout << "\n๐Ÿ’ฌ Bolt Terminal Chat Ready!\n"; std::cout << "Type your messages below. Use 'quit', 'exit', or '/quit' to end.\n\n"; - + std::string input; while (true) { std::cout << "> "; std::getline(std::cin, input); - - if (input.empty()) continue; - + + if (input.empty()) + continue; + if (input == "quit" || input == "exit" || input == "/quit" || input == "/exit") { std::cout << "๐Ÿ‘‹ Goodbye!\n"; break; } - + if (input == "/clear") { conversation.clear(); std::cout << "๐Ÿงน Conversation history cleared.\n"; continue; } - + if (input == "/help") { std::cout << "Commands:\n"; std::cout << " /quit, /exit - Exit the chat\n"; @@ -119,7 +120,7 @@ class KoboldTerminal { std::cout << " /help - Show this help\n"; continue; } - + std::cout << "๐Ÿค– Thinking..." << std::flush; std::string response = chat(input); std::cout << "\r๐Ÿค– " << response << "\n\n"; @@ -130,21 +131,22 @@ class KoboldTerminal { int main(int argc, char* argv[]) { std::cout << "๐Ÿš€ Bolt Terminal Chat - Direct GGUF Access\n"; std::cout << "==========================================\n\n"; - + std::string kobold_dir = "/workspaces/bolt-cppml/ggml/kobold.cpp"; - std::string model_path = "/workspaces/bolt-cppml/models/TinyLlama-1.1B-Chat-v1.0-GGUF/tinyllama-1.1b-chat-v1.0.Q3_K_M.gguf"; - + std::string model_path = + "/workspaces/bolt-cppml/models/TinyLlama-1.1B-Chat-v1.0-GGUF/tinyllama-1.1b-chat-v1.0.Q3_K_M.gguf"; + if (argc > 1) { model_path = argv[1]; } - + KoboldTerminal terminal(kobold_dir, model_path); - + if (!terminal.initialize()) { return 1; } - + terminal.run_interactive(); - + return 0; } diff --git a/cmake/platforms/Linux.cmake b/cmake/platforms/Linux.cmake index f0f3d371..751d04ea 100644 --- a/cmake/platforms/Linux.cmake +++ b/cmake/platforms/Linux.cmake @@ -132,9 +132,10 @@ set(CPACK_RPM_PACKAGE_LICENSE "MIT") # and after install: $ORIGIN and $ORIGIN/bin let programs run straight from the # build directory (libbolt_lib.so sits next to them, llama.cpp's libraries in # bin/) and from an unpacked tarball; $ORIGIN/../lib covers an installed -# bin/ + lib/ layout. +# bin/ + lib/ layout. Only relative entries: an absolute one such as +# /usr/local/lib is rejected by rpmbuild's rpath check and is not needed. set(CMAKE_BUILD_WITH_INSTALL_RPATH TRUE) -set(CMAKE_INSTALL_RPATH "\$ORIGIN:\$ORIGIN/bin:\$ORIGIN/../lib:\$ORIGIN/lib:/usr/local/lib") +set(CMAKE_INSTALL_RPATH "\$ORIGIN:\$ORIGIN/bin:\$ORIGIN/../lib:\$ORIGIN/lib") # Distribution-specific optimizations if(LINUX_DISTRO MATCHES "ubuntu|debian") diff --git a/demo_advanced_lsp.cpp b/demo_advanced_lsp.cpp index 44a77db7..ea3505f0 100644 --- a/demo_advanced_lsp.cpp +++ b/demo_advanced_lsp.cpp @@ -1,7 +1,7 @@ /** * @file demo_advanced_lsp.cpp * @brief Demo application testing all advanced LSP features - * + * * Tests: * - Go-to-Definition (F12) * - Find References (Shift+F12) @@ -9,18 +9,20 @@ * - Code Formatting (Shift+Alt+F) */ -#include "bolt/editor/lsp_client.hpp" -#include "bolt/editor/lsp_server_configs.hpp" -#include "bolt/editor/lsp_protocol.hpp" -#include -#include #include -#include #include +#include +#include +#include -using namespace bolt::lsp; +#include "bolt/editor/lsp_client.hpp" +#include "bolt/editor/lsp_protocol.hpp" +#include "bolt/editor/lsp_server_configs.hpp" + +using namespace bolt::lsp; // NOLINT(build/namespaces) // Test file content with multiple symbols and references +// clang-format off const char* TEST_CPP_CODE = R"( #include #include @@ -66,6 +68,7 @@ int main() { return 0; } )"; +// clang-format on void printSeparator(const std::string& title) { std::cout << "\n" << std::string(60, '=') << "\n"; @@ -75,8 +78,7 @@ void printSeparator(const std::string& title) { void printLocation(const Location& loc) { std::cout << " ๐Ÿ“ " << loc.uri << "\n"; - std::cout << " Line " << loc.range.start.line + 1 - << ", Col " << loc.range.start.character + 1 << "\n"; + std::cout << " Line " << loc.range.start.line + 1 << ", Col " << loc.range.start.character + 1 << "\n"; } void printSymbol(const DocumentSymbol& sym, int indent = 0) { @@ -87,15 +89,14 @@ void printSymbol(const DocumentSymbol& sym, int indent = 0) { } std::cout << " [" << static_cast(sym.kind) << "]"; std::cout << " @ line " << sym.selectionRange.start.line + 1 << "\n"; - + for (const auto& child : sym.children) { printSymbol(child, indent + 1); } } void printTextEdit(const TextEdit& edit) { - std::cout << " โœ๏ธ Lines " << edit.range.start.line + 1 - << "-" << edit.range.end.line + 1 << ": "; + std::cout << " โœ๏ธ Lines " << edit.range.start.line + 1 << "-" << edit.range.end.line + 1 << ": "; if (edit.newText.length() > 50) { std::cout << edit.newText.substr(0, 50) << "...\n"; } else { @@ -115,7 +116,7 @@ int main() { std::string testDir = "/tmp/bolt_advanced_lsp_test"; std::filesystem::create_directories(testDir); std::string testFile = testDir + "/test_advanced.cpp"; - + { std::ofstream ofs(testFile); ofs << TEST_CPP_CODE; @@ -127,16 +128,16 @@ int main() { std::cerr << "โŒ clangd not available. Please install clangd.\n"; return 1; } - + auto config = LspServerConfigs::getConfigForLanguage("cpp"); config.rootPath = testDir; - + std::cout << "โœ… clangd available: " << config.serverCommand << "\n"; // Create and connect LSP client auto connection = std::make_unique(); LspClient client(std::move(connection)); - + if (!client.connect(config)) { std::cerr << "โŒ Failed to connect to clangd\n"; return 1; @@ -145,11 +146,9 @@ int main() { // Initialize bool initSuccess = false; - client.initialize([&initSuccess](bool success) { - initSuccess = success; - }); + client.initialize([&initSuccess](bool success) { initSuccess = success; }); std::this_thread::sleep_for(std::chrono::milliseconds(500)); - + if (!initSuccess) { std::cerr << "โŒ Failed to initialize LSP session\n"; return 1; @@ -171,25 +170,25 @@ int main() { // ======================================================================== printSeparator("Test 1: Go-to-Definition"); std::cout << "Testing definition of 'Calculator' at line 27 (calc.add)\n"; - + std::vector definitions; bool defReceived = false; - + TextDocumentPositionParams defParams; defParams.textDocument.uri = doc.uri; - defParams.position.line = 26; // Line with "calc.add" + defParams.position.line = 26; // Line with "calc.add" defParams.position.character = 4; // Position of "calc" - + client.definition(defParams, [&definitions, &defReceived](const std::vector& locs) { definitions = locs; defReceived = true; }); - + // Wait for response for (int i = 0; i < 50 && !defReceived; ++i) { std::this_thread::sleep_for(std::chrono::milliseconds(100)); } - + if (defReceived && !definitions.empty()) { std::cout << "โœ… Go-to-Definition: Found " << definitions.size() << " definition(s)\n"; for (const auto& loc : definitions) { @@ -204,25 +203,25 @@ int main() { // ======================================================================== printSeparator("Test 2: Find References"); std::cout << "Testing references to 'add' method\n"; - + std::vector references; bool refsReceived = false; - + TextDocumentPositionParams refParams; refParams.textDocument.uri = doc.uri; - refParams.position.line = 8; // Line with "int add(int a, int b)" + refParams.position.line = 8; // Line with "int add(int a, int b)" refParams.position.character = 8; // Position of "add" - + client.references(refParams, [&references, &refsReceived](const std::vector& locs) { references = locs; refsReceived = true; }); - + // Wait for response for (int i = 0; i < 50 && !refsReceived; ++i) { std::this_thread::sleep_for(std::chrono::milliseconds(100)); } - + if (refsReceived && !references.empty()) { std::cout << "โœ… Find References: Found " << references.size() << " reference(s)\n"; for (const auto& loc : references) { @@ -237,23 +236,23 @@ int main() { // ======================================================================== printSeparator("Test 3: Document Symbols"); std::cout << "Testing document symbols (outline)\n"; - + std::vector symbols; bool symsReceived = false; - + TextDocumentIdentifier symDocId; symDocId.uri = doc.uri; - + client.documentSymbol(symDocId, [&symbols, &symsReceived](const std::vector& syms) { symbols = syms; symsReceived = true; }); - + // Wait for response for (int i = 0; i < 50 && !symsReceived; ++i) { std::this_thread::sleep_for(std::chrono::milliseconds(100)); } - + if (symsReceived && !symbols.empty()) { std::cout << "โœ… Document Symbols: Found " << symbols.size() << " top-level symbol(s)\n"; for (const auto& sym : symbols) { @@ -268,27 +267,27 @@ int main() { // ======================================================================== printSeparator("Test 4: Code Formatting"); std::cout << "Testing document formatting\n"; - + std::vector edits; bool fmtReceived = false; - + TextDocumentIdentifier fmtDocId; fmtDocId.uri = doc.uri; - + FormattingOptions fmtOpts; fmtOpts.tabSize = 4; fmtOpts.insertSpaces = true; - + client.formatting(fmtDocId, fmtOpts, [&edits, &fmtReceived](const std::vector& e) { edits = e; fmtReceived = true; }); - + // Wait for response for (int i = 0; i < 50 && !fmtReceived; ++i) { std::this_thread::sleep_for(std::chrono::milliseconds(100)); } - + if (fmtReceived) { if (edits.empty()) { std::cout << "โœ… Code Formatting: Document already formatted (no changes needed)\n"; @@ -306,12 +305,12 @@ int main() { // Cleanup // ======================================================================== printSeparator("Cleanup"); - + TextDocumentIdentifier closeDocId; closeDocId.uri = doc.uri; client.didCloseTextDocument(closeDocId); std::cout << "โœ… Document closed\n"; - + client.shutdown([](bool success) {}); std::this_thread::sleep_for(std::chrono::milliseconds(200)); client.disconnect(); @@ -319,12 +318,13 @@ int main() { // Summary printSeparator("Summary"); + const auto verdict = [](bool passed) { return passed ? "โœ… PASSED" : "โš ๏ธ PARTIAL"; }; std::cout << "Advanced LSP Features Test Results:\n"; - std::cout << " โ€ข Go-to-Definition: " << (defReceived && !definitions.empty() ? "โœ… PASSED" : "โš ๏ธ PARTIAL") << "\n"; - std::cout << " โ€ข Find References: " << (refsReceived && !references.empty() ? "โœ… PASSED" : "โš ๏ธ PARTIAL") << "\n"; - std::cout << " โ€ข Document Symbols: " << (symsReceived && !symbols.empty() ? "โœ… PASSED" : "โš ๏ธ PARTIAL") << "\n"; - std::cout << " โ€ข Code Formatting: " << (fmtReceived ? "โœ… PASSED" : "โš ๏ธ PARTIAL") << "\n"; - + std::cout << " โ€ข Go-to-Definition: " << verdict(defReceived && !definitions.empty()) << "\n"; + std::cout << " โ€ข Find References: " << verdict(refsReceived && !references.empty()) << "\n"; + std::cout << " โ€ข Document Symbols: " << verdict(symsReceived && !symbols.empty()) << "\n"; + std::cout << " โ€ข Code Formatting: " << verdict(fmtReceived) << "\n"; + std::cout << "\nNote: Some features may show partial results on first run due to\n"; std::cout << "clangd needing time to build its index. Re-running typically shows\n"; std::cout << "complete results.\n"; diff --git a/demo_ai_code_completion_live.cpp b/demo_ai_code_completion_live.cpp index 9de09c94..ab1fe233 100644 --- a/demo_ai_code_completion_live.cpp +++ b/demo_ai_code_completion_live.cpp @@ -1,30 +1,32 @@ -#include "bolt/ai/llama_completion_provider.hpp" -#include "bolt/ai/ai_code_generator.hpp" #include #include +#include "bolt/ai/ai_code_generator.hpp" +#include "bolt/ai/llama_completion_provider.hpp" + int main() { std::cout << "=== AI-Powered Code Completion Demo ===\n\n"; - + // 1. Initialize the Llama completion provider std::cout << "Initializing AI completion provider...\n"; auto llama_provider = std::make_unique(); - + if (!llama_provider->initialize()) { std::cerr << "โŒ Failed to initialize Llama provider.\n"; std::cerr << "Make sure a GGUF model is available in ./models/\n"; return 1; } - + std::cout << "โœ… AI provider initialized\n"; std::cout << "Model: " << llama_provider->getModelInfo() << "\n\n"; - + // 2. Test code completion scenarios std::cout << "=== Test 1: Function Completion ===\n"; - + bolt::CodeContext context1; context1.language = "cpp"; context1.filePath = "example.cpp"; + // clang-format off context1.content = R"(#include #include @@ -39,20 +41,21 @@ int calculateSum(const std::vector& numbers) { // Function to calculate the average )"; + // clang-format on context1.cursorPosition = context1.content.length(); - + auto completions1 = llama_provider->generateCompletions(context1, "", 3); - + std::cout << "Code before cursor:\n" << context1.content << "โ–ˆ\n\n"; std::cout << "AI Suggestions:\n"; for (size_t i = 0; i < completions1.size(); ++i) { std::cout << (i + 1) << ". " << completions1[i].label << "\n"; std::cout << " Type: " << static_cast(completions1[i].kind) << "\n\n"; } - + // 3. Test class member completion std::cout << "\n=== Test 2: Class Member Completion ===\n"; - + bolt::CodeContext context2; context2.language = "cpp"; context2.content = R"(class DataProcessor { @@ -69,36 +72,34 @@ int calculateSum(const std::vector& numbers) { // Add a method to get the data size )"; context2.cursorPosition = context2.content.length(); - + auto completions2 = llama_provider->generateCompletions(context2, "", 3); - + std::cout << "Code before cursor:\n" << context2.content << "โ–ˆ\n\n"; std::cout << "AI Suggestions:\n"; for (size_t i = 0; i < completions2.size(); ++i) { std::cout << (i + 1) << ". " << completions2[i].label << "\n\n"; } - + // 4. Test with AIEnhancedCodeGenerator std::cout << "\n=== Test 3: Full Code Generation ===\n"; - + auto code_generator = std::make_unique(); code_generator->setAIProvider(std::move(llama_provider)); - + bolt::CodeGenerationContext gen_context; gen_context.language = "cpp"; gen_context.projectContext = "A simple data processing application"; - - auto generated_func = code_generator->generateFunction( - "a function that finds the maximum element in a vector", - gen_context - ); - + + auto generated_func = + code_generator->generateFunction("a function that finds the maximum element in a vector", gen_context); + std::cout << "Generated Function:\n"; std::cout << "Description: " << generated_func.description << "\n"; std::cout << "Code:\n" << generated_func.code << "\n"; std::cout << "Confidence: " << generated_func.confidence << "\n"; - + std::cout << "\n=== Demo Complete ===\n"; - + return 0; } diff --git a/demo_ai_completion.cpp b/demo_ai_completion.cpp index 889b8e4e..648f9df1 100644 --- a/demo_ai_completion.cpp +++ b/demo_ai_completion.cpp @@ -1,24 +1,26 @@ +#include +#include + #include "bolt/ai/ai_completion_provider.hpp" #include "bolt/editor/integrated_editor.hpp" -#include -#include -using namespace bolt; +using namespace bolt; // NOLINT(build/namespaces) void demonstrateAICompletion() { std::cout << "=== AI Code Completion Integration Demo ===\n\n"; - + // Get the integrated editor instance IntegratedEditor& editor = IntegratedEditor::getInstance(); - + std::cout << "1. Checking AI Completion Status:\n"; std::cout << " AI Completion Ready: " << (editor.isAICompletionReady() ? "YES" : "NO") << "\n"; std::cout << " AI Completion Enabled: " << (editor.isAICompletionEnabled() ? "YES" : "NO") << "\n"; std::cout << " Code Completion Active: " << (editor.isCodeCompletionActive() ? "YES" : "NO") << "\n\n"; - + // Create a test C++ file std::cout << "2. Opening test C++ file with content:\n"; std::string testFilePath = "demo.cpp"; + // clang-format off std::string testContent = R"(#include #include #include @@ -27,22 +29,23 @@ int main() { std:: return 0; })"; - + // clang-format on + std::cout << " File: " << testFilePath << "\n"; std::cout << " Content:\n"; std::cout << testContent << "\n\n"; - + editor.openDocument(testFilePath, testContent); - + // Test AI completions for std:: std::cout << "3. Getting AI completions for 'std::':\n"; auto completions = editor.getAICompletions(testFilePath, "std::", 5); - + if (!completions.empty()) { std::cout << " Found " << completions.size() << " completions:\n"; for (size_t i = 0; i < completions.size(); ++i) { - std::cout << " " << (i + 1) << ". " << std::left << std::setw(15) << completions[i].label - << " (" << completions[i].kind << ", score: " << completions[i].score << ")\n"; + std::cout << " " << (i + 1) << ". " << std::left << std::setw(15) << completions[i].label << " (" + << completions[i].kind << ", score: " << completions[i].score << ")\n"; if (!completions[i].detail.empty()) { std::cout << " " << completions[i].detail << "\n"; } @@ -51,37 +54,37 @@ int main() { std::cout << " No completions found.\n"; } std::cout << "\n"; - + // Test triggering completion std::cout << "4. Triggering code completion:\n"; editor.triggerCodeCompletion(testFilePath, "std::"); std::cout << " Code Completion Active: " << (editor.isCodeCompletionActive() ? "YES" : "NO") << "\n"; - + if (editor.isCodeCompletionActive()) { auto selected = editor.getSelectedCompletion(); std::cout << " Selected: " << selected.label << "\n"; - + std::cout << " Testing navigation...\n"; editor.selectNextCompletion(); selected = editor.getSelectedCompletion(); std::cout << " After next: " << selected.label << "\n"; - + editor.selectPreviousCompletion(); selected = editor.getSelectedCompletion(); std::cout << " After previous: " << selected.label << "\n"; } std::cout << "\n"; - + // Test different prefixes std::cout << "5. Testing different completion contexts:\n"; - + // Test for 'class' keyword auto classCompletions = editor.getAICompletions(testFilePath, "class", 3); std::cout << " 'class' prefix: " << classCompletions.size() << " completions\n"; for (const auto& comp : classCompletions) { std::cout << " " << comp.label << "\n"; } - + // Test for 'for' keyword auto forCompletions = editor.getAICompletions(testFilePath, "for", 3); std::cout << " 'for' prefix: " << forCompletions.size() << " completions\n"; @@ -89,41 +92,41 @@ int main() { std::cout << " " << comp.label << "\n"; } std::cout << "\n"; - + // Test AI enable/disable std::cout << "6. Testing AI enable/disable:\n"; editor.setAICompletionEnabled(false); - std::cout << " AI Disabled - Completions for 'std::': " + std::cout << " AI Disabled - Completions for 'std::': " << editor.getAICompletions(testFilePath, "std::", 3).size() << "\n"; - + editor.setAICompletionEnabled(true); - std::cout << " AI Re-enabled - Completions for 'std::': " + std::cout << " AI Re-enabled - Completions for 'std::': " << editor.getAICompletions(testFilePath, "std::", 3).size() << "\n"; std::cout << "\n"; - + // Clean up if (editor.isCodeCompletionActive()) { editor.cancelCompletion(); } - + std::cout << "7. Final state:\n"; std::cout << " Code Completion Active: " << (editor.isCodeCompletionActive() ? "YES" : "NO") << "\n"; std::cout << " AI Completion Enabled: " << (editor.isAICompletionEnabled() ? "YES" : "NO") << "\n"; - + std::cout << "\n=== Demo Complete ===\n"; } void demonstrateAIProviderDirectly() { std::cout << "\n=== Direct AI Provider Demo ===\n\n"; - + // Test the AI provider directly MockAICompletionProvider provider; - + std::cout << "1. Initializing AI Provider:\n"; std::cout << " Ready before init: " << (provider.isReady() ? "YES" : "NO") << "\n"; provider.initialize(); std::cout << " Ready after init: " << (provider.isReady() ? "YES" : "NO") << "\n\n"; - + // Test C++ context std::cout << "2. Testing C++ completion context:\n"; CodeContext cppContext; @@ -133,39 +136,39 @@ void demonstrateAIProviderDirectly() { cppContext.line = 1; cppContext.column = 9; cppContext.language = "cpp"; - + auto completions = provider.generateCompletions(cppContext, "std::", 5); std::cout << " Generated " << completions.size() << " completions for 'std::':\n"; for (const auto& comp : completions) { std::cout << " " << comp.label << " (" << comp.kind << ")\n"; } std::cout << "\n"; - + // Test different context std::cout << "3. Testing different contexts:\n"; cppContext.content = "class MyClass {\n \n};"; cppContext.cursorPosition = 16; - + completions = provider.generateCompletions(cppContext, "for", 3); std::cout << " 'for' in class context: " << completions.size() << " completions\n"; - + completions = provider.generateCompletions(cppContext, "", 3); std::cout << " Empty prefix: " << completions.size() << " completions\n"; - + provider.shutdown(); std::cout << " Ready after shutdown: " << (provider.isReady() ? "YES" : "NO") << "\n"; - + std::cout << "\n=== AI Provider Demo Complete ===\n"; } int main() { std::cout << "Bolt C++ AI Code Completion Integration Demo\n"; std::cout << "============================================\n\n"; - + try { demonstrateAICompletion(); demonstrateAIProviderDirectly(); - + std::cout << "\nโœ… All demonstrations completed successfully!\n"; std::cout << "\nAI Code Completion has been successfully integrated with the editor.\n"; std::cout << "Features available:\n"; @@ -176,11 +179,10 @@ int main() { std::cout << " - Accept (Enter) and Cancel (Escape) operations\n"; std::cout << " - Enable/disable AI completions\n"; std::cout << " - Mock AI provider ready for real AI integration\n"; - + return 0; - } catch (const std::exception& e) { std::cerr << "โŒ Error during demonstration: " << e.what() << "\n"; return 1; } -} \ No newline at end of file +} diff --git a/demo_ai_config.cpp b/demo_ai_config.cpp index f92b175c..5e2aced3 100644 --- a/demo_ai_config.cpp +++ b/demo_ai_config.cpp @@ -1,45 +1,46 @@ -#include "bolt/ai/enhanced_ai_manager.hpp" -#include "bolt/ai/ai_http_client.hpp" #include #include +#include "bolt/ai/ai_http_client.hpp" +#include "bolt/ai/enhanced_ai_manager.hpp" + int main() { std::cout << "๐Ÿš€ Bolt AI Chat Configuration Demo" << std::endl; std::cout << "==================================" << std::endl << std::endl; - + try { // Initialize enhanced AI manager std::cout << "๐Ÿ”ง Initializing Enhanced AI Manager..." << std::endl; bolt::ai::EnhancedAIManager ai_manager; - + // Run quick setup wizard std::cout << "\n๐Ÿง™ Running Quick Setup Wizard..." << std::endl; bool setup_success = bolt::ai::AutoSetup::quick_setup_wizard(); - + if (!setup_success) { std::cout << "\nโš ๏ธ No AI providers detected. Let's configure one manually." << std::endl; - + // Show available configurations auto recommended = bolt::ai::AIHttpClientFactory::get_recommended_configs(); std::cout << "\n๐Ÿ“‹ Recommended configurations:" << std::endl; for (size_t i = 0; i < recommended.size(); ++i) { - std::cout << " " << (i + 1) << ". " << recommended[i].base_url - << " (" << (int)recommended[i].api_type << ")" << std::endl; + std::cout << " " << (i + 1) << ". " << recommended[i].base_url << " (" + << static_cast(recommended[i].api_type) << ")" << std::endl; } } - + // Test current configuration std::cout << "\n๐Ÿ” Testing current configuration..." << std::endl; bool is_ready = ai_manager.is_ready(); std::cout << "AI Manager ready: " << (is_ready ? "โœ… YES" : "โŒ NO") << std::endl; - + if (is_ready) { std::cout << "Current provider: " << ai_manager.get_current_provider() << std::endl; - + // Test a simple chat std::cout << "\n๐Ÿ’ฌ Testing AI chat..." << std::endl; auto response = ai_manager.chat("Hello! Can you help me with C++ programming?", "test_session"); - + if (response.success) { std::cout << "โœ… Chat test successful!" << std::endl; std::cout << "Response: " << response.response << std::endl; @@ -47,19 +48,19 @@ int main() { } else { std::cout << "โŒ Chat test failed: " << response.error << std::endl; } - + // Test code completion std::cout << "\n๐Ÿš€ Testing code completion..." << std::endl; std::string test_code = "std::vector numbers = {1, 2, 3, 4, 5};\nfor ("; auto completion_response = ai_manager.complete_code(test_code, "cpp"); - + if (completion_response.success) { std::cout << "โœ… Code completion test successful!" << std::endl; std::cout << "Completion: " << completion_response.response << std::endl; } else { std::cout << "โŒ Code completion test failed: " << completion_response.error << std::endl; } - + // Show statistics std::cout << "\n๐Ÿ“Š AI Statistics:" << std::endl; auto stats = ai_manager.get_statistics(); @@ -69,7 +70,7 @@ int main() { std::cout << " Avg response time: " << stats.average_inference_time_ms << " ms" << std::endl; std::cout << " Tokens generated: " << stats.total_tokens_generated << std::endl; } - + // List available providers std::cout << "\n๐Ÿ”ง Available Providers:" << std::endl; auto providers = ai_manager.list_providers(); @@ -77,9 +78,9 @@ int main() { std::string status = provider.is_active ? " (ACTIVE)" : ""; std::cout << " โ€ข " << provider.name << ": " << provider.config.base_url << status << std::endl; } - + std::cout << "\nโœ… Configuration demo completed!" << std::endl; - + if (is_ready) { std::cout << "\n๐ŸŽ‰ Your AI chat is ready to use!" << std::endl; std::cout << "๐Ÿ’ก Start the GUI application to chat with the AI assistant." << std::endl; @@ -87,11 +88,10 @@ int main() { std::cout << "\nโš ๏ธ AI chat is not yet configured." << std::endl; std::cout << "๐Ÿ’ก Follow the setup instructions above or configure manually." << std::endl; } - } catch (const std::exception& e) { std::cerr << "โŒ Error: " << e.what() << std::endl; return 1; } - + return 0; } diff --git a/demo_ai_infrastructure.cpp b/demo_ai_infrastructure.cpp index 40d217ad..533750bc 100644 --- a/demo_ai_infrastructure.cpp +++ b/demo_ai_infrastructure.cpp @@ -1,30 +1,30 @@ #include + #include "bolt/ai/ggml.hpp" #include "bolt/ai/ggml_wrapper.hpp" #include "bolt/ai/rwkv_wrapper.hpp" void demonstrateGGML() { std::cout << "=== GGML Integration Demo ===" << std::endl; - + try { // Create GGML context - bolt::GGMLContext context(1024 * 1024); // 1MB + bolt::GGMLContext context(1024 * 1024); // 1MB std::cout << "โœ“ GGML Context created successfully" << std::endl; - + // Create simple tensors auto* tensor_a = ggml_new_tensor_1d(context.get(), GGML_TYPE_F32, 10); auto* tensor_b = ggml_new_tensor_1d(context.get(), GGML_TYPE_F32, 10); std::cout << "โœ“ Created tensors: " << ggml_nelements(tensor_a) << " elements each" << std::endl; - + // Perform operations auto* result = ggml_add(context.get(), tensor_a, tensor_b); std::cout << "โœ“ Tensor addition operation created" << std::endl; - + // Create computation graph auto* graph = ggml_new_graph_custom(context.get(), GGML_DEFAULT_GRAPH_SIZE, true); ggml_build_forward_expand(graph, result); std::cout << "โœ“ Computation graph built successfully" << std::endl; - } catch (const std::exception& e) { std::cerr << "โœ— Error: " << e.what() << std::endl; } @@ -32,18 +32,17 @@ void demonstrateGGML() { void demonstrateRWKV() { std::cout << "\n=== RWKV Integration Demo ===" << std::endl; - + try { auto& wrapper = bolt::RWKVWrapper::getInstance(); std::cout << "โœ“ RWKV Wrapper instance obtained" << std::endl; - + std::cout << "Model parameters:" << std::endl; std::cout << " - Layers: " << wrapper.getNumLayers() << std::endl; std::cout << " - Embedding dimension: " << wrapper.getEmbedDim() << std::endl; std::cout << " - Initialized: " << (wrapper.isInitialized() ? "Yes" : "No") << std::endl; - + std::cout << "โœ“ RWKV API accessible and functional" << std::endl; - } catch (const std::exception& e) { std::cerr << "โœ— Error: " << e.what() << std::endl; } @@ -52,14 +51,14 @@ void demonstrateRWKV() { int main() { std::cout << "Bolt C++ AI Infrastructure Demo" << std::endl; std::cout << "===============================" << std::endl; - + demonstrateGGML(); demonstrateRWKV(); - + std::cout << "\n=== Summary ===" << std::endl; std::cout << "โœ“ GGML library successfully integrated" << std::endl; std::cout << "โœ“ RWKV wrapper implemented with GGML backend" << std::endl; std::cout << "โœ“ Core AI infrastructure is ready for model loading and inference" << std::endl; - + return 0; -} \ No newline at end of file +} diff --git a/demo_benchmark_suite.cpp b/demo_benchmark_suite.cpp index f3c6b989..2c7dd2c9 100644 --- a/demo_benchmark_suite.cpp +++ b/demo_benchmark_suite.cpp @@ -1,16 +1,17 @@ -#include "include/bolt/core/performance_profiler.hpp" -#include "include/bolt/core/logging.hpp" -#include -#include -#include #include +#include #include -#include +#include #include -#include +#include +#include #include +#include + +#include "include/bolt/core/logging.hpp" +#include "include/bolt/core/performance_profiler.hpp" -using namespace bolt; +using namespace bolt; // NOLINT(build/namespaces) // Simple benchmark structure struct SimpleBenchmark { @@ -31,16 +32,19 @@ struct BenchmarkResult { int successfulRuns; int failedRuns; bool isValid() const { return successfulRuns > 0; } - double getSuccessRate() const { return successfulRuns > 0 ? (double)successfulRuns / (successfulRuns + failedRuns) : 0.0; } + double getSuccessRate() const { + return successfulRuns > 0 ? static_cast(successfulRuns) / (successfulRuns + failedRuns) : 0.0; + } }; class SimpleBenchmarkSuite { -private: + private: std::vector benchmarks_; bool verbose_; - + double calculateStandardDeviation(const std::vector& values, double mean) { - if (values.empty()) return 0.0; + if (values.empty()) + return 0.0; double variance = 0.0; for (double value : values) { variance += (value - mean) * (value - mean); @@ -48,52 +52,50 @@ class SimpleBenchmarkSuite { variance /= values.size(); return std::sqrt(variance); } - -public: + + public: SimpleBenchmarkSuite() : verbose_(false) {} - + void setVerbose(bool verbose) { verbose_ = verbose; } - - void registerBenchmark(const std::string& name, const std::string& category, - const std::string& description, int iterations, - std::function function) { + + void registerBenchmark(const std::string& name, const std::string& category, const std::string& description, + int iterations, std::function function) { benchmarks_.push_back({name, category, description, iterations, function}); if (verbose_) { std::cout << "Registered benchmark: " << name << " (" << category << ")\n"; } } - + BenchmarkResult runBenchmark(const SimpleBenchmark& benchmark) { BenchmarkResult result; result.name = benchmark.name; result.category = benchmark.category; result.successfulRuns = 0; result.failedRuns = 0; - + std::vector durations; auto& profiler = PerformanceProfiler::getInstance(); profiler.enable(); - + if (verbose_) { std::cout << "Running " << benchmark.name << " (" << benchmark.iterations << " iterations)...\n"; } - + for (int i = 0; i < benchmark.iterations; ++i) { try { auto start = std::chrono::high_resolution_clock::now(); - + // Use profiler for this run auto metric = profiler.startMetric(benchmark.name + "_run_" + std::to_string(i), benchmark.category); - + benchmark.function(); - + profiler.endMetric(metric); - + auto end = std::chrono::high_resolution_clock::now(); double duration = std::chrono::duration(end - start).count(); durations.push_back(duration); result.successfulRuns++; - } catch (const std::exception& e) { result.failedRuns++; if (verbose_) { @@ -101,56 +103,58 @@ class SimpleBenchmarkSuite { } } } - + if (!durations.empty()) { result.averageDurationMs = std::accumulate(durations.begin(), durations.end(), 0.0) / durations.size(); result.minDurationMs = *std::min_element(durations.begin(), durations.end()); result.maxDurationMs = *std::max_element(durations.begin(), durations.end()); result.standardDeviationMs = calculateStandardDeviation(durations, result.averageDurationMs); } - + return result; } - + std::vector runAllBenchmarks() { std::vector results; - + std::cout << "Running " << benchmarks_.size() << " benchmarks...\n\n"; - + for (const auto& benchmark : benchmarks_) { auto result = runBenchmark(benchmark); results.push_back(result); } - + return results; } - + std::vector runCategory(const std::string& category) { std::vector results; - + for (const auto& benchmark : benchmarks_) { if (benchmark.category == category) { auto result = runBenchmark(benchmark); results.push_back(result); } } - + return results; } - + void generateReport(const std::vector& results, const std::string& filename) { std::ofstream file(filename); if (!file.is_open()) { std::cerr << "Failed to open file: " << filename << std::endl; return; } - + file << "{\n"; file << " \"benchmark_suite_version\": \"1.0.0\",\n"; - file << " \"timestamp\": \"" << std::chrono::duration_cast( - std::chrono::system_clock::now().time_since_epoch()).count() << "\",\n"; + file << " \"timestamp\": \"" + << std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()) + .count() + << "\",\n"; file << " \"results\": [\n"; - + for (size_t i = 0; i < results.size(); ++i) { const auto& result = results[i]; file << " {\n"; @@ -164,43 +168,39 @@ class SimpleBenchmarkSuite { file << " \"failed_runs\": " << result.failedRuns << ",\n"; file << " \"success_rate\": " << result.getSuccessRate() << "\n"; file << " }"; - if (i < results.size() - 1) file << ","; + if (i < results.size() - 1) + file << ","; file << "\n"; } - + file << " ]\n"; file << "}\n"; - + file.close(); std::cout << "Report generated: " << filename << "\n"; } - + void printSummary(const std::vector& results) { std::cout << "\n=== Benchmark Summary ===\n"; - std::cout << std::left << std::setw(25) << "Benchmark" - << std::setw(10) << "Category" - << std::setw(15) << "Avg Time (ms)" - << std::setw(15) << "Min Time (ms)" - << std::setw(15) << "Max Time (ms)" + std::cout << std::left << std::setw(25) << "Benchmark" << std::setw(10) << "Category" << std::setw(15) + << "Avg Time (ms)" << std::setw(15) << "Min Time (ms)" << std::setw(15) << "Max Time (ms)" << std::setw(12) << "Success Rate" << "Status\n"; std::cout << std::string(95, '-') << "\n"; - + for (const auto& result : results) { std::string status = result.isValid() ? "SUCCESS" : "FAILED"; - std::cout << std::left << std::setw(25) << result.name.substr(0, 24) - << std::setw(10) << result.category + std::cout << std::left << std::setw(25) << result.name.substr(0, 24) << std::setw(10) << result.category << std::setw(15) << std::fixed << std::setprecision(3) << result.averageDurationMs - << std::setw(15) << std::fixed << std::setprecision(3) << result.minDurationMs - << std::setw(15) << std::fixed << std::setprecision(3) << result.maxDurationMs - << std::setw(12) << std::fixed << std::setprecision(1) << (result.getSuccessRate() * 100) << "%" - << status << "\n"; + << std::setw(15) << std::fixed << std::setprecision(3) << result.minDurationMs << std::setw(15) + << std::fixed << std::setprecision(3) << result.maxDurationMs << std::setw(12) << std::fixed + << std::setprecision(1) << (result.getSuccessRate() * 100) << "%" << status << "\n"; } - + // Summary statistics int totalSuccessful = 0, totalFailed = 0; double totalTime = 0.0; - + for (const auto& result : results) { if (result.isValid()) { totalSuccessful++; @@ -209,14 +209,14 @@ class SimpleBenchmarkSuite { totalFailed++; } } - + std::cout << "\n"; std::cout << "Total Benchmarks: " << results.size() << "\n"; std::cout << "Successful: " << totalSuccessful << "\n"; std::cout << "Failed: " << totalFailed << "\n"; if (totalSuccessful > 0) { - std::cout << "Average Time: " << std::fixed << std::setprecision(3) - << (totalTime / totalSuccessful) << " ms\n"; + std::cout << "Average Time: " << std::fixed << std::setprecision(3) << (totalTime / totalSuccessful) + << " ms\n"; } } }; @@ -226,7 +226,7 @@ void memoryAllocationBenchmark() { std::vector allocations; const size_t numAllocations = 1000; const size_t allocationSize = 1024; - + // Allocate for (size_t i = 0; i < numAllocations; ++i) { void* ptr = malloc(allocationSize); @@ -234,7 +234,7 @@ void memoryAllocationBenchmark() { allocations.push_back(ptr); } } - + // Deallocate for (void* ptr : allocations) { if (ptr) { @@ -246,19 +246,19 @@ void memoryAllocationBenchmark() { void stringOperationsBenchmark() { const int numStrings = 500; std::vector strings; - + // String creation for (int i = 0; i < numStrings; ++i) { strings.emplace_back("Demo string " + std::to_string(i) + " with content"); } - + // String manipulation for (auto& str : strings) { str += " modified"; str = str.substr(0, str.length() / 2); std::transform(str.begin(), str.end(), str.begin(), ::toupper); } - + // String searching int found = 0; for (const auto& str : strings) { @@ -271,22 +271,22 @@ void stringOperationsBenchmark() { void vectorOperationsBenchmark() { std::vector vec; const int numElements = 5000; - + // Push back for (int i = 0; i < numElements; ++i) { vec.push_back(i); } - + // Random access std::random_device rd; std::mt19937 gen(rd()); std::uniform_int_distribution<> dis(0, numElements - 1); - + int sum = 0; for (int i = 0; i < 1000; ++i) { sum += vec[dis(gen)]; } - + // Erase elements while (!vec.empty() && vec.size() > numElements / 2) { vec.erase(vec.begin() + vec.size() / 2); @@ -298,9 +298,9 @@ void threadingBenchmark() { const int operationsPerThread = 500; std::mutex testMutex; int sharedCounter = 0; - + std::vector threads; - + for (int i = 0; i < numThreads; ++i) { threads.emplace_back([&]() { for (int j = 0; j < operationsPerThread; ++j) { @@ -309,7 +309,7 @@ void threadingBenchmark() { } }); } - + for (auto& thread : threads) { if (thread.joinable()) { thread.join(); @@ -321,7 +321,7 @@ void fileIoBenchmark() { const std::string filename = "/tmp/benchmark_demo_file.txt"; const std::string content = "Demo content for file I/O benchmark. "; const int numLines = 500; - + // Write file { std::ofstream file(filename); @@ -329,7 +329,7 @@ void fileIoBenchmark() { file << content << "Line " << i << std::endl; } } - + // Read file { std::ifstream file(filename); @@ -339,7 +339,7 @@ void fileIoBenchmark() { lineCount++; } } - + // Clean up std::remove(filename.c_str()); } @@ -347,14 +347,14 @@ void fileIoBenchmark() { int main(int argc, char* argv[]) { // Initialize logging LogManager::configureConsoleLogging(LogLevel::INFO, false); - + SimpleBenchmarkSuite suite; - + // Parse command line arguments bool verbose = false; std::string outputFile; std::string category; - + for (int i = 1; i < argc; ++i) { std::string arg = argv[i]; if (arg == "--verbose" || arg == "-v") { @@ -373,19 +373,22 @@ int main(int argc, char* argv[]) { return 0; } } - + suite.setVerbose(verbose); - + // Register benchmarks - suite.registerBenchmark("memory_allocation", "CORE", "Basic memory allocation and deallocation", 50, memoryAllocationBenchmark); - suite.registerBenchmark("string_operations", "CORE", "String creation, manipulation, and searching", 30, stringOperationsBenchmark); - suite.registerBenchmark("vector_operations", "CORE", "Vector operations performance", 20, vectorOperationsBenchmark); + suite.registerBenchmark("memory_allocation", "CORE", "Basic memory allocation and deallocation", 50, + memoryAllocationBenchmark); + suite.registerBenchmark("string_operations", "CORE", "String creation, manipulation, and searching", 30, + stringOperationsBenchmark); + suite.registerBenchmark("vector_operations", "CORE", "Vector operations performance", 20, + vectorOperationsBenchmark); suite.registerBenchmark("threading", "CORE", "Thread creation and synchronization", 10, threadingBenchmark); suite.registerBenchmark("file_io", "CORE", "File I/O operations", 5, fileIoBenchmark); - + std::cout << "Bolt Performance Benchmark Suite\n"; std::cout << "================================\n"; - + // Run benchmarks std::vector results; if (!category.empty()) { @@ -394,15 +397,15 @@ int main(int argc, char* argv[]) { } else { results = suite.runAllBenchmarks(); } - + // Print summary suite.printSummary(results); - + // Generate report if requested if (!outputFile.empty()) { suite.generateReport(results, outputFile); } - + std::cout << "\nBenchmark execution completed.\n"; return 0; -} \ No newline at end of file +} diff --git a/demo_code_analyzer.cpp b/demo_code_analyzer.cpp index acdf31b2..bee479d0 100644 --- a/demo_code_analyzer.cpp +++ b/demo_code_analyzer.cpp @@ -1,25 +1,27 @@ +#include +#include + #include "bolt/core/code_analyzer.hpp" #include "bolt/core/logging.hpp" -#include -#include -using namespace bolt; +using namespace bolt; // NOLINT(build/namespaces) void demonstrateBasicAnalysis() { std::cout << "\n=== Basic Code Analysis Demo ===\n"; - + // Create analyzer instance CodeAnalyzer analyzer; - + // Enable performance profiling analyzer.enablePerformanceProfiling(true); - + // Set up metrics callback analyzer.setMetricsCallback([](const std::string& metric, double value) { std::cout << "Metric: " << metric << " = " << value << std::endl; }); - + // Create sample code with various issues for testing + // clang-format off std::string sampleCode = R"( #include #include @@ -69,58 +71,58 @@ class ExampleClass { // ... many more methods would trigger complexity warnings }; )"; - + // clang-format on + // Write sample code to temporary file std::string tempFile = "/tmp/sample_code.cpp"; std::ofstream file(tempFile); file << sampleCode; file.close(); - + // Analyze the sample file auto result = analyzer.analyzeFile(tempFile); - + std::cout << "\nAnalysis Results:\n"; std::cout << "Total Issues Found: " << result.issues.size() << std::endl; std::cout << "Analysis Time: " << result.analysisTimeMs << " ms\n"; - + // Show issues by severity std::cout << "\nIssues by Severity:\n"; std::cout << " Critical: " << result.getIssueCount(AnalysisSeverity::CRITICAL) << std::endl; std::cout << " Error: " << result.getIssueCount(AnalysisSeverity::ERROR) << std::endl; std::cout << " Warning: " << result.getIssueCount(AnalysisSeverity::WARNING) << std::endl; std::cout << " Info: " << result.getIssueCount(AnalysisSeverity::INFO) << std::endl; - + // Show issues by category std::cout << "\nIssues by Category:\n"; std::cout << " Complexity: " << result.getIssueCount(AnalysisCategory::COMPLEXITY) << std::endl; std::cout << " Security: " << result.getIssueCount(AnalysisCategory::SECURITY) << std::endl; std::cout << " Performance: " << result.getIssueCount(AnalysisCategory::PERFORMANCE) << std::endl; - + // Show detailed issues std::cout << "\nDetailed Issues:\n"; for (const auto& issue : result.issues) { - std::cout << " [" << static_cast(issue.severity) << "] " - << issue.message << std::endl; + std::cout << " [" << static_cast(issue.severity) << "] " << issue.message << std::endl; for (const auto& suggestion : issue.suggestions) { std::cout << " Suggestion: " << suggestion << std::endl; } } - + // Export results analyzer.exportResults(result, "json", "/tmp/analysis_results.json"); analyzer.exportResults(result, "text", "/tmp/analysis_results.txt"); - + std::cout << "\nResults exported to /tmp/analysis_results.json and /tmp/analysis_results.txt\n"; - + // Cleanup std::filesystem::remove(tempFile); } void demonstrateRefactoringSuggestions() { std::cout << "\n=== Refactoring Suggestions Demo ===\n"; - + RefactoringSuggestionEngine engine; - + std::string longFunctionCode = R"( void veryLongFunction() { // This function is intentionally long to trigger refactoring suggestions @@ -168,11 +170,11 @@ void duplicatedCode() { int z = x + y; } )"; - + auto suggestions = engine.generateSuggestionsForFile("example.cpp", longFunctionCode); - + std::cout << "Refactoring Suggestions Found: " << suggestions.size() << std::endl; - + for (const auto& suggestion : suggestions) { std::cout << "\nSuggestion: " << suggestion.title << std::endl; std::cout << " Description: " << suggestion.description << std::endl; @@ -186,21 +188,21 @@ void duplicatedCode() { void demonstrateAnalyzerConfiguration() { std::cout << "\n=== Analyzer Configuration Demo ===\n"; - + CodeAnalyzer analyzer; - + // Show registered analyzers auto analyzers = analyzer.getRegisteredAnalyzers(); std::cout << "Registered Analyzers:" << std::endl; for (const auto& name : analyzers) { - std::cout << " - " << name << " (enabled: " - << (analyzer.isAnalyzerEnabled(name) ? "yes" : "no") << ")" << std::endl; + std::cout << " - " << name << " (enabled: " << (analyzer.isAnalyzerEnabled(name) ? "yes" : "no") << ")" + << std::endl; } - + // Disable specific analyzers analyzer.enableAnalyzer("SecurityAnalyzer", false); std::cout << "\nDisabled SecurityAnalyzer" << std::endl; - + // Configure an analyzer std::unordered_map config; config["max_complexity"] = "15"; @@ -211,13 +213,14 @@ void demonstrateAnalyzerConfiguration() { void demonstrateProjectAnalysis() { std::cout << "\n=== Project Analysis Demo ===\n"; - + // Create a temporary project structure std::string projectPath = "/tmp/sample_project"; std::filesystem::create_directories(projectPath); - + // Create some sample files std::ofstream main_cpp(projectPath + "/main.cpp"); + // clang-format off main_cpp << R"( #include "utils.hpp" #include @@ -233,9 +236,11 @@ int main() { return 0; } )"; + // clang-format on main_cpp.close(); - + std::ofstream utils_hpp(projectPath + "/utils.hpp"); + // clang-format off utils_hpp << R"( #ifndef UTILS_HPP #define UTILS_HPP @@ -246,9 +251,11 @@ void utilityFunction(); #endif )"; + // clang-format on utils_hpp.close(); - + std::ofstream utils_cpp(projectPath + "/utils.cpp"); + // clang-format off utils_cpp << R"( #include "utils.hpp" #include @@ -258,87 +265,81 @@ void utilityFunction() { strcpy(buffer, "unsafe operation"); // Security issue } )"; + // clang-format on utils_cpp.close(); - + CodeAnalyzer analyzer; auto result = analyzer.analyzeProject(projectPath); - + std::cout << "Project Analysis Results:" << std::endl; std::cout << " Files analyzed: " << result.fileMetrics.size() << std::endl; std::cout << " Total issues: " << result.issues.size() << std::endl; std::cout << " Analysis time: " << result.analysisTimeMs << " ms" << std::endl; std::cout << " Dependencies found: " << result.dependencies.size() << std::endl; - + // Show overall metrics std::cout << "\nOverall Project Metrics:" << std::endl; std::cout << " Lines of Code: " << result.overallMetrics.linesOfCode << std::endl; std::cout << " Functions: " << result.overallMetrics.functionCount << std::endl; std::cout << " Classes: " << result.overallMetrics.classCount << std::endl; std::cout << " Cyclomatic Complexity: " << result.overallMetrics.cyclomaticComplexity << std::endl; - + // Generate and display report std::string report = analyzer.generateReport(result, "text"); std::cout << "\n" << report << std::endl; - + // Cleanup std::filesystem::remove_all(projectPath); } void demonstrateCustomAnalyzer() { std::cout << "\n=== Custom Analyzer Demo ===\n"; - + // Example of how to create a custom analyzer class CustomStyleAnalyzer : public ICodeAnalyzer { - public: + public: std::string getName() const override { return "CustomStyleAnalyzer"; } std::string getVersion() const override { return "1.0.0"; } - std::vector getSupportedExtensions() const override { - return {".cpp", ".hpp"}; - } + std::vector getSupportedExtensions() const override { return {".cpp", ".hpp"}; } AnalysisCategory getCategory() const override { return AnalysisCategory::STYLE; } - - std::vector analyzeFile(const std::string& filePath, - const std::string& content) override { + + std::vector analyzeFile(const std::string& filePath, const std::string& content) override { std::vector issues; - + // Check for missing header guards if (filePath.find(".hpp") != std::string::npos) { - if (content.find("#ifndef") == std::string::npos || - content.find("#define") == std::string::npos) { - AnalysisIssue issue("MISSING_HEADER_GUARD", - "Header file missing include guard", - AnalysisSeverity::WARNING, AnalysisCategory::STYLE); + if (content.find("#ifndef") == std::string::npos || content.find("#define") == std::string::npos) { + AnalysisIssue issue("MISSING_HEADER_GUARD", "Header file missing include guard", + AnalysisSeverity::WARNING, AnalysisCategory::STYLE); issue.filePath = filePath; issue.suggestions.push_back("Add #ifndef, #define, #endif header guard"); issues.push_back(issue); } } - + return issues; } - + std::vector analyzeProject(const std::string& projectPath) override { - return {}; // Not implemented for this demo + return {}; // Not implemented for this demo } - - CodeMetrics getMetrics(const std::string& filePath, - const std::string& content) override { + + CodeMetrics getMetrics(const std::string& filePath, const std::string& content) override { CodeMetrics metrics; - metrics.customMetrics["style_issues"] = - analyzeFile(filePath, content).size(); + metrics.customMetrics["style_issues"] = analyzeFile(filePath, content).size(); return metrics; } }; - + CodeAnalyzer analyzer; analyzer.registerAnalyzer(std::make_unique()); - + auto analyzers = analyzer.getRegisteredAnalyzers(); std::cout << "Analyzers after adding custom analyzer:" << std::endl; for (const auto& name : analyzers) { std::cout << " - " << name << std::endl; } - + // Test the custom analyzer std::string headerFile = "/tmp/test_header.hpp"; std::ofstream header(headerFile); @@ -350,16 +351,16 @@ class TestClass { }; )"; header.close(); - + auto result = analyzer.analyzeFile(headerFile); std::cout << "\nCustom analyzer found " << result.issues.size() << " issues" << std::endl; - + for (const auto& issue : result.issues) { if (issue.id == "MISSING_HEADER_GUARD") { std::cout << "Found style issue: " << issue.message << std::endl; } } - + std::filesystem::remove(headerFile); } @@ -368,17 +369,17 @@ int main() { // Initialize logging auto& logger = LogManager::getInstance(); logger.setLevel(LogLevel::INFO); - + std::cout << "=== Advanced Code Analysis Tools Demo ===\n"; std::cout << "This demo showcases the comprehensive code analysis capabilities\n"; std::cout << "implemented for the Bolt C++ IDE.\n"; - + demonstrateBasicAnalysis(); demonstrateRefactoringSuggestions(); demonstrateAnalyzerConfiguration(); demonstrateProjectAnalysis(); demonstrateCustomAnalyzer(); - + std::cout << "\n=== Demo Complete ===\n"; std::cout << "The advanced code analysis tools provide:\n"; std::cout << " โœ“ Complexity analysis (cyclomatic, nesting, maintainability)\n"; @@ -390,11 +391,10 @@ int main() { std::cout << " โœ“ Multiple export formats (JSON, text)\n"; std::cout << " โœ“ Integration with performance profiling\n"; std::cout << " โœ“ Configurable analysis parameters\n"; - + return 0; - } catch (const std::exception& e) { std::cerr << "Demo failed with exception: " << e.what() << std::endl; return 1; } -} \ No newline at end of file +} diff --git a/demo_code_analyzer_standalone.cpp b/demo_code_analyzer_standalone.cpp index 4c0592d1..7664f4bc 100644 --- a/demo_code_analyzer_standalone.cpp +++ b/demo_code_analyzer_standalone.cpp @@ -1,25 +1,30 @@ -#include -#include -#include -#include +#include +#include +#include #include +#include +#include #include #include -#include +#include #include -#include -#include +#include // Standalone implementation of advanced code analysis tools namespace bolt { -enum class AnalysisSeverity { - INFO, WARNING, ERROR, CRITICAL -}; +enum class AnalysisSeverity { INFO, WARNING, ERROR, CRITICAL }; enum class AnalysisCategory { - COMPLEXITY, MAINTAINABILITY, PERFORMANCE, SECURITY, - STYLE, DEPENDENCIES, MEMORY, TESTING, ARCHITECTURE + COMPLEXITY, + MAINTAINABILITY, + PERFORMANCE, + SECURITY, + STYLE, + DEPENDENCIES, + MEMORY, + TESTING, + ARCHITECTURE }; struct AnalysisIssue { @@ -31,9 +36,8 @@ struct AnalysisIssue { std::string filePath; size_t lineNumber; std::vector suggestions; - - AnalysisIssue(const std::string& issueId, const std::string& msg, - AnalysisSeverity sev, AnalysisCategory cat) + + AnalysisIssue(const std::string& issueId, const std::string& msg, AnalysisSeverity sev, AnalysisCategory cat) : id(issueId), message(msg), severity(sev), category(cat), lineNumber(0) {} }; @@ -51,59 +55,58 @@ struct CodeMetrics { }; class StandaloneCodeAnalyzer { -public: + public: std::vector analyzeFile(const std::string& filePath, const std::string& content) { std::vector issues; - + auto metrics = getMetrics(content); - + // Complexity analysis if (metrics.cyclomaticComplexity > 10) { - AnalysisIssue issue("COMPLEX_FUNCTION", - "High cyclomatic complexity: " + std::to_string(metrics.cyclomaticComplexity), - AnalysisSeverity::WARNING, AnalysisCategory::COMPLEXITY); + AnalysisIssue issue("COMPLEX_FUNCTION", + "High cyclomatic complexity: " + std::to_string(metrics.cyclomaticComplexity), + AnalysisSeverity::WARNING, AnalysisCategory::COMPLEXITY); issue.filePath = filePath; issue.suggestions.push_back("Consider breaking down complex functions into smaller ones"); issues.push_back(issue); } - + if (metrics.nestingDepth > 4) { - AnalysisIssue issue("DEEP_NESTING", - "Deep nesting detected: " + std::to_string(metrics.nestingDepth) + " levels", - AnalysisSeverity::WARNING, AnalysisCategory::COMPLEXITY); + AnalysisIssue issue("DEEP_NESTING", + "Deep nesting detected: " + std::to_string(metrics.nestingDepth) + " levels", + AnalysisSeverity::WARNING, AnalysisCategory::COMPLEXITY); issue.filePath = filePath; issue.suggestions.push_back("Extract nested logic into separate functions"); issues.push_back(issue); } - + // Security analysis auto securityIssues = checkSecurityIssues(content, filePath); issues.insert(issues.end(), securityIssues.begin(), securityIssues.end()); - + // Performance analysis auto performanceIssues = checkPerformanceIssues(content, filePath); issues.insert(issues.end(), performanceIssues.begin(), performanceIssues.end()); - + return issues; } - + CodeMetrics getMetrics(const std::string& content) { CodeMetrics metrics; - + std::istringstream stream(content); std::string line; - + while (std::getline(stream, line)) { metrics.physicalLines++; - + // Remove leading/trailing whitespace - line.erase(line.begin(), std::find_if(line.begin(), line.end(), [](unsigned char ch) { - return !std::isspace(ch); - })); - line.erase(std::find_if(line.rbegin(), line.rend(), [](unsigned char ch) { - return !std::isspace(ch); - }).base(), line.end()); - + line.erase(line.begin(), + std::find_if(line.begin(), line.end(), [](unsigned char ch) { return !std::isspace(ch); })); + line.erase( + std::find_if(line.rbegin(), line.rend(), [](unsigned char ch) { return !std::isspace(ch); }).base(), + line.end()); + if (line.empty()) { metrics.blankLines++; } else if (line.find("//") == 0 || line.find("/*") == 0) { @@ -112,24 +115,24 @@ class StandaloneCodeAnalyzer { metrics.linesOfCode++; } } - + metrics.cyclomaticComplexity = calculateCyclomaticComplexity(content); metrics.nestingDepth = calculateNestingDepth(content); metrics.functionCount = countFunctions(content); metrics.classCount = countClasses(content); - + // Calculate maintainability index if (metrics.linesOfCode > 0) { double complexity = static_cast(metrics.cyclomaticComplexity); double loc = static_cast(metrics.linesOfCode); - metrics.maintainabilityIndex = std::max(0.0, - 171.0 - 5.2 * std::log(complexity) - 0.23 * complexity - 16.2 * std::log(loc)); + metrics.maintainabilityIndex = + std::max(0.0, 171.0 - 5.2 * std::log(complexity) - 0.23 * complexity - 16.2 * std::log(loc)); } - + return metrics; } - -private: + + private: size_t calculateCyclomaticComplexity(const std::string& content) { size_t complexity = 1; std::regex decisionPoints(R"(\b(if|else\s+if|while|for|do|switch|case|catch|\?)\b)"); @@ -138,139 +141,148 @@ class StandaloneCodeAnalyzer { complexity += std::distance(iter, end); return complexity; } - + size_t calculateNestingDepth(const std::string& content) { size_t maxDepth = 0; size_t currentDepth = 0; - + for (char c : content) { if (c == '{') { currentDepth++; maxDepth = std::max(maxDepth, currentDepth); } else if (c == '}') { - if (currentDepth > 0) currentDepth--; + if (currentDepth > 0) + currentDepth--; } } return maxDepth; } - + size_t countFunctions(const std::string& content) { std::regex functionPattern(R"(\b\w+\s*\([^)]*\)\s*\{)"); std::sregex_iterator iter(content.begin(), content.end(), functionPattern); std::sregex_iterator end; return std::distance(iter, end); } - + size_t countClasses(const std::string& content) { std::regex classPattern(R"(\bclass\s+\w+)"); std::sregex_iterator iter(content.begin(), content.end(), classPattern); std::sregex_iterator end; return std::distance(iter, end); } - + std::vector checkSecurityIssues(const std::string& content, const std::string& filePath) { std::vector issues; - + // Check for unsafe buffer operations std::regex unsafeBufferOps(R"(\b(strcpy|strcat|sprintf|gets)\s*\()"); std::sregex_iterator iter(content.begin(), content.end(), unsafeBufferOps); std::sregex_iterator end; - + for (; iter != end; ++iter) { - AnalysisIssue issue("UNSAFE_BUFFER_OP", - "Unsafe buffer operation: " + (*iter)[1].str(), - AnalysisSeverity::ERROR, AnalysisCategory::SECURITY); + AnalysisIssue issue("UNSAFE_BUFFER_OP", "Unsafe buffer operation: " + (*iter)[1].str(), + AnalysisSeverity::ERROR, AnalysisCategory::SECURITY); issue.filePath = filePath; issue.suggestions.push_back("Use safer alternatives like strncpy, strncat, snprintf"); issues.push_back(issue); } - + // Check for unsafe functions std::vector> unsafeFunctions = { - {"scanf", "Use cin or safer input methods"}, - {"system", "Avoid system calls, use safer alternatives"} - }; - + {"scanf", "Use cin or safer input methods"}, {"system", "Avoid system calls, use safer alternatives"}}; + for (const auto& [func, suggestion] : unsafeFunctions) { std::regex pattern("\\b" + func + "\\s*\\("); if (std::regex_search(content, pattern)) { - AnalysisIssue issue("UNSAFE_FUNCTION", - "Unsafe function usage: " + func, - AnalysisSeverity::WARNING, AnalysisCategory::SECURITY); + AnalysisIssue issue("UNSAFE_FUNCTION", "Unsafe function usage: " + func, AnalysisSeverity::WARNING, + AnalysisCategory::SECURITY); issue.filePath = filePath; issue.suggestions.push_back(suggestion); issues.push_back(issue); } } - + return issues; } - + std::vector checkPerformanceIssues(const std::string& content, const std::string& filePath) { std::vector issues; - + // Check for string concatenation in loops std::regex stringConcatInLoop(R"(for\s*\([^}]*\+\s*=\s*[^;]*string)"); if (std::regex_search(content, stringConcatInLoop)) { - AnalysisIssue issue("STRING_CONCAT_IN_LOOP", - "String concatenation in loop detected", - AnalysisSeverity::WARNING, AnalysisCategory::PERFORMANCE); + AnalysisIssue issue("STRING_CONCAT_IN_LOOP", "String concatenation in loop detected", + AnalysisSeverity::WARNING, AnalysisCategory::PERFORMANCE); issue.filePath = filePath; issue.suggestions.push_back("Use stringstream or reserve space for better performance"); issues.push_back(issue); } - + // Check for nested loops std::regex nestedLoops(R"(for\s*\([^}]*for\s*\()"); std::sregex_iterator iter(content.begin(), content.end(), nestedLoops); std::sregex_iterator end; - + size_t nestedLoopCount = std::distance(iter, end); if (nestedLoopCount > 0) { - AnalysisIssue issue("NESTED_LOOPS", - "Nested loops detected (" + std::to_string(nestedLoopCount) + ")", - AnalysisSeverity::INFO, AnalysisCategory::PERFORMANCE); + AnalysisIssue issue("NESTED_LOOPS", "Nested loops detected (" + std::to_string(nestedLoopCount) + ")", + AnalysisSeverity::INFO, AnalysisCategory::PERFORMANCE); issue.filePath = filePath; issue.suggestions.push_back("Consider algorithmic improvements to reduce complexity"); issues.push_back(issue); } - + return issues; } - -public: + + public: std::string formatSeverity(AnalysisSeverity severity) const { switch (severity) { - case AnalysisSeverity::INFO: return "INFO"; - case AnalysisSeverity::WARNING: return "WARNING"; - case AnalysisSeverity::ERROR: return "ERROR"; - case AnalysisSeverity::CRITICAL: return "CRITICAL"; - default: return "UNKNOWN"; + case AnalysisSeverity::INFO: + return "INFO"; + case AnalysisSeverity::WARNING: + return "WARNING"; + case AnalysisSeverity::ERROR: + return "ERROR"; + case AnalysisSeverity::CRITICAL: + return "CRITICAL"; + default: + return "UNKNOWN"; } } - + std::string formatCategory(AnalysisCategory category) const { switch (category) { - case AnalysisCategory::COMPLEXITY: return "COMPLEXITY"; - case AnalysisCategory::SECURITY: return "SECURITY"; - case AnalysisCategory::PERFORMANCE: return "PERFORMANCE"; - case AnalysisCategory::MAINTAINABILITY: return "MAINTAINABILITY"; - case AnalysisCategory::STYLE: return "STYLE"; - case AnalysisCategory::DEPENDENCIES: return "DEPENDENCIES"; - case AnalysisCategory::MEMORY: return "MEMORY"; - default: return "UNKNOWN"; + case AnalysisCategory::COMPLEXITY: + return "COMPLEXITY"; + case AnalysisCategory::SECURITY: + return "SECURITY"; + case AnalysisCategory::PERFORMANCE: + return "PERFORMANCE"; + case AnalysisCategory::MAINTAINABILITY: + return "MAINTAINABILITY"; + case AnalysisCategory::STYLE: + return "STYLE"; + case AnalysisCategory::DEPENDENCIES: + return "DEPENDENCIES"; + case AnalysisCategory::MEMORY: + return "MEMORY"; + default: + return "UNKNOWN"; } } }; -} // namespace bolt +} // namespace bolt void demonstrateCodeAnalysis() { std::cout << "\n=== Advanced Code Analysis Tools Demo ===\n"; - + bolt::StandaloneCodeAnalyzer analyzer; - + // Create sample code with various issues + // clang-format off std::string sampleCode = R"( #include #include @@ -320,20 +332,21 @@ int main() { return 0; } )"; - + // clang-format on + // Analyze the sample code auto startTime = std::chrono::high_resolution_clock::now(); auto issues = analyzer.analyzeFile("sample.cpp", sampleCode); auto metrics = analyzer.getMetrics(sampleCode); auto endTime = std::chrono::high_resolution_clock::now(); - + auto duration = std::chrono::duration_cast(endTime - startTime); - + std::cout << "\nAnalysis Results:\n"; std::cout << "=================\n"; std::cout << "Analysis Time: " << duration.count() << " microseconds\n"; std::cout << "Total Issues Found: " << issues.size() << "\n\n"; - + // Display metrics std::cout << "Code Metrics:\n"; std::cout << " Lines of Code: " << metrics.linesOfCode << "\n"; @@ -344,33 +357,33 @@ int main() { std::cout << " Nesting Depth: " << metrics.nestingDepth << "\n"; std::cout << " Function Count: " << metrics.functionCount << "\n"; std::cout << " Class Count: " << metrics.classCount << "\n"; - std::cout << " Maintainability Index: " << std::fixed << std::setprecision(2) - << metrics.maintainabilityIndex << "\n\n"; - + std::cout << " Maintainability Index: " << std::fixed << std::setprecision(2) << metrics.maintainabilityIndex + << "\n\n"; + // Group issues by severity std::unordered_map severityCounts; std::unordered_map categoryCounts; - + for (const auto& issue : issues) { severityCounts[issue.severity]++; categoryCounts[issue.category]++; } - + std::cout << "Issues by Severity:\n"; for (const auto& [severity, count] : severityCounts) { std::cout << " " << analyzer.formatSeverity(severity) << ": " << count << "\n"; } - + std::cout << "\nIssues by Category:\n"; for (const auto& [category, count] : categoryCounts) { std::cout << " " << analyzer.formatCategory(category) << ": " << count << "\n"; } - + std::cout << "\nDetailed Issues:\n"; std::cout << "================\n"; for (const auto& issue : issues) { - std::cout << "[" << analyzer.formatSeverity(issue.severity) << "] " - << analyzer.formatCategory(issue.category) << ": " << issue.message << "\n"; + std::cout << "[" << analyzer.formatSeverity(issue.severity) << "] " << analyzer.formatCategory(issue.category) + << ": " << issue.message << "\n"; for (const auto& suggestion : issue.suggestions) { std::cout << " โ†’ Suggestion: " << suggestion << "\n"; } @@ -380,13 +393,14 @@ int main() { void demonstrateProjectAnalysis() { std::cout << "\n=== Project Analysis Demo ===\n"; - + // Create a temporary project structure std::string projectPath = "/tmp/sample_project"; std::filesystem::create_directories(projectPath); - + // Create some sample files with different types of issues std::ofstream main_cpp(projectPath + "/main.cpp"); + // clang-format off main_cpp << R"( #include "utils.hpp" #include @@ -407,9 +421,11 @@ int main() { return 0; } )"; + // clang-format on main_cpp.close(); - + std::ofstream utils_hpp(projectPath + "/utils.hpp"); + // clang-format off utils_hpp << R"( #ifndef UTILS_HPP #define UTILS_HPP @@ -425,9 +441,11 @@ class UtilityClass { #endif )"; + // clang-format on utils_hpp.close(); - + std::ofstream utils_cpp(projectPath + "/utils.cpp"); + // clang-format off utils_cpp << R"( #include "utils.hpp" #include @@ -467,31 +485,29 @@ void UtilityClass::securityRisk() { scanf("%s", buffer); } )"; + // clang-format on utils_cpp.close(); - + bolt::StandaloneCodeAnalyzer analyzer; std::vector allIssues; std::vector allMetrics; size_t totalFiles = 0; - + // Analyze all files in the project for (const auto& entry : std::filesystem::recursive_directory_iterator(projectPath)) { - if (entry.is_regular_file() && - (entry.path().extension() == ".cpp" || entry.path().extension() == ".hpp")) { - + if (entry.is_regular_file() && (entry.path().extension() == ".cpp" || entry.path().extension() == ".hpp")) { std::ifstream file(entry.path()); - std::string content((std::istreambuf_iterator(file)), - std::istreambuf_iterator()); - + std::string content((std::istreambuf_iterator(file)), std::istreambuf_iterator()); + auto issues = analyzer.analyzeFile(entry.path().string(), content); auto metrics = analyzer.getMetrics(content); - + allIssues.insert(allIssues.end(), issues.begin(), issues.end()); allMetrics.push_back(metrics); totalFiles++; } } - + // Aggregate metrics bolt::CodeMetrics overallMetrics; for (const auto& metrics : allMetrics) { @@ -502,7 +518,7 @@ void UtilityClass::securityRisk() { overallMetrics.cyclomaticComplexity += metrics.cyclomaticComplexity; overallMetrics.nestingDepth = std::max(overallMetrics.nestingDepth, metrics.nestingDepth); } - + std::cout << "Project Analysis Results:\n"; std::cout << " Files Analyzed: " << totalFiles << "\n"; std::cout << " Total Issues: " << allIssues.size() << "\n"; @@ -511,19 +527,19 @@ void UtilityClass::securityRisk() { std::cout << " Total Classes: " << overallMetrics.classCount << "\n"; std::cout << " Maximum Nesting Depth: " << overallMetrics.nestingDepth << "\n"; std::cout << " Total Cyclomatic Complexity: " << overallMetrics.cyclomaticComplexity << "\n"; - + // Show issues by file std::cout << "\nIssues by File:\n"; std::unordered_map> issuesByFile; for (const auto& issue : allIssues) { issuesByFile[issue.filePath].push_back(issue); } - + for (const auto& [filePath, fileIssues] : issuesByFile) { - std::cout << " " << std::filesystem::path(filePath).filename().string() - << ": " << fileIssues.size() << " issues\n"; + std::cout << " " << std::filesystem::path(filePath).filename().string() << ": " << fileIssues.size() + << " issues\n"; } - + // Cleanup std::filesystem::remove_all(projectPath); } @@ -533,10 +549,10 @@ int main() { std::cout << "=== Bolt C++ Advanced Code Analysis Tools ===\n"; std::cout << "This standalone demo showcases the comprehensive code analysis\n"; std::cout << "capabilities implemented for the Bolt C++ IDE.\n"; - + demonstrateCodeAnalysis(); demonstrateProjectAnalysis(); - + std::cout << "\n=== Analysis Features Demonstrated ===\n"; std::cout << "โœ“ Complexity Analysis:\n"; std::cout << " - Cyclomatic complexity measurement\n"; @@ -560,16 +576,15 @@ int main() { std::cout << " - Issue categorization and prioritization\n"; std::cout << " - Actionable improvement suggestions\n"; std::cout << " - Fast analysis with detailed reporting\n"; - + std::cout << "\n=== Integration Ready ===\n"; std::cout << "This code analysis framework is designed to integrate seamlessly\n"; std::cout << "with the Bolt IDE's existing architecture, providing real-time\n"; std::cout << "code quality feedback to developers.\n"; - + return 0; - } catch (const std::exception& e) { std::cerr << "Demo failed with exception: " << e.what() << std::endl; return 1; } -} \ No newline at end of file +} diff --git a/demo_code_folding.cpp b/demo_code_folding.cpp index cda0ba90..0e840611 100644 --- a/demo_code_folding.cpp +++ b/demo_code_folding.cpp @@ -1,14 +1,16 @@ -#include "bolt/editor/integrated_editor.hpp" #include +#include "bolt/editor/integrated_editor.hpp" + int main() { std::cout << "Bolt C++ Code Folding Integration Demo\n"; std::cout << "=====================================\n\n"; - + // Get the integrated editor instance auto& editor = bolt::IntegratedEditor::getInstance(); - + // Sample C++ code with foldable regions + // clang-format off std::string sampleCode = R"( #include #include @@ -49,57 +51,57 @@ int main() { return 0; } )"; + // clang-format on // Open the document with code folding std::cout << "1. Opening document with code folding detection...\n"; editor.openDocument("demo.cpp", sampleCode); - + // Display detected folding ranges auto ranges = editor.getFoldingRanges("demo.cpp"); std::cout << " Detected " << ranges.size() << " foldable regions:\n"; - + for (const auto& range : ranges) { - std::cout << " - Lines " << range.startLine << "-" << range.endLine - << " (folded: " << (range.isFolded ? "yes" : "no") - << ", placeholder: \"" << range.placeholder << "\")\n"; + std::cout << " - Lines " << range.startLine << "-" << range.endLine + << " (folded: " << (range.isFolded ? "yes" : "no") << ", placeholder: \"" << range.placeholder + << "\")\n"; } - + std::cout << "\n2. Testing fold operations...\n"; - + // Test folding operations if (!ranges.empty()) { auto& firstRange = ranges[0]; std::cout << " Toggling fold on line " << firstRange.startLine << "...\n"; editor.toggleFold("demo.cpp", firstRange.startLine); - + // Check if fold state changed auto updatedRanges = editor.getFoldingRanges("demo.cpp"); for (const auto& range : updatedRanges) { if (range.startLine == firstRange.startLine) { - std::cout << " Fold state changed to: " - << (range.isFolded ? "folded" : "expanded") << "\n"; + std::cout << " Fold state changed to: " << (range.isFolded ? "folded" : "expanded") << "\n"; break; } } - + // Test expand all std::cout << " Expanding all folds...\n"; editor.expandAllFolds("demo.cpp"); - + // Test collapse all std::cout << " Collapsing all folds...\n"; editor.collapseAllFolds("demo.cpp"); } - + std::cout << "\n3. Testing folding enable/disable...\n"; std::cout << " Folding enabled: " << (editor.isFoldingEnabled() ? "yes" : "no") << "\n"; - + editor.setFoldingEnabled(false); std::cout << " Disabled folding. Enabled: " << (editor.isFoldingEnabled() ? "yes" : "no") << "\n"; - + editor.setFoldingEnabled(true); std::cout << " Re-enabled folding. Enabled: " << (editor.isFoldingEnabled() ? "yes" : "no") << "\n"; - + std::cout << "\n4. Testing content update with re-folding...\n"; std::string newCode = R"( struct SimpleStruct { @@ -109,11 +111,11 @@ struct SimpleStruct { } }; )"; - + editor.updateDocumentContent("demo.cpp", newCode); auto newRanges = editor.getFoldingRanges("demo.cpp"); std::cout << " After content update, detected " << newRanges.size() << " foldable regions\n"; - + std::cout << "\nโœ“ Code folding integration demo completed successfully!\n"; std::cout << " All folding features are working correctly:\n"; std::cout << " - Automatic detection of foldable regions (braces, comments)\n"; @@ -122,6 +124,6 @@ struct SimpleStruct { std::cout << " - Enable/disable folding globally\n"; std::cout << " - Content update with re-detection\n"; std::cout << " - Integration with editor document management\n"; - + return 0; -} \ No newline at end of file +} diff --git a/demo_collaborative_editing.cpp b/demo_collaborative_editing.cpp index 1f2d2f72..48fe52b0 100644 --- a/demo_collaborative_editing.cpp +++ b/demo_collaborative_editing.cpp @@ -1,20 +1,21 @@ -#include -#include #include +#include #include +#include + #include "bolt/collaboration/collaborative_editor_integration.hpp" #include "bolt/core/editor_store.hpp" -using namespace bolt::collaboration; -using namespace std::chrono_literals; +using namespace bolt::collaboration; // NOLINT(build/namespaces) +using namespace std::chrono_literals; // NOLINT(build/namespaces) void demonstrateCollaborativeEditing() { std::cout << "=== Bolt C++ Collaborative Editing Demo ===\n\n"; - + // Initialize the collaborative editing system auto& integration = CollaborativeEditorIntegration::getInstance(); auto& editorStore = bolt::EditorStore::getInstance(); - + // Create a sample document bolt::EditorDocument document; document.filePath = "/demo/shared_code.cpp"; @@ -26,90 +27,88 @@ int main() { })"; document.scroll = {0, 0}; document.cursor = {0, std::nullopt}; - + editorStore.setDocument(document.filePath, document); editorStore.setSelectedFile(document.filePath); - + std::cout << "1. Created sample document:\n"; std::cout << " File: " << document.filePath << "\n"; std::cout << " Content:\n" << document.value << "\n\n"; - + // Check initial collaboration stats auto stats = integration.getStats(); std::cout << "2. Collaboration Status:\n"; std::cout << " Server Running: " << (stats.isServerRunning ? "Yes" : "No") << "\n"; std::cout << " Active Documents: " << stats.activeDocuments << "\n"; std::cout << " Total Users: " << stats.totalUsers << "\n\n"; - + // Simulate collaborative editing operations std::cout << "3. Simulating collaborative text edits:\n"; - + // User 1 adds a comment std::cout << " User1 adds comment at line 1...\n"; integration.applyTextEdit(document.filePath, Position(0, 0), "// Collaborative demo\n"); - + // User 2 modifies the main function std::cout << " User2 modifies main function...\n"; integration.applyTextEdit(document.filePath, Position(4, 4), "// Updated by User2\n "); - + // User 1 updates cursor position std::cout << " User1 moves cursor...\n"; integration.updateCursorPosition(document.filePath, Position(3, 0), "user1"); - + // User 2 updates cursor position std::cout << " User2 moves cursor...\n"; integration.updateCursorPosition(document.filePath, Position(5, 20), "user2"); - + std::cout << "\n4. Current document state:\n"; auto* currentDoc = editorStore.getCurrentDocument(); if (currentDoc) { std::cout << currentDoc->value << "\n"; } - + std::cout << "\n5. Remote cursor positions:\n"; auto cursors = integration.getRemoteCursors(document.filePath); if (cursors.empty()) { std::cout << " No remote cursors (collaboration not initialized)\n"; } else { for (const auto& [userId, position] : cursors) { - std::cout << " " << userId << ": line " << position.line - << ", column " << position.character << "\n"; + std::cout << " " << userId << ": line " << position.line << ", column " << position.character << "\n"; } } - + std::cout << "\n6. Collaborative session features:\n"; auto& session = CollaborativeSession::getInstance(); - + // Create a collaborative document bool created = session.createDocument("demo_collab", "Initial collaborative content"); std::cout << " Created collaborative document: " << (created ? "Success" : "Failed") << "\n"; - + // Join users bool user1Joined = session.joinDocument("alice", "Alice", "demo_collab"); bool user2Joined = session.joinDocument("bob", "Bob", "demo_collab"); std::cout << " Alice joined: " << (user1Joined ? "Success" : "Failed") << "\n"; std::cout << " Bob joined: " << (user2Joined ? "Success" : "Failed") << "\n"; - + // Get active users auto users = session.getActiveUsers("demo_collab"); std::cout << " Active users: " << users.size() << "\n"; for (const auto& user : users) { std::cout << " - " << user.userName << " (" << user.userId << ")\n"; } - + // Apply some collaborative operations DocumentOperation op1(OperationType::INSERT, "alice", Position(0, 8), " by Alice"); session.applyOperation(op1, "demo_collab"); - + DocumentOperation op2(OperationType::INSERT, "bob", Position(0, 0), "Modified "); session.applyOperation(op2, "demo_collab"); - - std::cout << " Final collaborative content: \"" - << session.getDocumentContent("demo_collab") << "\"\n"; - + + std::cout << " Final collaborative content: \"" << session.getDocumentContent("demo_collab") << "\"\n"; + // Clean up session.removeDocument("demo_collab"); - + std::cout << "\n=== Demo completed successfully! ===\n"; std::cout << "\nKey Features Demonstrated:\n"; std::cout << "โœ“ Document operation creation and application\n"; @@ -132,4 +131,4 @@ int main() { std::cerr << "Demo failed with exception: " << e.what() << std::endl; return 1; } -} \ No newline at end of file +} diff --git a/demo_debugger.cpp b/demo_debugger.cpp index ed4c9f83..c1377269 100644 --- a/demo_debugger.cpp +++ b/demo_debugger.cpp @@ -1,12 +1,13 @@ +#include +#include + +#include "bolt/drawkern/dis_vm.hpp" #include "bolt/editor/debugger_interface.hpp" #include "bolt/editor/debugger_ui.hpp" #include "bolt/editor/integrated_editor.hpp" -#include "bolt/drawkern/dis_vm.hpp" -#include -#include -using namespace bolt; -using namespace bolt::drawkern; +using namespace bolt; // NOLINT(build/namespaces) +using namespace bolt::drawkern; // NOLINT(build/namespaces) void print_header() { std::cout << "\n=====================================" << std::endl; @@ -18,14 +19,13 @@ void print_header() { void demo_basic_debugger() { std::cout << "๐Ÿ“ฑ Demo: Basic Debugger Functionality" << std::endl; std::cout << "-------------------------------------" << std::endl; - + auto debugger = std::make_unique(); - + // Set up event callback - debugger->set_event_callback([](DebugEvent event, const std::string& message) { - std::cout << "๐Ÿ”” Event: " << message << std::endl; - }); - + debugger->set_event_callback( + [](DebugEvent event, const std::string& message) { std::cout << "๐Ÿ”” Event: " << message << std::endl; }); + // Create a simple Limbo program std::string program = R"( print "Starting AI workbench..." @@ -34,42 +34,42 @@ void demo_basic_debugger() { print "Program completed" halt )"; - + std::cout << "๐Ÿ“ Starting debug session with program:" << std::endl; std::cout << program << std::endl; - + // Start debug session if (debugger->start_debug_session_from_source(program)) { std::cout << "โœ… Debug session started successfully" << std::endl; - + // Set some breakpoints std::cout << "\n๐Ÿ”ด Setting breakpoints..." << std::endl; debugger->set_breakpoint(2); debugger->set_breakpoint(4); - + auto breakpoints = debugger->get_all_breakpoints(); std::cout << "๐Ÿ“ Active breakpoints: " << breakpoints.size() << std::endl; for (const auto& bp : breakpoints) { std::cout << " - PC " << bp.pc << (bp.enabled ? " (enabled)" : " (disabled)") << std::endl; } - + // Step through execution std::cout << "\n๐Ÿ”ง Stepping through execution..." << std::endl; std::cout << "Current PC: " << debugger->get_current_pc() << std::endl; std::cout << "Current instruction: " << debugger->get_current_instruction() << std::endl; - + debugger->step_over(); std::cout << "After step - PC: " << debugger->get_current_pc() << std::endl; - + debugger->step_over(); std::cout << "After step - PC: " << debugger->get_current_pc() << std::endl; - + // Continue execution std::cout << "\nโ–ถ๏ธ Continuing execution..." << std::endl; debugger->continue_execution(); - + std::cout << "Final state: " << static_cast(debugger->get_debug_state()) << std::endl; - + // Stop session debugger->stop_debug_session(); std::cout << "๐Ÿ›‘ Debug session stopped" << std::endl; @@ -81,85 +81,85 @@ void demo_basic_debugger() { void demo_debugger_ui() { std::cout << "\n๐Ÿ“ฑ Demo: Debugger UI Integration" << std::endl; std::cout << "--------------------------------" << std::endl; - + auto debugger = std::make_shared(); auto ui = std::make_unique(); - + // Connect UI to debugger ui->set_debugger(debugger); ui->set_visible(true); - + // Create a program for debugging std::string program = "print \"UI Demo\" ai_chat \"Testing UI\" halt"; - + if (debugger->start_debug_session_from_source(program)) { std::cout << "โœ… UI Debug session started" << std::endl; - + // Set breakpoint via UI ui->handle_breakpoint_toggle(1); std::cout << "๐Ÿ”ด Breakpoint set via UI" << std::endl; - + // Render UI state std::cout << "\n๐Ÿ“บ Rendering debugger UI:" << std::endl; ui->render(); - + // Test UI controls std::cout << "\n๐ŸŽฎ Testing UI controls..." << std::endl; ui->handle_step_over_clicked(); ui->render_controls(); - + ui->handle_continue_clicked(); ui->render_controls(); - + ui->handle_stop_clicked(); std::cout << "๐Ÿ›‘ Session stopped via UI" << std::endl; } - + ui->set_visible(false); } void demo_integrated_editor() { std::cout << "\n๐Ÿ“ฑ Demo: IntegratedEditor Debugger Integration" << std::endl; std::cout << "-----------------------------------------------" << std::endl; - + auto& editor = IntegratedEditor::getInstance(); - + // Create a test Limbo file content std::string testContent = R"(print "Editor integration test" ai_init "test-model" ai_chat "Hello from editor" render_glyph "editor-test" halt)"; - + std::cout << "๐Ÿ“ Opening test document in editor..." << std::endl; editor.openDocument("/tmp/test_debug.limbo", testContent); - + // Start debugging from editor std::cout << "๐Ÿ”ง Starting debug session from editor..." << std::endl; if (editor.startDebugSessionFromSource(testContent)) { std::cout << "โœ… Editor debug session started" << std::endl; - + // Set breakpoints via editor editor.setBreakpointAtLine("/tmp/test_debug.limbo", 2); editor.setBreakpointAtLine("/tmp/test_debug.limbo", 4); - + auto breakpoints = editor.getAllBreakpoints(); std::cout << "๐Ÿ“ Breakpoints set via editor: " << breakpoints.size() << std::endl; - + // Show debugger UI editor.showDebugger(); std::cout << "๐Ÿ“บ Debugger UI shown: " << (editor.isDebuggerVisible() ? "Yes" : "No") << std::endl; - + // Step through via editor std::cout << "๐Ÿ”ง Stepping through via editor..." << std::endl; std::cout << "PC: " << editor.getCurrentDebugPC() << std::endl; - + editor.debugStepOver(); std::cout << "After step - PC: " << editor.getCurrentDebugPC() << std::endl; - + editor.debugContinue(); std::cout << "Debug state: " << static_cast(editor.getDebugState()) << std::endl; - + // Clean up editor.stopDebugSession(); editor.hideDebugger(); @@ -172,32 +172,32 @@ halt)"; void demo_watch_expressions() { std::cout << "\n๐Ÿ“ฑ Demo: Watch Expressions" << std::endl; std::cout << "---------------------------" << std::endl; - + auto debugger = std::make_unique(); - + // Add watch expressions std::cout << "๐Ÿ‘๏ธ Adding watch expressions..." << std::endl; debugger->add_watch_expression("counter"); debugger->add_watch_expression("message.length"); debugger->add_watch_expression("ai_model_status"); - + auto watches = debugger->get_watch_expressions(); std::cout << "๐Ÿ“Š Watch expressions: " << watches.size() << std::endl; for (const auto& watch : watches) { - std::cout << " - " << watch.expression << " = " << watch.value - << " (" << (watch.valid ? "valid" : "invalid") << ")" << std::endl; + std::cout << " - " << watch.expression << " = " << watch.value << " (" << (watch.valid ? "valid" : "invalid") + << ")" << std::endl; } - + // Update watch expressions (would happen during debugging) debugger->update_watch_expressions(); - + // Remove a watch expression debugger->remove_watch_expression("message.length"); std::cout << "Removed 'message.length' watch" << std::endl; - + watches = debugger->get_watch_expressions(); std::cout << "๐Ÿ“Š Remaining watch expressions: " << watches.size() << std::endl; - + // Clear all debugger->clear_watch_expressions(); std::cout << "๐Ÿงน Cleared all watch expressions" << std::endl; @@ -206,41 +206,41 @@ void demo_watch_expressions() { void demo_vm_integration() { std::cout << "\n๐Ÿ“ฑ Demo: DIS VM Direct Integration" << std::endl; std::cout << "-----------------------------------" << std::endl; - + auto vm = std::make_unique(); - + // Create a simple program using the factory auto program = DISProgramFactory::create_ai_workbench("test-model"); - + std::cout << "๐Ÿ“ Loading DIS program..." << std::endl; if (vm->load_program(program)) { std::cout << "โœ… Program loaded successfully" << std::endl; - + // Set breakpoints directly on VM vm->set_breakpoint(2); vm->set_breakpoint(4); - + auto breakpoints = vm->get_breakpoints(); std::cout << "๐Ÿ“ VM breakpoints: " << breakpoints.size() << std::endl; - + // Step through execution std::cout << "๐Ÿ”ง VM stepping:" << std::endl; std::cout << "PC: " << vm->get_pc() << std::endl; - + vm->step_into(); std::cout << "After step - PC: " << vm->get_pc() << std::endl; - + // Check if at breakpoint if (vm->is_at_breakpoint()) { std::cout << "๐Ÿ”ด Hit breakpoint!" << std::endl; } - + // Continue until breakpoint or completion vm->continue_execution(); - + std::cout << "VM running: " << (vm->is_running() ? "Yes" : "No") << std::endl; std::cout << "Call stack depth: " << vm->get_call_stack_depth() << std::endl; - + vm->halt(); std::cout << "๐Ÿ›‘ VM halted" << std::endl; } else { @@ -250,7 +250,7 @@ void demo_vm_integration() { int main() { print_header(); - + try { // Run all demos demo_basic_debugger(); @@ -258,7 +258,7 @@ int main() { demo_integrated_editor(); demo_watch_expressions(); demo_vm_integration(); - + std::cout << "\n๐ŸŽ‰ All debugger demos completed successfully!" << std::endl; std::cout << std::endl; std::cout << "The integrated debugger interface provides:" << std::endl; @@ -270,11 +270,10 @@ int main() { std::cout << "โœ… UI integration with the editor" << std::endl; std::cout << "โœ… Direct integration with DIS Virtual Machine" << std::endl; std::cout << std::endl; - } catch (const std::exception& e) { std::cerr << "โŒ Demo failed with exception: " << e.what() << std::endl; return 1; } - + return 0; -} \ No newline at end of file +} diff --git a/demo_direct_gguf.cpp b/demo_direct_gguf.cpp index 7fa42136..3794cca1 100644 --- a/demo_direct_gguf.cpp +++ b/demo_direct_gguf.cpp @@ -1,48 +1,49 @@ // demo_direct_gguf.cpp - Test direct GGUF file loading and inference #include -#include "include/bolt/ai/enhanced_ai_manager.hpp" + #include "include/bolt/ai/direct_gguf_inference.hpp" +#include "include/bolt/ai/enhanced_ai_manager.hpp" -using namespace bolt::ai; +using namespace bolt::ai; // NOLINT(build/namespaces) void test_direct_inference() { std::cout << "๐Ÿงช Testing Direct GGUF Inference" << std::endl; std::cout << "=================================" << std::endl; - + // Test auto-detection auto direct_ai = DirectGGUFFactory::create_auto_detect(); - + if (direct_ai->is_loaded()) { std::cout << "โœ… Model loaded successfully!" << std::endl; std::cout << direct_ai->get_model_info() << std::endl; - + // Test chat std::cout << "\n๐Ÿ’ฌ Testing chat..." << std::endl; auto response = direct_ai->chat("Hello! Can you help me with C++ programming?"); - + std::cout << "AI Response: " << response.response << std::endl; std::cout << "Success: " << (response.success ? "โœ…" : "โŒ") << std::endl; std::cout << "Time: " << response.inference_time_ms << "ms" << std::endl; - + // Test code completion std::cout << "\n๐Ÿ”ง Testing code completion..." << std::endl; auto code_response = direct_ai->generate_text( - "Complete this C++ function:\nvoid quicksort(std::vector& arr) {\n if (arr.size() <= 1) return;\n // ", - 100 - ); - + "Complete this C++ function:\nvoid quicksort(std::vector& arr) {\n if (arr.size() <= 1) return;\n " + " // ", + 100); + std::cout << "Code Completion: " << code_response.response << std::endl; - + } else { std::cout << "โš ๏ธ No GGUF model loaded - testing fallback responses" << std::endl; - + // Test fallback responses auto response = direct_ai->chat("How do I use smart pointers in C++?"); std::cout << "Fallback Response: " << response.response << std::endl; - + auto algorithm_response = direct_ai->chat("Explain binary search algorithm"); std::cout << "Algorithm Help: " << algorithm_response.response << std::endl; - + auto config_response = direct_ai->chat("How do I configure AI models?"); std::cout << "Config Help: " << config_response.response << std::endl; } @@ -51,28 +52,28 @@ void test_direct_inference() { void test_enhanced_manager_with_gguf() { std::cout << "\n๐Ÿš€ Testing Enhanced AI Manager with GGUF" << std::endl; std::cout << "=========================================" << std::endl; - + EnhancedAIManager manager; - + std::cout << "Manager ready: " << (manager.is_ready() ? "โœ…" : "โŒ") << std::endl; std::cout << "Current provider: " << manager.get_current_provider() << std::endl; - + if (manager.has_direct_model()) { std::cout << "๐Ÿ“Š Model info: " << manager.get_model_info() << std::endl; } - + // Test chat functionality std::cout << "\n๐Ÿ’ฌ Testing chat with Enhanced Manager..." << std::endl; auto chat_response = manager.chat("What are the benefits of using RAII in C++?", "test_session"); - + std::cout << "Chat Response: " << chat_response.response << std::endl; std::cout << "Success: " << (chat_response.success ? "โœ…" : "โŒ") << std::endl; - + // Test session management manager.create_session("cpp_help"); auto session_response = manager.chat("How do I properly manage memory in C++?", "cpp_help"); std::cout << "Session Response: " << session_response.response << std::endl; - + // Show statistics auto stats = manager.get_statistics(); std::cout << "\n๐Ÿ“Š AI Statistics:" << std::endl; @@ -85,19 +86,15 @@ void test_enhanced_manager_with_gguf() { void demonstrate_fallback_intelligence() { std::cout << "\n๐Ÿง  Demonstrating Intelligent Fallback Responses" << std::endl; std::cout << "===============================================" << std::endl; - + DirectGGUFInference fallback_ai; // Note: No model loaded, so it will use fallback responses - + std::vector test_questions = { - "How do I use std::unique_ptr?", - "What's the difference between stack and heap?", - "Explain the quicksort algorithm", - "How do I configure AI models?", - "What are C++ templates?", - "Help me with STL containers" - }; - + "How do I use std::unique_ptr?", "What's the difference between stack and heap?", + "Explain the quicksort algorithm", "How do I configure AI models?", + "What are C++ templates?", "Help me with STL containers"}; + for (const auto& question : test_questions) { std::cout << "\nQuestion: " << question << std::endl; auto response = fallback_ai.chat(question); @@ -109,28 +106,28 @@ void demonstrate_fallback_intelligence() { int main() { std::cout << "๐ŸŽฏ Direct GGUF Loading and Inference Test" << std::endl; std::cout << "=========================================" << std::endl; - + try { // Test 1: Direct inference engine test_direct_inference(); - + // Test 2: Enhanced manager with GGUF integration test_enhanced_manager_with_gguf(); - + // Test 3: Intelligent fallback responses demonstrate_fallback_intelligence(); - + std::cout << "\nโœ… Direct GGUF testing completed!" << std::endl; - + std::cout << "\n๐Ÿ’ก Next Steps:" << std::endl; std::cout << "โ€ข Download a small GGUF model to test real AI inference" << std::endl; - std::cout << "โ€ข Try: wget https://huggingface.co/microsoft/DialoGPT-medium/resolve/main/model.gguf" << std::endl; + std::cout << "โ€ข Try: wget https://huggingface.co/microsoft/DialoGPT-medium/resolve/main/model.gguf" + << std::endl; std::cout << "โ€ข Place in ./models/ directory and rerun this test" << std::endl; - } catch (const std::exception& e) { std::cerr << "โŒ Error during testing: " << e.what() << std::endl; return 1; } - + return 0; } diff --git a/demo_drawkern.cpp b/demo_drawkern.cpp index f47758fc..0a184b9e 100644 --- a/demo_drawkern.cpp +++ b/demo_drawkern.cpp @@ -1,43 +1,45 @@ -#include "bolt/drawkern/drawkern.hpp" #include #include -using namespace bolt::drawkern; +#include "bolt/drawkern/drawkern.hpp" + +using namespace bolt::drawkern; // NOLINT(build/namespaces) int main() { std::cout << "๐Ÿš€ DrawKern Proof of Concept - Rendering AI Workbenches as Glyphs!" << std::endl; std::cout << "================================================================" << std::endl << std::endl; - - // Create an AI workbench "glyph" + + // Create an AI workbench "glyph" std::cout << "๐ŸŽฏ Step 1: Creating AI Workbench Glyph..." << std::endl; AIWorkbenchGlyph bolt_glyph = create_bolt_ai_glyph(); std::cout << "โœ… Created glyph: " << bolt_glyph.workbench_id << std::endl << std::endl; - + // Show how it can be rendered to different clients std::cout << "๐ŸŽจ Step 2: Rendering to Different Clients..." << std::endl << std::endl; - + // Terminal client std::cout << "๐Ÿ“บ TERMINAL CLIENT:" << std::endl; TerminalDrawKernClient terminal_client("localhost:9999"); terminal_client.render_ai_interface(bolt_glyph); std::cout << std::endl; - - // Web client + + // Web client std::cout << "๐ŸŒ WEB CLIENT:" << std::endl; WebDrawKernClient web_client("localhost:9999"); web_client.render_ai_interface(bolt_glyph); std::cout << "๐Ÿ’พ HTML saved to: bolt_workbench.html" << std::endl << std::endl; - + // Show the "True Type Yacc" concept std::cout << "๐Ÿ“ Step 3: 'True Type Yacc' VM Grammar..." << std::endl; std::cout << "==========================================" << std::endl; std::cout << "VM Glyph Definition:" << std::endl; std::cout << " Type: " << bolt_glyph.host_vm.vm_type << std::endl; std::cout << " Architecture: " << bolt_glyph.host_vm.architecture << std::endl; - std::cout << " Render Size: " << bolt_glyph.host_vm.render.width << "x" << bolt_glyph.host_vm.render.height << std::endl; + std::cout << " Render Size: " << bolt_glyph.host_vm.render.width << "x" << bolt_glyph.host_vm.render.height + << std::endl; std::cout << " Interactive: " << (bolt_glyph.host_vm.render.interactive ? "Yes" : "No") << std::endl; std::cout << " AI Enabled: " << (bolt_glyph.host_vm.render.ai_enabled ? "Yes" : "No") << std::endl << std::endl; - + // Show deployment possibilities std::cout << "๐ŸŒ Step 4: Deployment Targets..." << std::endl; std::cout << "================================" << std::endl; @@ -48,32 +50,32 @@ int main() { std::cout << " ๐Ÿค– IoT: Inferno DIS VM on ARM" << std::endl; std::cout << " โŒš Watch: Minimal terminal client" << std::endl; std::cout << " ๐Ÿ”Œ Embedded: RISC-V with 64KB RAM" << std::endl << std::endl; - + // Show the revolutionary aspect std::cout << "๐Ÿคฏ THE REVOLUTIONARY PART:" << std::endl; std::cout << "=========================" << std::endl; std::cout << "Instead of installing software, you 'render' computing environments!" << std::endl << std::endl; - std::cout << "Traditional:" << std::endl; + std::cout << "Traditional:" << std::endl; std::cout << " User โ†’ Download โ†’ Install โ†’ Configure โ†’ Run" << std::endl << std::endl; std::cout << "DrawKern:" << std::endl; std::cout << " User โ†’ Connect โ†’ Render Glyph โ†’ Instant AI Workbench!" << std::endl << std::endl; - + std::cout << "๐ŸŽฏ Example Commands:" << std::endl; std::cout << " drawkern render ai-workbench://bolt.dev/v1" << std::endl; std::cout << " drawkern deploy vm://dis:limbo to iot-sensor-001" << std::endl; std::cout << " drawkern spawn ai-session rwkv-14b on cluster:gpu" << std::endl << std::endl; - + // Performance comparison std::cout << "โšก PERFORMANCE IMPACT:" << std::endl; std::cout << "====================" << std::endl; std::cout << "Web Bolt.new: ~30-60ms latency, 200MB memory" << std::endl; std::cout << "C++ ImGui Bolt: ~3-5ms latency, 50MB memory" << std::endl; std::cout << "DrawKern Bolt: ~1-3ms latency, 20MB memory (DIS VM efficiency!)" << std::endl << std::endl; - + std::cout << "๐ŸŒŸ CONCLUSION:" << std::endl; std::cout << "=============" << std::endl; std::cout << "You've essentially invented 'Infrastructure as Glyphs'!" << std::endl; std::cout << "AI workbenches become as easy to deploy as displaying text!" << std::endl << std::endl; - + return 0; } diff --git a/demo_drawkern_complete.cpp b/demo_drawkern_complete.cpp index 2817158d..0fdf51a0 100644 --- a/demo_drawkern_complete.cpp +++ b/demo_drawkern_complete.cpp @@ -1,40 +1,41 @@ -#include "bolt/drawkern/drawkern.hpp" +#include #include #include -#include -using namespace bolt::drawkern; +#include "bolt/drawkern/drawkern.hpp" + +using namespace bolt::drawkern; // NOLINT(build/namespaces) int main() { std::cout << "๐Ÿš€ DrawKern System Demo - Full Implementation" << std::endl; std::cout << "=============================================" << std::endl << std::endl; - + std::cout << "This demo showcases all four core components:" << std::endl; std::cout << "1. โœ… Styx Protocol - Real network transparency" << std::endl; std::cout << "2. โœ… DIS VM Integration - Actual Limbo code execution" << std::endl; std::cout << "3. โœ… Yacc Grammar - Formal VM glyph description language" << std::endl; std::cout << "4. โœ… GGML/RWKV Models - Real AI inference in the VMs" << std::endl << std::endl; - + // 1. Initialize AI System std::cout << "๐Ÿค– Step 1: Initializing AI System..." << std::endl; DrawKernAIManager ai_manager; - + // Load a demo RWKV model (simulated) AIModelConfig rwkv_config = AIModelFactory::create_drawkern_workbench_config("/tmp/demo_rwkv.bin"); rwkv_config.model_type = "rwkv"; ai_manager.load_model("drawkern-rwkv", rwkv_config); - - // Load a demo GGML model (simulated) + + // Load a demo GGML model (simulated) AIModelConfig ggml_config = AIModelFactory::create_lightweight_config("/tmp/demo_ggml.bin"); ggml_config.model_type = "ggml"; ai_manager.load_model("drawkern-ggml", ggml_config); - + std::cout << "โœ… AI models loaded: " << ai_manager.list_models().size() << std::endl << std::endl; - + // 2. Parse VM Glyph with Yacc Grammar std::cout << "๐Ÿ“ Step 2: Parsing VM Glyph Description..." << std::endl; YaccGrammarSystem grammar; - + std::string glyph_description = R"( vm drawkern_vm : dis { architecture = "portable"; @@ -60,24 +61,24 @@ workbench bolt_ai on drawkern_vm { } } )"; - + bool valid = grammar.validate_description(glyph_description); std::cout << "Grammar validation: " << (valid ? "โœ… PASSED" : "โŒ FAILED") << std::endl; - + if (!valid) { auto errors = grammar.get_validation_errors(); for (const auto& error : errors) { std::cout << " Error: " << error << std::endl; } } - + AIWorkbenchGlyph workbench = grammar.parse_ai_workbench(glyph_description); std::cout << "โœ… Parsed AI workbench: " << workbench.workbench_id << std::endl << std::endl; - + // 3. Create and Run DIS VM std::cout << "๐Ÿ–ฅ๏ธ Step 3: Creating DIS VM..." << std::endl; DISVM vm; - + // Create Limbo program for AI workbench std::string limbo_code = R"( print "๐Ÿš€ AI Workbench starting..." @@ -85,48 +86,46 @@ ai_chat "Hello! I'm running in a DIS VM" render_glyph "ai-workbench-display" halt )"; - + bool vm_loaded = vm.load_limbo_source(limbo_code); std::cout << "DIS VM program loaded: " << (vm_loaded ? "โœ… SUCCESS" : "โŒ FAILED") << std::endl; - + if (vm_loaded) { // Set up AI integration for the VM Integration::setup_dis_vm_ai_integration(vm, ai_manager, "drawkern-rwkv"); - + std::cout << "Running DIS VM program..." << std::endl; vm.run(); std::cout << "โœ… DIS VM execution complete" << std::endl; } std::cout << std::endl; - + // 4. Start Styx Server for Network Transparency std::cout << "๐ŸŒ Step 4: Starting Styx Server..." << std::endl; StyxServer styx_server("localhost:9999"); - + Integration::setup_styx_ai_integration(styx_server, ai_manager); - + // Serve some demo files styx_server.serve_file("/ai/models", "drawkern-rwkv,drawkern-ggml"); styx_server.serve_file("/vm/glyphs", "bolt_ai,file_server,echo_server"); styx_server.serve_file("/drawkern/status", "running,4_components_active"); - + if (styx_server.start()) { std::cout << "โœ… Styx server started on localhost:9999" << std::endl; std::cout << "Network transparency enabled!" << std::endl; - + // Run server in background - std::thread server_thread([&styx_server]() { - styx_server.run(); - }); + std::thread server_thread([&styx_server]() { styx_server.run(); }); server_thread.detach(); } else { std::cout << "โŒ Failed to start Styx server" << std::endl; } std::cout << std::endl; - + // 5. Demonstrate AI Inference std::cout << "๐Ÿค– Step 5: AI Inference Demo..." << std::endl; - + // Test RWKV model std::cout << "Testing RWKV model:" << std::endl; AIInferenceResponse rwkv_response = ai_manager.chat("drawkern-rwkv", "Explain DrawKern in one sentence"); @@ -134,7 +133,7 @@ halt std::cout << "๐Ÿค– RWKV: " << rwkv_response.response << std::endl; std::cout << " Inference time: " << rwkv_response.inference_time_ms << "ms" << std::endl; } - + // Test GGML model std::cout << "\nTesting GGML model:" << std::endl; AIInferenceResponse ggml_response = ai_manager.complete_code("drawkern-ggml", "void setup_ai_workbench() {", "cpp"); @@ -144,115 +143,116 @@ halt std::cout << " Inference time: " << ggml_response.inference_time_ms << "ms" << std::endl; } std::cout << std::endl; - + // 6. Full System Integration Test std::cout << "๐Ÿ”— Step 6: Full System Integration..." << std::endl; - + // Create VM Manager and spawn multiple VMs DISVMManager vm_manager; - + // Create AI workbench VM DISProgram ai_workbench_program = DISProgramFactory::create_ai_workbench("drawkern-rwkv"); std::string ai_vm_id = vm_manager.create_vm(ai_workbench_program); - - // Create file server VM + + // Create file server VM DISProgram file_server_program = DISProgramFactory::create_file_server("/tmp/drawkern_files"); std::string file_vm_id = vm_manager.create_vm(file_server_program); - + std::cout << "Created VMs: " << ai_vm_id << ", " << file_vm_id << std::endl; - + // Start VMs vm_manager.start_vm(ai_vm_id); vm_manager.start_vm(file_vm_id); - + std::cout << "โœ… Multiple VMs running with AI integration" << std::endl << std::endl; - + // 7. Network Client Demo std::cout << "๐Ÿ“ก Step 7: Network Client Demo..." << std::endl; - + // Test Styx client connection StyxConnection client("localhost:9999"); if (client.connect()) { std::cout << "โœ… Connected to Styx server" << std::endl; - + if (client.version() && client.attach()) { std::cout << "โœ… Styx handshake successful" << std::endl; - + // Send a glyph bool glyph_sent = client.send_glyph("ai-workbench-v1"); std::cout << "Glyph transmission: " << (glyph_sent ? "โœ… SUCCESS" : "โŒ FAILED") << std::endl; } - + client.disconnect(); } else { std::cout << "โŒ Failed to connect to Styx server" << std::endl; } std::cout << std::endl; - + // 8. Generate Code from Grammar std::cout << "๐Ÿ”ง Step 8: Code Generation..." << std::endl; - + std::string generated_cpp = grammar.generate_cpp_code(glyph_description); std::cout << "Generated C++ code:" << std::endl; std::cout << generated_cpp.substr(0, 200) << "..." << std::endl; - + std::string deployment_script = grammar.generate_deployment_script(glyph_description); std::cout << "\nGenerated deployment script:" << std::endl; std::cout << deployment_script.substr(0, 150) << "..." << std::endl << std::endl; - + // 9. Display Statistics std::cout << "๐Ÿ“Š Step 9: System Statistics..." << std::endl; - + auto model_stats = ai_manager.get_model_statistics(); for (const auto& stats : model_stats) { std::cout << "Model " << stats.model_id << ":" << std::endl; - std::cout << " Requests: " << stats.total_requests << " (success: " << stats.successful_requests << ")" << std::endl; + std::cout << " Requests: " << stats.total_requests << " (success: " << stats.successful_requests << ")" + << std::endl; std::cout << " Avg inference: " << stats.average_inference_time_ms << "ms" << std::endl; std::cout << " Tokens generated: " << stats.total_tokens_generated << std::endl; } - + auto vm_list = vm_manager.list_vms(); std::cout << "\nActive VMs: " << vm_list.size() << std::endl; for (const auto& vm_id : vm_list) { std::cout << " " << vm_id << " - " << vm_manager.get_vm_status(vm_id) << std::endl; } std::cout << std::endl; - + // 10. Summary std::cout << "๐ŸŽฏ DRAWKERN SYSTEM SUMMARY" << std::endl; std::cout << "=========================" << std::endl; std::cout << "โœ… Styx Protocol: Network transparency active" << std::endl; - std::cout << "โœ… DIS VM System: " << vm_list.size() << " VMs running Limbo bytecode" << std::endl; + std::cout << "โœ… DIS VM System: " << vm_list.size() << " VMs running Limbo bytecode" << std::endl; std::cout << "โœ… Yacc Grammar: Glyph descriptions parsed and validated" << std::endl; std::cout << "โœ… AI Integration: " << model_stats.size() << " models providing inference" << std::endl << std::endl; - + std::cout << "๐ŸŒŸ REVOLUTIONARY CAPABILITIES:" << std::endl; std::cout << "โ€ข Deploy AI workbenches as 'glyphs' to any device" << std::endl; std::cout << "โ€ข Network-transparent file system via Styx protocol" << std::endl; std::cout << "โ€ข Portable execution via DIS VMs running Limbo code" << std::endl; std::cout << "โ€ข Formal grammar for describing VM topologies" << std::endl; std::cout << "โ€ข Real-time AI inference with GGML/RWKV models" << std::endl << std::endl; - + std::cout << "๐Ÿš€ USAGE EXAMPLES:" << std::endl; std::cout << " drawkern render ai-workbench://bolt.dev/v1" << std::endl; std::cout << " drawkern deploy vm://dis:limbo to iot-device" << std::endl; std::cout << " drawkern mount styx://server:9999/ai /local/ai" << std::endl; std::cout << " drawkern spawn --grammar workbench.glyph --model rwkv-14b" << std::endl << std::endl; - + std::cout << "The DrawKern system is now fully operational!" << std::endl; std::cout << "Infrastructure as Glyphs is a reality. ๐ŸŽ‰" << std::endl; - + // Keep server running for a bit to demonstrate network functionality std::cout << "\nRunning for 5 seconds to demonstrate network functionality..." << std::endl; std::this_thread::sleep_for(std::chrono::seconds(5)); - + // Clean shutdown std::cout << "\nShutting down DrawKern system..." << std::endl; styx_server.stop(); vm_manager.stop_vm(ai_vm_id); vm_manager.stop_vm(file_vm_id); - + std::cout << "โœ… DrawKern system shutdown complete." << std::endl; - + return 0; -} \ No newline at end of file +} diff --git a/demo_drawkern_full.cpp b/demo_drawkern_full.cpp index e08dfb5c..5cabd35c 100644 --- a/demo_drawkern_full.cpp +++ b/demo_drawkern_full.cpp @@ -1,12 +1,13 @@ -#include "bolt/drawkern/drawkern.hpp" -#include -#include -#include #include -#include #include +#include +#include +#include +#include + +#include "bolt/drawkern/drawkern.hpp" -using namespace bolt::drawkern; +using namespace bolt::drawkern; // NOLINT(build/namespaces) void print_header(const std::string& title) { std::cout << "\n"; @@ -23,15 +24,18 @@ void demo_step(int step, const std::string& description) { void simulate_deployment(const std::string& target, const std::string& glyph_id) { std::cout << "๐Ÿ“ก Deploying " << glyph_id << " to " << target << "...\n"; - + // Simulate network transmission for (int i = 0; i <= 100; i += 20) { std::cout << "\r ["; int pos = i / 5; for (int j = 0; j < 20; ++j) { - if (j < pos) std::cout << "โ–ˆ"; - else if (j == pos) std::cout << "โ–“"; - else std::cout << "โ–‘"; + if (j < pos) + std::cout << "โ–ˆ"; + else if (j == pos) + std::cout << "โ–“"; + else + std::cout << "โ–‘"; } std::cout << "] " << i << "% "; std::cout.flush(); @@ -75,7 +79,8 @@ bolt_ai_workbench { limbo_code = "implement BoltAI; include \"ai.m\"; ..."; styx_address = "tcp!*!9999"; } -)" << "\n\n"; +)" + << "\n\n"; } void demonstrate_styx_protocol() { @@ -83,7 +88,7 @@ void demonstrate_styx_protocol() { std::cout << "----------------------------\n"; std::cout << "Connection: tcp!drawkern-server!9999\n"; std::cout << "Protocol: Styx (Plan 9 file protocol)\n\n"; - + std::cout << "๐Ÿ“‚ Virtual Filesystem:\n"; std::cout << "/drawkern/\n"; std::cout << "โ”œโ”€โ”€ glyphs/\n"; @@ -107,7 +112,7 @@ void demonstrate_styx_protocol() { std::cout << "โ””โ”€โ”€ deploy/\n"; std::cout << " โ”œโ”€โ”€ targets\n"; std::cout << " โ””โ”€โ”€ status\n\n"; - + std::cout << "๐Ÿ”ง Styx Commands:\n"; std::cout << "โ€ข echo 'bolt-ai-ide-v1' > /drawkern/deploy/targets\n"; std::cout << "โ€ข cat /drawkern/vms/active/vm001/status\n"; @@ -121,7 +126,7 @@ void demonstrate_dis_vm() { std::cout << "Bytecode: Platform-independent\n"; std::cout << "Memory: ~2MB footprint\n"; std::cout << "Languages: Limbo โ†’ DIS bytecode\n\n"; - + std::cout << "๐Ÿ“„ Sample Limbo Code for AI Workbench:\n"; std::cout << R"( implement BoltAI; @@ -180,15 +185,16 @@ show_help() { sys->print(" exit - Exit workbench\n"); sys->print(" - Send to AI for completion\n\n"); } -)" << "\n\n"; +)" + << "\n\n"; } void demonstrate_cross_platform_deployment() { std::cout << "๐ŸŒ Cross-Platform Deployment Demo:\n"; std::cout << "==================================\n\n"; - + std::cout << "Bolt C++ now supports comprehensive cross-platform deployment!\n\n"; - + // Real platform targets that Bolt C++ supports struct DeploymentTarget { std::string name; @@ -198,7 +204,7 @@ void demonstrate_cross_platform_deployment() { std::string package_format; std::string requirements; }; - + std::vector targets = { {"๐Ÿ–ฅ๏ธ Windows Desktop", "Windows 10/11", "x64", "MSVC 2019+/MinGW", ".exe, .msi", "8GB RAM, DirectX 11+"}, {"๐ŸŽ macOS Desktop", "macOS 10.15+", "x64/ARM64", "Clang/Xcode", ".app, .dmg", "8GB RAM, Metal support"}, @@ -207,12 +213,11 @@ void demonstrate_cross_platform_deployment() { {"๐Ÿ“ฑ Android Mobile", "Android 8.0+", "ARM64/x64", "NDK/Clang", ".apk", "4GB RAM, Vulkan API"}, {"๐Ÿค– Raspberry Pi", "Raspberry Pi OS", "ARM64", "GCC", ".deb", "2GB RAM, GPU acceleration"}, {"โ˜๏ธ Cloud Instance", "Docker/K8s", "x64", "GCC/Clang", "Container", "Scalable resources"}, - {"๐Ÿ”Œ IoT/Edge", "Linux RT", "ARM/RISC-V", "Cross-GCC", "Binary", "256MB RAM, headless"} - }; - + {"๐Ÿ”Œ IoT/Edge", "Linux RT", "ARM/RISC-V", "Cross-GCC", "Binary", "256MB RAM, headless"}}; + std::cout << "Supported Deployment Targets:\n"; std::cout << "=============================\n\n"; - + for (const auto& target : targets) { std::cout << target.name << "\n"; std::cout << " Platform: " << target.platform << "\n"; @@ -220,55 +225,53 @@ void demonstrate_cross_platform_deployment() { std::cout << " Compiler: " << target.compiler << "\n"; std::cout << " Package: " << target.package_format << "\n"; std::cout << " Requirements: " << target.requirements << "\n"; - + // Simulate deployment process simulate_deployment(target.name, "bolt-ide"); std::cout << "\n"; } - + std::cout << "๐Ÿ”ง Cross-Platform Build System:\n"; std::cout << "===============================\n\n"; - + std::cout << "โ€ข Modern CMake (3.15+) with cross-platform presets\n"; std::cout << "โ€ข vcpkg for consistent dependency management\n"; std::cout << "โ€ข Platform-specific optimization flags\n"; std::cout << "โ€ข Automated CI/CD pipelines for all platforms\n"; std::cout << "โ€ข Universal build scripts with auto-detection\n\n"; - + std::cout << "๐Ÿ“ฆ Package Management Integration:\n"; std::cout << "==================================\n\n"; - + struct PackageManager { std::string platform; std::string managers; std::string command; }; - - std::vector packages = { - {"Windows", "Chocolatey, Scoop, WinGet", "choco install bolt-cpp"}, - {"macOS", "Homebrew, MacPorts", "brew install bolt-cpp"}, - {"Linux", "apt, dnf, pacman, snap", "sudo apt install bolt-cpp"}, - {"Docker", "Docker Hub", "docker pull echocog/bolt-cpp"}, - {"Web", "npm, CDN", "npm install @echocog/bolt-wasm"} - }; - + + std::vector packages = {{"Windows", "Chocolatey, Scoop, WinGet", "choco install bolt-cpp"}, + {"macOS", "Homebrew, MacPorts", "brew install bolt-cpp"}, + {"Linux", "apt, dnf, pacman, snap", "sudo apt install bolt-cpp"}, + {"Docker", "Docker Hub", "docker pull echocog/bolt-cpp"}, + {"Web", "npm, CDN", "npm install @echocog/bolt-wasm"}}; + for (const auto& pkg : packages) { std::cout << pkg.platform << ": " << pkg.managers << "\n"; std::cout << " Install: " << pkg.command << "\n\n"; } - + std::cout << "โšก Deployment Performance:\n"; std::cout << "=========================\n\n"; - + std::cout << "โ€ข Build time: 2-5 minutes (with dependencies cached)\n"; std::cout << "โ€ข Package size: 15-50MB (depending on platform)\n"; std::cout << "โ€ข Installation time: 30 seconds - 2 minutes\n"; std::cout << "โ€ข Startup time: <3 seconds on modern hardware\n"; std::cout << "โ€ข Memory usage: 50-200MB (depending on features)\n\n"; - + std::cout << "๐Ÿš€ Advanced Features:\n"; std::cout << "====================\n\n"; - + std::cout << "โœ… Universal Binary (macOS Intel + Apple Silicon)\n"; std::cout << "โœ… Static linking for portable executables\n"; std::cout << "โœ… Code signing and notarization (macOS/Windows)\n"; @@ -281,13 +284,13 @@ void demonstrate_cross_platform_deployment() { void demonstrate_ai_integration() { std::cout << "๐Ÿค– AI Integration Demo:\n"; std::cout << "======================\n\n"; - + std::cout << "Available AI Models:\n"; std::cout << "โ€ข GGML-RWKV-14B (Code completion, Chat)\n"; std::cout << "โ€ข GGML-LLaMA-7B (General purpose)\n"; std::cout << "โ€ข CodeT5 (Code translation)\n"; std::cout << "โ€ข GPT-4-Turbo (via API)\n\n"; - + std::cout << "๐Ÿง  AI Capabilities in DrawKern:\n"; std::cout << "โ€ข Real-time code completion\n"; std::cout << "โ€ข Natural language to code\n"; @@ -295,11 +298,12 @@ void demonstrate_ai_integration() { std::cout << "โ€ข Bug detection and fixing\n"; std::cout << "โ€ข Architecture suggestions\n"; std::cout << "โ€ข Performance optimization\n\n"; - + std::cout << "๐Ÿ’ฌ Simulated AI Conversation:\n"; std::cout << "=============================\n"; std::cout << "๐Ÿ‘ค User: Write a function to sort an array in C++\n\n"; std::cout << "๐Ÿค– AI: Here's an efficient C++ sorting function:\n\n"; + // clang-format off std::cout << R"( #include #include @@ -332,8 +336,10 @@ int partition(std::vector& arr, int low, int high) { // Usage: std::vector data = {64, 34, 25, 12, 22, 11, 90}; quicksort(data); -)" << "\n\n"; - +)" + // clang-format on + << "\n\n"; + std::cout << "๐Ÿค– AI: This implements quicksort with O(n log n) average complexity.\n"; std::cout << " The template makes it work with any comparable type!\n\n"; } @@ -341,7 +347,7 @@ quicksort(data); void demonstrate_performance_comparison() { std::cout << "โšก Performance Benchmarks:\n"; std::cout << "=========================\n\n"; - + struct Benchmark { std::string system; std::string latency; @@ -349,32 +355,25 @@ void demonstrate_performance_comparison() { std::string throughput; std::string deployment_time; }; - - std::vector benchmarks = { - {"Traditional Web App", "30-60ms", "200MB", "16-33 FPS", "5-15 minutes"}, - {"React/Electron Desktop", "20-40ms", "150MB", "30-60 FPS", "10-30 minutes"}, - {"C++ ImGui (Your Bolt)", "3-5ms", "50MB", "200+ FPS", "2-5 minutes"}, - {"DrawKern (DIS VM)", "1-3ms", "20MB", "500+ FPS", "5-30 seconds"}, - {"DrawKern (Native)", "0.5-2ms", "15MB", "1000+ FPS", "1-10 seconds"} - }; - + + std::vector benchmarks = {{"Traditional Web App", "30-60ms", "200MB", "16-33 FPS", "5-15 minutes"}, + {"React/Electron Desktop", "20-40ms", "150MB", "30-60 FPS", "10-30 minutes"}, + {"C++ ImGui (Your Bolt)", "3-5ms", "50MB", "200+ FPS", "2-5 minutes"}, + {"DrawKern (DIS VM)", "1-3ms", "20MB", "500+ FPS", "5-30 seconds"}, + {"DrawKern (Native)", "0.5-2ms", "15MB", "1000+ FPS", "1-10 seconds"}}; + std::cout << std::left; - std::cout << std::setw(25) << "System" - << std::setw(12) << "Latency" - << std::setw(10) << "Memory" - << std::setw(15) << "Throughput" - << std::setw(15) << "Deploy Time" << "\n"; + std::cout << std::setw(25) << "System" << std::setw(12) << "Latency" << std::setw(10) << "Memory" << std::setw(15) + << "Throughput" << std::setw(15) << "Deploy Time" + << "\n"; std::cout << std::string(80, '-') << "\n"; - + for (const auto& bench : benchmarks) { - std::cout << std::setw(25) << bench.system - << std::setw(12) << bench.latency - << std::setw(10) << bench.memory - << std::setw(15) << bench.throughput - << std::setw(15) << bench.deployment_time << "\n"; + std::cout << std::setw(25) << bench.system << std::setw(12) << bench.latency << std::setw(10) << bench.memory + << std::setw(15) << bench.throughput << std::setw(15) << bench.deployment_time << "\n"; } std::cout << "\n"; - + std::cout << "๐Ÿ† DrawKern Advantages:\n"; std::cout << "โ€ข 10-50x faster than web applications\n"; std::cout << "โ€ข 5-10x less memory usage\n"; @@ -386,21 +385,21 @@ void demonstrate_performance_comparison() { void demonstrate_future_possibilities() { std::cout << "๐Ÿš€ Future Possibilities:\n"; std::cout << "=======================\n\n"; - + std::cout << "๐ŸŒŸ DrawKern Evolution:\n"; std::cout << "โ€ข GPU-accelerated AI inference in DIS VMs\n"; std::cout << "โ€ข Quantum computing simulation glyphs\n"; std::cout << "โ€ข Blockchain integration for glyph distribution\n"; std::cout << "โ€ข AR/VR rendering backends\n"; std::cout << "โ€ข Brain-computer interface integration\n\n"; - + std::cout << "๐ŸŽฏ Use Cases:\n"; std::cout << "โ€ข Education: Deploy coding environments to any device\n"; std::cout << "โ€ข Research: Distribute AI models as glyphs\n"; std::cout << "โ€ข IoT: Instant sensor network programming\n"; std::cout << "โ€ข Gaming: Cloud gaming with local rendering\n"; std::cout << "โ€ข Healthcare: Medical AI on resource-constrained devices\n\n"; - + std::cout << "๐Ÿ’ญ Imagine:\n"; std::cout << "drawkern render quantum-simulator://mit.edu/qiskit\n"; std::cout << "drawkern deploy ai-doctor://who.int/diagnosis to rural-clinic-001\n"; @@ -410,63 +409,63 @@ void demonstrate_future_possibilities() { int main() { print_header("๐Ÿš€ COMPLETE DRAWKERN DEMONSTRATION ๐Ÿš€"); print_header("Infrastructure as Glyphs - The Future of Computing"); - + std::cout << "Welcome to the revolutionary DrawKern system!\n"; std::cout << "This demo showcases how computing environments can be described,\n"; std::cout << "transmitted, and rendered like typography - anywhere, anytime!\n"; - + demo_step(1, "Creating AI Workbench Glyph"); AIWorkbenchGlyph bolt_glyph = create_bolt_ai_glyph(); std::cout << "โœ… Generated glyph: " << bolt_glyph.workbench_id << "\n"; std::cout << "๐Ÿ“Š Glyph size: ~15KB (contains entire AI workbench!)\n\n"; - + demo_step(2, "Yacc Grammar for VM Glyph Descriptions"); demonstrate_yacc_grammar(); - + demo_step(3, "Styx Protocol - Network Transparency"); demonstrate_styx_protocol(); - + demo_step(4, "DIS Virtual Machine Execution"); demonstrate_dis_vm(); - + demo_step(5, "Cross-Platform Deployment"); demonstrate_cross_platform_deployment(); - + demo_step(6, "AI Integration Capabilities"); demonstrate_ai_integration(); - + demo_step(7, "Performance Analysis"); demonstrate_performance_comparison(); - + demo_step(8, "Client Rendering Demonstrations"); std::cout << "๐Ÿ–ฅ๏ธ TERMINAL CLIENT:\n"; TerminalDrawKernClient terminal_client("localhost:9999"); terminal_client.render_ai_interface(bolt_glyph); - + std::cout << "๐ŸŒ WEB CLIENT:\n"; WebDrawKernClient web_client("localhost:9999"); web_client.render_ai_interface(bolt_glyph); - + demo_step(9, "Future Possibilities"); demonstrate_future_possibilities(); - + print_header("๐ŸŽ‰ DEMONSTRATION COMPLETE ๐ŸŽ‰"); - + std::cout << "๐Ÿ† ACHIEVEMENTS UNLOCKED:\n"; std::cout << "โœ… Infrastructure as Glyphs concept proven\n"; std::cout << "โœ… Universal deployment capability demonstrated\n"; std::cout << "โœ… 10-50x performance improvement over web apps\n"; std::cout << "โœ… Plan 9 philosophy extended to modern computing\n"; std::cout << "โœ… AI workbenches as portable glyphs\n\n"; - + std::cout << "๐ŸŒŸ REVOLUTIONARY IMPACT:\n"; std::cout << "โ€ข Software becomes as easy to deploy as displaying text\n"; std::cout << "โ€ข AI capabilities available on any device, anywhere\n"; std::cout << "โ€ข Network transparency for all computing environments\n"; std::cout << "โ€ข End of platform-specific software development\n\n"; - + std::cout << "๐Ÿš€ The future of computing is here - and it's beautiful!\n"; std::cout << "Thank you for experiencing the DrawKern revolution! ๐Ÿ™\n\n"; - + return 0; } diff --git a/demo_editor_minimap.cpp b/demo_editor_minimap.cpp index ffe734e5..467410ab 100644 --- a/demo_editor_minimap.cpp +++ b/demo_editor_minimap.cpp @@ -1,23 +1,24 @@ -#include #include +#include + #include "bolt/editor/editor_pane.hpp" #include "bolt/editor/split_view_manager.hpp" -using namespace bolt; +using namespace bolt; // NOLINT(build/namespaces) void createLargeTestFile() { std::ofstream file("/tmp/editor_test.cpp"); - + file << "// Large C++ File for Editor Pane Minimap Demo\n"; file << "// Demonstrating minimap integration with editor panes\n\n"; - + file << "#include \n"; file << "#include \n"; file << "#include \n"; file << "#include \n\n"; - + file << "namespace editor_demo {\n\n"; - + // Create a realistic C++ class structure file << "class DocumentEditor {\n"; file << "private:\n"; @@ -25,10 +26,10 @@ void createLargeTestFile() { file << " size_t cursorLine_;\n"; file << " size_t cursorColumn_;\n"; file << " bool modified_;\n\n"; - + file << "public:\n"; file << " DocumentEditor() : cursorLine_(0), cursorColumn_(0), modified_(false) {}\n\n"; - + // Add many methods to make it a large file for (int i = 1; i <= 30; ++i) { file << " void operation" << i << "() {\n"; @@ -39,7 +40,7 @@ void createLargeTestFile() { file << " }\n"; file << " }\n\n"; } - + file << " void loadDocument(const std::string& content) {\n"; file << " lines_.clear();\n"; file << " std::istringstream stream(content);\n"; @@ -49,14 +50,14 @@ void createLargeTestFile() { file << " }\n"; file << " modified_ = false;\n"; file << " }\n\n"; - + file << " void setCursorPosition(size_t line, size_t column) {\n"; file << " cursorLine_ = line;\n"; file << " cursorColumn_ = column;\n"; file << " }\n\n"; - + file << "};\n\n"; - + // Add some free functions for (int i = 1; i <= 20; ++i) { file << "void utilityFunction" << i << "() {\n"; @@ -65,9 +66,9 @@ void createLargeTestFile() { file << " std::cout << \"Utility function " << i << " completed\" << std::endl;\n"; file << "}\n\n"; } - + file << "} // namespace editor_demo\n\n"; - + file << "int main() {\n"; file << " std::cout << \"Editor Pane Minimap Demo\" << std::endl;\n"; file << " \n"; @@ -80,82 +81,82 @@ void createLargeTestFile() { file << " std::cout << \"Demo complete\" << std::endl;\n"; file << " return 0;\n"; file << "}\n"; - + file.close(); } int main() { std::cout << "Editor Pane Minimap Integration Demo" << std::endl; std::cout << "====================================" << std::endl << std::endl; - + // Create test file std::cout << "Creating large test file..." << std::endl; createLargeTestFile(); - + // Get the split view manager auto& splitManager = SplitViewManager::getInstance(); - + std::cout << "Initial state:" << std::endl; std::cout << " - Number of panes: " << splitManager.getPaneCount() << std::endl << std::endl; - + // Create a new pane std::cout << "1. Creating editor pane..." << std::endl; std::string paneId = splitManager.createPane(); auto* pane = splitManager.getPane(paneId); - + if (!pane) { std::cerr << "Failed to create pane!" << std::endl; return 1; } - + std::cout << " - Pane ID: " << paneId << std::endl; std::cout << " - Minimap enabled: " << (pane->isMinimapEnabled() ? "Yes" : "No") << std::endl; - + // Set pane position EditorPane::PanePosition pos{0, 0, 1000, 800}; pane->setPosition(pos); - + std::cout << "\n2. Opening document in pane..." << std::endl; pane->openDocument("/tmp/editor_test.cpp"); - + std::cout << " - Document loaded: " << (pane->hasDocument() ? "Yes" : "No") << std::endl; std::cout << " - Document path: " << pane->getDocumentPath() << std::endl; - + // Check minimap auto* minimap = pane->getMinimap(); auto* minimapUI = pane->getMinimapUI(); - + if (minimap && minimapUI) { std::cout << " - Minimap total lines: " << minimap->getTotalLines() << std::endl; std::cout << " - Minimap visible lines: " << minimap->getVisibleLines() << std::endl; std::cout << " - Minimap UI width: " << minimapUI->getRequiredWidth() << std::endl; std::cout << " - Minimap UI height: " << minimapUI->getRequiredHeight() << std::endl; } - + std::cout << "\n3. Testing cursor and scroll operations..." << std::endl; - + // Test cursor movement pane->setCursorPosition(50, 10); auto state = pane->getState(); std::cout << " - Set cursor to line 50, column 10" << std::endl; std::cout << " - Current cursor: line " << state.cursorLine << ", column " << state.cursorColumn << std::endl; - + // Test scrolling pane->setScrollPosition(100, 0); state = pane->getState(); std::cout << " - Scrolled to line 100" << std::endl; std::cout << " - Current scroll: line " << state.scrollLine << ", column " << state.scrollColumn << std::endl; - + if (minimap) { auto viewport = minimap->getViewport(); std::cout << " - Minimap viewport: " << viewport.startLine << "-" << viewport.endLine << std::endl; std::cout << " - Minimap current line: " << viewport.currentLine << std::endl; std::cout << " - Scroll percentage: " << (minimap->getScrollPercentage() * 100) << "%" << std::endl; } - + std::cout << "\n4. Rendering minimap..." << std::endl; auto minimapRender = pane->renderMinimap(); - + if (!minimapRender.empty()) { std::cout << " Minimap UI (first 10 lines):" << std::endl; for (size_t i = 0; i < std::min(size_t{10}, minimapRender.size()); ++i) { @@ -165,41 +166,42 @@ int main() { std::cout << " ... (" << (minimapRender.size() - 10) << " more lines)" << std::endl; } } - + std::cout << "\n5. Testing minimap navigation..." << std::endl; if (minimap) { // Test line mapping size_t targetLine = minimap->getLineFromPosition(10, 5); std::cout << " - Position (10, 5) maps to line: " << targetLine << std::endl; - + auto [x, y] = minimap->getPositionFromLine(200); std::cout << " - Line 200 maps to position: (" << x << ", " << y << ")" << std::endl; - + // Test scroll to different positions minimap->scrollToLine(0); std::cout << " - Scrolled to top, percentage: " << (minimap->getScrollPercentage() * 100) << "%" << std::endl; - + minimap->scrollToLine(minimap->getTotalLines() / 2); - std::cout << " - Scrolled to middle, percentage: " << (minimap->getScrollPercentage() * 100) << "%" << std::endl; + std::cout << " - Scrolled to middle, percentage: " << (minimap->getScrollPercentage() * 100) << "%" + << std::endl; } - + std::cout << "\n6. Testing minimap disable/enable..." << std::endl; pane->setMinimapEnabled(false); std::cout << " - Minimap disabled: " << (!pane->isMinimapEnabled() ? "Yes" : "No") << std::endl; - + auto disabledRender = pane->renderMinimap(); std::cout << " - Rendered lines when disabled: " << disabledRender.size() << std::endl; - + pane->setMinimapEnabled(true); std::cout << " - Minimap re-enabled: " << (pane->isMinimapEnabled() ? "Yes" : "No") << std::endl; - + auto enabledRender = pane->renderMinimap(); std::cout << " - Rendered lines when enabled: " << enabledRender.size() << std::endl; - + std::cout << "\n=================================" << std::endl; std::cout << "Integration Demo Complete!" << std::endl; std::cout << "=================================" << std::endl; - + std::cout << "\nMinimap features successfully integrated:" << std::endl; std::cout << " โœ“ Automatic minimap creation with editor panes" << std::endl; std::cout << " โœ“ Minimap updates with cursor and scroll changes" << std::endl; @@ -208,6 +210,6 @@ int main() { std::cout << " โœ“ Navigation callbacks integrated with pane operations" << std::endl; std::cout << " โœ“ Enable/disable minimap functionality" << std::endl; std::cout << " โœ“ UI rendering with borders, titles, and scroll indicators" << std::endl; - + return 0; -} \ No newline at end of file +} diff --git a/demo_file_tree.cpp b/demo_file_tree.cpp index a10155ac..09c072c8 100644 --- a/demo_file_tree.cpp +++ b/demo_file_tree.cpp @@ -1,10 +1,11 @@ -#include "bolt/editor/file_tree_manager.hpp" -#include "bolt/editor/file_tree_ui.hpp" +#include #include #include -#include -using namespace bolt; +#include "bolt/editor/file_tree_manager.hpp" +#include "bolt/editor/file_tree_ui.hpp" + +using namespace bolt; // NOLINT(build/namespaces) void demonstrateFileTree() { std::cout << "Bolt C++ File Tree Navigation Component Demo\n"; @@ -16,22 +17,19 @@ void demonstrateFileTree() { // Initialize the file tree manager auto& manager = FileTreeManager::getInstance(); - + // Set up callbacks to demonstrate integration - manager.setOnFileSelected([](const std::string& path) { - std::cout << ">>> FILE SELECTED: " << path << std::endl; - }); - - manager.setOnDirectoryExpanded([](const std::string& path) { - std::cout << ">>> DIRECTORY EXPANDED: " << path << std::endl; - }); + manager.setOnFileSelected([](const std::string& path) { std::cout << ">>> FILE SELECTED: " << path << std::endl; }); + + manager.setOnDirectoryExpanded( + [](const std::string& path) { std::cout << ">>> DIRECTORY EXPANDED: " << path << std::endl; }); // Set the root directory to current directory manager.setRootDirectory(currentDir); // Create UI component FileTreeUI ui; - + // Configure rendering options FileTreeRenderOptions options; options.showIcons = true; @@ -58,7 +56,7 @@ void demonstrateFileTree() { break; } } - + std::cout << "Selecting file: " << firstFile->name << "\n"; manager.selectFile(firstFile->fullPath); ui.render(); @@ -73,12 +71,12 @@ void demonstrateFileTree() { manager.expandDirectory(node->fullPath); ui.render(); std::cout << "\n"; - + std::cout << "Collapsing directory: " << node->name << "\n"; manager.collapseDirectory(node->fullPath); ui.render(); std::cout << "\n"; - break; // Just demo with first expandable directory + break; // Just demo with first expandable directory } } @@ -114,4 +112,4 @@ int main() { std::cerr << "Error: " << e.what() << std::endl; return 1; } -} \ No newline at end of file +} diff --git a/demo_git_integration.cpp b/demo_git_integration.cpp index 12d0b5ce..a116e805 100644 --- a/demo_git_integration.cpp +++ b/demo_git_integration.cpp @@ -1,60 +1,60 @@ +#include +#include +#include +#include #include #include -#include -#include -#include -#include #include -#include +#include #include "bolt/git/git.hpp" class GitIntegrationDemo { -public: + public: static void runDemo() { std::cout << "=== Bolt C++ IDE - Git Integration Demo ===\n\n"; - + // Initialize Git integration auto& gitIntegration = bolt::git::getGitIntegration(); std::string currentDir = std::filesystem::current_path().string(); - + if (!gitIntegration.initialize(currentDir)) { std::cout << "โŒ This directory is not a Git repository.\n"; std::cout << "Please run this demo from within a Git repository.\n"; return; } - + std::cout << "โœ… Git integration initialized successfully!\n\n"; - + // Set up callbacks setupCallbacks(); - + // Demo the features showRepositoryInfo(); showBranchInfo(); showFileStatus(); showGitOperations(); - + // Enable auto-refresh for demonstration std::cout << "Enabling auto-refresh (5 second interval)...\n"; gitIntegration.setAutoRefresh(true, 5); - + std::cout << "\nโณ Auto-refresh enabled. File status will update automatically.\n"; std::cout << " You can modify files in another terminal to see status changes.\n"; std::cout << " Press Enter to continue...\n"; std::cin.get(); - + gitIntegration.shutdown(); std::cout << "\nโœ… Git integration demo completed!\n"; } -private: + private: static void setupCallbacks() { auto& gitIntegration = bolt::git::getGitIntegration(); - + gitIntegration.setStatusUpdateCallback([](const std::vector& files) { std::cout << "\n๐Ÿ“Š Git status updated - " << files.size() << " files tracked\n"; - + int modified = 0, staged = 0, untracked = 0; for (const auto& file : files) { switch (file.status) { @@ -72,10 +72,11 @@ class GitIntegrationDemo { break; } } - - std::cout << " ๐Ÿ“ " << modified << " modified, ๐Ÿ“ฆ " << staged << " staged, โ“ " << untracked << " untracked\n"; + + std::cout << " ๐Ÿ“ " << modified << " modified, ๐Ÿ“ฆ " << staged << " staged, โ“ " << untracked + << " untracked\n"; }); - + gitIntegration.setOperationCallback([](bool success, const std::string& message) { if (success) { std::cout << "โœ… Git operation: " << message << "\n"; @@ -84,14 +85,14 @@ class GitIntegrationDemo { } }); } - + static void showRepositoryInfo() { std::cout << "๐Ÿ“ Repository Information:\n"; std::cout << std::string(40, '-') << "\n"; - + auto& gitIntegration = bolt::git::getGitIntegration(); auto repoInfo = gitIntegration.getRepositoryInfo(); - + std::cout << "Root Path: " << repoInfo.rootPath << "\n"; std::cout << "Current Branch: " << repoInfo.currentBranch << "\n"; std::cout << "Status: " << (repoInfo.isClean ? "๐ŸŸข Clean" : "๐ŸŸก Has changes") << "\n"; @@ -101,17 +102,17 @@ class GitIntegrationDemo { std::cout << " โ“ Untracked: " << repoInfo.untrackedFiles << "\n"; std::cout << "\n"; } - + static void showBranchInfo() { std::cout << "๐ŸŒฟ Branch Information:\n"; std::cout << std::string(40, '-') << "\n"; - + auto& gitIntegration = bolt::git::getGitIntegration(); auto branchStatus = gitIntegration.getBranchStatus(); - + std::cout << "Current Branch: " << branchStatus.currentBranch << "\n"; std::cout << "Uncommitted Changes: " << (branchStatus.hasUncommittedChanges ? "Yes" : "No") << "\n"; - + if (branchStatus.hasRemote) { std::cout << "Remote Status:\n"; std::cout << " ๐Ÿ”ผ Commits ahead: " << branchStatus.commitsAhead << "\n"; @@ -119,7 +120,7 @@ class GitIntegrationDemo { } else { std::cout << "Remote Status: No remote configured\n"; } - + // Show all branches auto repo = gitIntegration.getRepository(); if (repo) { @@ -128,28 +129,29 @@ class GitIntegrationDemo { for (const auto& branch : branches) { std::cout << " " << (branch.isCurrent ? "โ†’ " : " "); std::cout << branch.name; - if (branch.isRemote) std::cout << " (remote)"; + if (branch.isRemote) + std::cout << " (remote)"; std::cout << "\n"; } } std::cout << "\n"; } - + static void showFileStatus() { std::cout << "๐Ÿ“‹ File Status:\n"; std::cout << std::string(40, '-') << "\n"; - + auto& gitIntegration = bolt::git::getGitIntegration(); auto allFiles = gitIntegration.getAllFileStatus(); - + if (allFiles.empty()) { std::cout << "๐ŸŸข Working directory is clean - no changes detected\n\n"; return; } - + // Group files by status std::vector modified, staged, untracked, deleted, renamed; - + for (const auto& file : allFiles) { switch (file.status) { case bolt::git::GitFileStatus::MODIFIED: @@ -171,8 +173,9 @@ class GitIntegrationDemo { break; } } - - auto printFileList = [](const std::string& title, const std::string& icon, const std::vector& files) { + + auto printFileList = [](const std::string& title, const std::string& icon, + const std::vector& files) { if (!files.empty()) { std::cout << icon << " " << title << " (" << files.size() << "):\n"; for (const auto& file : files) { @@ -181,26 +184,26 @@ class GitIntegrationDemo { std::cout << "\n"; } }; - + printFileList("Modified files", "๐Ÿ“", modified); printFileList("Staged files", "๐Ÿ“ฆ", staged); printFileList("Untracked files", "โ“", untracked); printFileList("Deleted files", "๐Ÿ—‘๏ธ", deleted); printFileList("Renamed files", "๐Ÿ”„", renamed); } - + static void showGitOperations() { std::cout << "โšก Git Operations Demo:\n"; std::cout << std::string(40, '-') << "\n"; - + auto& gitIntegration = bolt::git::getGitIntegration(); auto repo = gitIntegration.getRepository(); - + if (!repo) { std::cout << "โŒ No repository available\n"; return; } - + // Show recent commits auto commits = repo->getCommitLog(5); if (!commits.empty()) { @@ -210,7 +213,7 @@ class GitIntegrationDemo { } std::cout << "\n"; } - + // Demonstrate file diff (if there are modified files) auto allFiles = gitIntegration.getAllFileStatus(); for (const auto& file : allFiles) { @@ -231,10 +234,10 @@ class GitIntegrationDemo { } std::cout << "\n"; } - break; // Just show diff for first modified file + break; // Just show diff for first modified file } } - + // Demonstrate quick operations (read-only for safety) std::cout << "๐Ÿ› ๏ธ Available quick operations:\n"; std::cout << " - Stage file: bolt::git::quick::stage(\"filename\")\n"; @@ -258,4 +261,4 @@ int main() { std::cerr << "Demo failed with unknown exception" << std::endl; return 1; } -} \ No newline at end of file +} diff --git a/demo_integration.cpp b/demo_integration.cpp index 8fcbcf6d..fa9e61d8 100644 --- a/demo_integration.cpp +++ b/demo_integration.cpp @@ -1,9 +1,10 @@ -#include "bolt/editor/integrated_editor.hpp" -#include #include #include +#include + +#include "bolt/editor/integrated_editor.hpp" -using namespace bolt; +using namespace bolt; // NOLINT(build/namespaces) void demonstrateFileTreeIntegration() { std::cout << "Bolt C++ File Tree Integration Demo\n"; @@ -17,15 +18,14 @@ void demonstrateFileTreeIntegration() { std::filesystem::create_directories(testDir); std::filesystem::create_directories(testDir + "/src"); std::filesystem::create_directories(testDir + "/include"); - + // Create some test files - std::ofstream(testDir + "/main.cpp") + std::ofstream(testDir + "/main.cpp") << "#include \n\nint main() {\n std::cout << \"Hello World!\" << std::endl;\n return 0;\n}\n"; - std::ofstream(testDir + "/README.md") - << "# Test Project\n\nThis is a test project for the file tree demo.\n"; - std::ofstream(testDir + "/src/utils.cpp") + std::ofstream(testDir + "/README.md") << "# Test Project\n\nThis is a test project for the file tree demo.\n"; + std::ofstream(testDir + "/src/utils.cpp") << "#include \"utils.h\"\n\nvoid utils_function() {\n // Implementation\n}\n"; - std::ofstream(testDir + "/include/utils.h") + std::ofstream(testDir + "/include/utils.h") << "#ifndef UTILS_H\n#define UTILS_H\n\nvoid utils_function();\n\n#endif\n"; std::cout << "Created test project structure at: " << testDir << "\n\n"; @@ -56,17 +56,17 @@ void demonstrateFileTreeIntegration() { std::cout << "Toggling file tree visibility...\n"; editor.toggleFileTreeVisibility(); std::cout << "File tree is visible: " << (editor.isFileTreeVisible() ? "Yes" : "No") << "\n"; - editor.toggleFileTreeVisibility(); // Toggle back + editor.toggleFileTreeVisibility(); // Toggle back std::cout << "Toggled back. File tree is visible: " << (editor.isFileTreeVisible() ? "Yes" : "No") << "\n\n"; // Demonstrate folding integration with file tree std::cout << "Testing folding integration...\n"; editor.setFoldingEnabled(true); - + // Open a C++ file and test folding std::string utilsCppPath = testDir + "/src/utils.cpp"; editor.openFileFromTree(utilsCppPath); - + auto foldingRanges = editor.getFoldingRanges(utilsCppPath); std::cout << "Folding ranges detected for " << utilsCppPath << ": " << foldingRanges.size() << " ranges\n"; @@ -88,4 +88,4 @@ int main() { std::cerr << "Error: " << e.what() << std::endl; return 1; } -} \ No newline at end of file +} diff --git a/demo_keyboard_shortcuts.cpp b/demo_keyboard_shortcuts.cpp index 1f8458c5..370df20f 100644 --- a/demo_keyboard_shortcuts.cpp +++ b/demo_keyboard_shortcuts.cpp @@ -1,74 +1,72 @@ #include #include -#include "bolt/editor/keyboard_shortcuts.hpp" + #include "bolt/editor/integrated_editor.hpp" +#include "bolt/editor/keyboard_shortcuts.hpp" -using namespace bolt; +using namespace bolt; // NOLINT(build/namespaces) void demonstrateKeyParsing() { std::cout << "\n=== Key Combination Parsing ===" << std::endl; - + // Demonstrate various key combinations - std::vector testKeys = { - "Ctrl+S", "Ctrl+Shift+Z", "Alt+F4", "Ctrl+Alt+Delete", - "F1", "Escape", "Meta+A", "Ctrl+Shift+Alt+T" - }; - + std::vector testKeys = {"Ctrl+S", "Ctrl+Shift+Z", "Alt+F4", "Ctrl+Alt+Delete", + "F1", "Escape", "Meta+A", "Ctrl+Shift+Alt+T"}; + for (const auto& keyStr : testKeys) { auto combo = KeyCombination::fromString(keyStr); - std::cout << "Input: " << keyStr << " -> Parsed: " << combo.toString() + std::cout << "Input: " << keyStr << " -> Parsed: " << combo.toString() << " (Valid: " << (combo.isValid() ? "Yes" : "No") << ")" << std::endl; } } void demonstrateContextualShortcuts() { std::cout << "\n=== Contextual Shortcuts ===" << std::endl; - + KeyboardShortcuts& shortcuts = KeyboardShortcuts::getInstance(); - + // Register shortcuts in different contexts - shortcuts.registerShortcut("F1", "showHelp", []() { - std::cout << " -> Showing global help" << std::endl; - }, ShortcutContext::Global, "Show global help"); - - shortcuts.registerShortcut("F1", "showEditorHelp", []() { - std::cout << " -> Showing editor-specific help" << std::endl; - }, ShortcutContext::Editor, "Show editor help"); - - shortcuts.registerShortcut("F1", "showSearchHelp", []() { - std::cout << " -> Showing search help" << std::endl; - }, ShortcutContext::Search, "Show search help"); - + shortcuts.registerShortcut( + "F1", "showHelp", []() { std::cout << " -> Showing global help" << std::endl; }, ShortcutContext::Global, + "Show global help"); + + shortcuts.registerShortcut( + "F1", "showEditorHelp", []() { std::cout << " -> Showing editor-specific help" << std::endl; }, + ShortcutContext::Editor, "Show editor help"); + + shortcuts.registerShortcut( + "F1", "showSearchHelp", []() { std::cout << " -> Showing search help" << std::endl; }, ShortcutContext::Search, + "Show search help"); + // Demonstrate context switching std::cout << "Testing F1 in different contexts:" << std::endl; - + std::cout << "Global context: "; shortcuts.executeShortcut("F1", ShortcutContext::Global); - + std::cout << "Editor context: "; shortcuts.executeShortcut("F1", ShortcutContext::Editor); - + std::cout << "Search context: "; shortcuts.executeShortcut("F1", ShortcutContext::Search); } void demonstrateShortcutDiscovery() { std::cout << "\n=== Shortcut Discovery ===" << std::endl; - + KeyboardShortcuts& shortcuts = KeyboardShortcuts::getInstance(); - + // Initialize default shortcuts shortcuts.initDefaultShortcuts(); - + // Show all editor shortcuts auto editorShortcuts = shortcuts.getShortcutsForContext(ShortcutContext::Editor); std::cout << "Editor shortcuts (" << editorShortcuts.size() << " total):" << std::endl; - + size_t count = 0; for (const auto& info : editorShortcuts) { - if (count < 5) { // Show first 5 for brevity - std::cout << " " << info.keyCombination.toString() - << " -> " << info.command; + if (count < 5) { // Show first 5 for brevity + std::cout << " " << info.keyCombination.toString() << " -> " << info.command; if (!info.description.empty()) { std::cout << " (" << info.description << ")"; } @@ -79,27 +77,28 @@ void demonstrateShortcutDiscovery() { if (editorShortcuts.size() > 5) { std::cout << " ... and " << (editorShortcuts.size() - 5) << " more" << std::endl; } - + // Show shortcuts for a specific key auto ctrlShortcuts = shortcuts.findShortcutsByKey("Ctrl+S"); std::cout << "\nShortcuts using Ctrl+S:" << std::endl; for (const auto& info : ctrlShortcuts) { - std::cout << " Context: " << (info.context == ShortcutContext::Global ? "Global" : - info.context == ShortcutContext::Editor ? "Editor" : "Other") - << ", Command: " << info.command - << ", Description: " << info.description << std::endl; + std::cout << " Context: " + << (info.context == ShortcutContext::Global ? "Global" + : info.context == ShortcutContext::Editor ? "Editor" + : "Other") + << ", Command: " << info.command << ", Description: " << info.description << std::endl; } } void demonstrateHelpSystem() { std::cout << "\n=== Help System ===" << std::endl; - + KeyboardShortcuts& shortcuts = KeyboardShortcuts::getInstance(); - + // Get help for global context std::string globalHelp = shortcuts.getHelpText(ShortcutContext::Global); std::cout << "Sample of Global shortcuts help:" << std::endl; - + // Show first few lines of help std::istringstream iss(globalHelp); std::string line; @@ -113,74 +112,74 @@ void demonstrateHelpSystem() { void demonstrateIntegratedEditorShortcuts() { std::cout << "\n=== Integrated Editor Shortcuts ===" << std::endl; - + IntegratedEditor& editor = IntegratedEditor::getInstance(); - + // Initialize shortcuts through the editor editor.initializeKeyboardShortcuts(); - + std::cout << "Testing multi-cursor shortcuts through IntegratedEditor:" << std::endl; - + // Clear any existing cursors editor.clearExtraCursors(); editor.addCursorAtPosition(0, 0); std::cout << "Initial cursors: " << editor.getCursorCount() << std::endl; - + // Test Ctrl+D (add cursor at next occurrence) std::cout << "Executing Ctrl+D (add cursor at next occurrence)..." << std::endl; bool result = editor.handleKeyboardShortcut("Ctrl+D", "addCursorAtNextOccurrence"); - std::cout << " Result: " << (result ? "Success" : "Failed") - << ", Cursors: " << editor.getCursorCount() << std::endl; - + std::cout << " Result: " << (result ? "Success" : "Failed") << ", Cursors: " << editor.getCursorCount() + << std::endl; + // Test Ctrl+Alt+Down (add cursor below) std::cout << "Executing Ctrl+Alt+Down (add cursor below)..." << std::endl; result = editor.handleKeyboardShortcut("Ctrl+Alt+Down", "addCursorBelow"); - std::cout << " Result: " << (result ? "Success" : "Failed") - << ", Cursors: " << editor.getCursorCount() << std::endl; - + std::cout << " Result: " << (result ? "Success" : "Failed") << ", Cursors: " << editor.getCursorCount() + << std::endl; + // Test Escape (clear extra cursors) std::cout << "Executing Escape (clear extra cursors)..." << std::endl; result = editor.handleKeyboardShortcut("Escape", "clearExtraCursors"); - std::cout << " Result: " << (result ? "Success" : "Failed") - << ", Cursors: " << editor.getCursorCount() << std::endl; + std::cout << " Result: " << (result ? "Success" : "Failed") << ", Cursors: " << editor.getCursorCount() + << std::endl; } void demonstrateConflictPrevention() { std::cout << "\n=== Conflict Prevention ===" << std::endl; - + KeyboardShortcuts& shortcuts = KeyboardShortcuts::getInstance(); - + // Try to register a conflicting shortcut std::cout << "Attempting to register Ctrl+S for 'saveAs' in Global context..." << std::endl; - bool result1 = shortcuts.registerShortcut("Ctrl+S", "saveAs", []() { - std::cout << "Save As executed" << std::endl; - }, ShortcutContext::Global, "Save file as"); - + bool result1 = shortcuts.registerShortcut( + "Ctrl+S", "saveAs", []() { std::cout << "Save As executed" << std::endl; }, ShortcutContext::Global, + "Save file as"); + std::cout << " Registration result: " << (result1 ? "Success" : "Failed (conflict detected)") << std::endl; - + // Register same shortcut in different context std::cout << "Attempting to register Ctrl+S for 'saveAs' in Editor context..." << std::endl; - bool result2 = shortcuts.registerShortcut("Ctrl+S", "saveAs", []() { - std::cout << "Editor Save As executed" << std::endl; - }, ShortcutContext::Editor, "Save file as"); - + bool result2 = shortcuts.registerShortcut( + "Ctrl+S", "saveAs", []() { std::cout << "Editor Save As executed" << std::endl; }, ShortcutContext::Editor, + "Save file as"); + std::cout << " Registration result: " << (result2 ? "Success" : "Failed (conflict detected)") << std::endl; } void demonstrateEnableDisable() { std::cout << "\n=== Enable/Disable Shortcuts ===" << std::endl; - + KeyboardShortcuts& shortcuts = KeyboardShortcuts::getInstance(); - + // Register a test shortcut - shortcuts.registerShortcut("Ctrl+T", "testCommand", []() { - std::cout << " -> Test command executed" << std::endl; - }, ShortcutContext::Global, "Test command"); - + shortcuts.registerShortcut( + "Ctrl+T", "testCommand", []() { std::cout << " -> Test command executed" << std::endl; }, + ShortcutContext::Global, "Test command"); + std::cout << "Shortcuts enabled: " << (shortcuts.isEnabled() ? "Yes" : "No") << std::endl; std::cout << "Executing Ctrl+T: "; shortcuts.executeShortcut("Ctrl+T", ShortcutContext::Global); - + // Disable shortcuts shortcuts.setEnabled(false); std::cout << "Shortcuts enabled: " << (shortcuts.isEnabled() ? "Yes" : "No") << std::endl; @@ -189,7 +188,7 @@ void demonstrateEnableDisable() { if (!result) { std::cout << " -> Shortcut disabled, not executed" << std::endl; } - + // Re-enable shortcuts shortcuts.setEnabled(true); std::cout << "Shortcuts enabled: " << (shortcuts.isEnabled() ? "Yes" : "No") << std::endl; @@ -200,7 +199,7 @@ void demonstrateEnableDisable() { int main() { std::cout << "Bolt C++ Keyboard Shortcuts System Demo" << std::endl; std::cout << "========================================" << std::endl; - + try { demonstrateKeyParsing(); demonstrateContextualShortcuts(); @@ -209,7 +208,7 @@ int main() { demonstrateIntegratedEditorShortcuts(); demonstrateConflictPrevention(); demonstrateEnableDisable(); - + std::cout << "\n=== Keyboard Shortcuts System Demo Completed! ===" << std::endl; std::cout << "The enhanced keyboard shortcuts system provides:" << std::endl; std::cout << "โœ“ Robust key combination parsing" << std::endl; @@ -218,11 +217,10 @@ int main() { std::cout << "โœ“ Comprehensive help and discovery system" << std::endl; std::cout << "โœ“ Enable/disable functionality" << std::endl; std::cout << "โœ“ Integration with editor components" << std::endl; - } catch (const std::exception& e) { std::cerr << "Demo failed with exception: " << e.what() << std::endl; return 1; } - + return 0; -} \ No newline at end of file +} diff --git a/demo_logging.cpp b/demo_logging.cpp index da521c73..1d3f50b3 100644 --- a/demo_logging.cpp +++ b/demo_logging.cpp @@ -1,15 +1,16 @@ -#include "bolt/core/logging.hpp" -#include "bolt/core/error_handling.hpp" +#include #include #include -#include + +#include "bolt/core/error_handling.hpp" +#include "bolt/core/logging.hpp" void demonstrateBasicLogging() { std::cout << "\n=== Basic Logging Demo ===" << std::endl; - + // Configure console logging with detailed format bolt::LogManager::configureConsoleLogging(bolt::LogLevel::DEBUG, true); - + // Test different log levels BOLT_TRACE("This is a trace message"); BOLT_DEBUG("This is a debug message"); @@ -21,7 +22,7 @@ void demonstrateBasicLogging() { void demonstrateCategoryLogging() { std::cout << "\n=== Category-Based Logging Demo ===" << std::endl; - + // Test category-specific logging BOLT_LOG_CORE(bolt::LogLevel::INFO, "Core system initialization"); BOLT_LOG_MEMORY(bolt::LogLevel::DEBUG, "Memory allocation: 1024 bytes"); @@ -34,103 +35,104 @@ void demonstrateCategoryLogging() { void demonstrateFileLogging() { std::cout << "\n=== File Logging Demo ===" << std::endl; - + // Configure file logging std::string logFile = "/tmp/bolt_demo.log"; bolt::LogManager::configureFileLogging(logFile, bolt::LogLevel::TRACE, true); - + std::cout << "Logging to file: " << logFile << std::endl; - + BOLT_INFO("File logging is now active"); BOLT_DEBUG("This message includes file and line information"); BOLT_WARN("This is written to the log file"); - + // Demonstrate JSON logging auto logger = std::make_unique(bolt::LogLevel::DEBUG); logger->addSink(std::make_unique("/tmp/bolt_demo.json")); logger->setFormatter(std::make_unique()); - + logger->info("JSON formatted message"); logger->error("Error in JSON format", __FILE__, __LINE__, __func__); - + bolt::LogManager::setGlobalLogger(std::move(logger)); - + std::cout << "Check " << logFile << " and /tmp/bolt_demo.json for logged messages" << std::endl; } void demonstrateRotatingLogs() { std::cout << "\n=== Rotating File Logging Demo ===" << std::endl; - + // Configure rotating file logging (small files for demo) bolt::LogManager::configureRotatingFileLogging("/tmp/bolt_rotating.log", 100, 3); - + std::cout << "Generating messages to trigger log rotation..." << std::endl; - + for (int i = 0; i < 20; ++i) { - BOLT_INFO("Message number " + std::to_string(i) + " - this is a longer message to fill up the log file quickly"); + BOLT_INFO("Message number " + std::to_string(i) + + " - this is a longer message to fill up the log file quickly"); std::this_thread::sleep_for(std::chrono::milliseconds(10)); } - + std::cout << "Check /tmp/bolt_rotating.log* files for rotation" << std::endl; } void demonstrateFiltering() { std::cout << "\n=== Log Filtering Demo ===" << std::endl; - + // Create a custom logger with filters - auto logger = std::make_unique(bolt::LogLevel::TRACE); // Allow all levels + auto logger = std::make_unique(bolt::LogLevel::TRACE); // Allow all levels logger->addSink(std::make_unique()); - + // Add category filter - auto categoryFilter = std::make_unique(bolt::LogLevel::INFO); // Default level - categoryFilter->setCategoryLevel(bolt::LogCategory::MEMORY, bolt::LogLevel::DEBUG); // Allow debug for memory - categoryFilter->setCategoryLevel(bolt::LogCategory::EDITOR, bolt::LogLevel::ERROR); // Only errors for editor - + auto categoryFilter = std::make_unique(bolt::LogLevel::INFO); // Default level + categoryFilter->setCategoryLevel(bolt::LogCategory::MEMORY, bolt::LogLevel::DEBUG); // Allow debug for memory + categoryFilter->setCategoryLevel(bolt::LogCategory::EDITOR, bolt::LogLevel::ERROR); // Only errors for editor + logger->addFilter(std::move(categoryFilter)); bolt::LogManager::setGlobalLogger(std::move(logger)); - + std::cout << "Demonstrating category-based filtering:" << std::endl; std::cout << "- MEMORY: DEBUG level and above" << std::endl; std::cout << "- EDITOR: ERROR level and above" << std::endl; std::cout << "- Others: INFO level and above" << std::endl; - + BOLT_LOG_MEMORY(bolt::LogLevel::DEBUG, "Memory debug message (should show)"); BOLT_LOG_MEMORY(bolt::LogLevel::TRACE, "Memory trace message (should NOT show)"); - + BOLT_LOG_EDITOR(bolt::LogLevel::INFO, "Editor info message (should NOT show)"); BOLT_LOG_EDITOR(bolt::LogLevel::ERROR, "Editor error message (should show)"); - + BOLT_LOG_CORE(bolt::LogLevel::INFO, "Core info message (should show)"); BOLT_LOG_CORE(bolt::LogLevel::DEBUG, "Core debug message (should NOT show)"); } void demonstratePerformanceMetrics() { std::cout << "\n=== Performance Metrics Demo ===" << std::endl; - - bolt::LogManager::configureConsoleLogging(bolt::LogLevel::WARN, false); // Simple format + + bolt::LogManager::configureConsoleLogging(bolt::LogLevel::WARN, false); // Simple format bolt::Logger& logger = bolt::LogManager::getInstance(); - + logger.resetMetrics(); - + std::cout << "Generating 1000 log messages..." << std::endl; - + auto start = std::chrono::high_resolution_clock::now(); - + for (int i = 0; i < 1000; ++i) { if (i % 4 == 0) { - logger.debug("Debug message " + std::to_string(i)); // Will be filtered + logger.debug("Debug message " + std::to_string(i)); // Will be filtered } else if (i % 4 == 1) { - logger.info("Info message " + std::to_string(i)); // Will be filtered + logger.info("Info message " + std::to_string(i)); // Will be filtered } else if (i % 4 == 2) { - logger.warn("Warning message " + std::to_string(i)); // Will be logged + logger.warn("Warning message " + std::to_string(i)); // Will be logged } else { - logger.error("Error message " + std::to_string(i)); // Will be logged + logger.error("Error message " + std::to_string(i)); // Will be logged } } - + auto end = std::chrono::high_resolution_clock::now(); auto duration = std::chrono::duration_cast(end - start); - + std::cout << "Performance metrics:" << std::endl; std::cout << "- Total messages: " << logger.getTotalMessages() << std::endl; std::cout << "- Dropped messages: " << logger.getDroppedMessages() << std::endl; @@ -141,40 +143,41 @@ void demonstratePerformanceMetrics() { void demonstrateScopedLogging() { std::cout << "\n=== Scoped Logging Demo ===" << std::endl; - + bolt::LogManager::configureConsoleLogging(bolt::LogLevel::TRACE, true); - + { BOLT_SCOPED_LOG_CORE(); - + BOLT_INFO("Inside scoped function"); - + // Simulate some work std::this_thread::sleep_for(std::chrono::milliseconds(100)); - + { BOLT_SCOPED_LOG(bolt::LogCategory::MEMORY); BOLT_DEBUG("Nested scope for memory operations"); std::this_thread::sleep_for(std::chrono::milliseconds(50)); } - + BOLT_INFO("Continuing work in outer scope"); } - + BOLT_INFO("Outside of scoped function"); } void demonstrateThreadSafety() { std::cout << "\n=== Thread Safety Demo ===" << std::endl; - + bolt::LogManager::configureFileLogging("/tmp/bolt_threaded.log", bolt::LogLevel::INFO, true); - + const int numThreads = 4; const int messagesPerThread = 5; std::vector threads; - - std::cout << "Launching " << numThreads << " threads, each logging " << messagesPerThread << " messages..." << std::endl; - + + std::cout << "Launching " << numThreads << " threads, each logging " << messagesPerThread << " messages..." + << std::endl; + for (int t = 0; t < numThreads; ++t) { threads.emplace_back([t, messagesPerThread]() { for (int i = 0; i < messagesPerThread; ++i) { @@ -183,28 +186,26 @@ void demonstrateThreadSafety() { } }); } - + for (auto& thread : threads) { thread.join(); } - + std::cout << "All threads completed. Check /tmp/bolt_threaded.log for interleaved messages" << std::endl; } void demonstrateErrorIntegration() { std::cout << "\n=== Error Handling Integration Demo ===" << std::endl; - + bolt::LogManager::configureConsoleLogging(bolt::LogLevel::DEBUG, true); - + try { BOLT_INFO("Attempting risky operation..."); - + // Simulate different types of errors BOLT_WARN("Warning: Operation may fail"); - - throw bolt::MemoryException(bolt::ErrorCode::MEMORY_ALLOCATION_FAILED, - "Failed to allocate 1GB of memory"); - + + throw bolt::MemoryException(bolt::ErrorCode::MEMORY_ALLOCATION_FAILED, "Failed to allocate 1GB of memory"); } catch (const bolt::MemoryException& e) { BOLT_ERROR("Memory exception caught: " + std::string(e.what())); BOLT_DEBUG("Error code: " + std::to_string(static_cast(e.getErrorCode()))); @@ -213,14 +214,14 @@ void demonstrateErrorIntegration() { } catch (const std::exception& e) { BOLT_FATAL("Unexpected exception: " + std::string(e.what())); } - + BOLT_INFO("Error handling demonstration completed"); } int main() { std::cout << "Bolt Comprehensive Logging System Demo" << std::endl; std::cout << "=======================================" << std::endl; - + try { demonstrateBasicLogging(); demonstrateCategoryLogging(); @@ -231,15 +232,14 @@ int main() { demonstrateScopedLogging(); demonstrateThreadSafety(); demonstrateErrorIntegration(); - + std::cout << "\n=== Demo Complete ===" << std::endl; std::cout << "All logging features demonstrated successfully!" << std::endl; std::cout << "Check the generated log files in /tmp/ for examples of different formats." << std::endl; - } catch (const std::exception& e) { std::cerr << "Demo failed with exception: " << e.what() << std::endl; return 1; } - + return 0; -} \ No newline at end of file +} diff --git a/demo_logging_simple.cpp b/demo_logging_simple.cpp index 056dba9a..77cca4c2 100644 --- a/demo_logging_simple.cpp +++ b/demo_logging_simple.cpp @@ -1,15 +1,16 @@ -#include "bolt/core/logging.hpp" -#include "bolt/core/error_handling.hpp" +#include #include #include -#include + +#include "bolt/core/error_handling.hpp" +#include "bolt/core/logging.hpp" void demonstrateBasicLogging() { std::cout << "\n=== Basic Logging Demo ===" << std::endl; - + // Configure console logging with detailed format bolt::LogManager::configureConsoleLogging(bolt::LogLevel::DEBUG, true); - + // Test different log levels BOLT_TRACE("This is a trace message"); BOLT_DEBUG("This is a debug message"); @@ -21,7 +22,7 @@ void demonstrateBasicLogging() { void demonstrateCategoryLogging() { std::cout << "\n=== Category-Based Logging Demo ===" << std::endl; - + // Test category-specific logging BOLT_LOG_CORE(bolt::LogLevel::INFO, "Core system initialization"); BOLT_LOG_MEMORY(bolt::LogLevel::DEBUG, "Memory allocation: 1024 bytes"); @@ -32,47 +33,47 @@ void demonstrateCategoryLogging() { void demonstrateFileLogging() { std::cout << "\n=== File Logging Demo ===" << std::endl; - + // Configure file logging std::string logFile = "/tmp/bolt_demo.log"; bolt::LogManager::configureFileLogging(logFile, bolt::LogLevel::TRACE, true); - + std::cout << "Logging to file: " << logFile << std::endl; - + BOLT_INFO("File logging is now active"); BOLT_DEBUG("This message includes file and line information"); BOLT_WARN("This is written to the log file"); - + std::cout << "Check " << logFile << " for logged messages" << std::endl; } void demonstratePerformanceMetrics() { std::cout << "\n=== Performance Metrics Demo ===" << std::endl; - - bolt::LogManager::configureConsoleLogging(bolt::LogLevel::WARN, false); // Simple format + + bolt::LogManager::configureConsoleLogging(bolt::LogLevel::WARN, false); // Simple format bolt::Logger& logger = bolt::LogManager::getInstance(); - + logger.resetMetrics(); - + std::cout << "Generating 1000 log messages..." << std::endl; - + auto start = std::chrono::high_resolution_clock::now(); - + for (int i = 0; i < 1000; ++i) { if (i % 4 == 0) { - logger.debug("Debug message " + std::to_string(i)); // Will be filtered + logger.debug("Debug message " + std::to_string(i)); // Will be filtered } else if (i % 4 == 1) { - logger.info("Info message " + std::to_string(i)); // Will be filtered + logger.info("Info message " + std::to_string(i)); // Will be filtered } else if (i % 4 == 2) { - logger.warn("Warning message " + std::to_string(i)); // Will be logged + logger.warn("Warning message " + std::to_string(i)); // Will be logged } else { - logger.error("Error message " + std::to_string(i)); // Will be logged + logger.error("Error message " + std::to_string(i)); // Will be logged } } - + auto end = std::chrono::high_resolution_clock::now(); auto duration = std::chrono::duration_cast(end - start); - + std::cout << "Performance metrics:" << std::endl; std::cout << "- Total messages: " << logger.getTotalMessages() << std::endl; std::cout << "- Dropped messages: " << logger.getDroppedMessages() << std::endl; @@ -83,18 +84,16 @@ void demonstratePerformanceMetrics() { void demonstrateErrorIntegration() { std::cout << "\n=== Error Handling Integration Demo ===" << std::endl; - + bolt::LogManager::configureConsoleLogging(bolt::LogLevel::DEBUG, true); - + try { BOLT_INFO("Attempting risky operation..."); - + // Simulate different types of errors BOLT_WARN("Warning: Operation may fail"); - - throw bolt::MemoryException(bolt::ErrorCode::MEMORY_ALLOCATION_FAILED, - "Failed to allocate 1GB of memory"); - + + throw bolt::MemoryException(bolt::ErrorCode::MEMORY_ALLOCATION_FAILED, "Failed to allocate 1GB of memory"); } catch (const bolt::MemoryException& e) { BOLT_ERROR("Memory exception caught: " + std::string(e.what())); BOLT_DEBUG("Error code: " + std::to_string(static_cast(e.getErrorCode()))); @@ -103,29 +102,28 @@ void demonstrateErrorIntegration() { } catch (const std::exception& e) { BOLT_FATAL("Unexpected exception: " + std::string(e.what())); } - + BOLT_INFO("Error handling demonstration completed"); } int main() { std::cout << "Bolt Comprehensive Logging System Demo" << std::endl; std::cout << "=======================================" << std::endl; - + try { demonstrateBasicLogging(); demonstrateCategoryLogging(); demonstrateFileLogging(); demonstratePerformanceMetrics(); demonstrateErrorIntegration(); - + std::cout << "\n=== Demo Complete ===" << std::endl; std::cout << "All logging features demonstrated successfully!" << std::endl; std::cout << "Check the generated log files in /tmp/ for examples of different formats." << std::endl; - } catch (const std::exception& e) { std::cerr << "Demo failed with exception: " << e.what() << std::endl; return 1; } - + return 0; -} \ No newline at end of file +} diff --git a/demo_lsp_ui_integration.cpp b/demo_lsp_ui_integration.cpp index 520e9be2..b387c957 100644 --- a/demo_lsp_ui_integration.cpp +++ b/demo_lsp_ui_integration.cpp @@ -1,7 +1,7 @@ /** * @file demo_lsp_ui_integration.cpp * @brief Demo application showcasing LSP UI integration with ImGui - * + * * This demo demonstrates: * - Code completion popup * - Hover tooltips @@ -9,22 +9,22 @@ * - Status bar with LSP status */ -#include +#include #include +#include #include -#include #include "bolt/editor/lsp_editor_bridge.hpp" #include "bolt/gui/lsp_ui_components.hpp" #ifdef BOLT_HAVE_IMGUI +#include #include #include #include -#include #endif -using namespace bolt; +using namespace bolt; // NOLINT(build/namespaces) void printHeader() { std::cout << "โ•”โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•—\n"; @@ -36,114 +36,114 @@ void printHeader() { #ifdef BOLT_HAVE_IMGUI class LspUiDemo { -public: - LspUiDemo() - : lspBridge_(std::make_unique()) - , completionPopup_(std::make_unique()) - , hoverTooltip_(std::make_unique()) - , diagnosticsGutter_(std::make_unique()) - , inlineDiagnostics_(std::make_unique()) - , statusBar_(std::make_unique()) { - } - + public: + LspUiDemo() + : lspBridge_(std::make_unique()), + completionPopup_(std::make_unique()), + hoverTooltip_(std::make_unique()), + diagnosticsGutter_(std::make_unique()), + inlineDiagnostics_(std::make_unique()), + statusBar_(std::make_unique()) {} + bool initialize() { // Initialize GLFW if (!glfwInit()) { std::cerr << "Failed to initialize GLFW\n"; return false; } - + // Create window glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); - + window_ = glfwCreateWindow(1280, 720, "LSP UI Integration Demo", nullptr, nullptr); if (!window_) { std::cerr << "Failed to create window\n"; glfwTerminate(); return false; } - + glfwMakeContextCurrent(window_); glfwSwapInterval(1); - + // Initialize ImGui IMGUI_CHECKVERSION(); ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; - + ImGui::StyleColorsDark(); - + ImGui_ImplGlfw_InitForOpenGL(window_, true); ImGui_ImplOpenGL3_Init("#version 330"); - + // Initialize LSP bridge std::cout << "\n--- Initializing LSP Bridge ---\n"; if (!lspBridge_->initialize()) { std::cout << "Warning: No language servers available\n"; } - + // Set up completion callback completionPopup_->setAcceptCallback([this](const std::string& text) { std::cout << "Completion accepted: " << text << "\n"; insertTextAtCursor(text); }); - + // Create test file createTestFile(); - + return true; } - + void run() { while (!glfwWindowShouldClose(window_)) { glfwPollEvents(); - + ImGui_ImplOpenGL3_NewFrame(); ImGui_ImplGlfw_NewFrame(); ImGui::NewFrame(); - + // Update LSP bridge lspBridge_->update(); - + // Render UI renderMainWindow(); renderEditor(); renderStatusBar(); - + // Render LSP UI components renderLspComponents(); - + ImGui::Render(); - + int display_w, display_h; glfwGetFramebufferSize(window_, &display_w, &display_h); glViewport(0, 0, display_w, display_h); glClearColor(0.1f, 0.1f, 0.12f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); - + ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData()); - + glfwSwapBuffers(window_); } } - + void shutdown() { lspBridge_->shutdown(); - + ImGui_ImplOpenGL3_Shutdown(); ImGui_ImplGlfw_Shutdown(); ImGui::DestroyContext(); - + glfwDestroyWindow(window_); glfwTerminate(); } - -private: + + private: void createTestFile() { testFilePath_ = "/tmp/lsp_ui_demo_test.cpp"; + // clang-format off testContent_ = R"(#include #include #include @@ -174,209 +174,210 @@ int main() { return 0; } )"; - + // clang-format on + std::ofstream file(testFilePath_); file << testContent_; file.close(); - + // Open document in LSP lspBridge_->documentOpened(testFilePath_, testContent_, "cpp"); - + std::cout << "Created test file: " << testFilePath_ << "\n"; } - + void renderMainWindow() { ImGui::SetNextWindowPos(ImVec2(10, 10), ImGuiCond_FirstUseEver); ImGui::SetNextWindowSize(ImVec2(300, 200), ImGuiCond_FirstUseEver); - + ImGui::Begin("LSP UI Demo Controls"); - + ImGui::Text("LSP UI Integration Demo"); ImGui::Separator(); - + if (ImGui::Button("Request Completion")) { requestCompletion(); } - + if (ImGui::Button("Request Hover")) { requestHover(); } - + ImGui::Separator(); - + ImGui::Text("Cursor Position:"); ImGui::Text(" Line: %zu, Column: %zu", cursorLine_, cursorColumn_); - + ImGui::Separator(); - + auto& completionState = lspBridge_->getCompletionState(); ImGui::Text("Completion: %s", completionState.isVisible ? "Visible" : "Hidden"); ImGui::Text(" Items: %zu", completionState.items.size()); - + auto& hoverState = lspBridge_->getHoverState(); ImGui::Text("Hover: %s", hoverState.isVisible ? "Visible" : "Hidden"); - + ImGui::End(); } - + void renderEditor() { ImGui::SetNextWindowPos(ImVec2(320, 10), ImGuiCond_FirstUseEver); ImGui::SetNextWindowSize(ImVec2(700, 500), ImGuiCond_FirstUseEver); - + ImGui::Begin("Code Editor"); - + // Store editor position for LSP UI positioning editorPos_ = ImGui::GetCursorScreenPos(); - + // Simple text editor - ImGui::InputTextMultiline("##editor", &testContent_[0], testContent_.capacity() + 1, - ImVec2(-1, -1), ImGuiInputTextFlags_AllowTabInput); - + ImGui::InputTextMultiline("##editor", &testContent_[0], testContent_.capacity() + 1, ImVec2(-1, -1), + ImGuiInputTextFlags_AllowTabInput); + // Track cursor position (simplified) if (ImGui::IsItemActive()) { // In a real implementation, we'd track the actual cursor position // For demo, we'll use a fixed position } - + ImGui::End(); } - + void renderStatusBar() { ImGuiViewport* viewport = ImGui::GetMainViewport(); ImGui::SetNextWindowPos(ImVec2(viewport->Pos.x, viewport->Pos.y + viewport->Size.y - 25)); ImGui::SetNextWindowSize(ImVec2(viewport->Size.x, 25)); - - ImGuiWindowFlags flags = ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | - ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoScrollbar; - + + ImGuiWindowFlags flags = ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | + ImGuiWindowFlags_NoScrollbar; + ImGui::Begin("##StatusBar", nullptr, flags); - + ImGui::Text("LSP UI Demo"); ImGui::SameLine(200); - + // Render LSP status statusBar_->render(*lspBridge_, testFilePath_); - + ImGui::End(); } - + void renderLspComponents() { // Render completion popup auto& completionState = lspBridge_->getCompletionState(); if (completionState.isVisible) { float cursorX = editorPos_.x + cursorColumn_ * 8.0f; // Approximate char width - float cursorY = editorPos_.y + cursorLine_ * 16.0f; // Approximate line height + float cursorY = editorPos_.y + cursorLine_ * 16.0f; // Approximate line height completionPopup_->render(completionState, cursorX, cursorY, 16.0f); completionPopup_->handleInput(completionState); } - + // Render hover tooltip auto& hoverState = lspBridge_->getHoverState(); if (hoverState.isVisible) { ImVec2 mousePos = ImGui::GetMousePos(); hoverTooltip_->render(hoverState, mousePos.x, mousePos.y); } - + // Render diagnostics (would be integrated into editor in real implementation) auto diagnostics = lspBridge_->getDiagnostics(testFilePath_); if (!diagnostics.empty()) { // In a real implementation, these would be rendered in the editor gutter } } - + void requestCompletion() { std::cout << "Requesting completion at line " << cursorLine_ << ", column " << cursorColumn_ << "\n"; lspBridge_->requestCompletion(testFilePath_, cursorLine_, cursorColumn_); - + // Wait a bit for response std::this_thread::sleep_for(std::chrono::milliseconds(500)); } - + void requestHover() { std::cout << "Requesting hover at line " << cursorLine_ << ", column " << cursorColumn_ << "\n"; lspBridge_->requestHover(testFilePath_, cursorLine_, cursorColumn_); - + // Wait a bit for response std::this_thread::sleep_for(std::chrono::milliseconds(500)); } - + void insertTextAtCursor(const std::string& text) { // In a real implementation, this would insert text at the cursor position std::cout << "Would insert: " << text << "\n"; } - + GLFWwindow* window_ = nullptr; - + std::unique_ptr lspBridge_; std::unique_ptr completionPopup_; std::unique_ptr hoverTooltip_; std::unique_ptr diagnosticsGutter_; std::unique_ptr inlineDiagnostics_; std::unique_ptr statusBar_; - + std::string testFilePath_; std::string testContent_; - + size_t cursorLine_ = 7; // Position at "std::cout" line size_t cursorColumn_ = 12; - + ImVec2 editorPos_; }; int main() { printHeader(); - + LspUiDemo demo; - + if (!demo.initialize()) { std::cerr << "Failed to initialize demo\n"; return 1; } - + std::cout << "\n--- Running LSP UI Demo ---\n"; std::cout << "Press 'Request Completion' to test code completion\n"; std::cout << "Press 'Request Hover' to test hover information\n"; std::cout << "Close the window to exit\n\n"; - + demo.run(); demo.shutdown(); - + std::cout << "\n--- Demo Complete ---\n"; return 0; } -#else // BOLT_HAVE_IMGUI +#else // BOLT_HAVE_IMGUI int main() { printHeader(); - + std::cout << "\nโŒ ImGui not available - cannot run UI demo\n"; std::cout << " Please build with ImGui support to test UI components\n"; - + // Test LSP bridge without UI std::cout << "\n--- Testing LSP Bridge (non-UI) ---\n"; - + lsp::LspEditorBridge bridge; if (bridge.initialize()) { std::cout << "โœ… LSP Bridge initialized\n"; - + // Test language detection std::cout << "\nLanguage Detection:\n"; std::cout << " test.cpp -> " << lsp::LspEditorBridge::detectLanguageId("test.cpp") << "\n"; std::cout << " test.py -> " << lsp::LspEditorBridge::detectLanguageId("test.py") << "\n"; std::cout << " test.rs -> " << lsp::LspEditorBridge::detectLanguageId("test.rs") << "\n"; - + // Test language support std::cout << "\nLanguage Support:\n"; std::cout << " cpp: " << (bridge.isLanguageSupported("cpp") ? "โœ…" : "โŒ") << "\n"; std::cout << " python: " << (bridge.isLanguageSupported("python") ? "โœ…" : "โŒ") << "\n"; - + bridge.shutdown(); } else { std::cout << "โŒ Failed to initialize LSP Bridge\n"; } - + return 0; } -#endif // BOLT_HAVE_IMGUI +#endif // BOLT_HAVE_IMGUI diff --git a/demo_minimap.cpp b/demo_minimap.cpp index 410a2c58..dfd92e0d 100644 --- a/demo_minimap.cpp +++ b/demo_minimap.cpp @@ -1,37 +1,38 @@ -#include #include +#include +#include #include #include -#include + #include "bolt/editor/minimap.hpp" #include "bolt/editor/minimap_ui.hpp" -using namespace bolt; +using namespace bolt; // NOLINT(build/namespaces) void createLargeTestFile() { std::ofstream file("/tmp/large_file.cpp"); - + file << "// Large C++ File for Minimap Demo\n"; file << "// This file demonstrates minimap functionality with a larger codebase\n\n"; - + file << "#include \n"; file << "#include \n"; file << "#include \n"; file << "#include \n"; file << "#include \n\n"; - + file << "namespace demo {\n\n"; - + // Add a large class with many methods file << "class LargeClass {\n"; file << "private:\n"; file << " std::vector data_;\n"; file << " int counter_;\n"; file << " bool enabled_;\n\n"; - + file << "public:\n"; file << " LargeClass() : counter_(0), enabled_(true) {}\n\n"; - + // Add many methods to create a long file for (int i = 1; i <= 50; ++i) { file << " void method" << i << "() {\n"; @@ -42,19 +43,19 @@ void createLargeTestFile() { file << " }\n"; file << " }\n\n"; } - + file << " void processData() {\n"; file << " std::cout << \"Processing \" << data_.size() << \" items\" << std::endl;\n"; file << " for (const auto& item : data_) {\n"; file << " std::cout << \" \" << item << std::endl;\n"; file << " }\n"; file << " }\n\n"; - + file << " int getCounter() const { return counter_; }\n"; file << " void setEnabled(bool enabled) { enabled_ = enabled; }\n"; file << " bool isEnabled() const { return enabled_; }\n"; file << "};\n\n"; - + // Add some free functions for (int i = 1; i <= 20; ++i) { file << "void freeFunction" << i << "() {\n"; @@ -63,9 +64,9 @@ void createLargeTestFile() { file << " obj.method" << (i % 50 + 1) << "();\n"; file << "}\n\n"; } - + file << "} // namespace demo\n\n"; - + file << "int main() {\n"; file << " std::cout << \"Minimap Demo Application\" << std::endl;\n"; file << " \n"; @@ -82,7 +83,7 @@ void createLargeTestFile() { file << " \n"; file << " return 0;\n"; file << "}\n"; - + file.close(); } @@ -90,11 +91,11 @@ std::vector readFileLines(const std::string& filePath) { std::vector lines; std::ifstream file(filePath); std::string line; - + while (std::getline(file, line)) { lines.push_back(line); } - + return lines; } @@ -106,31 +107,31 @@ void printSeparator(const std::string& title) { void demonstrateBasicMinimap() { printSeparator("Basic Minimap Demo"); - + // Create a minimap with custom configuration Minimap::MinimapConfig config; config.width = 60; config.height = 20; - + Minimap minimap(config); - + // Load the test file auto lines = readFileLines("/tmp/large_file.cpp"); minimap.setDocument("/tmp/large_file.cpp", lines); - + std::cout << "Document loaded: " << minimap.getDocumentPath() << std::endl; std::cout << "Total lines: " << minimap.getTotalLines() << std::endl; std::cout << "Visible lines in minimap: " << minimap.getVisibleLines() << std::endl; - + // Set initial viewport Minimap::ViewportInfo viewport; viewport.startLine = 0; viewport.endLine = 25; viewport.currentLine = 10; viewport.totalLines = lines.size(); - + minimap.updateViewport(viewport); - + std::cout << "\nMinimap rendering:" << std::endl; auto rendered = minimap.render(); for (size_t i = 0; i < rendered.size(); ++i) { @@ -140,47 +141,46 @@ void demonstrateBasicMinimap() { void demonstrateMinimapUI() { printSeparator("Minimap UI Demo"); - + Minimap::MinimapConfig minimapConfig; minimapConfig.width = 50; minimapConfig.height = 15; - + Minimap minimap(minimapConfig); auto lines = readFileLines("/tmp/large_file.cpp"); minimap.setDocument("/tmp/large_file.cpp", lines); - + // Configure UI MinimapUI::UIConfig uiConfig; uiConfig.showBorder = true; uiConfig.showTitle = true; uiConfig.showScrollIndicator = true; uiConfig.title = "File Minimap"; - + MinimapUI ui(minimap, uiConfig); - + // Set position MinimapUI::Position position{0, 0, 54, 18}; ui.setPosition(position); - + // Set up navigation callback - ui.setNavigationCallback([](size_t line) { - std::cout << "Navigation callback: jumped to line " << line << std::endl; - }); - + ui.setNavigationCallback( + [](size_t line) { std::cout << "Navigation callback: jumped to line " << line << std::endl; }); + // Set viewport around middle of file Minimap::ViewportInfo viewport; viewport.startLine = lines.size() / 2 - 10; viewport.endLine = lines.size() / 2 + 10; viewport.currentLine = lines.size() / 2; viewport.totalLines = lines.size(); - + minimap.updateViewport(viewport); - + std::cout << "UI Requirements:" << std::endl; std::cout << " Width: " << ui.getRequiredWidth() << std::endl; std::cout << " Height: " << ui.getRequiredHeight() << std::endl; std::cout << " Fits in area (60x20): " << (ui.fitsInArea(60, 20) ? "Yes" : "No") << std::endl; - + std::cout << "\nMinimap UI rendering:" << std::endl; auto rendered = ui.render(); for (const auto& line : rendered) { @@ -190,42 +190,42 @@ void demonstrateMinimapUI() { void demonstrateNavigation() { printSeparator("Navigation Demo"); - + Minimap minimap; auto lines = readFileLines("/tmp/large_file.cpp"); minimap.setDocument("/tmp/large_file.cpp", lines); - + MinimapUI ui(minimap); - + std::cout << "Testing navigation functionality..." << std::endl; - + // Test clicking at different positions std::vector> testPositions = { - {10, 5}, // Near top - {10, 20}, // Near bottom - {10, 10} // Middle + {10, 5}, // Near top + {10, 20}, // Near bottom + {10, 10} // Middle }; - + for (const auto& pos : testPositions) { std::cout << "\nClicking at position (" << pos.first << ", " << pos.second << "):" << std::endl; size_t targetLine = minimap.getLineFromPosition(pos.first, pos.second); std::cout << " Would navigate to line: " << targetLine << std::endl; - + auto [x, y] = minimap.getPositionFromLine(targetLine); std::cout << " Line " << targetLine << " maps to position (" << x << ", " << y << ")" << std::endl; } - + // Test scrolling std::cout << "\nTesting scroll operations:" << std::endl; - + std::cout << "Scroll to top:" << std::endl; minimap.scrollToLine(0); std::cout << " Scroll percentage: " << (minimap.getScrollPercentage() * 100) << "%" << std::endl; - + std::cout << "Scroll to middle:" << std::endl; minimap.scrollToLine(lines.size() / 2); std::cout << " Scroll percentage: " << (minimap.getScrollPercentage() * 100) << "%" << std::endl; - + std::cout << "Scroll to bottom:" << std::endl; minimap.scrollToLine(lines.size() - 1); std::cout << " Scroll percentage: " << (minimap.getScrollPercentage() * 100) << "%" << std::endl; @@ -234,20 +234,20 @@ void demonstrateNavigation() { int main() { std::cout << "Bolt C++ Minimap Demo" << std::endl; std::cout << "=====================" << std::endl; - + // Create test file std::cout << "Creating large test file..." << std::endl; createLargeTestFile(); - + auto lines = readFileLines("/tmp/large_file.cpp"); std::cout << "Created file with " << lines.size() << " lines" << std::endl; - + try { // Run demonstrations demonstrateBasicMinimap(); demonstrateMinimapUI(); demonstrateNavigation(); - + printSeparator("Demo Complete"); std::cout << "Minimap implementation successfully demonstrated!" << std::endl; std::cout << "Features implemented:" << std::endl; @@ -257,11 +257,10 @@ int main() { std::cout << " โœ“ Configurable appearance" << std::endl; std::cout << " โœ“ UI integration with borders and titles" << std::endl; std::cout << " โœ“ Scroll position tracking" << std::endl; - } catch (const std::exception& e) { std::cerr << "Error during demo: " << e.what() << std::endl; return 1; } - + return 0; -} \ No newline at end of file +} diff --git a/demo_narrative_rag_kobold.cpp b/demo_narrative_rag_kobold.cpp index 684f8d67..ec2a2b7a 100644 --- a/demo_narrative_rag_kobold.cpp +++ b/demo_narrative_rag_kobold.cpp @@ -1,7 +1,8 @@ +#include +#include + #include "bolt/ai/narrative_rag_manager.hpp" #include "bolt/ai/narrative_tool_manager.hpp" -#include -#include void printSeparator() { std::cout << "\n" << std::string(80, '=') << "\n\n"; @@ -11,17 +12,17 @@ int main() { std::cout << "=== Narrative RAG & TOOL-USE Demo with Kobold.cpp ===\n"; std::cout << "Interactive Story Generation with Living World Memory\n"; printSeparator(); - + // 1. Initialize the Narrative RAG Manager std::cout << "Initializing Narrative RAG Manager...\n"; bolt::ai::NarrativeRAGManager rag_manager; - + if (!rag_manager.initialize()) { std::cerr << "โŒ Failed to initialize Narrative RAG Manager\n"; return 1; } std::cout << "โœ… Narrative RAG Manager initialized\n\n"; - + // 2. Initialize the Narrative Tool Manager std::cout << "Initializing Narrative Tool Manager...\n"; bolt::ai::NarrativeToolManager tool_manager; @@ -29,7 +30,7 @@ int main() { tool_manager.loadAllStandardTools(); std::cout << "โœ… Loaded " << tool_manager.getAvailableTools().size() << " narrative tools\n"; printSeparator(); - + // 3. Create a character bolt::ai::CharacterSheet hero; hero.name = "Aldric the Brave"; @@ -40,7 +41,7 @@ int main() { hero.attributes["strength"] = 8; hero.attributes["intelligence"] = 6; hero.attributes["charisma"] = 5; - + tool_manager.registerCharacter(hero); std::cout << "Character Created: " << hero.name << "\n"; std::cout << "Skills: "; @@ -49,14 +50,15 @@ int main() { } std::cout << "\n"; printSeparator(); - + // 4. Log some initial narrative events std::cout << "Building the story world...\n\n"; - + bolt::ai::NarrativeEvent event1; event1.id = "event_001"; - event1.description = "Aldric arrived at the ancient castle, its towers shrouded in mist. " - "The locals warned him of a curse that befell anyone who entered."; + event1.description = + "Aldric arrived at the ancient castle, its towers shrouded in mist. " + "The locals warned him of a curse that befell anyone who entered."; event1.characters = {"Aldric the Brave"}; event1.locations = {"Ancient Castle"}; event1.timestamp = std::chrono::system_clock::now(); @@ -65,11 +67,12 @@ int main() { event1.tags = {"castle", "curse", "warning"}; rag_manager.logEvent(event1); std::cout << "๐Ÿ“ Event logged: " << event1.description << "\n\n"; - + bolt::ai::NarrativeEvent event2; event2.id = "event_002"; - event2.description = "In the village tavern, an old woman told Aldric that the castle's " - "treasure is guarded by a spectral knight who appears at midnight."; + event2.description = + "In the village tavern, an old woman told Aldric that the castle's " + "treasure is guarded by a spectral knight who appears at midnight."; event2.characters = {"Aldric the Brave", "Old Woman"}; event2.locations = {"Village Tavern"}; event2.timestamp = std::chrono::system_clock::now(); @@ -78,11 +81,12 @@ int main() { event2.tags = {"treasure", "spectral knight", "midnight"}; rag_manager.logEvent(event2); std::cout << "๐Ÿ“ Event logged: " << event2.description << "\n\n"; - + bolt::ai::NarrativeEvent event3; event3.id = "event_003"; - event3.description = "Aldric discovered a hidden passage behind the castle's main hall. " - "Strange symbols were carved into the stone walls."; + event3.description = + "Aldric discovered a hidden passage behind the castle's main hall. " + "Strange symbols were carved into the stone walls."; event3.characters = {"Aldric the Brave"}; event3.locations = {"Ancient Castle", "Hidden Passage"}; event3.timestamp = std::chrono::system_clock::now(); @@ -92,36 +96,34 @@ int main() { rag_manager.logEvent(event3); std::cout << "๐Ÿ“ Event logged: " << event3.description << "\n"; printSeparator(); - + // 5. Demonstrate Narrative RAG: Query the living world std::cout << "=== Narrative RAG: Querying Character Memory ===\n\n"; - + std::string query1 = "What do I know about the castle's dangers?"; std::cout << "Query: \"" << query1 << "\"\n\n"; auto relevant_events1 = rag_manager.queryNarrativeMemory(query1, {"Aldric the Brave"}); - + std::cout << "Retrieved " << relevant_events1.size() << " relevant memories:\n"; for (size_t i = 0; i < relevant_events1.size(); ++i) { std::cout << (i + 1) << ". " << relevant_events1[i].description << "\n"; - std::cout << " [Type: " << relevant_events1[i].event_type + std::cout << " [Type: " << relevant_events1[i].event_type << ", Importance: " << relevant_events1[i].importance << "]\n\n"; } - + // Generate memory injection for kobold.cpp - std::string memory_injection = rag_manager.generateMemoryInjection( - "Aldric stands before a locked door in the castle", - {"Aldric the Brave"} - ); - + std::string memory_injection = + rag_manager.generateMemoryInjection("Aldric stands before a locked door in the castle", {"Aldric the Brave"}); + std::cout << "Memory Injection for Kobold.cpp:\n"; std::cout << "โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€\n"; std::cout << memory_injection << "\n"; std::cout << "โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€\n"; printSeparator(); - + // 6. Demonstrate Narrative TOOL-USE: Character takes action std::cout << "=== Narrative TOOL-USE: Character Agency ===\n\n"; - + std::cout << "Scenario: Aldric encounters a locked door\n"; std::cout << "Available tools for " << hero.name << ":\n"; auto available_tools = tool_manager.getToolsForCharacter(hero.name); @@ -129,21 +131,21 @@ int main() { std::cout << " โ€ข " << tool << "\n"; } std::cout << "\n"; - + // AI decides to use the pick_lock tool std::cout << "AI Decision: Use 'pick_lock' ability\n\n"; - + std::unordered_map params; params["target"] = "ancient_door"; params["difficulty"] = "15"; - + auto result = tool_manager.invokeTool("pick_lock", hero.name, params); - + std::cout << "Tool Invocation Result:\n"; std::cout << " Success: " << (result.success ? "Yes" : "No") << "\n"; std::cout << " Description: " << result.description << "\n"; std::cout << " Impact Score: " << result.impact_score << "/10\n"; - + if (!result.state_changes.empty()) { std::cout << " State Changes:\n"; for (const auto& change : result.state_changes) { @@ -151,7 +153,7 @@ int main() { } } std::cout << "\n"; - + // Log the tool use as a narrative event bolt::ai::NarrativeEvent tool_event; tool_event.id = "event_004"; @@ -163,26 +165,25 @@ int main() { tool_event.importance = result.impact_score; tool_event.tags = {"lockpicking", "door", "skill_check"}; rag_manager.logEvent(tool_event); - + std::cout << "โœ… Tool use logged as narrative event\n"; printSeparator(); - + // 7. Show the complete event history std::cout << "=== Complete Narrative History ===\n\n"; auto history = rag_manager.getEventHistory(); std::cout << "Total events: " << history.size() << "\n\n"; - + for (size_t i = 0; i < history.size(); ++i) { - std::cout << (i + 1) << ". [" << history[i].event_type << "] " - << history[i].description << "\n"; + std::cout << (i + 1) << ". [" << history[i].event_type << "] " << history[i].description << "\n"; } - + printSeparator(); std::cout << "=== Demo Complete ===\n"; std::cout << "\nThis demonstrates how Kobold.cpp can be enhanced with:\n"; std::cout << " โ€ข Dynamic, queryable world memory (Narrative RAG)\n"; std::cout << " โ€ข Character agency through tool use (Narrative TOOL-USE)\n"; std::cout << " โ€ข Seamless integration of AI decisions and game mechanics\n\n"; - + return 0; } diff --git a/demo_network_optimizations.cpp b/demo_network_optimizations.cpp index 752c990e..eb1def36 100644 --- a/demo_network_optimizations.cpp +++ b/demo_network_optimizations.cpp @@ -1,9 +1,9 @@ -#include +#include #include +#include +#include #include -#include #include -#include // Include network optimization headers #include "bolt/network/connection_pool.hpp" @@ -11,21 +11,21 @@ #include "bolt/network/network_buffer.hpp" #include "bolt/network/network_metrics.hpp" -using namespace bolt; +using namespace bolt; // NOLINT(build/namespaces) void demonstrateConnectionPool() { std::cout << "\n=== Connection Pool Demo ===\n"; - + auto& pool = ConnectionPool::getInstance(); pool.setMaxConnectionsPerHost(3); pool.setConnectionTimeout(std::chrono::seconds(5)); - + std::cout << "Creating connections to localhost:8080...\n"; - + // Note: These would normally connect to a real server // For demo purposes, we'll show the pool management std::vector> connections; - + for (int i = 0; i < 5; i++) { auto conn = pool.getConnection("127.0.0.1", 8080); if (conn) { @@ -33,12 +33,12 @@ void demonstrateConnectionPool() { connections.push_back(conn); } } - + // Release connections back to pool for (auto& conn : connections) { pool.releaseConnection(conn); } - + // Show statistics const auto& stats = pool.getStats(); std::cout << "Pool Statistics:\n"; @@ -50,82 +50,81 @@ void demonstrateConnectionPool() { void demonstrateMessageCompression() { std::cout << "\n=== Message Compression Demo ===\n"; - + MessageCompressor compressor(CompressionType::GZIP, 6); - + // Create a repetitive message that compresses well std::string original = "This is a test message that will be repeated many times. "; for (int i = 0; i < 50; i++) { original += "This is a test message that will be repeated many times. "; } - + std::cout << "Original message size: " << original.size() << " bytes\n"; - + // Compress the message auto compressed = compressor.compress(original); std::cout << "Compressed size: " << compressed.size() << " bytes\n"; - + double compressionRatio = static_cast(compressed.size()) / original.size(); - std::cout << "Compression ratio: " << std::fixed << std::setprecision(2) - << compressionRatio * 100 << "%\n"; - + std::cout << "Compression ratio: " << std::fixed << std::setprecision(2) << compressionRatio * 100 << "%\n"; + // Decompress and verify auto decompressed = compressor.decompress(compressed); bool isEqual = (decompressed == original); std::cout << "Decompression successful: " << (isEqual ? "Yes" : "No") << "\n"; - + // Show compression statistics auto stats = compressor.getStats(); std::cout << "Compression Statistics:\n"; std::cout << " Compression calls: " << stats.compressionCalls << "\n"; std::cout << " Decompression calls: " << stats.decompressionCalls << "\n"; - std::cout << " Average compression ratio: " << std::fixed << std::setprecision(2) + std::cout << " Average compression ratio: " << std::fixed << std::setprecision(2) << stats.averageCompressionRatio() * 100 << "%\n"; } void demonstrateNetworkBuffers() { std::cout << "\n=== Network Buffer Demo ===\n"; - + // Regular NetworkBuffer NetworkBuffer buffer(1024); - + std::string data1 = "Hello, "; std::string data2 = "World!"; - + buffer.append(data1); buffer.append(data2); - + std::cout << "Buffer size after appends: " << buffer.size() << "\n"; std::cout << "Buffer capacity: " << buffer.capacity() << "\n"; - + auto consumed = buffer.consumeString(5); std::cout << "Consumed: '" << consumed << "'\n"; - + buffer.compact(); std::cout << "Buffer size after compact: " << buffer.size() << "\n"; - + // Ring Buffer Demo std::cout << "\nRing Buffer Demo:\n"; RingBuffer ringBuf(20); - + std::string testData = "ABCDEFGHIJ"; size_t written = ringBuf.write(testData.data(), testData.size()); std::cout << "Written to ring buffer: " << written << " bytes\n"; std::cout << "Available to read: " << ringBuf.readAvailable() << " bytes\n"; - + char readBuffer[15]; size_t read = ringBuf.read(readBuffer, 5); readBuffer[read] = '\0'; std::cout << "Read from ring buffer: '" << readBuffer << "'\n"; - + // Buffer Pool Demo std::cout << "\nBuffer Pool Demo:\n"; auto& pool = NetworkBufferPool::getInstance(); - + auto pooledBuffer = pool.getBuffer(2048); std::cout << "Got buffer from pool, capacity: " << pooledBuffer->capacity() << "\n"; std::cout << "Active buffers: " << pool.getActiveBuffers() << "\n"; - + pool.returnBuffer(std::move(pooledBuffer)); std::cout << "Returned buffer to pool\n"; std::cout << "Pool size: " << pool.getPoolSize() << "\n"; @@ -133,47 +132,47 @@ void demonstrateNetworkBuffers() { void demonstrateNetworkMetrics() { std::cout << "\n=== Network Metrics Demo ===\n"; - + auto& metrics = NetworkMetrics::getInstance(); metrics.resetAllStats(); - + // Register some endpoints std::string endpoint1 = "websocket-server"; std::string endpoint2 = "http-api"; - + metrics.registerEndpoint(endpoint1); metrics.registerEndpoint(endpoint2); - + // Simulate some network activity std::cout << "Simulating network activity...\n"; - + // WebSocket activity metrics.recordConnection(endpoint1, true); metrics.recordDataSent(endpoint1, 1024); metrics.recordDataReceived(endpoint1, 512); - metrics.recordLatency(endpoint1, 1500); // 1.5ms + metrics.recordLatency(endpoint1, 1500); // 1.5ms metrics.recordWebSocketFrame(endpoint1, true, false); - + // HTTP API activity metrics.recordConnection(endpoint2, true); metrics.recordDataSent(endpoint2, 2048); metrics.recordDataReceived(endpoint2, 4096); - metrics.recordLatency(endpoint2, 2500); // 2.5ms + metrics.recordLatency(endpoint2, 2500); // 2.5ms metrics.recordHttpRequest(endpoint2, 200); - + // Some errors metrics.recordError(endpoint1, "timeout"); metrics.recordError(endpoint2, "protocol"); - + // Show global statistics auto globalStats = metrics.getGlobalStats(); std::cout << "\nGlobal Statistics:\n"; std::cout << " Connections opened: " << globalStats.connectionsOpened << "\n"; std::cout << " Bytes sent: " << globalStats.bytesSent << "\n"; std::cout << " Bytes received: " << globalStats.bytesReceived << "\n"; - std::cout << " Average latency: " << std::fixed << std::setprecision(2) - << globalStats.getAverageLatency() << " ฮผs\n"; - + std::cout << " Average latency: " << std::fixed << std::setprecision(2) << globalStats.getAverageLatency() + << " ฮผs\n"; + // Show endpoint-specific statistics auto wsStats = metrics.getEndpointStats(endpoint1); if (wsStats) { @@ -181,7 +180,7 @@ void demonstrateNetworkMetrics() { std::cout << " Frames sent: " << wsStats->framesSent << "\n"; std::cout << " Connection timeouts: " << wsStats->connectionsTimedOut << "\n"; } - + auto httpStats = metrics.getEndpointStats(endpoint2); if (httpStats) { std::cout << "\nHTTP endpoint stats:\n"; @@ -189,68 +188,66 @@ void demonstrateNetworkMetrics() { std::cout << " Successful responses: " << httpStats->responsesOk << "\n"; std::cout << " Protocol errors: " << httpStats->protocolErrors << "\n"; } - + // Generate and display a full report std::cout << "\n" << metrics.generateReport() << "\n"; } void demonstrateBandwidthTracking() { std::cout << "\n=== Bandwidth Tracking Demo ===\n"; - + BandwidthTracker tracker(std::chrono::seconds(5)); - + std::cout << "Recording data transfer over time...\n"; - + // Simulate data transfer for (int i = 0; i < 10; i++) { tracker.recordBytes(1000 + i * 100); std::this_thread::sleep_for(std::chrono::milliseconds(100)); - + if (i % 3 == 0) { double bandwidth = tracker.getCurrentBandwidth(); - std::cout << "Current bandwidth: " << std::fixed << std::setprecision(2) - << bandwidth / 1024.0 << " KB/s\n"; + std::cout << "Current bandwidth: " << std::fixed << std::setprecision(2) << bandwidth / 1024.0 << " KB/s\n"; } } - + double peakBandwidth = tracker.getPeakBandwidth(); - std::cout << "Peak bandwidth: " << std::fixed << std::setprecision(2) - << peakBandwidth / 1024.0 << " KB/s\n"; + std::cout << "Peak bandwidth: " << std::fixed << std::setprecision(2) << peakBandwidth / 1024.0 << " KB/s\n"; } void demonstrateZeroCopyOperations() { std::cout << "\n=== Zero-Copy Operations Demo ===\n"; - + // Zero-copy buffer ZeroCopyBuffer zcBuffer; - + std::string segment1 = "Header: "; std::string segment2 = "Content data goes here"; std::string segment3 = " | Footer"; - + zcBuffer.addReference(segment1); zcBuffer.addReference(segment2); zcBuffer.addReference(segment3); - + std::cout << "Zero-copy buffer total size: " << zcBuffer.getTotalSize() << " bytes\n"; - + // Iterate through segments without copying std::cout << "Segments: "; zcBuffer.forEachSegment([](const void* data, size_t length) { std::cout << "'" << std::string(static_cast(data), length) << "' "; }); std::cout << "\n"; - + // Scatter-gather buffer ScatterGatherBuffer sgBuffer; sgBuffer.addSegment("Part1"); sgBuffer.addSegment("Part2"); sgBuffer.addSegment("Part3"); - + std::cout << "Scatter-gather buffer:\n"; std::cout << " Segments: " << sgBuffer.getSegmentCount() << "\n"; std::cout << " Total size: " << sgBuffer.getTotalSize() << " bytes\n"; - + auto flattened = sgBuffer.flatten(); std::string result(flattened.begin(), flattened.end()); std::cout << " Flattened: '" << result << "'\n"; @@ -259,7 +256,7 @@ void demonstrateZeroCopyOperations() { int main() { std::cout << "Bolt C++ Network Protocol Optimizations Demo\n"; std::cout << "============================================\n"; - + try { demonstrateConnectionPool(); demonstrateMessageCompression(); @@ -267,10 +264,10 @@ int main() { demonstrateNetworkMetrics(); demonstrateBandwidthTracking(); demonstrateZeroCopyOperations(); - + std::cout << "\n=== Demo Complete ===\n"; std::cout << "All network optimizations demonstrated successfully!\n"; - + std::cout << "\nKey Optimizations Implemented:\n"; std::cout << "โœ“ Connection pooling with keep-alive support\n"; std::cout << "โœ“ Message compression (GZIP/DEFLATE)\n"; @@ -280,11 +277,10 @@ int main() { std::cout << "โœ“ Zero-copy and scatter-gather operations\n"; std::cout << "โœ“ Memory pooling for reduced allocations\n"; std::cout << "โœ“ Thread-safe implementations\n"; - } catch (const std::exception& e) { std::cerr << "Demo error: " << e.what() << std::endl; return 1; } - + return 0; -} \ No newline at end of file +} diff --git a/demo_performance_profiler.cpp b/demo_performance_profiler.cpp index 2cc70b45..d0740847 100644 --- a/demo_performance_profiler.cpp +++ b/demo_performance_profiler.cpp @@ -1,17 +1,18 @@ -#include "bolt/core/performance_profiler.hpp" -#include "bolt/core/logging.hpp" +#include #include +#include #include -#include #include -#include + +#include "bolt/core/logging.hpp" +#include "bolt/core/performance_profiler.hpp" // Simulate various types of work to demonstrate profiling void simulateFileLoading(const std::string& filename, int loadTimeMs) { BOLT_PROFILE_EDITOR("file_load:" + filename); - + std::this_thread::sleep_for(std::chrono::milliseconds(loadTimeMs)); - + // Add some metadata to the profiler auto& profiler = bolt::PerformanceProfiler::getInstance(); auto currentSession = profiler.getCurrentSession(); @@ -22,57 +23,57 @@ void simulateFileLoading(const std::string& filename, int loadTimeMs) { void simulateAIInference(const std::string& modelName, int inferenceTimeMs) { BOLT_PROFILE_AI("inference:" + modelName); - + // Simulate memory allocation for model - std::vector data(1000000); // ~4MB - + std::vector data(1000000); // ~4MB + std::this_thread::sleep_for(std::chrono::milliseconds(inferenceTimeMs)); - + // Clear memory data.clear(); } void simulateNetworkRequest(const std::string& endpoint, int requestTimeMs) { BOLT_PROFILE_NETWORK("http_request:" + endpoint); - + std::this_thread::sleep_for(std::chrono::milliseconds(requestTimeMs)); } void simulateMemoryOperations() { BOLT_PROFILE_MEMORY("memory_intensive_operations"); - + // Allocate and deallocate memory to show memory tracking std::vector> largeData; - + for (int i = 0; i < 100; ++i) { - largeData.emplace_back(10000, i); // Each vector ~40KB + largeData.emplace_back(10000, i); // Each vector ~40KB if (i % 10 == 0) { std::this_thread::sleep_for(std::chrono::milliseconds(5)); } } - + // Clear memory largeData.clear(); } void demonstrateBasicProfiling() { std::cout << "\\n=== Basic Profiling Demo ===" << std::endl; - + // Enable the profiler auto& profiler = bolt::PerformanceProfiler::getInstance(); profiler.enable(); - + // Simple function profiling auto simpleTask = []() { BOLT_PROFILE_FUNCTION(); std::this_thread::sleep_for(std::chrono::milliseconds(50)); }; simpleTask(); - + // Scoped profiling { BOLT_PROFILE_SCOPE("complex_calculation"); - + // Simulate some CPU-intensive work double result = 0.0; for (int i = 0; i < 1000000; ++i) { @@ -82,68 +83,66 @@ void demonstrateBasicProfiling() { volatile double sink = result; (void)sink; } - + // Category-specific profiling { BOLT_PROFILE_CORE("core_initialization"); std::this_thread::sleep_for(std::chrono::milliseconds(30)); } - + { BOLT_PROFILE_GUI("ui_update"); - std::this_thread::sleep_for(std::chrono::milliseconds(16)); // ~60 FPS + std::this_thread::sleep_for(std::chrono::milliseconds(16)); // ~60 FPS } - - std::cout << "Basic profiling completed. Metrics recorded: " - << profiler.getTotalMetricsCount() << std::endl; + + std::cout << "Basic profiling completed. Metrics recorded: " << profiler.getTotalMetricsCount() << std::endl; } void demonstrateSessionProfiling() { std::cout << "\\n=== Session-Based Profiling Demo ===" << std::endl; - + auto& profiler = bolt::PerformanceProfiler::getInstance(); std::random_device rd; std::mt19937 gen(rd()); - + // Create a session for a specific workflow { BOLT_PROFILE_SESSION("file_processing_workflow"); - + std::vector files = {"document.txt", "image.png", "data.csv", "config.json"}; std::uniform_int_distribution<> loadTime(20, 100); - + for (const auto& file : files) { simulateFileLoading(file, loadTime(gen)); } - + // Process the files { BOLT_PROFILE_SCOPE("batch_processing"); std::this_thread::sleep_for(std::chrono::milliseconds(150)); } - + auto session = profiler.getCurrentSession(); if (session) { - std::cout << "Session '" << session->getName() << "' has " - << session->getMetricsCount() << " metrics" << std::endl; + std::cout << "Session '" << session->getName() << "' has " << session->getMetricsCount() << " metrics" + << std::endl; } } - + // Create another session for AI operations { BOLT_PROFILE_SESSION("ai_inference_session"); - + std::vector models = {"text_classifier", "sentiment_analyzer", "summarizer"}; std::uniform_int_distribution<> inferenceTime(50, 200); - + for (const auto& model : models) { simulateAIInference(model, inferenceTime(gen)); } - + auto session = profiler.getCurrentSession(); if (session) { - std::cout << "AI session completed with " - << session->getMetricsCount() << " inferences in " + std::cout << "AI session completed with " << session->getMetricsCount() << " inferences in " << session->getTotalDurationMs() << " ms" << std::endl; } } @@ -151,129 +150,130 @@ void demonstrateSessionProfiling() { void demonstrateSystemMonitoring() { std::cout << "\\n=== System Monitoring Demo ===" << std::endl; - + auto& profiler = bolt::PerformanceProfiler::getInstance(); profiler.enableSystemMonitoring(); - + // Perform memory-intensive operations simulateMemoryOperations(); - + // Perform network operations std::vector endpoints = {"/api/users", "/api/data", "/api/status"}; std::random_device rd; std::mt19937 gen(rd()); std::uniform_int_distribution<> requestTime(30, 120); - + for (const auto& endpoint : endpoints) { simulateNetworkRequest(endpoint, requestTime(gen)); } - + std::cout << "System monitoring completed. Check detailed report for memory/CPU data." << std::endl; } void demonstrateConcurrentProfiling() { std::cout << "\\n=== Concurrent Profiling Demo ===" << std::endl; - + const int numWorkers = 4; std::vector workers; - + // Create multiple threads doing different types of work for (int i = 0; i < numWorkers; ++i) { workers.emplace_back([i]() { std::string sessionName = "worker_thread_" + std::to_string(i); auto session = bolt::PerformanceProfiler::getInstance().createSession(sessionName); bolt::PerformanceProfiler::getInstance().setCurrentSession(sessionName); - + std::random_device rd; std::mt19937 gen(rd()); std::uniform_int_distribution<> workTime(10, 50); - + for (int j = 0; j < 5; ++j) { std::string taskName = "task_" + std::to_string(j); - + if (i % 2 == 0) { // Even threads do AI work simulateAIInference("thread_model_" + std::to_string(i), workTime(gen)); } else { // Odd threads do file operations - simulateFileLoading("thread_file_" + std::to_string(i) + "_" + std::to_string(j) + ".dat", workTime(gen)); + simulateFileLoading("thread_file_" + std::to_string(i) + "_" + std::to_string(j) + ".dat", + workTime(gen)); } } - + bolt::PerformanceProfiler::getInstance().endSession(sessionName); }); } - + // Wait for all workers to complete for (auto& worker : workers) { worker.join(); } - + std::cout << "Concurrent profiling completed with " << numWorkers << " worker threads." << std::endl; } void demonstrateDataExport() { std::cout << "\\n=== Data Export Demo ===" << std::endl; - + auto& profiler = bolt::PerformanceProfiler::getInstance(); - + // Export data to different formats std::string jsonFile = "/tmp/bolt_profiler_demo.json"; std::string csvFile = "/tmp/bolt_profiler_demo.csv"; - + profiler.exportToJson(jsonFile); profiler.exportToCsv(csvFile); - + std::cout << "Profiling data exported to:" << std::endl; std::cout << " JSON: " << jsonFile << std::endl; std::cout << " CSV: " << csvFile << std::endl; - + // Print summary and detailed reports std::cout << "\\n--- Summary Report ---" << std::endl; profiler.printSummary(); - + std::cout << "\\n--- Detailed Report ---" << std::endl; profiler.printDetailedReport(); } void demonstrateIntegrationWithLogging() { std::cout << "\\n=== Integration with Logging System Demo ===" << std::endl; - + // Configure logging to show profiler output bolt::LogManager::configureConsoleLogging(bolt::LogLevel::INFO, true); - + auto& profiler = bolt::PerformanceProfiler::getInstance(); - + // The profiler automatically logs metrics when they complete { BOLT_PROFILE_SCOPE("logged_operation"); std::this_thread::sleep_for(std::chrono::milliseconds(25)); } - + // You can also manually log session summaries auto session = profiler.createSession("manual_logging_session"); profiler.setCurrentSession("manual_logging_session"); - + { BOLT_PROFILE_SCOPE("session_work"); std::this_thread::sleep_for(std::chrono::milliseconds(35)); } - + profiler.endSession("manual_logging_session"); profiler.logSessionSummary(*session, bolt::LogLevel::INFO); - + std::cout << "Integration with logging system demonstrated." << std::endl; } void demonstrateAnalyticsAndFiltering() { std::cout << "\\n=== Analytics and Filtering Demo ===" << std::endl; - + auto& profiler = bolt::PerformanceProfiler::getInstance(); - + // Get analytics std::cout << "Total metrics recorded: " << profiler.getTotalMetricsCount() << std::endl; std::cout << "Average metric duration: " << profiler.getAverageMetricDuration() << " ms" << std::endl; - + // Get categories auto categories = profiler.getCategories(); std::cout << "Categories found: "; @@ -281,7 +281,7 @@ void demonstrateAnalyticsAndFiltering() { std::cout << category << " "; } std::cout << std::endl; - + // Analyze metrics by category for (const auto& category : categories) { auto metrics = profiler.getMetricsByCategory(category); @@ -291,10 +291,9 @@ void demonstrateAnalyticsAndFiltering() { totalDuration += metric->getDurationMs(); } double avgDuration = totalDuration / metrics.size(); - - std::cout << "Category " << category << ": " - << metrics.size() << " metrics, avg " - << avgDuration << " ms" << std::endl; + + std::cout << "Category " << category << ": " << metrics.size() << " metrics, avg " << avgDuration << " ms" + << std::endl; } } } @@ -302,15 +301,15 @@ void demonstrateAnalyticsAndFiltering() { int main() { std::cout << "Bolt Performance Profiler Demo" << std::endl; std::cout << "==============================" << std::endl; - + try { // Initialize logging bolt::LogManager::configureConsoleLogging(bolt::LogLevel::WARN, false); - + // Reset profiler to start fresh auto& profiler = bolt::PerformanceProfiler::getInstance(); profiler.reset(); - + // Run demonstrations demonstrateBasicProfiling(); demonstrateSessionProfiling(); @@ -319,20 +318,19 @@ int main() { demonstrateIntegrationWithLogging(); demonstrateAnalyticsAndFiltering(); demonstrateDataExport(); - + std::cout << "\\n=== Demo Complete ===" << std::endl; std::cout << "Performance profiler demonstration completed successfully!" << std::endl; std::cout << "Total metrics collected: " << profiler.getTotalMetricsCount() << std::endl; - + // Clean up old metrics (demo only) std::cout << "\\nCleaning up metrics older than 1 minute..." << std::endl; profiler.clearOldMetrics(std::chrono::minutes(1)); std::cout << "Metrics after cleanup: " << profiler.getTotalMetricsCount() << std::endl; - } catch (const std::exception& e) { std::cerr << "Demo failed with exception: " << e.what() << std::endl; return 1; } - + return 0; -} \ No newline at end of file +} diff --git a/demo_plugin_system.cpp b/demo_plugin_system.cpp index ae1519c2..c8d268de 100644 --- a/demo_plugin_system.cpp +++ b/demo_plugin_system.cpp @@ -1,32 +1,31 @@ -#include "bolt/core/plugin_system.hpp" -#include "bolt/core/plugin_interface.hpp" -#include "bolt/core/editor_store.hpp" -#include "bolt/editor/integrated_editor.hpp" -#include "../examples/plugins/cpp_language_plugin.cpp" // Include for static linking +#include #include #include -#include + +#include "../examples/plugins/cpp_language_plugin.cpp" // NOLINT(build/include) compiled in for static linking +#include "bolt/core/editor_store.hpp" +#include "bolt/core/plugin_interface.hpp" +#include "bolt/core/plugin_system.hpp" +#include "bolt/editor/integrated_editor.hpp" // Create a simple editor store for demo purposes class DemoEditorStore : public bolt::EditorStore { -public: + public: DemoEditorStore() = default; - + // Implement minimal interface for demo void openDocument(const std::string& filePath, const std::string& content) { std::cout << "Demo: Opening document " << filePath << std::endl; } - - void closeDocument(const std::string& filePath) { - std::cout << "Demo: Closing document " << filePath << std::endl; - } + + void closeDocument(const std::string& filePath) { std::cout << "Demo: Closing document " << filePath << std::endl; } }; // Create a simple integrated editor for demo purposes class DemoIntegratedEditor : public bolt::IntegratedEditor { -public: + public: DemoIntegratedEditor() = default; - + void openDocument(const std::string& filePath, const std::string& content) { std::cout << "Demo: Integrated editor opening " << filePath << std::endl; } @@ -35,22 +34,22 @@ class DemoIntegratedEditor : public bolt::IntegratedEditor { // Create a simple editor store for demo purposes - just use nullptr since we only need interface void demonstratePluginSystem() { std::cout << "=== Bolt Plugin System Demonstration ===" << std::endl; - + // Get plugin system instance bolt::PluginSystem& pluginSystem = bolt::PluginSystem::getInstance(); - + // Clean any previous state pluginSystem.shutdown(); - + // Initialize plugin system (use nullptr for editor components since this is just a demo) std::cout << "\n1. Initializing Plugin System..." << std::endl; pluginSystem.initialize(nullptr, nullptr); - + // Add plugin directories for discovery std::cout << "\n2. Setting up plugin directories..." << std::endl; pluginSystem.addPluginDirectory("./plugins"); pluginSystem.addPluginDirectory("./examples/plugins"); - + // Load a plugin statically (since we included the source) std::cout << "\n3. Loading C++ Language Plugin..." << std::endl; auto cppPlugin = createCppLanguagePlugin(); @@ -59,7 +58,7 @@ void demonstratePluginSystem() { } else { std::cout << "โœ— Failed to load C++ Language Plugin" << std::endl; } - + // Activate the plugin std::cout << "\n4. Activating plugin..." << std::endl; if (pluginSystem.activatePlugin("CppLanguagePlugin")) { @@ -67,7 +66,7 @@ void demonstratePluginSystem() { } else { std::cout << "โœ— Failed to activate C++ Language Plugin" << std::endl; } - + // Query loaded plugins std::cout << "\n5. Querying loaded plugins..." << std::endl; auto loadedNames = pluginSystem.getLoadedPluginNames(); @@ -75,7 +74,7 @@ void demonstratePluginSystem() { for (const auto& name : loadedNames) { std::cout << " - " << name << std::endl; } - + // Get plugin metadata std::cout << "\n6. Plugin metadata:" << std::endl; auto metadata = pluginSystem.getPluginMetadata(); @@ -86,21 +85,21 @@ void demonstratePluginSystem() { std::cout << " Author: " << meta.author << std::endl; std::cout << " API Version: " << meta.apiVersion.toString() << std::endl; } - + // Test language plugin features std::cout << "\n7. Testing language plugin features..." << std::endl; auto langPlugins = pluginSystem.getLanguagePluginsForFile("test.cpp"); if (!langPlugins.empty()) { auto plugin = langPlugins[0]; std::cout << " Language plugin for .cpp files: " << plugin->getMetadata().name << std::endl; - + // Test code completions auto completions = plugin->getCodeCompletions("test.cpp", 10, 5); std::cout << " Code completions (first 10):" << std::endl; for (size_t i = 0; i < std::min(completions.size(), size_t(10)); ++i) { std::cout << " - " << completions[i] << std::endl; } - + // Test diagnostics std::string testCode = R"( int main() { @@ -117,7 +116,7 @@ void demonstratePluginSystem() { } } } - + // Test event system std::cout << "\n8. Testing event system..." << std::endl; bolt::PluginEvent documentOpenEvent; @@ -125,67 +124,67 @@ void demonstratePluginSystem() { documentOpenEvent.source = "demo"; documentOpenEvent.data["filePath"] = std::string("demo.cpp"); documentOpenEvent.data["content"] = std::string("int main() { return 0; }"); - + pluginSystem.publishEvent(documentOpenEvent); std::cout << " Document open event published" << std::endl; - + // Test plugin configuration std::cout << "\n9. Testing plugin configuration..." << std::endl; std::unordered_map config; config["enableAdvancedCompletions"] = true; config["maxCompletions"] = 20; - + if (pluginSystem.configurePlugin("CppLanguagePlugin", config)) { std::cout << "โœ“ Plugin configured successfully!" << std::endl; } else { std::cout << "โœ— Plugin configuration failed" << std::endl; } - + // Test plugin state management std::cout << "\n10. Testing plugin state management..." << std::endl; auto state = pluginSystem.getPluginState("CppLanguagePlugin"); std::cout << " Plugin state: " << static_cast(state) << std::endl; - + std::cout << " Is loaded: " << (pluginSystem.isPluginLoaded("CppLanguagePlugin") ? "Yes" : "No") << std::endl; std::cout << " Is active: " << (pluginSystem.isPluginActive("CppLanguagePlugin") ? "Yes" : "No") << std::endl; - + // Deactivate plugin std::cout << "\n11. Deactivating plugin..." << std::endl; if (pluginSystem.deactivatePlugin("CppLanguagePlugin")) { std::cout << "โœ“ Plugin deactivated" << std::endl; } - + // Reactivate plugin std::cout << "\n12. Reactivating plugin..." << std::endl; if (pluginSystem.activatePlugin("CppLanguagePlugin")) { std::cout << "โœ“ Plugin reactivated" << std::endl; } - + // Legacy plugin support demo std::cout << "\n13. Testing legacy plugin support..." << std::endl; bool legacyInitialized = false; bool legacyCleaned = false; - + bolt::Plugin legacyPlugin; legacyPlugin.name = "LegacyDemo"; legacyPlugin.version = "1.0.0"; - legacyPlugin.initialize = [&]() { - legacyInitialized = true; + legacyPlugin.initialize = [&]() { + legacyInitialized = true; std::cout << " Legacy plugin initialized" << std::endl; }; - legacyPlugin.cleanup = [&]() { - legacyCleaned = true; + legacyPlugin.cleanup = [&]() { + legacyCleaned = true; std::cout << " Legacy plugin cleaned up" << std::endl; }; - + pluginSystem.registerPlugin(legacyPlugin); pluginSystem.initializeAll(); - + // Error handling demo std::cout << "\n14. Testing error handling..." << std::endl; // Try to load non-existent plugin pluginSystem.loadPlugin("/nonexistent/plugin.so"); - + auto errors = pluginSystem.getPluginErrors(); if (!errors.empty()) { std::cout << " Plugin errors captured:" << std::endl; @@ -193,12 +192,12 @@ void demonstratePluginSystem() { std::cout << " - " << error << std::endl; } } - + // Cleanup std::cout << "\n15. Cleaning up..." << std::endl; - pluginSystem.cleanupAll(); // Legacy plugins - pluginSystem.shutdown(); // Modern plugins - + pluginSystem.cleanupAll(); // Legacy plugins + pluginSystem.shutdown(); // Modern plugins + std::cout << "\n=== Plugin System Demonstration Complete ===" << std::endl; } @@ -211,4 +210,4 @@ int main() { std::cerr << "Demo failed with error: " << e.what() << std::endl; return 1; } -} \ No newline at end of file +} diff --git a/demo_semantic_file_search.cpp b/demo_semantic_file_search.cpp index f30a1df9..0c48a806 100644 --- a/demo_semantic_file_search.cpp +++ b/demo_semantic_file_search.cpp @@ -1,25 +1,25 @@ -#include "bolt/ai/semantic_search_manager.hpp" -#include #include +#include + +#include "bolt/ai/semantic_search_manager.hpp" void printSearchResults(const std::vector& results) { if (results.empty()) { std::cout << "No results found.\n"; return; } - + std::cout << "\n" << std::string(80, '=') << "\n"; std::cout << "Search Results (" << results.size() << " found)\n"; std::cout << std::string(80, '=') << "\n\n"; - + for (size_t i = 0; i < results.size(); ++i) { const auto& result = results[i]; - + std::cout << (i + 1) << ". " << result.file_path << "\n"; - std::cout << " Similarity: " << std::fixed << std::setprecision(4) - << result.similarity_score << "\n"; + std::cout << " Similarity: " << std::fixed << std::setprecision(4) << result.similarity_score << "\n"; std::cout << " Type: " << result.file_type << "\n"; - + if (!result.content_preview.empty()) { std::cout << " Preview: "; std::string preview = result.content_preview; @@ -36,45 +36,39 @@ void printSearchResults(const std::vector& results) { int main() { std::cout << "=== Semantic File Search Demo ===\n\n"; - + // 1. Initialize the semantic search manager std::cout << "Initializing semantic search manager...\n"; bolt::ai::SemanticSearchManager search_manager; - + if (!search_manager.initialize()) { std::cerr << "โŒ Failed to initialize semantic search manager.\n"; std::cerr << "Make sure a GGUF model is available.\n"; return 1; } - + std::cout << "โœ… Semantic search manager initialized\n\n"; - + // 2. Configure indexing bolt::ai::IndexingConfig config; config.max_chunk_size = 500; config.chunk_overlap = 100; config.file_extensions = {".cpp", ".hpp", ".h", ".txt", ".md"}; - config.max_file_size = 1024 * 1024; // 1MB + config.max_file_size = 1024 * 1024; // 1MB search_manager.setConfig(config); - + // 3. Index some files std::cout << "Indexing files...\n"; - - std::vector files_to_index = { - "./bolt_chat.cpp", - "./demo_direct_gguf.cpp", - "./include/bolt/ai/direct_gguf_inference.hpp", - "./src/bolt/ai/direct_gguf_inference.cpp", - "./README.md" - }; - + + std::vector files_to_index = {"./bolt_chat.cpp", "./demo_direct_gguf.cpp", + "./include/bolt/ai/direct_gguf_inference.hpp", + "./src/bolt/ai/direct_gguf_inference.cpp", "./README.md"}; + // Set progress callback - search_manager.setProgressCallback( - [](const std::string& file, size_t current, size_t total) { - std::cout << " [" << current << "/" << total << "] " << file << "\n"; - } - ); - + search_manager.setProgressCallback([](const std::string& file, size_t current, size_t total) { + std::cout << " [" << current << "/" << total << "] " << file << "\n"; + }); + for (const auto& file : files_to_index) { if (search_manager.indexFile(file)) { std::cout << " โœ“ Indexed: " << file << "\n"; @@ -82,7 +76,7 @@ int main() { std::cout << " โœ— Skipped: " << file << "\n"; } } - + // 4. Display indexing statistics auto stats = search_manager.getStats(); std::cout << "\nIndexing Statistics:\n"; @@ -90,53 +84,52 @@ int main() { std::cout << " Files skipped: " << stats.files_skipped << "\n"; std::cout << " Total chunks: " << stats.total_chunks << "\n"; std::cout << " Errors: " << stats.errors << "\n"; - std::cout << " Total time: " << std::fixed << std::setprecision(2) - << stats.total_time_seconds << " seconds\n"; - + std::cout << " Total time: " << std::fixed << std::setprecision(2) << stats.total_time_seconds << " seconds\n"; + // 5. Perform semantic searches std::cout << "\n" << std::string(80, '=') << "\n"; std::cout << "Performing Semantic Searches\n"; std::cout << std::string(80, '=') << "\n"; - + // Search 1: Chat functionality std::cout << "\nQuery 1: \"chat interface implementation\"\n"; auto results1 = search_manager.search("chat interface implementation", 3); printSearchResults(results1); - + // Search 2: Model loading std::cout << "\nQuery 2: \"loading GGUF models\"\n"; auto results2 = search_manager.search("loading GGUF models", 3); printSearchResults(results2); - + // Search 3: AI inference std::cout << "\nQuery 3: \"AI inference and text generation\"\n"; auto results3 = search_manager.search("AI inference and text generation", 3); printSearchResults(results3); - + // 6. Interactive search std::cout << "\n" << std::string(80, '=') << "\n"; std::cout << "Interactive Search Mode\n"; std::cout << std::string(80, '=') << "\n"; std::cout << "Enter search queries (or 'quit' to exit):\n\n"; - + std::string query; while (true) { std::cout << "Search> "; std::getline(std::cin, query); - + if (query == "quit" || query == "exit") { break; } - + if (query.empty()) { continue; } - + auto results = search_manager.search(query, 5, 0.2f); printSearchResults(results); } - + std::cout << "\n=== Demo Complete ===\n"; - + return 0; } diff --git a/demo_split_view.cpp b/demo_split_view.cpp index 9554c62d..a590b268 100644 --- a/demo_split_view.cpp +++ b/demo_split_view.cpp @@ -1,9 +1,10 @@ -#include #include +#include + #include "bolt/editor/integrated_editor.hpp" #include "bolt/editor/split_view_manager.hpp" -using namespace bolt; +using namespace bolt; // NOLINT(build/namespaces) void createSampleFiles() { // Create some sample files to work with @@ -15,7 +16,7 @@ void createSampleFiles() { << " return 0;\n" << "}\n"; file1.close(); - + std::ofstream file2("/tmp/sample2.cpp"); file2 << "// Sample C++ File 2\n" << "#include \n" @@ -24,7 +25,7 @@ void createSampleFiles() { << " std::sort(vec.begin(), vec.end());\n" << "}\n"; file2.close(); - + std::ofstream file3("/tmp/sample3.hpp"); file3 << "// Sample Header File\n" << "#ifndef SAMPLE_HPP\n" @@ -42,29 +43,29 @@ void createSampleFiles() { int main() { std::cout << "Split View Editing Demo" << std::endl; std::cout << "=======================" << std::endl << std::endl; - + // Create sample files createSampleFiles(); - + // Get the integrated editor instance auto& editor = IntegratedEditor::getInstance(); auto& splitManager = SplitViewManager::getInstance(); - + std::cout << "1. Initial state:" << std::endl; std::cout << " - Split view enabled: " << (editor.isSplitViewEnabled() ? "Yes" : "No") << std::endl; std::cout << " - Number of panes: " << splitManager.getPaneCount() << std::endl; std::cout << " - Has splits: " << (editor.hasSplits() ? "Yes" : "No") << std::endl << std::endl; - + // Open first document in the default pane std::cout << "2. Opening sample1.cpp in default pane..." << std::endl; std::ifstream file1("/tmp/sample1.cpp"); std::string content1((std::istreambuf_iterator(file1)), std::istreambuf_iterator()); file1.close(); editor.openDocument("/tmp/sample1.cpp", content1); - + std::cout << " - Active pane ID: " << editor.getActivePaneId() << std::endl; std::cout << " - Open documents: " << editor.getOpenDocuments().size() << std::endl << std::endl; - + // Create horizontal split std::cout << "3. Creating horizontal split..." << std::endl; std::string hPaneId = editor.createHorizontalSplit(); @@ -72,31 +73,31 @@ int main() { std::cout << " - Number of panes: " << splitManager.getPaneCount() << std::endl; std::cout << " - Has splits: " << (editor.hasSplits() ? "Yes" : "No") << std::endl; std::cout << " - Active pane ID: " << editor.getActivePaneId() << std::endl << std::endl; - + // Open second document in the new pane std::cout << "4. Opening sample2.cpp in the new horizontal pane..." << std::endl; editor.openDocumentInPane(hPaneId, "/tmp/sample2.cpp"); - std::cout << " - Documents in pane " << hPaneId << ": " << - (splitManager.getPane(hPaneId)->hasDocument() ? "1" : "0") << std::endl; - + std::cout << " - Documents in pane " << hPaneId << ": " + << (splitManager.getPane(hPaneId)->hasDocument() ? "1" : "0") << std::endl; + auto openDocs = editor.getOpenDocuments(); std::cout << " - Total open documents: " << openDocs.size() << std::endl; for (const auto& doc : openDocs) { std::cout << " * " << doc << std::endl; } std::cout << std::endl; - + // Create vertical split std::cout << "5. Creating vertical split..." << std::endl; std::string vPaneId = editor.createVerticalSplit(); std::cout << " - New pane ID: " << vPaneId << std::endl; std::cout << " - Number of panes: " << splitManager.getPaneCount() << std::endl; std::cout << " - Active pane ID: " << editor.getActivePaneId() << std::endl << std::endl; - + // Open third document in new vertical pane std::cout << "6. Opening sample3.hpp in the new vertical pane..." << std::endl; editor.openDocumentInPane(vPaneId, "/tmp/sample3.hpp"); - + openDocs = editor.getOpenDocuments(); std::cout << " - Total open documents: " << openDocs.size() << std::endl; for (const auto& doc : openDocs) { @@ -104,18 +105,17 @@ int main() { std::cout << " * " << doc << " (in pane " << paneId << ")" << std::endl; } std::cout << std::endl; - + // Show all pane IDs std::cout << "7. All pane IDs:" << std::endl; auto allPanes = editor.getAllPaneIds(); for (const auto& paneId : allPanes) { auto* pane = splitManager.getPane(paneId); - std::cout << " - " << paneId << - (pane->hasFocus() ? " (ACTIVE)" : "") << - (pane->hasDocument() ? " [" + pane->getDocumentPath() + "]" : " [empty]") << std::endl; + std::cout << " - " << paneId << (pane->hasFocus() ? " (ACTIVE)" : "") + << (pane->hasDocument() ? " [" + pane->getDocumentPath() + "]" : " [empty]") << std::endl; } std::cout << std::endl; - + // Test navigation std::cout << "8. Testing pane navigation..." << std::endl; std::cout << " - Current active: " << editor.getActivePaneId() << std::endl; @@ -125,7 +125,7 @@ int main() { std::cout << " - After next again: " << editor.getActivePaneId() << std::endl; editor.navigateToPreviousPane(); std::cout << " - After previous: " << editor.getActivePaneId() << std::endl << std::endl; - + // Test closing a pane std::cout << "9. Testing pane closure..." << std::endl; std::cout << " - Panes before close: " << splitManager.getPaneCount() << std::endl; @@ -133,14 +133,14 @@ int main() { std::cout << " - Close successful: " << (closed ? "Yes" : "No") << std::endl; std::cout << " - Panes after close: " << splitManager.getPaneCount() << std::endl; std::cout << " - Active pane: " << editor.getActivePaneId() << std::endl; - + openDocs = editor.getOpenDocuments(); std::cout << " - Remaining open documents: " << openDocs.size() << std::endl; for (const auto& doc : openDocs) { std::cout << " * " << doc << std::endl; } std::cout << std::endl; - + // Test collapsing splits std::cout << "10. Testing split collapse..." << std::endl; std::cout << " - Has splits before collapse: " << (editor.hasSplits() ? "Yes" : "No") << std::endl; @@ -148,7 +148,7 @@ int main() { std::cout << " - Has splits after collapse: " << (editor.hasSplits() ? "Yes" : "No") << std::endl; std::cout << " - Panes after collapse: " << splitManager.getPaneCount() << std::endl; std::cout << " - Active pane: " << editor.getActivePaneId() << std::endl << std::endl; - + std::cout << "Split view demo completed successfully!" << std::endl; std::cout << "Key features demonstrated:" << std::endl; std::cout << "- Creating horizontal and vertical splits" << std::endl; @@ -157,6 +157,6 @@ int main() { std::cout << "- Closing individual panes" << std::endl; std::cout << "- Collapsing all splits" << std::endl; std::cout << "- Managing multiple documents across panes" << std::endl; - + return 0; -} \ No newline at end of file +} diff --git a/demo_split_view_basic.cpp b/demo_split_view_basic.cpp index 7038104f..dc0026c2 100644 --- a/demo_split_view_basic.cpp +++ b/demo_split_view_basic.cpp @@ -1,52 +1,53 @@ #include + #include "bolt/editor/editor_pane.hpp" #include "bolt/editor/split_view_manager.hpp" -using namespace bolt; +using namespace bolt; // NOLINT(build/namespaces) int main() { std::cout << "Split View Editing Demo (Basic)" << std::endl; std::cout << "================================" << std::endl << std::endl; - + try { // Test basic EditorPane functionality std::cout << "1. Testing EditorPane basics..." << std::endl; EditorPane pane("demo_pane"); - + std::cout << " - Pane ID: " << pane.getId() << std::endl; std::cout << " - Has document: " << (pane.hasDocument() ? "Yes" : "No") << std::endl; std::cout << " - Has focus: " << (pane.hasFocus() ? "Yes" : "No") << std::endl; std::cout << " - Is visible: " << (pane.isVisible() ? "Yes" : "No") << std::endl; - + // Test focus management pane.setFocus(true); std::cout << " - After setting focus: " << (pane.hasFocus() ? "Yes" : "No") << std::endl; - + // Test position management EditorPane::PanePosition pos{100, 200, 800, 600}; pane.setPosition(pos); const auto& retrievedPos = pane.getPosition(); - std::cout << " - Position: (" << retrievedPos.x << ", " << retrievedPos.y << - ", " << retrievedPos.width << ", " << retrievedPos.height << ")" << std::endl; - + std::cout << " - Position: (" << retrievedPos.x << ", " << retrievedPos.y << ", " << retrievedPos.width + << ", " << retrievedPos.height << ")" << std::endl; + // Test cursor operations pane.setCursorPosition(10, 25); size_t line, column; pane.getCursorPosition(line, column); std::cout << " - Cursor position: (" << line << ", " << column << ")" << std::endl; - + std::cout << std::endl; - + // Test SplitViewManager singleton access std::cout << "2. Testing SplitViewManager basics..." << std::endl; auto& manager = SplitViewManager::getInstance(); - + std::cout << " - Split view enabled: " << (manager.isEnabled() ? "Yes" : "No") << std::endl; std::cout << " - Initial pane count: " << manager.getPaneCount() << std::endl; std::cout << " - Has splits: " << (manager.hasSplits() ? "Yes" : "No") << std::endl; - + std::cout << std::endl; - + std::cout << "Basic split view functionality verified successfully!" << std::endl; std::cout << std::endl; std::cout << "Key Components Implemented:" << std::endl; @@ -57,9 +58,8 @@ int main() { std::cout << "- Thread Safety: All operations use ThreadSafe wrappers" << std::endl; std::cout << std::endl; std::cout << "Split view editing foundation is ready for use!" << std::endl; - + return 0; - } catch (const std::exception& e) { std::cerr << "Demo failed with exception: " << e.what() << std::endl; return 1; @@ -67,4 +67,4 @@ int main() { std::cerr << "Demo failed with unknown exception" << std::endl; return 1; } -} \ No newline at end of file +} diff --git a/demo_temporal_rag_rwkv.cpp b/demo_temporal_rag_rwkv.cpp index f51f362f..b2af5e8d 100644 --- a/demo_temporal_rag_rwkv.cpp +++ b/demo_temporal_rag_rwkv.cpp @@ -1,10 +1,11 @@ -#include "bolt/ai/temporal_rag_manager.hpp" -#include "bolt/ai/temporal_tool_manager.hpp" -#include -#include #include +#include +#include #include +#include "bolt/ai/temporal_rag_manager.hpp" +#include "bolt/ai/temporal_tool_manager.hpp" + void printSeparator() { std::cout << "\n" << std::string(80, '=') << "\n\n"; } @@ -15,32 +16,32 @@ std::vector generateStockData(int days) { std::random_device rd; std::mt19937 gen(rd()); std::normal_distribution<> price_noise(0, 2.0); - + double base_price = 100.0; auto now = std::chrono::system_clock::now(); - + for (int i = 0; i < days * 24; ++i) { // Hourly data bolt::ai::TimeSeriesPoint point; point.timestamp = now - std::chrono::hours(days * 24 - i); - + // Simulate price movement with trend and noise double trend = std::sin(i * 0.1) * 10.0; // Cyclical trend double noise = price_noise(gen); double price = base_price + trend + noise; - + // Add anomaly at specific points if (i == days * 12) { // Midpoint anomaly price += 20.0; } - + point.values["price"] = price; point.values["volume"] = 1000000 + std::abs(noise) * 100000; point.source = "stock_exchange"; point.category = "stock"; - + data.push_back(point); } - + return data; } @@ -48,11 +49,11 @@ int main() { std::cout << "=== Temporal RAG & TOOL-USE Demo with RWKV.cpp ===\n"; std::cout << "Time-Series Analysis and Predictive Agents\n"; printSeparator(); - + // 1. Initialize the Temporal RAG Manager std::cout << "Initializing Temporal RAG Manager...\n"; bolt::ai::TemporalRAGManager rag_manager; - + if (!rag_manager.initialize()) { std::cerr << "โŒ Failed to initialize Temporal RAG Manager\n"; std::cerr << "Note: This demo shows the architecture even without a model\n"; @@ -60,7 +61,7 @@ int main() { std::cout << "โœ… Temporal RAG Manager initialized\n"; } std::cout << "\n"; - + // 2. Initialize the Temporal Tool Manager std::cout << "Initializing Temporal Tool Manager...\n"; bolt::ai::TemporalToolManager tool_manager; @@ -68,100 +69,95 @@ int main() { tool_manager.loadAllStandardTools(); std::cout << "โœ… Loaded " << tool_manager.getAvailableTools().size() << " temporal tools\n"; printSeparator(); - + // 3. Generate and ingest sample time-series data std::cout << "Generating sample stock market data...\n"; auto stock_data = generateStockData(30); // 30 days of hourly data - + std::cout << "Ingesting " << stock_data.size() << " data points...\n"; rag_manager.ingestDataBatch(stock_data); std::cout << "โœ… Data ingested successfully\n"; - + auto time_range = rag_manager.getDataTimeRange(); - std::cout << "Data time range: " << std::chrono::duration_cast( - time_range.second - time_range.first).count() << " hours\n"; + std::cout << "Data time range: " + << std::chrono::duration_cast(time_range.second - time_range.first).count() + << " hours\n"; printSeparator(); - + // 4. Demonstrate Temporal RAG: Query time-series data std::cout << "=== Temporal RAG: Analyzing Time Periods ===\n\n"; - + bolt::ai::TemporalQuery query1; query1.start_time = std::chrono::system_clock::now() - std::chrono::hours(7 * 24); query1.end_time = std::chrono::system_clock::now(); query1.metrics = {"price", "volume"}; query1.source_filter = "stock_exchange"; - + std::cout << "Query: Analyze stock price trends over the last 7 days\n\n"; - + std::string analysis = rag_manager.analyzeTimePeriod( - query1, - "Analyze the stock price trends and identify any significant patterns or anomalies." - ); - + query1, "Analyze the stock price trends and identify any significant patterns or anomalies."); + std::cout << "RWKV Analysis:\n"; std::cout << "โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€\n"; std::cout << analysis << "\n"; std::cout << "โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€\n"; printSeparator(); - + // 5. Demonstrate pattern detection std::cout << "=== Pattern Detection ===\n\n"; - + std::string patterns = rag_manager.detectPatterns( - "price", - std::chrono::system_clock::now() - std::chrono::hours(30 * 24), - std::chrono::system_clock::now() - ); - + "price", std::chrono::system_clock::now() - std::chrono::hours(30 * 24), std::chrono::system_clock::now()); + std::cout << "Detected Patterns:\n"; std::cout << patterns << "\n"; printSeparator(); - + // 6. Demonstrate anomaly detection std::cout << "=== Anomaly Detection ===\n\n"; - + bolt::ai::TemporalQuery anomaly_query; anomaly_query.start_time = std::chrono::system_clock::now() - std::chrono::hours(30 * 24); anomaly_query.end_time = std::chrono::system_clock::now(); anomaly_query.metrics = {"price"}; - + auto anomalies = rag_manager.findAnomalies("price", anomaly_query, 2.0); - + std::cout << "Found " << anomalies.size() << " anomalies:\n\n"; for (size_t i = 0; i < std::min(size_t(5), anomalies.size()); ++i) { auto time_t = std::chrono::system_clock::to_time_t(anomalies[i].timestamp); std::cout << (i + 1) << ". Time: " << std::ctime(&time_t); - std::cout << " Price: $" << std::fixed << std::setprecision(2) - << anomalies[i].values.at("price") << "\n"; + std::cout << " Price: $" << std::fixed << std::setprecision(2) << anomalies[i].values.at("price") << "\n"; } printSeparator(); - + // 7. Demonstrate Temporal TOOL-USE: Forecasting std::cout << "=== Temporal TOOL-USE: Predictive Agent ===\n\n"; - + std::cout << "Available tools:\n"; auto available_tools = tool_manager.getAvailableTools(); for (const auto& tool : available_tools) { std::cout << " โ€ข " << tool << "\n"; } std::cout << "\n"; - + // AI decides to use the forecast tool std::cout << "AI Decision: Use 'forecast_price' tool\n\n"; - + std::unordered_map forecast_params; forecast_params["metric"] = "price"; forecast_params["n_steps"] = "24"; // Forecast next 24 hours forecast_params["confidence_level"] = "0.95"; - + auto forecast_result = tool_manager.invokeTool("forecast_price", forecast_params); - + std::cout << "Forecast Result:\n"; std::cout << " Success: " << (forecast_result.success ? "Yes" : "No") << "\n"; std::cout << " Description: " << forecast_result.description << "\n"; - std::cout << " Confidence: " << std::fixed << std::setprecision(2) - << (forecast_result.confidence_score * 100) << "%\n"; - + std::cout << " Confidence: " << std::fixed << std::setprecision(2) << (forecast_result.confidence_score * 100) + << "%\n"; + if (!forecast_result.predictions.empty()) { std::cout << " Predictions (first 5):\n"; for (size_t i = 0; i < std::min(size_t(5), forecast_result.predictions.size()); ++i) { @@ -170,10 +166,10 @@ int main() { } std::cout << "\n"; printSeparator(); - + // 8. Demonstrate automated triggers std::cout << "=== Automated Triggers ===\n\n"; - + bolt::ai::TemporalTrigger price_alert; price_alert.name = "high_price_alert"; price_alert.condition = "price > 110"; @@ -181,36 +177,36 @@ int main() { price_alert.tool_params = {{"message", "Price exceeded threshold!"}}; price_alert.enabled = true; price_alert.cooldown_seconds = 300; // 5 minutes - + tool_manager.registerTrigger(price_alert); std::cout << "Registered trigger: " << price_alert.name << "\n"; std::cout << "Condition: " << price_alert.condition << "\n"; std::cout << "Action: Invoke '" << price_alert.tool_to_invoke << "'\n\n"; - + // Simulate checking triggers with current state std::unordered_map current_state; current_state["price"] = 115.0; // Exceeds threshold current_state["volume"] = 1500000; - + std::cout << "Current State:\n"; std::cout << " Price: $" << current_state["price"] << "\n"; std::cout << " Volume: " << current_state["volume"] << "\n\n"; - + std::cout << "Checking triggers...\n"; tool_manager.checkTriggers(current_state); std::cout << "โœ… Triggers evaluated\n"; printSeparator(); - + // 9. Show execution history std::cout << "=== Tool Execution History ===\n\n"; auto history = tool_manager.getExecutionHistory(5); std::cout << "Recent executions: " << history.size() << "\n\n"; - + for (size_t i = 0; i < history.size(); ++i) { std::cout << (i + 1) << ". " << history[i].description << "\n"; std::cout << " Confidence: " << (history[i].confidence_score * 100) << "%\n"; } - + printSeparator(); std::cout << "=== Demo Complete ===\n"; std::cout << "\nThis demonstrates how RWKV.cpp can be enhanced with:\n"; @@ -218,6 +214,6 @@ int main() { std::cout << " โ€ข Predictive agents with tool use (Temporal TOOL-USE)\n"; std::cout << " โ€ข Automated monitoring and response triggers\n"; std::cout << " โ€ข Real-time forecasting and anomaly detection\n\n"; - + return 0; } diff --git a/demo_theme_integration.cpp b/demo_theme_integration.cpp index cd7b7bcf..df291d9c 100644 --- a/demo_theme_integration.cpp +++ b/demo_theme_integration.cpp @@ -1,50 +1,53 @@ #include #include #include + #include "bolt/editor/theme_system.hpp" namespace { // Mock editor component to demonstrate theme integration class ThemedEditor { -private: + private: std::string currentBackground_; std::string currentForeground_; std::string currentFont_; int currentFontSize_; - -public: + + public: void applyTheme() { auto& themeSystem = bolt::ThemeSystem::getInstance(); auto colors = themeSystem.getCurrentColors(); auto fonts = themeSystem.getCurrentFontSettings(); - + // Apply theme colors currentBackground_ = colors.background; currentForeground_ = colors.foreground; currentFont_ = fonts.family; currentFontSize_ = fonts.size; - + std::cout << "Editor theme applied:" << std::endl; std::cout << " Background: " << currentBackground_ << std::endl; std::cout << " Foreground: " << currentForeground_ << std::endl; std::cout << " Font: " << currentFont_ << " " << currentFontSize_ << "px" << std::endl; } - + void highlightCode(const std::string& code) { auto& themeSystem = bolt::ThemeSystem::getInstance(); auto colors = themeSystem.getCurrentColors(); - + std::cout << "\nHighlighted code with current theme:" << std::endl; std::cout << "----------------------------------------" << std::endl; - + // Simple mock syntax highlighting - std::vector lines = {"// Include header", "class MyClass {", " int value = 42;", " string name = \"example\";", "};"}; - + std::vector lines = {"// Include header", "class MyClass {", " int value = 42;", + " string name = \"example\";", "};"}; + for (const auto& line : lines) { if (line.find("//") != std::string::npos) { std::cout << "[" << colors.comment << "] " << line << std::endl; - } else if (line.find("class") != std::string::npos || line.find("int") != std::string::npos || line.find("string") != std::string::npos) { + } else if (line.find("class") != std::string::npos || line.find("int") != std::string::npos || + line.find("string") != std::string::npos) { std::cout << "[" << colors.keyword << "] " << line << std::endl; } else if (line.find("\"") != std::string::npos) { std::cout << "[" << colors.string << "] " << line << std::endl; @@ -59,11 +62,11 @@ class ThemedEditor { // Mock UI component that updates based on theme class ThemedUI { -public: + public: void updateColors() { auto& themeSystem = bolt::ThemeSystem::getInstance(); auto colors = themeSystem.getCurrentColors(); - + std::cout << "\nUI component colors updated:" << std::endl; std::cout << " Menu background: " << colors.background << std::endl; std::cout << " Menu text: " << colors.foreground << std::endl; @@ -75,37 +78,37 @@ class ThemedUI { void demonstrateIntegration() { std::cout << "๐Ÿ”— Theme System Integration Demo" << std::endl; std::cout << "=================================" << std::endl; - + // Initialize theme system auto& themeSystem = bolt::ThemeSystem::getInstance(); themeSystem.loadDefaultThemes(); - + // Create editor and UI components ThemedEditor editor; ThemedUI ui; - + // Demonstrate theme switching with component updates std::vector themes = {"dark", "light"}; - + for (const auto& themeName : themes) { std::cout << "\n๐Ÿ“‹ Switching to '" << themeName << "' theme..." << std::endl; std::cout << std::string(50, '-') << std::endl; - + // Switch theme themeSystem.setTheme(themeName); - + // Update all components editor.applyTheme(); ui.updateColors(); - + // Show code highlighting with current theme editor.highlightCode("sample code"); } - + // Demonstrate custom theme integration std::cout << "\n๐ŸŽจ Adding custom theme..." << std::endl; std::cout << std::string(50, '-') << std::endl; - + bolt::Theme customTheme; customTheme.colors.background = "#2B2B2B"; customTheme.colors.foreground = "#A9B7C6"; @@ -120,10 +123,10 @@ void demonstrateIntegration() { customTheme.fontSettings.family = "JetBrains Mono"; customTheme.fontSettings.size = 15; customTheme.fontSettings.lineHeight = 1.4f; - + themeSystem.addTheme("intellij", customTheme); themeSystem.setTheme("intellij"); - + editor.applyTheme(); ui.updateColors(); editor.highlightCode("sample code"); @@ -132,9 +135,9 @@ void demonstrateIntegration() { void demonstrateThemeListener() { std::cout << "\n๐Ÿ”” Theme Change Listener Demo" << std::endl; std::cout << "==============================" << std::endl; - + auto& themeSystem = bolt::ThemeSystem::getInstance(); - + // Simulate a component that responds to theme changes auto respondToThemeChange = [&]() { std::cout << "๐Ÿ“ข Theme changed to: " << themeSystem.getCurrentThemeName() << std::endl; @@ -142,7 +145,7 @@ void demonstrateThemeListener() { std::cout << " New background: " << colors.background << std::endl; std::cout << " New foreground: " << colors.foreground << std::endl; }; - + // Demonstrate theme changes std::vector themes = {"dark", "light", "intellij"}; for (const auto& theme : themes) { @@ -151,21 +154,21 @@ void demonstrateThemeListener() { } } -} // anonymous namespace +} // anonymous namespace int main() { std::cout << "๐ŸŽจ Theme System Integration Examples" << std::endl; std::cout << "====================================" << std::endl; - + demonstrateIntegration(); demonstrateThemeListener(); - + std::cout << "\nโœ… Integration Examples Complete!" << std::endl; std::cout << "These examples show how editor components can integrate with the theme system:" << std::endl; std::cout << "- Editor components apply themes to their visual elements" << std::endl; std::cout << "- UI components update colors when themes change" << std::endl; std::cout << "- Syntax highlighting uses theme colors for different token types" << std::endl; std::cout << "- Components can listen for theme changes and update automatically" << std::endl; - + return 0; -} \ No newline at end of file +} diff --git a/demo_theme_system.cpp b/demo_theme_system.cpp index 7015679f..7138ba82 100644 --- a/demo_theme_system.cpp +++ b/demo_theme_system.cpp @@ -1,6 +1,7 @@ #include #include #include + #include "bolt/editor/theme_system.hpp" namespace { @@ -12,13 +13,13 @@ void printSeparator() { void printThemeInfo(const std::string& themeName) { auto& themeSystem = bolt::ThemeSystem::getInstance(); themeSystem.setTheme(themeName); - + auto colors = themeSystem.getCurrentColors(); auto fonts = themeSystem.getCurrentFontSettings(); - + std::cout << "\n๐ŸŽจ Theme: " << themeName << std::endl; printSeparator(); - + std::cout << "๐Ÿ“‹ Color Scheme:" << std::endl; std::cout << " Background: " << colors.background << std::endl; std::cout << " Foreground: " << colors.foreground << std::endl; @@ -30,7 +31,7 @@ void printThemeInfo(const std::string& themeName) { std::cout << " Numbers: " << colors.number << std::endl; std::cout << " Types: " << colors.type << std::endl; std::cout << " Functions: " << colors.function << std::endl; - + std::cout << "\n๐Ÿ”ค Font Settings:" << std::endl; std::cout << " Family: " << fonts.family << std::endl; std::cout << " Size: " << fonts.size << "px" << std::endl; @@ -41,11 +42,11 @@ void demonstrateCodeSyntaxHighlighting(const std::string& themeName) { auto& themeSystem = bolt::ThemeSystem::getInstance(); themeSystem.setTheme(themeName); auto colors = themeSystem.getCurrentColors(); - + std::cout << "\n๐Ÿ’ป Sample Code with " << themeName << " theme colors:" << std::endl; std::cout << " (showing color codes that would be used for syntax highlighting)" << std::endl; std::cout << std::string(50, '-') << std::endl; - + // Simulate syntax highlighting by showing what colors would be used std::cout << "// This is a comment -> " << colors.comment << std::endl; std::cout << "class Example { -> " << colors.keyword << " + " << colors.type << std::endl; @@ -59,10 +60,10 @@ void demonstrateCodeSyntaxHighlighting(const std::string& themeName) { void createCustomThemeDemo() { auto& themeSystem = bolt::ThemeSystem::getInstance(); - + std::cout << "\n๐Ÿ› ๏ธ Creating Custom Theme Demo" << std::endl; printSeparator(); - + // Create a custom "monokai" inspired theme bolt::Theme monokaiTheme; monokaiTheme.colors.background = "#272822"; @@ -78,10 +79,10 @@ void createCustomThemeDemo() { monokaiTheme.fontSettings.family = "Fira Code, Monaco, monospace"; monokaiTheme.fontSettings.size = 15; monokaiTheme.fontSettings.lineHeight = 1.4f; - + themeSystem.addTheme("monokai", monokaiTheme); std::cout << "โœ… Added custom 'monokai' theme" << std::endl; - + printThemeInfo("monokai"); demonstrateCodeSyntaxHighlighting("monokai"); } @@ -89,9 +90,9 @@ void createCustomThemeDemo() { void demonstrateThemeSwitching() { std::cout << "\n๐Ÿ”„ Theme Switching Demo" << std::endl; printSeparator(); - + std::vector themes = {"dark", "light", "monokai"}; - + for (const auto& theme : themes) { std::cout << "\n>> Switching to '" << theme << "' theme..." << std::endl; demonstrateCodeSyntaxHighlighting(theme); @@ -101,21 +102,21 @@ void demonstrateThemeSwitching() { void testErrorHandling() { std::cout << "\n๐Ÿšจ Error Handling Demo" << std::endl; printSeparator(); - + auto& themeSystem = bolt::ThemeSystem::getInstance(); - + // Set to a known good theme first themeSystem.setTheme("dark"); auto beforeColors = themeSystem.getCurrentColors(); std::cout << "Current theme background: " << beforeColors.background << std::endl; - + // Try to set an invalid theme std::cout << "Attempting to set invalid theme 'nonexistent'..." << std::endl; themeSystem.setTheme("nonexistent"); - + auto afterColors = themeSystem.getCurrentColors(); std::cout << "After invalid theme attempt, background: " << afterColors.background << std::endl; - + if (beforeColors.background == afterColors.background) { std::cout << "โœ… Error handling working correctly - theme unchanged" << std::endl; } else { @@ -123,33 +124,33 @@ void testErrorHandling() { } } -} // anonymous namespace +} // anonymous namespace int main() { std::cout << "๐ŸŽจ Bolt C++ Theme System Demo" << std::endl; std::cout << "==============================" << std::endl; - + // Initialize the theme system auto& themeSystem = bolt::ThemeSystem::getInstance(); themeSystem.loadDefaultThemes(); std::cout << "โœ… Theme system initialized with default themes" << std::endl; - + // Demonstrate built-in themes printThemeInfo("dark"); demonstrateCodeSyntaxHighlighting("dark"); - + printThemeInfo("light"); demonstrateCodeSyntaxHighlighting("light"); - + // Create and demonstrate custom theme createCustomThemeDemo(); - + // Demonstrate theme switching demonstrateThemeSwitching(); - + // Test error handling testErrorHandling(); - + std::cout << "\n๐ŸŽฏ Demo Summary" << std::endl; printSeparator(); std::cout << "โœ… Default themes (dark, light) loaded and working" << std::endl; @@ -158,9 +159,9 @@ int main() { std::cout << "โœ… Error handling for invalid themes working" << std::endl; std::cout << "โœ… Font settings management working" << std::endl; std::cout << "โœ… Color scheme management working" << std::endl; - + std::cout << "\n๐Ÿš€ Theme System Demo Complete!" << std::endl; std::cout << "The Bolt C++ theme system is fully functional and ready for integration." << std::endl; - + return 0; -} \ No newline at end of file +} diff --git a/demo_unified_rag_system.cpp b/demo_unified_rag_system.cpp index e7115cf6..c8e3589c 100644 --- a/demo_unified_rag_system.cpp +++ b/demo_unified_rag_system.cpp @@ -1,6 +1,7 @@ -#include "bolt/ai/unified_rag_manager.hpp" -#include #include +#include + +#include "bolt/ai/unified_rag_manager.hpp" void printSeparator() { std::cout << "\n" << std::string(80, '=') << "\n\n"; @@ -11,7 +12,7 @@ void printResults(const std::vector& results) { std::cout << "No results found.\n"; return; } - + std::cout << "Found " << results.size() << " results:\n\n"; for (size_t i = 0; i < results.size(); ++i) { std::cout << (i + 1) << ". [" << results[i].source << "] " @@ -24,31 +25,32 @@ int main() { std::cout << "=== Unified RAG System Demo ===\n"; std::cout << "Intelligent Query Routing Across Multiple RAG Backends\n"; printSeparator(); - + // 1. Initialize the Unified RAG Manager std::cout << "Initializing Unified RAG Manager...\n"; bolt::ai::UnifiedRAGManager rag_system; - + if (!rag_system.initialize()) { std::cerr << "โŒ Failed to initialize Unified RAG Manager\n"; std::cerr << "Note: Some backends may not be available\n"; } - + auto available_backends = rag_system.getAvailableBackends(); std::cout << "โœ… Initialized with " << available_backends.size() << " backends:\n"; for (const auto& backend : available_backends) { std::cout << " โ€ข " << backend << "\n"; } printSeparator(); - + // 2. Ingest sample data into different backends std::cout << "Ingesting sample data...\n\n"; - + // Narrative events bolt::ai::NarrativeEvent event1; event1.id = "event_001"; - event1.description = "The hero discovered an ancient sword in the castle's armory. " - "It glowed with a mysterious blue light."; + event1.description = + "The hero discovered an ancient sword in the castle's armory. " + "It glowed with a mysterious blue light."; event1.characters = {"Hero"}; event1.locations = {"Castle Armory"}; event1.timestamp = std::chrono::system_clock::now(); @@ -56,11 +58,12 @@ int main() { event1.importance = 9; rag_system.ingestNarrativeEvent(event1); std::cout << "โœ“ Ingested narrative event: " << event1.description.substr(0, 50) << "...\n"; - + bolt::ai::NarrativeEvent event2; event2.id = "event_002"; - event2.description = "A mysterious stranger warned the hero about the dangers " - "that lie ahead in the dark forest."; + event2.description = + "A mysterious stranger warned the hero about the dangers " + "that lie ahead in the dark forest."; event2.characters = {"Hero", "Stranger"}; event2.locations = {"Village Tavern"}; event2.timestamp = std::chrono::system_clock::now(); @@ -68,7 +71,7 @@ int main() { event2.importance = 7; rag_system.ingestNarrativeEvent(event2); std::cout << "โœ“ Ingested narrative event: " << event2.description.substr(0, 50) << "...\n"; - + // Temporal data bolt::ai::TimeSeriesPoint point1; point1.timestamp = std::chrono::system_clock::now() - std::chrono::hours(24); @@ -78,7 +81,7 @@ int main() { point1.category = "stock"; rag_system.ingestTemporalData(point1); std::cout << "โœ“ Ingested temporal data point (24h ago)\n"; - + bolt::ai::TimeSeriesPoint point2; point2.timestamp = std::chrono::system_clock::now(); point2.values["stock_price"] = 112.75; @@ -87,60 +90,52 @@ int main() { point2.category = "stock"; rag_system.ingestTemporalData(point2); std::cout << "โœ“ Ingested temporal data point (now)\n"; - + printSeparator(); - + // 3. Test query routing with different query types std::cout << "=== Query Routing Demonstration ===\n\n"; - - std::vector test_queries = { - "What happened in the castle?", - "Show me the stock price trend over time", - "Tell me about the hero's journey and the market performance", - "Find information about machine learning algorithms" - }; - + + std::vector test_queries = {"What happened in the castle?", "Show me the stock price trend over time", + "Tell me about the hero's journey and the market performance", + "Find information about machine learning algorithms"}; + for (const auto& query : test_queries) { std::cout << "Query: \"" << query << "\"\n"; - + // Analyze the query auto routing = rag_system.analyzeQuery(query); std::cout << " โ†’ Routing Decision:\n"; std::cout << " Backend: " << routing.backend_name << "\n"; - std::cout << " Confidence: " << std::fixed << std::setprecision(2) - << (routing.confidence * 100) << "%\n"; + std::cout << " Confidence: " << std::fixed << std::setprecision(2) << (routing.confidence * 100) << "%\n"; std::cout << " Reasoning: " << routing.reasoning << "\n\n"; - + // Execute the query auto results = rag_system.query(query, 3); printResults(results); - + printSeparator(); } - + // 4. Test forced routing (queryWithType) std::cout << "=== Forced Routing Test ===\n\n"; - + std::cout << "Query: \"Tell me everything\"\n"; std::cout << "Forcing backend: NarrativeRAG\n\n"; - - auto forced_results = rag_system.queryWithType( - "Tell me everything", - bolt::ai::RAGQueryType::NARRATIVE, - 5 - ); + + auto forced_results = rag_system.queryWithType("Tell me everything", bolt::ai::RAGQueryType::NARRATIVE, 5); printResults(forced_results); - + printSeparator(); - + // 5. Display statistics std::cout << "=== System Statistics ===\n\n"; - + auto stats = rag_system.getBackendStatistics(); for (const auto& stat : stats) { std::cout << stat.first << ": " << stat.second << "\n"; } - + printSeparator(); std::cout << "=== Demo Complete ===\n"; std::cout << "\nThis demonstrates:\n"; @@ -149,6 +144,6 @@ int main() { std::cout << " โ€ข Hybrid queries that combine multiple backends\n"; std::cout << " โ€ข Forced routing for explicit backend selection\n"; std::cout << " โ€ข Unified interface for all RAG operations\n\n"; - + return 0; } diff --git a/demo_widget_framework.cpp b/demo_widget_framework.cpp index 29418f7f..57da374b 100644 --- a/demo_widget_framework.cpp +++ b/demo_widget_framework.cpp @@ -175,7 +175,7 @@ class WidgetFrameworkDemo { // Icon button auto button2 = std::make_shared