### Quick Start Integration Examples Source: https://github.com/loonghao/auroraview/blob/main/README.md Common integration patterns for desktop apps and specific DCC software. ```python from auroraview import run_desktop # Launch standalone app - blocks until closed run_desktop(title="My App", url="http://localhost:3000") ``` ```python from auroraview import QtWebView import maya.OpenMayaUI as omui # Create WebView as Qt widget webview = QtWebView( parent=maya_main_window(), url="http://localhost:3000", width=800, height=600 ) webview.show() # Non-blocking, auto timer ``` ```python from auroraview import QtWebView import hou webview = QtWebView( parent=hou.qt.mainWindow(), url="http://localhost:3000" ) webview.show() # Non-blocking, auto timer ``` ```python from auroraview import AuroraView webview = AuroraView(url="http://localhost:3000") webview.show() # Get HWND for Unreal embedding hwnd = webview.get_hwnd() if hwnd: import unreal unreal.parent_external_window_to_slate(hwnd) ``` -------------------------------- ### Clone and Setup Repository Source: https://github.com/loonghao/auroraview/blob/main/docs/guide/contributing.md Commands to clone the repository, install dependencies, and verify the development environment. ```bash # Clone the repository git clone https://github.com/loonghao/auroraview.git cd auroraview # Install Rust toolchain rustup update stable # Install Python development dependencies pip install -e ".[dev]" # Install Node.js dependencies for SDK cd packages/auroraview-sdk npm install cd ../.. # Verify setup just check ``` -------------------------------- ### Python Backend API - Quick Start Source: https://github.com/loonghao/auroraview/blob/main/docs/guide/window-management.md Use the `create_webview()` function for a simple setup with built-in window API enabled. ```APIDOC ## Python Backend API - Quick Start ### Description This section provides a quick start guide for creating a WebView using the `create_webview()` function, which automatically enables the built-in window API. ### Method `create_webview(url, **kwargs)` ### Parameters - **url** (string) - The initial URL to load in the WebView. - ****kwargs** - Additional keyword arguments. `window_api` can be set to `True` (default) or `False`. ### Request Example ```python from auroraview import create_webview # One line to create a fully-featured WebView webview = create_webview(url="http://localhost:3000") webview.show() # JavaScript can directly call window.* APIs: # await auroraview.call('window.minimize') # await auroraview.call('window.setTitle', { title: 'New Title' }) ``` ### Response Returns a WebView instance. ``` -------------------------------- ### Initialize TabContainer and Manage Tabs Source: https://github.com/loonghao/auroraview/blob/main/docs/api/tab-container.md Quick start example demonstrating TabContainer initialization with callbacks, tab creation, navigation, and tab closing. ```python from auroraview.browser.tab_container import TabContainer # Create container with callbacks container = TabContainer( on_tabs_update=lambda tabs: print(f"Tabs: {len(tabs)}"), on_tab_change=lambda tab: print(f"Active: {tab.title}"), default_url="https://example.com" ) # Create tabs tab1 = container.create_tab("https://github.com", "GitHub") tab2 = container.create_tab("https://google.com", "Google") # Navigate container.navigate("https://new-url.com") # Close tab container.close_tab(tab1.id) ``` -------------------------------- ### Python CLI (auroraview) - Quick Start Source: https://github.com/loonghao/auroraview/blob/main/docs/guide/cli.md Instructions for installing and running the Python CLI for quick WebView previews. ```APIDOC ## Installation ```bash pip install auroraview # or uv pip install auroraview ``` ## Basic Usage ### Load a URL ```bash auroraview --url https://example.com ``` ### Load a local HTML file ```bash auroraview --html /path/to/file.html ``` ### Custom Window Configuration ```bash auroraview --url https://example.com --title "My App" --width 1024 --height 768 ``` ``` -------------------------------- ### HWND Integration Example Source: https://github.com/loonghao/auroraview/blob/main/docs/api/auroraview.md Example showing how to get the HWND and use it for external integration, such as with Unreal Engine. ```python from auroraview import AuroraView view = AuroraView(url="http://localhost:3000") view.show() # Get HWND hwnd = view.get_hwnd() # Use with Unreal Engine if hwnd: import unreal unreal.parent_external_window_to_slate(hwnd) ``` -------------------------------- ### Multi-Window Demo Setup Source: https://github.com/loonghao/auroraview/blob/main/docs/guide/examples.md Imports necessary modules for a multi-window demonstration. This example focuses on creating and managing multiple independent WebView windows with inter-window communication. ```python """Multi-Window Demo - Multiple WebView windows with communication. This example demonstrates how to create and manage multiple WebView windows in AuroraView, including inter-window communication patterns. Features demonstrated: - Creating multiple independent windows - Parent-child window relationships - Inter-window messaging via Python - Window lifecycle management - Synchronized state across windows """ from __future__ import annotations import threading from typing import Dict, List, Optional from auroraview import WebView ``` -------------------------------- ### Simulate Dependency Installation Events Source: https://github.com/loonghao/auroraview/blob/main/docs/zh/guide/examples.md Mocks a WebView interface to emit and track installation progress events, including start, progress, error, and completion states. ```python def simulate_progress_events(): """Simulate the progress events that would be emitted during installation.""" # Mock WebView for testing class MockWebView: def __init__(self): self.events = [] def emit(self, event_name, data): timestamp = time.strftime("%H:%M:%S") print(f"[{timestamp}] EVENT: {event_name}") print(f" Data: {data}") print("-" * 50) self.events.append((event_name, data)) webview = MockWebView() # Simulate installation start webview.emit( "dependency:install_start", { "total": 2, "packages": ["openai>=1.0.0", "requests>=2.0.0"], "message": "Starting installation of 2 packages...", }, ) time.sleep(0.5) # Simulate first package installation webview.emit( "dependency:install_progress", { "type": "start", "package": "openai", "index": 0, "total": 2, "message": "[09:21:40] Installing openai...", }, ) time.sleep(0.3) # Simulate download progress for progress in [10, 25, 50, 75, 90, 100]: webview.emit( "dependency:install_progress", { "type": "output", "package": "openai", "line": f"[09:21:41] Downloading openai... {progress}%", }, ) time.sleep(0.2) # Simulate completion of first package webview.emit( "dependency:install_progress", { "type": "complete", "package": "openai", "success": True, "message": "[09:21:43] Successfully installed openai", }, ) time.sleep(0.5) # Simulate second package with error webview.emit( "dependency:install_progress", { "type": "start", "package": "requests", "index": 1, "total": 2, "message": "[09:21:44] Installing requests...", }, ) time.sleep(0.3) # Simulate error webview.emit( "dependency:install_progress", { "type": "error", "package": "requests", "success": False, "message": "[09:21:45] Failed to install requests (exit 1)", "output": "ERROR: Could not find a version that satisfies the requirement requests>=999.0.0\nERROR: No matching distribution found for requests>=999.0.0", }, ) time.sleep(0.5) # Simulate installation completion with mixed results webview.emit( "dependency:install_done", { "success": False, "installed": ["openai>=1.0.0"], "failed": ["requests>=2.0.0"], "output": "Installation completed with errors. See details above.", "cancelled": False, }, ) print(f"\nSimulation completed. Total events emitted: {len(webview.events)}") return webview.events ``` -------------------------------- ### Run Examples via CLI Source: https://github.com/loonghao/auroraview/blob/main/docs/zh/guide/examples.md Commands for executing example scripts and generating documentation screenshots. ```bash # 运行任意示例 python examples/.py ``` ```bash # 生成所有示例截图 vx just example-screenshots # 生成特定示例截图 vx just example-screenshot window_effects_demo # 列出可用示例 vx just example-list ``` -------------------------------- ### Qt Application Setup and Custom Menu Window Source: https://github.com/loonghao/auroraview/blob/main/docs/guide/examples.md Initializes the Qt application and displays a custom window with a context menu. Ensure you have PyQt or PySide installed. ```python from PyQt5.QtWidgets import QApplication, QMainWindow, QMenu, QAction from PyQt5.QtCore import Qt import sys class CustomMenuWindow(QMainWindow): def __init__(self): super().__init__() self.setWindowTitle("Qt Custom Context Menu Demo") self.setGeometry(100, 100, 600, 400) def contextMenuEvent(self, event): context_menu = QMenu(self) # Add actions to the context menu action1 = QAction("Action 1", self) action1.triggered.connect(lambda: self.on_action_triggered("Action 1")) context_menu.addAction(action1) action2 = QAction("Action 2", self) action2.triggered.connect(lambda: self.on_action_triggered("Action 2")) context_menu.addAction(action2) # Add a separator context_menu.addSeparator() # Add a sub-menu sub_menu = context_menu.addMenu("Sub Menu") sub_action = QAction("Sub Action", self) sub_action.triggered.connect(lambda: self.on_action_triggered("Sub Action")) sub_menu.addAction(sub_action) # Show the context menu at the cursor position context_menu.exec_(event.globalPos()) def on_action_triggered(self, action_text): print(f"{action_text} triggered") def main(): app = QApplication.instance() or QApplication(sys.argv) window = CustomMenuWindow() window.show() print("Qt Custom Context Menu Demo") print("Right-click in the window to see the custom menu!") sys.exit(app.exec_()) if __name__ == "__main__": main() ``` -------------------------------- ### Run Qt Style Tool Example Source: https://github.com/loonghao/auroraview/blob/main/docs/guide/examples.md Command to execute the provided Qt style tool example script. ```bash python examples/qt_style_tool.py ``` -------------------------------- ### List Available Examples Source: https://github.com/loonghao/auroraview/blob/main/docs/guide/examples.md Use this command to list all available examples that can be used for screenshot generation. ```bash vx just example-list ``` -------------------------------- ### Simulate Installation with Cancel Functionality Source: https://github.com/loonghao/auroraview/blob/main/docs/guide/examples.md This Python script simulates an installation process that can be cancelled. It uses mock objects for webview and installer to demonstrate event emission and cancellation logic. Ensure the threading and Event modules are imported. ```python #!/usr/bin/env python3 """ Test script to verify the cancel button fix. This simulates the installation and cancellation process. """ import time import threading from threading import Event def simulate_installation_with_cancel(): """Simulate installation process with cancel capability.""" class MockWebView: def __init__(self): self.events = [] def emit(self, event_name, data): timestamp = time.strftime("%H:%M:%S") print(f"[{timestamp}] EVENT: {event_name} -> {data}") self.events.append((event_name, data)) class MockInstaller: def __init__(self, webview): self.webview = webview self._install_cancel_event = None def install_dependencies(self): """Start installation process.""" self._install_cancel_event = Event() # Start installation self.webview.emit( "dependency:install_start", { "total": 3, "packages": ["openai", "requests", "pyside6"], "message": "Starting installation of 3 packages...", }, ) def install_worker(): packages = ["openai", "requests", "pyside6"] for i, package in enumerate(packages): if self._install_cancel_event.is_set(): print(f"Installation cancelled during {package}") self.webview.emit( "dependency:install_done", { "success": False, "cancelled": True, "installed": packages[:i], "failed": packages[i:], }, ) return # Start package installation self.webview.emit( "dependency:install_progress", {"type": "start", "package": package, "total": len(packages), "index": i}, ) # Simulate installation progress for progress in [25, 50, 75, 100]: if self._install_cancel_event.is_set(): print(f"Installation cancelled during {package} at {progress}%") self.webview.emit( "dependency:install_done", { "success": False, "cancelled": True, "installed": packages[:i], "failed": packages[i:], }, ) return self.webview.emit( "dependency:install_progress", { "type": "output", "line": f"Downloading {package}... {progress}%", "package": package, }, ) time.sleep(0.5) # Simulate download time # Complete package self.webview.emit( "dependency:install_progress", { "type": "complete", "package": package, "total": len(packages), "index": i, }, ) # All packages completed self.webview.emit( "dependency:install_done", {"success": True, "installed": packages, "failed": [], "cancelled": False}, ) thread = threading.Thread(target=install_worker, daemon=True) thread.start() return {"started": True} def cancel_installation(self): """Cancel ongoing installation.""" if self._install_cancel_event is None: return {"success": False, "error": "No installation in progress"} try: # Send cancel progress events self.webview.emit( "dependency:cancel_progress", {"type": "cancelling", "message": "Requesting cancellation..."}, ) # Set cancel event self._install_cancel_event.set() # Send cancel confirmation self.webview.emit( "dependency:cancel_progress", ``` -------------------------------- ### Simulate installation with cancellation Source: https://github.com/loonghao/auroraview/blob/main/docs/zh/guide/examples.md Uses threading and Event objects to mimic a multi-package installation process that can be interrupted mid-execution. ```python #!/usr/bin/env python3 """ Test script to verify the cancel button fix. This simulates the installation and cancellation process. """ import time import threading from threading import Event def simulate_installation_with_cancel(): """Simulate installation process with cancel capability.""" class MockWebView: def __init__(self): self.events = [] def emit(self, event_name, data): timestamp = time.strftime("%H:%M:%S") print(f"[{timestamp}] EVENT: {event_name} -> {data}") self.events.append((event_name, data)) class MockInstaller: def __init__(self, webview): self.webview = webview self._install_cancel_event = None def install_dependencies(self): """Start installation process.""" self._install_cancel_event = Event() # Start installation self.webview.emit( "dependency:install_start", { "total": 3, "packages": ["openai", "requests", "pyside6"], "message": "Starting installation of 3 packages...", }, ) def install_worker(): packages = ["openai", "requests", "pyside6"] for i, package in enumerate(packages): if self._install_cancel_event.is_set(): print(f"Installation cancelled during {package}") self.webview.emit( "dependency:install_done", { "success": False, "cancelled": True, "installed": packages[:i], "failed": packages[i:], }, ) return # Start package installation self.webview.emit( "dependency:install_progress", {"type": "start", "package": package, "total": len(packages), "index": i}, ) # Simulate installation progress for progress in [25, 50, 75, 100]: if self._install_cancel_event.is_set(): print(f"Installation cancelled during {package} at {progress}%") self.webview.emit( "dependency:install_done", { "success": False, "cancelled": True, "installed": packages[:i], "failed": packages[i:], }, ) return self.webview.emit( "dependency:install_progress", { "type": "output", "line": f"Downloading {package}... {progress}%", "package": package, }, ) time.sleep(0.5) # Simulate download time # Complete package self.webview.emit( "dependency:install_progress", { "type": "complete", "package": package, "total": len(packages), "index": i, }, ) # All packages completed self.webview.emit( "dependency:install_done", {"success": True, "installed": packages, "failed": [], "cancelled": False}, ) thread = threading.Thread(target=install_worker, daemon=True) thread.start() return {"started": True} def cancel_installation(self): """Cancel ongoing installation.""" if self._install_cancel_event is None: return {"success": False, "error": "No installation in progress"} try: # Send cancel progress events self.webview.emit( "dependency:cancel_progress", {"type": "cancelling", "message": "Requesting cancellation..."}, ) # Set cancel event self._install_cancel_event.set() # Send cancel confirmation self.webview.emit( "dependency:cancel_progress", ``` -------------------------------- ### Complete Application Example (Python + React) Source: https://github.com/loonghao/auroraview/blob/main/docs/guide/window-management.md A full example showing how to set up a main window using Python and interact with it from a React frontend, including setting up the window API. ```APIDOC ## Complete Application Example (Python + React) ### Description This example illustrates a complete application structure using AuroraView, with a Python backend for the main window and a React frontend for the UI. It shows how to create the main WebView, set up the window API, and how the frontend can interact with window controls. ### Python Backend (`app.py`) #### Description Sets up the main application window using `WebView.create` and configures the window API. #### Method `WebView.create(title, url, width, height)` `setup_window_api(webview)` #### Request Example ```python from auroraview import WebView, setup_window_api def main(): # Main window main_window = WebView.create( "My App", url="http://localhost:3000", width=1200, height=800, ) setup_window_api(main_window) # Settings will be created from JavaScript # using Window.create() main_window.show() if __name__ == "__main__": main() ``` ### React Frontend (`settings-window.tsx` - conceptual) #### Description While `settings-window.tsx` is shown in a previous snippet for its specific functionality, in a complete app, it would be loaded by the main window. The main window's JavaScript context would typically handle creating and managing such secondary windows using `Window.create()`. #### Request Example (Conceptual Interaction) ```javascript // In the main window's JavaScript context (e.g., loaded via main_window.url) import { Window } from '@auroraview/sdk'; async function openSettings() { await Window.create('Settings', { url: 'http://localhost:3000/settings', width: 600, height: 400, // ... other options }); } ``` ### Response - The Python script launches the main WebView window. - The React component (if loaded) provides the UI and interacts with the window API. ``` -------------------------------- ### Playwright Mode Quick Start Source: https://github.com/loonghao/auroraview/blob/main/docs/guide/headless-testing.md Use Playwright mode for fast, reliable, and cross-platform UI testing in headless environments. No special setup is required beyond installing Playwright. ```python from auroraview.testing.headless_webview import HeadlessWebView with HeadlessWebView.playwright() as webview: webview.goto("https://example.com") webview.click("#button") assert webview.text("#result") == "Success" ``` -------------------------------- ### Quick Start Window Management Source: https://github.com/loonghao/auroraview/blob/main/docs/api/window-manager.md Demonstrates basic registration, retrieval, and event broadcasting using the global manager. ```python from auroraview.core.window_manager import get_window_manager, broadcast_event # Get the global manager wm = get_window_manager() # Register a window uid = wm.register(webview) # Get all windows windows = wm.get_all() # Broadcast event to all windows broadcast_event("app:theme_changed", {"theme": "dark"}) ``` -------------------------------- ### Setup Development Environment Source: https://github.com/loonghao/auroraview/blob/main/CONTRIBUTING.md Commands to clone the repository and initialize the development environment using vx. ```bash git clone https://github.com/YOUR_USERNAME/dcc_webview.git cd dcc_webview # Install tools and hooks from vx.toml vx setup # Install Python dependencies vx just install ``` -------------------------------- ### Run DCC Integration Example Source: https://github.com/loonghao/auroraview/blob/main/docs/guide/examples.md Executes a Python script to demonstrate integrating AuroraView with DCC applications. This example requires Python and AuroraView to be installed. ```bash python examples/dcc_integration_example.py ``` -------------------------------- ### Initialize WebView with Configuration Source: https://github.com/loonghao/auroraview/blob/main/docs/guide/design-philosophy.md Demonstrates minimal and fully customized WebView initialization. ```python # Minimal configuration - works out of the box webview = WebView.create("My App", url="http://localhost:3000") webview.show() # Full customization when needed webview = WebView.create( title="My App", url="http://localhost:3000", width=1024, height=768, resizable=True, frame=True, debug=True, context_menu=False, asset_root="./assets", ) ``` -------------------------------- ### Simulate Dependency Installation Progress Events Source: https://github.com/loonghao/auroraview/blob/main/docs/guide/examples.md Simulates the progress events emitted during a dependency installation process. This includes start, progress, output, completion, and error events for multiple packages. Use this to test event handling logic. ```python import sys import time from pathlib import Path # Add project root to path PROJECT_ROOT = Path(__file__).resolve().parents[1] if str(PROJECT_ROOT) not in sys.path: sys.path.insert(0, str(PROJECT_ROOT)) def simulate_progress_events(): """Simulate the progress events that would be emitted during installation.""" # Mock WebView for testing class MockWebView: def __init__(self): self.events = [] def emit(self, event_name, data): timestamp = time.strftime("%H:%M:%S") print(f"[{timestamp}] EVENT: {event_name}") print(f" Data: {data}") print("-" * 50) self.events.append((event_name, data)) webview = MockWebView() # Simulate installation start webview.emit( "dependency:install_start", { "total": 2, "packages": ["openai>=1.0.0", "requests>=2.0.0"], "message": "Starting installation of 2 packages...", }, ) time.sleep(0.5) # Simulate first package installation webview.emit( "dependency:install_progress", { "type": "start", "package": "openai", "index": 0, "total": 2, "message": "[09:21:40] Installing openai...", }, ) time.sleep(0.3) # Simulate download progress for progress in [10, 25, 50, 75, 90, 100]: webview.emit( "dependency:install_progress", { "type": "output", "package": "openai", "line": f"[09:21:41] Downloading openai... {progress}%", }, ) time.sleep(0.2) # Simulate completion of first package webview.emit( "dependency:install_progress", { "type": "complete", "package": "openai", "success": True, "message": "[09:21:43] Successfully installed openai", }, ) time.sleep(0.5) # Simulate second package with error webview.emit( "dependency:install_progress", { "type": "start", "package": "requests", "index": 1, "total": 2, "message": "[09:21:44] Installing requests...", }, ) time.sleep(0.3) # Simulate error webview.emit( "dependency:install_progress", { "type": "error", "package": "requests", "success": False, "message": "[09:21:45] Failed to install requests (exit 1)", "output": "ERROR: Could not find a version that satisfies the requirement requests>=999.0.0\nERROR: No matching distribution found for requests>=999.0.0", }, ) time.sleep(0.5) # Simulate installation completion with mixed results webview.emit( "dependency:install_done", { "success": False, "installed": ["openai>=1.0.0"], "failed": ["requests>=2.0.0"], "output": "Installation completed with errors. See details above.", "cancelled": False, }, ) print(f"\nSimulation completed. Total events emitted: {len(webview.events)}") return webview.events ``` -------------------------------- ### Initialize WebView for different environments Source: https://github.com/loonghao/auroraview/blob/main/docs/guide/unified-api.md Demonstrates creating a WebView instance for standalone, Qt, and HWND integration scenarios. ```python from auroraview import create_webview # 1. Standalone window (no parent) webview = create_webview(url="http://localhost:3000") webview.show() # 2. Qt integration (pass QWidget parent) webview = create_webview(parent=maya_main_window(), url="http://localhost:3000") webview.show() # 3. HWND integration (pass int HWND) webview = create_webview(parent=unreal_hwnd, url="http://localhost:3000") webview.show() ``` -------------------------------- ### Test Dependency Installation Script Source: https://github.com/loonghao/auroraview/blob/main/docs/zh/guide/examples.md This script verifies that required Python dependencies (requests and beautifulsoup4) are installed and functional. It checks their versions and performs a simple HTTP GET request to ensure network connectivity and basic library operation. ```python #!/usr/bin/env python3 """ Test Dependency Installation This script tests the automatic dependency installation feature. Requirements: - requests>=2.25.0 - beautifulsoup4>=4.9.0 Usage: python test_dependency_install.py """ import sys from pathlib import Path # Add the project root to the path project_root = Path(__file__).parent.parent sys.path.insert(0, str(project_root / "python")) try: import requests import bs4 print("✅ All dependencies are installed!") print(f"requests version: {requests.__version__}") print(f"beautifulsoup4 version: {bs4.__version__}") # Test a simple HTTP request response = requests.get("https://httpbin.org/json", timeout=5) print(f"✅ HTTP test successful: {response.status_code}") except ImportError as e: print(f"❌ Missing dependency: {e}") sys.exit(1) except Exception as e: print(f"❌ Error: {e}") sys.exit(1) print("🎉 Test completed successfully!") ``` -------------------------------- ### Initialize Application Source: https://github.com/loonghao/auroraview/blob/main/docs/guide/examples.md Handles the ready event and application startup sequence. ```python # Initialize grid after load @view.on("ready") def on_ready(): init_grid() print("Starting DOM Batch Operations Demo...") print("Features: Batch operations, Form handling, DOM traversal") view.show() if __name__ == "__main__": main() ``` -------------------------------- ### Traverse Parent Element Source: https://github.com/loonghao/auroraview/blob/main/docs/zh/guide/examples.md Initiates a traversal up the DOM tree from a specific element to its parent. This function is a starting point for parent traversal examples. ```python @view.bind_call("api.traverse_parent") def traverse_parent() -> dict: ``` -------------------------------- ### Initialize Qt Application and Load OpenAI (Python) Source: https://github.com/loonghao/auroraview/blob/main/docs/zh/guide/examples.md Sets up the PySide6 application, creates the main window, and attempts to import the OpenAI library. Handles the case where PySide6 is not installed. ```python if not HAS_QT: print("\n" + "=" * 60) print("ERROR: PySide6 is required for this demo") print("Please install it with: pip install PySide6>=6.5.0") print("=" * 60) sys.exit(1) print("\n" + "=" * 60) print("AI Chat Assistant Demo") print("=" * 60) print("\nThis demo shows Qt + WebView hybrid application with:") print(" - Left panel: Qt controls for API configuration") print(" - Right panel: WebView chat interface (DeepSeek)") print("\nTo use the chat:") print(" 1. Enter your DeepSeek API key in the left panel") print(" 2. Click 'Test Connection' to verify") print(" 3. Type messages in the chat panel") print("\nEnvironment variable: Set DEEPSEEK_API_KEY to pre-fill the key") print("=" * 60 + "\n") app = QApplication(sys.argv) app.setStyle("Fusion") window = AIChatWindow() # Try importing OpenAI after UI created; if missing, user can install via UI. try: global OpenAI OpenAI = importlib.import_module("openai").OpenAI except Exception: OpenAI = None window.show() sys.exit(app.exec()) ``` -------------------------------- ### Manage Documentation Source: https://github.com/loonghao/auroraview/blob/main/docs/guide/contributing.md Commands to start the development server or build the documentation site. ```bash # Start documentation dev server cd docs npm run dev # Build documentation npm run build ``` -------------------------------- ### Run Sample Application Source: https://github.com/loonghao/auroraview/blob/main/packages/auroraview-mcp/README.md Starts a specified sample application and lists the currently running processes. ```text User: Run the hello_world sample AI: [Call run_sample(name="hello_world")] → Sample started, PID: 12345 [Call list_processes] → Shows running processes Sample successfully started. ``` -------------------------------- ### Interact with 3ds Max API from JavaScript Source: https://github.com/loonghao/auroraview/blob/main/docs/dcc/3dsmax.md Example of how to call the bound Python API methods from JavaScript running in the QtWebView. It demonstrates getting selection, creating a box, and setting its position. ```javascript // JavaScript side const sel = await auroraview.api.get_selection(); console.log('Selected:', sel.selection); await auroraview.api.create_box({ name: 'myBox', size: 20.0 }); await auroraview.api.set_position({ name: 'myBox', x: 10, y: 0, z: 5 }); ``` -------------------------------- ### Auto-Detection Mode Quick Start Source: https://github.com/loonghao/auroraview/blob/main/docs/guide/headless-testing.md Leverage auto-detection mode to automatically select the most suitable headless WebView testing strategy for the current environment. This mode simplifies setup by abstracting the underlying mechanism. ```python from auroraview.testing.headless_webview import HeadlessWebView # Automatically selects the best mode for current environment with HeadlessWebView.auto() as webview: webview.goto("https://example.com") ``` -------------------------------- ### Initialize WebView and CommandRegistry Source: https://github.com/loonghao/auroraview/blob/main/docs/zh/guide/examples.md Setup for the WebView instance and the CommandRegistry backend. ```python view = WebView(title="Command Registry Demo", html=html_content, width=950, height=850) # Create a CommandRegistry instance commands = CommandRegistry() # In-memory data store for demo ``` -------------------------------- ### Initialize QtWebView in 3ds Max Source: https://github.com/loonghao/auroraview/blob/main/docs/dcc/3dsmax.md Quick start example to initialize a QtWebView within the 3ds Max environment. It retrieves the main window handle and creates a webview instance pointing to a local server. ```python from auroraview import QtWebView from qtpy import QtWidgets from pymxs import runtime as rt def max_main_window(): """Get 3ds Max main window as QWidget.""" hwnd = rt.windows.getMAXHWND() return QtWidgets.QWidget.find(hwnd) # AuroraView auto-detects 3ds Max and enables thread safety webview = QtWebView( parent=max_main_window(), url="http://localhost:3000", width=800, height=600 ) webview.show() ``` -------------------------------- ### Build AuroraView from Source Source: https://github.com/loonghao/auroraview/blob/main/README_zh.md Steps to clone the repository, set up required tools using `vx setup`, install Python dependencies, and perform a unified build. Includes a command for a release-style local rebuild. ```bash # 克隆仓库 git clone https://github.com/loonghao/auroraview.git cd auroraview # 安装 vx.toml 中声明的工具 vx setup # 安装 Python 依赖并执行统一构建入口 vx just install vx just build # 如需 release 风格的本地重建(同时刷新前端资源) vx just rebuild-pylib ``` -------------------------------- ### Initialize Main Application Source: https://github.com/loonghao/auroraview/blob/main/docs/guide/examples.md Entry point for the signals advanced demo, initializing the WebView. ```python def main(): """Run the signals advanced demo.""" from auroraview import WebView view = WebView( html=HTML, title="Signals Advanced Demo", width=1150, height=850, ) ``` -------------------------------- ### Custom Context Menu Demo Setup Source: https://github.com/loonghao/auroraview/blob/main/docs/zh/guide/examples.md This Python code sets up the necessary import for the Custom Context Menu Demo. It's a placeholder for a more complex example that disables the native context menu and uses JavaScript for a custom one. ```python """Custom Context Menu Demo. This example demonstrates how to disable the native browser context menu and implement a custom right-click menu using JavaScript. Note: This example uses the low-level WebView API for demonstration. For most use cases, prefer QtWebView, AuroraView, or run_desktop. Signed-off-by: Hal Long """ from auroraview import WebView ``` -------------------------------- ### Initialize and Show WebView Source: https://github.com/loonghao/auroraview/blob/main/docs/guide/examples.md Sets up the HTML content for the WebView and initializes the WebView component with specified dimensions. The WebView is then displayed. ```python html_content = """ log('Timer close event received'); document.getElementById('statusIndicator').className = 'status-indicator status-stopped'; document.getElementById('statusText').textContent = 'Stopped'; }); // Initial display update updateTimerDisplay(); setInterval(updateTimerDisplay, 1000); " view = WebView(title="Event Timer Demo", html=html_content, width=900, height=800) # Timer state timer_state = {"tick_count": 0, "interval_ms": 16, "start_time": None} # Note: In standalone mode, WebView.show() handles its own event loop. # This demo shows how EventTimer would be used in embedded/DCC mode. # For demonstration, we'll simulate the timer behavior using periodic emit. @view.bind_call("api.get_timer_status") def get_timer_status() -> dict: """Get current timer status.""" return { "is_running": True, # In demo, always running "interval_ms": timer_state["interval_ms"], "tick_count": timer_state["tick_count"], "uptime_seconds": ( (datetime.now() - timer_state["start_time"]).total_seconds() if timer_state["start_time"] else 0 ), } @view.bind_call("api.set_interval") def set_interval(interval_ms: int = 16) -> dict: """Set timer interval (demo only - actual change requires timer restart).""" timer_state["interval_ms"] = interval_ms return {"ok": True, "new_interval": interval_ms} @view.bind_call("api.trigger_tick") def trigger_tick() -> dict: """Manually trigger a tick callback.""" timer_state["tick_count"] += 1 view.emit("timer_tick", {"tick_count": timer_state["tick_count"], "manual": True}) return {"ok": True, "tick_count": timer_state["tick_count"]} # Demonstrate EventTimer API (for documentation purposes) print("=" * 60) print("EventTimer Demo - Timer-Based Event Processing") print("=" * 60) print() print("EventTimer is designed for embedded WebView scenarios where") print("the WebView is integrated into a host application's event loop.") print() print("Example usage in DCC environments:") print() print(" from auroraview import WebView") print(" from auroraview.utils.event_timer import EventTimer") print() print(" # Create WebView in embedded mode") print(" webview = WebView(parent=parent_hwnd, mode='owner')") print() print(" # Create timer with 16ms interval (60 FPS)") print(" timer = EventTimer(webview, interval_ms=16)") print() print(" # Register callbacks") print(" @timer.on_tick") print(" def handle_tick():") print(" # Called every 16ms") print(" pass") print() print(" @timer.on_close") print(" def handle_close():") print(" timer.stop()") print() print(" # Start the timer") print(" timer.start()") print() print("=" * 60) timer_state["start_time"] = datetime.now() print("\nStarting Event Timer Demo...") view.show() if __name__ == "__main__": main() ``` -------------------------------- ### Complete Asset Browser with AI Assistant Source: https://github.com/loonghao/auroraview/blob/main/docs/guide/qt-integration.md This example demonstrates a full Qt application for an Asset Browser, integrating an AI Assistant via QtWebView. It includes UI setup, signal handling for asset selection and activation, and exposes a Python API to the JavaScript environment. ```python from auroraview import QtWebView from qtpy.QtWidgets import ( QMainWindow, QDockWidget, QTreeWidget, QTreeWidgetItem, QVBoxLayout, QWidget, QSplitter ) from qtpy.QtCore import Qt class AssetBrowser(QMainWindow): """Legacy asset browser tool with AI assistant sidebar.""" def __init__(self): super().__init__() self.setWindowTitle("Asset Browser") self.resize(1200, 800) self._setup_ui() self._setup_ai_panel() self._connect_signals() def _setup_ui(self): """Set up the main asset browser UI.""" splitter = QSplitter(Qt.Horizontal) # Asset tree (existing functionality) self.asset_tree = QTreeWidget() self.asset_tree.setHeaderLabels(["Name", "Type", "Size"]) self._populate_assets() splitter.addWidget(self.asset_tree) # Preview panel (existing functionality) self.preview = QWidget() splitter.addWidget(self.preview) self.setCentralWidget(splitter) def _setup_ai_panel(self): """Add AI assistant as a dock widget.""" dock = QDockWidget("AI Assistant", self) self.ai_view = QtWebView( parent=dock, url="http://localhost:3000/asset-ai", ) # Expose asset browser API self.ai_view.bind_api(AssetBrowserAPI(self)) dock.setWidget(self.ai_view) self.addDockWidget(Qt.RightDockWidgetArea, dock) # WebView initializes automatically when parent is shown! def _connect_signals(self): """Connect Qt signals to WebView events.""" self.asset_tree.itemSelectionChanged.connect(self._on_selection_changed) self.asset_tree.itemDoubleClicked.connect(self._on_item_activated) def _on_selection_changed(self): """Forward selection to AI assistant.""" items = self.asset_tree.selectedItems() self.ai_view.emit("asset:selection", { "assets": [self._item_to_dict(item) for item in items], }) def _on_item_activated(self, item): """Forward activation to AI assistant.""" self.ai_view.emit("asset:activated", self._item_to_dict(item)) def _item_to_dict(self, item: QTreeWidgetItem) -> dict: return { "name": item.text(0), "type": item.text(1), "size": item.text(2), } def _populate_assets(self): # ... populate tree ... pass class AssetBrowserAPI: """API for AI assistant to interact with asset browser.""" def __init__(self, browser: AssetBrowser): self.browser = browser def get_selected_assets(self) -> list: items = self.browser.asset_tree.selectedItems() return [self.browser._item_to_dict(item) for item in items] def search_assets(self, query: str, asset_type: str = None) -> list: # Implement search logic return [] def open_asset(self, name: str) -> dict: # Implement open logic return {"ok": True} def get_asset_metadata(self, name: str) -> dict: # Return asset metadata return {} ``` -------------------------------- ### Run Gallery from Source Source: https://github.com/loonghao/auroraview/blob/main/docs/guide/gallery.md Commands to clone the repository, install dependencies, build the frontend, and launch the application. ```bash # Clone the repository git clone https://github.com/loonghao/auroraview.git cd auroraview # Install dependencies pip install -e . cd gallery npm install # Build frontend npm run build # Run Gallery cd .. python gallery/main.py ``` -------------------------------- ### Generate Specific Example Screenshot Source: https://github.com/loonghao/auroraview/blob/main/docs/guide/examples.md Use this command to generate a screenshot for a specific example. Replace 'window_effects_demo' with the desired example name. ```bash vx just example-screenshot window_effects_demo ``` -------------------------------- ### Install AuroraView CLI on Linux/macOS Source: https://github.com/loonghao/auroraview/blob/main/README_zh.md Installs the `auroraview-cli` using a curl command and bash script. Ensure you have bash and curl installed. ```bash curl -fsSL https://raw.githubusercontent.com/loonghao/auroraview/main/scripts/install.sh | bash ``` -------------------------------- ### Main Application Entry Point Source: https://github.com/loonghao/auroraview/blob/main/docs/guide/examples.md Sets up the main window, broadcasts the initial window list, and displays the main window. This is the starting point for the multi-window application. ```python def main(): """Run the multi-window demo.""" main_window = create_main_window() broadcast_window_list() main_window.show() # Use show() instead of run() ``` -------------------------------- ### Install AuroraView with MCP Server Source: https://github.com/loonghao/auroraview/blob/main/docs/guide/ai-agent-cdp.md Install the AuroraView package along with its MCP server. Alternatively, install from source by navigating to the `packages/auroraview-mcp` directory. ```bash # Install AuroraView with MCP server pip install auroraview auroraview-mcp # Or install from source cd packages/auroraview-mcp pip install -e . ``` -------------------------------- ### Implement Plugin Entry Point Source: https://github.com/loonghao/auroraview/blob/main/docs/dcc/substance-painter.md The __init__.py file handles plugin lifecycle management. ```python from . import plugin def start_plugin(): plugin.start() def close_plugin(): plugin.close() ``` -------------------------------- ### Initialize Desktop App Demo Source: https://github.com/loonghao/auroraview/blob/main/docs/guide/examples.md Setup and execution of a desktop webview instance using the AuroraView API. ```python def main(): """Run the desktop app demo.""" # Create webview webview = auroraview.WebView( title="AuroraView Desktop App Demo", width=1100, height=900, html=create_demo_html(), debug=True, ) print("Desktop App Demo") print("================") print("This demo showcases desktop application capabilities:") print("- File dialogs (open, save, folder selection)") print("- File system operations (read, write, list)") print("- Shell commands and script execution") print("- Environment variables") print() print("Starting webview...") webview.show() if __name__ == "__main__": main() ``` -------------------------------- ### Install AuroraView Source: https://github.com/loonghao/auroraview/blob/main/docs/dcc/index.md Basic installation using pip. ```bash pip install auroraview ``` -------------------------------- ### Initialize and Run Browser Source: https://github.com/loonghao/auroraview/blob/main/docs/rfcs/0004-multi-window-management.md Demonstrates creating a standalone browser instance and launching it in a blocking mode. ```python >>> browser = Browser(title="My Browser") >>> browser.new_tab("https://google.com") >>> browser.new_tab("https://github.com") >>> browser.run() # Blocking ``` -------------------------------- ### Install AuroraView on Linux Source: https://github.com/loonghao/auroraview/blob/main/README.md Install AuroraView on Linux by first installing system dependencies and then downloading a wheel from GitHub Releases. Alternatively, build from source. ```bash # Install system dependencies first sudo apt install libwebkit2gtk-4.1-dev libgtk-3-dev # Debian/Ubuntu # sudo dnf install gtk3-devel webkit2gtk3-devel # Fedora/CentOS # sudo pacman -S webkit2gtk # Arch Linux # Download and install wheel from GitHub Releases pip install https://github.com/loonghao/auroraview/releases/latest/download/auroraview-{version}-cp37-abi3-linux_x86_64.whl ``` ```bash pip install auroraview --no-binary :all: ```