# Pyloid Documentation ## Overview Pyloid is a Python framework for building desktop applications with web technologies (HTML, CSS, JavaScript). It provides an Electron-like experience for Python developers. Website: https://www.pyloid.com GitHub: https://github.com/pyloid/pyloid ================================================================================ # Quick Start ================================================================================ ## File: index.mdx --- title: Quick Start description: Quick Start for Pyloid --- ## Pyloid CLI Before using the CLI, you need to install 3 tools: [Prequisites](/docs/prequisites) ```bash tab="npm" npm create pyloid-app@latest ``` ```bash tab="pnpm" pnpm create pyloid-app@latest ``` ```bash tab="yarn" yarn create pyloid-app@latest ``` ```bash tab="bun" bun create pyloid-app@latest ``` ## CLI Project Setup Process ### 1. Specify Project Path Enter the path where you want to create your project. The default is `pyloid-app`. if you `./` for the path, the project will be created in the current directory. ``` Enter the path to create the project (default: pyloid-app): ``` ### 2. Select a Package Manager - npm - pnpm - yarn - bun ### 3. Select a Framework - React - Vue - Svelte - Next.js - SvelteKit ### 4. Select a Language - JavaScript - TypeScript ### 5. Select a Backend - pyloidrpc - fastapi -------------------------------------------------------------------------------- ## File: llm-for-ai.mdx --- title: LLMs for AI description: Documentation files optimized for Large Language Models --- ## Available Documentation Files ### Full Documentation - **llms-full.txt** - Complete documentation with all content - Includes code examples and detailed API descriptions - Best for comprehensive understanding ### Quick Reference - **llms.txt** - Lightweight link directory - Quick navigation to specific topics - Best for finding specific documentation pages ## Usage These files are designed to be consumed by: - AI assistants (Claude, GPT, etc.) - Documentation search tools - LLM-powered development tools -------------------------------------------------------------------------------- ## File: prequisites.mdx --- title: Prequisites description: You need to install 3 tools --- ## Common Prerequisites ### 1. Python - **Required Version**: 3.9 ~ 3.13 (`>=3.9,<3.14`) - If not installed or needs an update, download and install from the official Python website. [Python installation](https://www.python.org/downloads/) ### 2. uv - **Required**: uv is a Python package installer and environment manager - Install with the following command: `pip install uv` - Verify installation: Run `uv --version` in the terminal [uv installation](https://docs.astral.sh/uv/getting-started/installation/) ### 3. Node.js - **Required Version**: 18 or higher - Check installation: Run `node --version` in the terminal (ensure it outputs 18.x or higher) [Node.js installation](https://nodejs.org/en/download) -------------------------------------------------------------------------------- # Core Concepts ================================================================================ ## File: core-concepts/thread-safety.mdx --- title: Thread Safety description: Thread Safety Architecture --- Thread Safety Pyloid is designed so that GUI functions, which must run only on the main thread in PySide6-based applications, can be called safely and asynchronously from other threads using **QEventLoop** and its own event loop mechanism. This structure enables seamless integration with various Python server frameworks (such as FastAPI, Flask, Django, etc.), allowing events or commands from the server to be reflected in the GUI in real time. The core principles of Pyloid are as follows: - **Thread communication using command_signal and result_signal** When a GUI-related function is called from a separate thread, the command is sent to the main thread via a signal. The main thread processes the event using its own **QEventLoop**. Once the GUI function finishes execution, the result is sent back via another signal, so the calling thread can safely receive the result. - **Asynchronous command processing and custom event loop** For each command, Pyloid creates its own **QEventLoop** to wait asynchronously for the command to complete. This allows the server thread and GUI thread to communicate without blocking each other, maintaining GUI responsiveness. - **Strong compatibility with server-client architectures** Thanks to this structure, it is possible to safely implement various scenarios, such as launching a window directly from a server thread or dynamically controlling the GUI in response to web requests. For example, you can update the contents of a Pyloid window in real time upon receiving an HTTP request in a FastAPI server, or immediately reflect events from Flask in the GUI. -------------------------------------------------------------------------------- # API Reference - Pyloid ================================================================================ ## File: api/pyloid/browserwindow.mdx --- title: BrowserWindow --- The BrowserWindow class is designed to manage browser windows within a pyloid application The BrowserWindow object is created through the create_window method of the Pyloid class --- ## Window Content ### load_file Loads a local HTML file into the web view. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) window = app.create_window(title="My Window") window.load_file("path/to/index.html") ``` **Parameters** **Returns** --- ### load_url Sets the URL of the window. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) window = app.create_window(title="My Window") window.load_url("https://example.com") ``` **Parameters** **Returns** --- ### load_html Loads HTML content directly into the web view. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) window = app.create_window(title="My Window") html_content = "

Hello Pyloid!

" window.load_html(html_content) ``` **Parameters** **Returns** --- ## Window Properties ### set_title Sets the title of the window. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) window = app.create_window(title="My Window") window.set_title("New Title") ``` **Parameters** **Returns** --- ### set_size Sets the size of the window. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) window = app.create_window(title="My Window") window.set_size(800, 600) ``` **Parameters** **Returns** --- ### set_position Sets the position of the window. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) window = app.create_window(title="My Window") window.set_position(100, 100) ``` **Parameters** **Returns** --- ### set_position_by_anchor Positions the window at a specific location on the screen. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) window = app.create_window(title="My Window") window.set_position_by_anchor("center") ``` **Parameters** **Returns** --- ### set_frame Sets the frame of the window. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) window = app.create_window(title="My Window") window.set_frame(True) ``` **Parameters** **Returns** --- ### set_context_menu Sets the context menu of the window. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) window = app.create_window(title="My Window") window.set_context_menu(True) ``` **Parameters** **Returns** --- ### set_dev_tools Sets the developer tools of the window. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) window = app.create_window(title="My Window") window.set_dev_tools(True) ``` **Parameters** **Returns** --- ### open_dev_tools Opens the developer tools window. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) window = app.create_window(title="My Window") window.open_dev_tools() ``` **Returns** --- ### get_window_properties Returns the properties of the window. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) window = app.create_window(title="My Window") properties = window.get_window_properties() print(properties) ``` **Returns** --- ### get_id Returns the ID of the window. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) window = app.create_window(title="My Window") window_id = window.get_id() print(window_id) ``` **Returns** --- ### get_transparent Returns the transparency state of the window. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) window = app.create_window(title="My Window") is_transparent = window.get_transparent() print(f"Is transparent: {is_transparent}") ``` **Returns** --- ### get_size Returns the size of the window. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) window = app.create_window(title="My Window") size = window.get_size() print(f"Size: {size['width']}x{size['height']}") ``` **Returns** --- ### get_position Returns the position of the window. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) window = app.create_window(title="My Window") position = window.get_position() print(f"Position: ({position['x']}, {position['y']})") ``` **Returns** --- ### get_title Returns the title of the window. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) window = app.create_window(title="My Window") title = window.get_title() print(f"Title: {title}") ``` **Returns** --- ### get_url Returns the URL of the window. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) window = app.create_window(title="My Window") url = window.get_url() print(f"URL: {url}") ``` **Returns** --- ### get_visible Returns the visibility of the window. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) window = app.create_window(title="My Window") is_visible = window.get_visible() print(f"Is visible: {is_visible}") ``` **Returns** --- ### get_frame Returns the frame enabled state of the window. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) window = app.create_window(title="My Window") has_frame = window.get_frame() print(f"Has frame: {has_frame}") ``` **Returns** --- ## Window Visibility ### hide Hides the window. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) window = app.create_window(title="My Window") window.hide() ``` **Returns** --- ### show Shows the window. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) window = app.create_window(title="My Window") window.show() ``` **Returns** --- ### focus Focuses the window. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) window = app.create_window(title="My Window") window.focus() ``` **Returns** --- ### show_and_focus Shows and focuses the window. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) window = app.create_window(title="My Window") window.show_and_focus() ``` **Returns** --- ### close Closes the window. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) window = app.create_window(title="My Window") window.close() ``` **Returns** --- ## Window State ### toggle_fullscreen Toggles the fullscreen mode of the window. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) window = app.create_window(title="My Window") window.toggle_fullscreen() ``` **Returns** --- ### minimize Minimizes the window. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) window = app.create_window(title="My Window") window.minimize() ``` **Returns** --- ### maximize Maximizes the window. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) window = app.create_window(title="My Window") window.maximize() ``` **Returns** --- ### unmaximize Restores the window from maximized state. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) window = app.create_window(title="My Window") window.unmaximize() ``` **Returns** --- ### fullscreen Enters fullscreen mode. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) window = app.create_window(title="My Window") window.fullscreen() ``` **Returns** --- ### toggle_maximize Toggles the maximized state of the window. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) window = app.create_window(title="My Window") window.toggle_maximize() ``` **Returns** --- ### is_fullscreen Returns True if the window is fullscreen. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) window = app.create_window(title="My Window") is_fullscreen = window.is_fullscreen() print(f"Is fullscreen: {is_fullscreen}") ``` **Returns** --- ### is_maximized Returns True if the window is maximized. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) window = app.create_window(title="My Window") is_maximized = window.is_maximized() print(f"Is maximized: {is_maximized}") ``` **Returns** --- ## Window Capture ### capture Captures the current window. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) window = app.create_window(title="My Window") image_path = window.capture("screenshot.png") ``` **Parameters** **Returns** --- ## Keyboard Shortcuts ### add_shortcut Adds a keyboard shortcut to the window if it does not already exist. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) window = app.create_window(title="My Window") def on_shortcut(): print("Shortcut pressed!") shortcut = window.add_shortcut("Ctrl+C", on_shortcut) ``` **Parameters** **Returns** --- ### remove_shortcut Removes a keyboard shortcut from the window. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) window = app.create_window(title="My Window") window.remove_shortcut("Ctrl+C") ``` **Parameters** **Returns** --- ### get_all_shortcuts Returns all registered shortcuts in the window. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) window = app.create_window(title="My Window") shortcuts = window.get_all_shortcuts() print(shortcuts) ``` **Returns** --- ## Events ### invoke Invokes an event to the JavaScript side. [Event](/docs/api/pyloid-js/event) ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) window = app.create_window(title="My Window") window.invoke("customEvent", {"message": "Hello, Pyloid!"}) ``` **Parameters** **Returns** --- ## Window Resizing ### set_resizable Sets whether the window can be resized by the user. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) window = app.create_window(title="My Window") window.set_resizable(True) ``` **Parameters** **Returns** --- ### set_minimum_size Sets the minimum size of the window. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) window = app.create_window(title="My Window") window.set_minimum_size(400, 300) ``` **Parameters** **Returns** --- ### set_maximum_size Sets the maximum size of the window. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) window = app.create_window(title="My Window") window.set_maximum_size(1024, 768) ``` **Parameters** **Returns** --- ### get_minimum_size Returns the minimum size of the window. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) window = app.create_window(title="My Window") min_size = window.get_minimum_size() print(f"Minimum size: {min_size['width']}x{min_size['height']}") ``` **Returns** --- ### get_maximum_size Returns the maximum size of the window. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) window = app.create_window(title="My Window") max_size = window.get_maximum_size() print(f"Maximum size: {max_size['width']}x{max_size['height']}") ``` **Returns** --- ### get_resizable Returns the resizability of the window. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) window = app.create_window(title="My Window") is_resizable = window.get_resizable() print(f"Is resizable: {is_resizable}") ``` **Returns** --- ## Splash Screen Provides splash screen functionality displayed during application loading. Supports both static images and animated GIFs with customizable positioning and behavior. ### set_static_image_splash_screen Displays a static image as a splash screen during window loading. The splash screen automatically positions itself and can be configured to close on page load or stay visible until manually closed. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) window = app.create_window(title="My Window") ########## Usage ########## # Basic usage with default settings window.set_static_image_splash_screen("assets/loading.png") # Advanced configuration window.set_static_image_splash_screen( image_path="assets/loading.png", close_on_load=True, stay_on_top=True, clickable=True, position="center" ) ``` **Parameters** **Returns** --- ### set_gif_splash_screen Displays an animated GIF as a splash screen during window loading. Provides visual feedback during long loading operations with smooth animations and customizable display options. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) window = app.create_window(title="My Window") ########## Usage ########## # Basic usage with default settings window.set_gif_splash_screen("assets/loading.gif") # Advanced configuration for loading screens window.set_gif_splash_screen( gif_path="assets/loading.gif", close_on_load=True, stay_on_top=True, clickable=True, position="center" ) ``` **Parameters** **Returns** --- ### close_splash_screen Manually closes the splash screen if it is currently displayed. Useful when you want to control the timing of splash screen dismissal independently of page load events. ```python from pyloid import Pyloid from pyloid.timer import PyloidTimer app = Pyloid(app_name="MyApp", single_instance=True) window = app.create_window(title="My Window") ########## Usage ########## # Manual closure after specific operations window.set_static_image_splash_screen("assets/loading.png") # Close splash screen and show main window after 3 seconds timer_manager = PyloidTimer() timer_manager.start_single_shot_timer(3000, lambda: ( window.close_splash_screen(), window.show_and_focus() )) # Or close immediately when ready window.close_splash_screen() ``` **Returns** -------------------------------------------------------------------------------- ## File: api/pyloid/monitor.mdx --- title: Monitor --- The Monitor class provides functionality to manage and manipulate information about computer monitors. --- ## Initialization ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) ########## Usage ########## monitors = app.get_monitors() monitor = monitors[0] # Monitor objects are typically accessed through app.get_monitors() ``` --- ## Screen Capture ### capture ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) monitors = app.get_monitors() monitor = monitors[0] # Get first monitor # Capture full screen monitor.capture("screenshot.png") # Capture specific area monitor.capture("area.png", x=100, y=100, width=800, height=600) ``` **Parameters** **Returns** --- ## Monitor Information ### info Returns information about the monitor. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) monitors = app.get_monitors() monitor = monitors[0] info = monitor.info() print(info) ``` **Returns** ```json { 'index': 0, 'name': 'Primary Monitor', 'manufacturer': 'Dell', 'model': 'U2718Q', 'serial_number': 'SN123456789', 'x': 0, 'y': 0, 'width': 2560, 'height': 1440, 'is_primary': True, 'geometry': { 'x': 0, 'y': 0, 'width': 2560, 'height': 1440, }, 'size': { 'width': 2560, 'height': 1440, }, 'available_geometry': { 'x': 0, 'y': 0, 'width': 2560, 'height': 1400, }, 'available_size': { 'width': 2560, 'height': 1400, }, 'virtual_geometry': { 'x': 0, 'y': 0, 'width': 5120, 'height': 1440, }, 'virtual_size': { 'width': 5120, 'height': 1440, }, 'available_virtual_geometry': { 'x': 0, 'y': 0, 'width': 5120, 'height': 1400, }, 'available_virtual_size': { 'width': 5120, 'height': 1400, }, 'physical_size': { 'width': 600, 'height': 340, }, 'depth': 24, 'device_pixel_ratio': 1.0, 'logical_dots_per_inch': 96.0, 'logical_dots_per_inch_x': 96.0, 'logical_dots_per_inch_y': 96.0, 'orientation': 'Landscape', 'physical_dots_per_inch': 109.0, 'physical_dots_per_inch_x': 109.0, 'physical_dots_per_inch_y': 109.0, 'refresh_rate': 60.0, } ``` --- ### is_primary Checks if the monitor is the primary monitor. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) monitors = app.get_monitors() monitor = monitors[0] is_primary = monitor.is_primary() print(f"Is primary monitor: {is_primary}") ``` **Returns** --- ### name Returns the name of the monitor. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) monitors = app.get_monitors() monitor = monitors[0] name = monitor.name() print(f"Monitor name: {name}") ``` **Returns** --- ### manufacturer Returns the manufacturer of the monitor. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) monitors = app.get_monitors() monitor = monitors[0] manufacturer = monitor.manufacturer() print(f"Manufacturer: {manufacturer}") ``` **Returns** --- ### model Returns the model of the monitor. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) monitors = app.get_monitors() monitor = monitors[0] model = monitor.model() print(f"Model: {model}") ``` **Returns** --- ### serial_number Returns the serial number of the monitor. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) monitors = app.get_monitors() monitor = monitors[0] serial = monitor.serial_number() print(f"Serial number: {serial}") ``` **Returns** --- ## Geometry and Size ### size Returns the size of the monitor. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) monitors = app.get_monitors() monitor = monitors[0] size = monitor.size() print(f"Size: {size['width']}x{size['height']}") ``` **Returns** --- ### geometry Returns the geometry of the monitor. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) monitors = app.get_monitors() monitor = monitors[0] geometry = monitor.geometry() print(f"Position: ({geometry['x']}, {geometry['y']}) Size: {geometry['width']}x{geometry['height']}") ``` **Returns** --- ### available_geometry Returns the available geometry of the monitor. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) monitors = app.get_monitors() monitor = monitors[0] available_geometry = monitor.available_geometry() print(f"Available area: {available_geometry}") ``` **Returns** --- ### available_size Returns the available size of the monitor. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) monitors = app.get_monitors() monitor = monitors[0] available_size = monitor.available_size() print(f"Available size: {available_size}") ``` **Returns** --- ### virtual_geometry Returns the virtual geometry of the monitor. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) monitors = app.get_monitors() monitor = monitors[0] virtual_geometry = monitor.virtual_geometry() print(f"Virtual geometry: {virtual_geometry}") ``` **Returns** --- ### virtual_size Returns the virtual size of the monitor. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) monitors = app.get_monitors() monitor = monitors[0] virtual_size = monitor.virtual_size() print(f"Virtual size: {virtual_size}") ``` **Returns** --- ### available_virtual_geometry Returns the available virtual geometry of the monitor. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) monitors = app.get_monitors() monitor = monitors[0] available_virtual_geometry = monitor.available_virtual_geometry() print(f"Available virtual geometry: {available_virtual_geometry}") ``` **Returns** --- ### available_virtual_size Returns the available virtual size of the monitor. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) monitors = app.get_monitors() monitor = monitors[0] available_virtual_size = monitor.available_virtual_size() print(f"Available virtual size: {available_virtual_size}") ``` **Returns** --- ### physical_size Returns the physical size of the monitor. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) monitors = app.get_monitors() monitor = monitors[0] physical_size = monitor.physical_size() print(f"Physical size: {physical_size['width']}x{physical_size['height']} mm") ``` **Returns** --- ## DPI and Display Properties ### depth Returns the depth of the monitor. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) monitors = app.get_monitors() monitor = monitors[0] depth = monitor.depth() print(f"Color depth: {depth} bits") ``` **Returns** --- ### device_pixel_ratio Returns the device pixel ratio of the monitor. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) monitors = app.get_monitors() monitor = monitors[0] ratio = monitor.device_pixel_ratio() print(f"Device pixel ratio: {ratio}") ``` **Returns** --- ### logical_dots_per_inch Returns the logical dots per inch (DPI) of the monitor. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) monitors = app.get_monitors() monitor = monitors[0] dpi = monitor.logical_dots_per_inch() print(f"Logical DPI: {dpi}") ``` **Returns** --- ### logical_dots_per_inch_x Returns the logical dots per inch (DPI) along the X axis of the monitor. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) monitors = app.get_monitors() monitor = monitors[0] dpi_x = monitor.logical_dots_per_inch_x() print(f"Horizontal logical DPI: {dpi_x}") ``` **Returns** --- ### logical_dots_per_inch_y Returns the logical dots per inch (DPI) along the Y axis of the monitor. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) monitors = app.get_monitors() monitor = monitors[0] dpi_y = monitor.logical_dots_per_inch_y() print(f"Vertical logical DPI: {dpi_y}") ``` **Returns** --- ### physical_dots_per_inch Returns the physical dots per inch (DPI) of the monitor. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) monitors = app.get_monitors() monitor = monitors[0] physical_dpi = monitor.physical_dots_per_inch() print(f"Physical DPI: {physical_dpi}") ``` **Returns** --- ### physical_dots_per_inch_x Returns the physical dots per inch (DPI) along the X axis of the monitor. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) monitors = app.get_monitors() monitor = monitors[0] physical_dpi_x = monitor.physical_dots_per_inch_x() print(f"Horizontal physical DPI: {physical_dpi_x}") ``` **Returns** --- ### physical_dots_per_inch_y Returns the physical dots per inch (DPI) along the Y axis of the monitor. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) monitors = app.get_monitors() monitor = monitors[0] physical_dpi_y = monitor.physical_dots_per_inch_y() print(f"Vertical physical DPI: {physical_dpi_y}") ``` **Returns** --- ### orientation Returns the orientation of the monitor. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) monitors = app.get_monitors() monitor = monitors[0] orientation = monitor.orientation() print(f"Orientation: {orientation}") ``` **Returns** --- ### refresh_rate Returns the refresh rate of the monitor. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) monitors = app.get_monitors() monitor = monitors[0] refresh_rate = monitor.refresh_rate() print(f"Refresh rate: {refresh_rate} Hz") ``` **Returns** --- ## Event Callbacks ### geometry_changed Registers a callback for the event that occurs when the geometry of the monitor changes. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) monitors = app.get_monitors() monitor = monitors[0] def on_geometry_changed(): print("Monitor geometry changed!") monitor.geometry_changed(on_geometry_changed) ``` **Parameters** **Returns** --- ### orientation_changed Registers a callback for the event that occurs when the orientation of the monitor changes. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) monitors = app.get_monitors() monitor = monitors[0] def on_orientation_changed(): print("Monitor orientation changed!") monitor.orientation_changed(on_orientation_changed) ``` **Parameters** **Returns** --- ### refresh_rate_changed Registers a callback for the event that occurs when the refresh rate of the monitor changes. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) monitors = app.get_monitors() monitor = monitors[0] def on_refresh_rate_changed(): print("Monitor refresh rate changed!") monitor.refresh_rate_changed(on_refresh_rate_changed) ``` **Parameters** **Returns** -------------------------------------------------------------------------------- ## File: api/pyloid/pyloid.mdx --- title: Pyloid --- Pyloid is a desktop application framework built on top of PySide6. It simplifies window creation, system tray management, clipboard interaction, RPC communication, file watching, and more. All functions in Pyloid are thread-safe, meaning they can be safely executed from threads other than the main thread. --- ## Initialization ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) ``` **Parameters** **Returns** --- ## Window Management ### create_window ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) window = app.create_window( title="Main Window", width=1024, height=768, x=100, y=100, frame=True, context_menu=True, dev_tools=True, rpc=rpc ) ``` **Parameters** **Returns** --- ### get_windows Returns a dictionary of all browser windows. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) window = app.create_window(title="Your Window Title") ########## Usage ########## windows = app.get_windows() print(windows["your-window-id"].get_title()) # "Your Window Title" ``` **Returns** --- ### get_window_by_id Returns the window with the given ID. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) window = app.create_window(title="Your Window Title") ########## Usage ########## window_by_id = app.get_window_by_id(window.get_id()) # BrowserWindow instance # window == window_by_id : same instance # you can use this to get the window instance by id for multi window application print(window_by_id.get_title()) # "Your Window Title" ``` **Parameters** **Returns** --- ### show_main_window Shows and focuses the first window. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) window = app.create_window(title="Your Window Title") ########## Usage ########## app.show_main_window() # main window is the first window that was created ``` **Returns** --- ### focus_main_window Focuses the first window. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) window = app.create_window(title="Your Window Title") ########## Usage ########## app.focus_main_window() # main window is the first window that was created ``` **Returns** --- ### show_and_focus_main_window Shows and focuses the first window. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) window = app.create_window(title="Your Window Title") ########## Usage ########## app.show_and_focus_main_window() # main window is the first window that was created ``` **Returns** --- ### close_all_windows Closes all windows. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) window = app.create_window(title="Your Window Title") ########## Usage ########## app.close_all_windows() # close all windows ``` **Returns** --- ### quit Quits the application. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) ########## Usage ########## app.quit() # quit the application ``` **Returns** --- ## Application Icon ### set_icon Dynamically sets the application's icon. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) ########## Usage ########## app.set_icon("icon.png") # set the application icon ``` **Parameters** **Returns** --- ## Tray System ### set_tray_icon Dynamically sets the tray icon. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) ########## Usage ########## app.set_tray_icon("icon.png") # set the tray icon ``` **Parameters** **Returns** ### set_tray_menu_items Dynamically sets the tray menu items. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) ########## Usage ########## app.set_tray_menu_items([ {"label": "Open", "callback": lambda: app.show_main_window()}, {"label": "Quit", "callback": app.quit} ]) ``` **Parameters** **Returns** ### set_tray_actions Dynamically sets the actions for tray icon activation. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) ########## Usage ########## app.set_tray_actions({TrayEvent.DoubleClick: lambda: app.show_main_window()}) ``` **Parameters** **Returns** ### set_tray_icon_animation Dynamically sets and starts the animation for the tray icon. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) ########## Usage ########## app.set_tray_icon_animation( [ 'frame1.png', 'frame2.png', 'frame3.png', ], 100, ) ``` **Parameters** **Returns** ### set_tray_tooltip Dynamically sets the tooltip for the tray icon. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) ########## Usage ########## app.set_tray_tooltip('Pyloid is running') ``` **Parameters** **Returns** --- ## Notification ### show_notification Displays a notification in the system tray. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) ########## Usage ########## app.show_notification("Hello", "This is a notification.") ``` **Parameters** **Returns** ### set_notification_callback Sets the callback function to be called when a notification is clicked. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) ########## Usage ########## def on_notification_click(): print("Notification clicked") app.set_notification_callback(on_notification_click) ``` **Parameters** **Returns** --- ## Clipboard ### set_clipboard_text Copies text to the clipboard. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) ########## Usage ########## app.set_clipboard_text("Copied text") ``` **Parameters** **Returns** --- ### get_clipboard_text You can use this function to retrieve the text currently on the clipboard. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) ########## Usage ########## text = app.get_clipboard_text() print(text) # "Copied text" ``` **Returns** --- ### set_clipboard_image Copies an image to the clipboard. This function can accept not only image file paths but also byte data or `os.PathLike` objects. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) ########## Usage ########## app.set_clipboard_image("image.png") ``` **Parameters** **Returns** --- ### get_clipboard_image You can use this function to retrieve the image currently on the clipboard. The returned image is of [`QImage`](https://doc.qt.io/qtforpython-6/PySide6/QtGui/QImage.html) type. If there's no image on the clipboard, it returns None. With the [`QImage`](https://doc.qt.io/qtforpython-6/PySide6/QtGui/QImage.html) object, you can perform various operations such as image processing, display, saving, etc. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) ########## Usage ########## img = app.get_clipboard_image() print(img) # QImage object ``` **Returns** --- ## Monitor ### get_all_monitors Returns information about all connected monitors. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) ########## Usage ########## monitors = app.get_all_monitors() for monitor in monitors: print(monitor.info()) ``` **Returns** ### get_primary_monitor Returns information about the primary monitor. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) ########## Usage ########## primary_monitor = app.get_primary_monitor() print(primary_monitor.info()) ``` **Returns** --- ## Autostart ### set_auto_start Sets the application to start automatically at system startup. more guide [here](/docs/guides/autostart). ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) ########## Usage ########## app.set_auto_start(True) # enable auto-start app.set_auto_start(False) # disable auto-start # in production, it will return True or False # in development, it will return None and do nothing ``` **Parameters** **Returns** --- ### is_auto_start Checks if the application is set to start automatically at system startup. more guide [here](/docs/guides/autostart). ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) ########## Usage ########## print(app.is_auto_start()) # True or False ``` **Returns** --- ## File Watcher ### watch_file Adds a file to the watch list. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) ########## Usage ########## result = app.watch_file("path/to/file.txt") print(result) # True if successful ``` **Parameters** **Returns** --- ### watch_directory Adds a directory to the watch list. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) ########## Usage ########## result = app.watch_directory("path/to/directory") ``` **Parameters** **Returns** --- ### stop_watching Removes a file or directory from the watch list. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) ########## Usage ########## result = app.stop_watching("path/to/watch") ``` **Parameters** **Returns** --- ### get_watched_paths Returns all currently watched paths. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) ########## Usage ########## paths = app.get_watched_paths() ``` **Returns** --- ### get_watched_files Returns all currently watched files. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) ########## Usage ########## files = app.get_watched_files() ``` **Returns** --- ### get_watched_directories Returns all currently watched directories. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) ########## Usage ########## directories = app.get_watched_directories() ``` **Returns** --- ### remove_all_watched_paths Removes all paths from the watch list. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) ########## Usage ########## app.remove_all_watched_paths() ``` **Returns** --- ### set_file_change_callback Sets the callback function to be called when a file is changed. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) ########## Usage ########## app.set_file_change_callback(lambda path: print(f"File changed: {path}")) ``` **Parameters** **Returns** --- ### set_directory_change_callback Sets the callback function to be called when a directory is changed. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) ########## Usage ########## app.set_directory_change_callback(lambda path: print(f"Directory changed: {path}")) ``` **Parameters** **Returns** --- ## File Dialogs ### open_file_dialog Opens a dialog to open a file. This functionality is implemented using PySide6's `QFileDialog` class. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) ########## Usage ########## file_path = app.open_file_dialog(dir="/home/user", filter="Text Files (*.txt);;All Files (*)") if file_path: print("Selected file:", file_path) ``` **Parameters** **Returns** --- ### save_file_dialog Opens a dialog to save a file. This functionality is implemented using PySide6's `QFileDialog` class. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) ########## Usage ########## file_path = app.save_file_dialog(dir="/home/user", filter="Text Files (*.txt);;All Files (*)") if file_path: print("File will be saved to:", file_path) ``` **Parameters** **Returns** --- ### select_directory_dialog Opens a dialog to select a directory. This functionality is implemented using PySide6's `QFileDialog` class. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) ########## Usage ########## directory_path = app.select_directory_dialog(dir="/home/user") if directory_path: print("Selected directory:", directory_path) ``` **Parameters** **Returns** --- ## Platform Dirs ### user_data_dir Returns the user data directory path. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) ########## Usage ########## data_dir = app.user_data_dir() ``` **Returns** --- ### site_data_dir Returns the site data directory path. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) ########## Usage ########## data_dir = app.site_data_dir() ``` **Returns** --- ### user_cache_dir Returns the user cache directory path. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) ########## Usage ########## cache_dir = app.user_cache_dir() ``` **Returns** --- ### user_log_dir Returns the user log directory path. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) ########## Usage ########## log_dir = app.user_log_dir() ``` **Returns** --- ### user_documents_dir Returns the user documents directory path. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) ########## Usage ########## docs_dir = app.user_documents_dir() ``` **Returns** --- ### user_downloads_dir Returns the user downloads directory path. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) ########## Usage ########## downloads_dir = app.user_downloads_dir() ``` **Returns** --- ### user_pictures_dir Returns the user pictures directory path. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) ########## Usage ########## pictures_dir = app.user_pictures_dir() ``` **Returns** --- ### user_videos_dir Returns the user videos directory path. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) ########## Usage ########## videos_dir = app.user_videos_dir() ``` **Returns** --- ### user_music_dir Returns the user music directory path. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) ########## Usage ########## music_dir = app.user_music_dir() ``` **Returns** --- ### user_desktop_dir Returns the user desktop directory path. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) ########## Usage ########## desktop_dir = app.user_desktop_dir() ``` **Returns** --- ### user_runtime_dir Returns the user runtime directory path. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) ########## Usage ########## runtime_dir = app.user_runtime_dir() ``` **Returns** --- ## Store API ### store Returns a Store instance for the given path. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) ########## Usage ########## store = app.store("settings.json") store.set("theme", "dark") print(store.get("theme")) ``` **Parameters** **Returns** --- ## Run the App ### run Runs the application event loop. ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) ########## Usage ########## app.run() ``` **Returns** -------------------------------------------------------------------------------- ## File: api/pyloid/pyloidipc.mdx --- title: PyloidIPC --- PyloidIPC enables communication between JavaScript and Python via IPC (Inter-Process Communication). It allows JavaScript code running in the browser window to call Python methods and receive responses. --- ## Initialization ```python from pyloid.ipc import PyloidIPC class CustomIPC(PyloidIPC): pass ``` --- ## Bridge Decorator ### Bridge Creates a slot that can be called from JavaScript via IPC. ```python from pyloid.ipc import PyloidIPC, Bridge class CustomIPC(PyloidIPC): @Bridge(str, result=str) def echo(self, message): return f'Message received in Python: {message}' ``` --- ## Usage Example (Python) ```python from pyloid import Pyloid from pyloid.ipc import PyloidIPC, Bridge app = Pyloid('Pyloid-App') class CustomIPC(PyloidIPC): @Bridge(str, result=str) def echo(self, message): return f'Message received in Python: {message}' @Bridge(int, int, result=int) def add(self, a, b): return a + b @Bridge(result=str) def create_window(self): win = self.pyloid.create_window(title='Pyloid Browser') win.load_url('https://www.google.com') win.show() win.focus() return win.get_id() # Create main window window = app.create_window( title='Pyloid Browser', ipc=[CustomIPC()], ) window.load_file('index.html') window.show() window.focus() app.run() ``` (JavaScript) ```javascript import { ipc } from 'pyloid-js'; let result = await ipc.CustomIPC.echo('Hello, Pyloid!').then((result) => { console.log(result); // "Message received in Python: Hello, Pyloid!" }) let sum = await ipc.CustomIPC.add(5, 3).then((sum) => { console.log(sum); // 8 }) let window_id = await ipc.CustomIPC.create_window().then((window_id) => { console.log(window_id); // "eae338a3-c8cb-4103-852f-404486beea0d" }) ``` -------------------------------------------------------------------------------- ## File: api/pyloid/pyloidrpc.mdx --- title: PyloidRPC --- PyloidRPC based on HTTP, easy function calls between the frontend (web) and backend (Python) ## Initialization ### PyloidRPC The main RPC class that manages method registration and handles RPC calls. ```python from pyloid.rpc import PyloidRPC server = PyloidRPC() ``` --- ## Method Decorator ### method The decorator to register a method to the RPC server. ```python @server.method() def greet(name: str): return f"Hello, {name}!" ``` **Parameters** --- ## RPCContext ### RPCContext The `RPCContext` class provides access to the current application state when a parameter named `ctx` is present in your method signature. **Properties** - `RPCContext.pyloid`: The Pyloid application instance - `RPCContext.window`: The current browser window instance --- ## Basic Usage ### Simple RPC Method ```python from pyloid.rpc import PyloidRPC server = PyloidRPC() @server.method() async def greet(name: str): return f"Hello, {name}!" ``` --- ### RPC Method with Context ```python from pyloid.rpc import PyloidRPC, RPCContext server = PyloidRPC() @server.method() async def create_google_window(ctx: RPCContext): window = ctx.pyloid.create_window(title="Google") window.load_url("https://www.google.com") window.show_and_focus() ``` --- ### Toggle Fullscreen Example ```python from pyloid.rpc import PyloidRPC, RPCContext server = PyloidRPC() @server.method() async def toggle_fullscreen(ctx: RPCContext): # Access the current window through context is_fullscreen = ctx.window.is_fullscreen() ctx.window.set_fullscreen(not is_fullscreen) return not is_fullscreen ``` --- ## Error Handling ### RPCError Pyloid provides a custom `RPCError` class for handling application-specific errors: ```python from pyloid.rpc import PyloidRPC, RPCError server = PyloidRPC() @server.method() async def divide(a: float, b: float): if b == 0: # Create a custom error with code and message raise RPCError("Division by zero is not allowed", code=-32000) return a / b ``` --- ## Connecting RPC to Windows ### Window Integration ```python from pyloid import Pyloid from pyloid.rpc import PyloidRPC # Create an RPC server instance server = PyloidRPC() @server.method() async def greet(name: str): return f"Hello, {name}!" # Connect the RPC server instance app = Pyloid(app_name="MyApp", single_instance=True, server=server) ``` --- ## Frontend RPC Calls Once your RPC server is running, you can call your methods from the frontend ```javascript import { rpc } from 'pyloid-js'; // Call the 'greet' RPC function to receive a greeting. rpc .call('greet', { name: 'Alice' }) .then((response) => { console.log(response); // Outputs "Hello, Alice!" }) .catch((error) => { console.error('Error occurred during RPC call:', error); }); ``` --- ## Notes - All RPC functions must be defined as async, and you can use await inside them. - When calling RPC functions from the frontend, simply pass the function name and parameters as they are. - **All GUI-related functions in Pyloid are designed to be thread-safe.** Therefore, unlike typical Python GUI frameworks, you can safely call GUI-related methods (app, window, etc.) inside RPC functions (asynchronous/other threads) even if they are not on the main thread. Without any additional synchronization or queuing, you can freely control the GUI from RPC server. -------------------------------------------------------------------------------- ## File: api/pyloid/pyloidtimer.mdx --- title: PyloidTimer --- PyloidTimer is a convenient timer management class based on PySide6's QTimer. It allows you to easily create and manage various types of timers with thread-safe operations. --- ## Initialization ### PyloidTimer Creates a new PyloidTimer instance for managing timers. ```python from pyloid.timer import PyloidTimer timer_manager = PyloidTimer() ``` **Returns** --- ## Timer Creation ### start_periodic_timer Starts a timer that runs periodically at specified intervals. ```python from pyloid import Pyloid from pyloid.timer import PyloidTimer app = Pyloid(app_name="MyApp", single_instance=True) timer_manager = PyloidTimer() ########## Usage ########## def print_hello(): print("Hello!") # Start a timer that prints "Hello!" every 2 seconds timer_id = timer_manager.start_periodic_timer(2000, print_hello) app.run() ``` **Parameters** **Returns** --- ### start_single_shot_timer Starts a timer that runs only once after the specified delay. ```python from pyloid import Pyloid from pyloid.timer import PyloidTimer app = Pyloid(app_name="MyApp", single_instance=True) timer_manager = PyloidTimer() ########## Usage ########## def delayed_message(): print("5 seconds have passed!") # Start a single-shot timer that prints a message after 5 seconds timer_id = timer_manager.start_single_shot_timer(5000, delayed_message) app.run() ``` **Parameters** **Returns** --- ### start_precise_periodic_timer Starts a high-precision periodic timer for timing-critical applications. ```python from pyloid import Pyloid from pyloid.timer import PyloidTimer app = Pyloid(app_name="MyApp", single_instance=True) timer_manager = PyloidTimer() ########## Usage ########## def precise_task(): print("Executing precise task") # Start a precise periodic timer with 100ms interval precise_timer_id = timer_manager.start_precise_periodic_timer(100, precise_task) app.run() ``` **Parameters** **Returns** --- ## Timer Control ### stop_timer Stops a running timer using its ID. ```python from pyloid import Pyloid from pyloid.timer import PyloidTimer app = Pyloid(app_name="MyApp", single_instance=True) timer_manager = PyloidTimer() ########## Usage ########## # Stop a timer using its ID timer_manager.stop_timer(timer_id) app.run() ``` **Parameters** **Returns** --- ### set_interval Changes the interval of a running timer. ```python from pyloid import Pyloid from pyloid.timer import PyloidTimer app = Pyloid(app_name="MyApp", single_instance=True) timer_manager = PyloidTimer() ########## Usage ########## # Change the timer interval to 3 seconds timer_manager.set_interval(timer_id, 3000) app.run() ``` **Parameters** **Returns** --- ## Timer Information ### is_timer_active Checks if a timer is currently running. ```python from pyloid import Pyloid from pyloid.timer import PyloidTimer app = Pyloid(app_name="MyApp", single_instance=True) timer_manager = PyloidTimer() ########## Usage ########## if timer_manager.is_timer_active(timer_id): print("The timer is still running.") else: print("The timer has stopped.") app.run() ``` **Parameters** **Returns** --- ### get_remaining_time Gets the remaining time until a timer fires. ```python from pyloid import Pyloid from pyloid.timer import PyloidTimer app = Pyloid(app_name="MyApp", single_instance=True) timer_manager = PyloidTimer() ########## Usage ########## remaining_time = timer_manager.get_remaining_time(timer_id) if remaining_time is not None: print(f"{remaining_time}ms left until the timer fires.") app.run() ``` **Parameters** **Returns** -------------------------------------------------------------------------------- ## File: api/pyloid/serve.mdx --- title: Serve --- Pyloid provides functionality to serve static files with zero-copy optimization for high-performance frontend delivery. The server uses aiohttp with sendfile system calls and supports advanced features like range requests and ETag caching. --- ## Static File Serving ### pyloid_serve Starts a zero-copy optimized static file server using aiohttp with advanced performance features. - Uses **zero-copy file serving** with sendfile() system calls for maximum performance - Supports **HTTP range requests** for partial content delivery (resumable downloads) - Implements **ETag caching** to reduce unnecessary data transfer - Automatically finds available ports when not specified - Optimized for both development and production environments ```python from pyloid import Pyloid from pyloid.serve import pyloid_serve app = Pyloid(app_name="MyApp", single_instance=True) ########## Usage ########## # Serve static files from a directory url = pyloid_serve("dist-frontend") # Create window and load the served content window = app.create_window(title="My App", width=1200, height=800) window.load_url(url) window.show_and_focus() ``` **Parameters** **Returns** ## Server Features ### Zero-Copy File Serving The server uses zero-copy to transfer files directly from disk to network without copying data through user space, providing maximum performance for large files. ### HTTP Range Requests Supports partial content delivery, enabling: - Resumable downloads in web browsers - Video/audio streaming with seeking capability - Efficient delivery of large files ### ETag Caching Implements HTTP ETag headers for intelligent caching: - Browser can check if file has changed without downloading - Reduces bandwidth usage and improves load times - Automatic cache validation based on file modification time and size ### Automatic Port Allocation When no port is specified, the server automatically finds an available port using the system's port allocation mechanism, preventing port conflicts. ## Security Features - **Directory Traversal Protection**: Prevents access to files outside the served directory - **Path Validation**: Ensures all requested paths are within the allowed directory - **Safe Path Resolution**: Uses pathlib for secure path handling ## Performance Optimizations - **Async I/O**: Uses aiohttp for non-blocking I/O operations - **Threaded Execution**: Runs server in daemon thread that terminates with main application - **Optimized Chunk Sizes**: Uses 64KB chunks for efficient streaming - **Connection Backlog**: Configured for high concurrency - **Keep-Alive**: Optimized connection reuse ## Usage Examples ### Basic Static File Serving ```python from pyloid.serve import pyloid_serve # Serve a built React/Vue/Angular app url = pyloid_serve("build") print(f"Server started at: {url}") ``` ### Custom Port ```python from pyloid.serve import pyloid_serve # Use specific port url = pyloid_serve("public", port=3000) # Server will be available at http://127.0.0.1:3000 ``` ### Integration with Pyloid App ```python from pyloid import Pyloid from pyloid.serve import pyloid_serve app = Pyloid(app_name="MyApp") # Start server frontend_url = pyloid_serve("dist") # Create main window main_window = app.create_window( title="My Application", width=1200, height=800 ) main_window.load_url(frontend_url) main_window.show_and_focus() # Run the application app.run() ``` -------------------------------------------------------------------------------- ## File: api/pyloid/store.mdx --- title: Store --- The `Store` class is a lightweight key-value database used by creating it via `app.store("store.json")` from a Pyloid app instance. You can store any Python object that is JSON serializable, and the data is persistently managed as a database file. --- ## Creating a Store ### store ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) store = app.store("store.json") ``` **Parameters** **Returns** --- ## Data Operations ### get ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) store = app.store("store.json") store.set("user", {"name": "Hong Gil-dong", "age": 30}) user = store.get("user") print(user) # {'name': 'Hong Gil-dong', 'age': 30} print(store.get("nonexistent_key")) # None ``` Returns the value associated with the specified key. If the key does not exist, returns `default`. **Parameters** **Returns** --- ### set ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) store = app.store("store.json") store.set("settings", {"theme": "dark", "notifications": True}) store.set("counter", 42) store.set("items", ["apple", "banana", "orange"]) ``` Adds or updates a key-value pair in the database. The value must be a JSON-serializable Python object. **Parameters** **Returns** --- ### remove ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) store = app.store("store.json") store.set("temp", "temporary data") store.remove("temp") # True store.remove("nonexistent_key") # False ``` Deletes the value associated with the specified key from the database. **Parameters** **Returns** --- ## Bulk Operations ### all ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) store = app.store("store.json") store.set("key1", "value1") store.set("key2", "value2") keys = store.all() print(keys) # ['key1', 'key2'] ``` Returns a list of all keys stored in the database. **Returns** --- ### purge ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) store = app.store("store.json") store.set("key1", "value1") store.set("key2", "value2") store.purge() # True print(store.all()) # [] ``` Deletes all keys and values from the database. **Returns** --- ## Persistence ### save ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) store = app.store("store.json") store.set("key", "value") store.save() # True ``` Saves the current state of the database to the file. You can specify orjson serialization options with the `option` parameter. **Parameters** **Returns** --- ## Summary - **Store** is created from a Pyloid app instance using `app.store("store.json")`. - You can store any Python object that is JSON serializable, such as strings, numbers, lists, and dictionaries. - Main methods: `get`, `set`, `remove`, `all`, `purge`, `save` - Data is persistently managed as a database file. -------------------------------------------------------------------------------- ## File: api/pyloid/trayevent.mdx # TrayEvent `TrayEvent` is an enumeration (Enum) class that represents events related to the system tray icon. This class is mapped to `QSystemTrayIcon.ActivationReason`. --- ## TrayEvent Members ### DoubleClick Event that occurs when the tray icon is double-clicked. --- ### MiddleClick Event that occurs when the tray icon is clicked with the middle button. --- ### RightClick Event that occurs when the tray icon is clicked with the right button (context menu). --- ### LeftClick Event that occurs when the tray icon is clicked with the left button. --- ### Unknown Unknown event. --- ## Usage Example ### Tray Event Handling ```python from pyloid import Pyloid, TrayEvent app = Pyloid(app_name="MyApp", single_instance=True) app.set_tray_icon("icons/icon.ico") app.set_tray_actions( { TrayEvent.DoubleClick: lambda: print("Tray icon was double-clicked."), TrayEvent.MiddleClick: lambda: print("Tray icon was middle-clicked."), TrayEvent.RightClick: lambda: print("Tray icon was right-clicked."), TrayEvent.LeftClick: lambda: print("Tray icon was left-clicked."), } ) ``` **Parameters** **Returns** -------------------------------------------------------------------------------- ## File: api/pyloid/utils.mdx --- title: Utils --- Pyloid provides utility functions to help with resource path resolution, environment detection, platform identification, and networking. --- ## Production & Development ### get_production_path Constructs the absolute path to a resource file, adjusting based on the execution environment. - In a production environment (e.g., when packaged with PyInstaller), it prepends the application's base directory to the provided relative path. - If no path is provided, it returns the base path itself. - In a development environment (regular Python script), it simply returns the provided path as is. If no path is provided, it returns `None`. ```python tab="production" from pyloid.utils import get_production_path ########## Usage ########## # In production (e.g., PyInstaller bundle, sys._MEIPASS = '/tmp/_MEIabcde') prod_path = get_production_path("assets/icon.ico") print(prod_path) # '/tmp/_MEIabcde/assets/icon.ico' base_prod_path = get_production_path() print(base_prod_path) # '/tmp/_MEIabcde' ``` ```python tab="development" from pyloid.utils import get_production_path ########## Usage ########## path = get_production_path("assets/icon.ico") print(path) # 'assets/icon.ico' base_path = get_production_path() print(base_path) # None ``` **Production Example** The example shows how `get_production_path()` automatically returns the correct path in both development (dev) and bundled (prod) environments, allowing you to use the same code without additional branching. ```python from pyloid import Pyloid from pyloid.utils import get_production_path app = Pyloid(app_name="MyApp", single_instance=True) app.set_icon(get_production_path("assets/icon.ico")) # set the icon app.set_tray_icon(get_production_path("assets/icon.ico")) # set the tray icon ``` **Parameters** **Returns** ### is_production Checks if the current environment is a production environment (e.g., PyInstaller or Nuitka bundle). - Returns `True` if running in a production environment, otherwise `False`. ```python from pyloid.utils import is_production ########## Usage ########## if is_production(): print("Running in production environment.") else: print("Not in production environment.") ``` **Returns** ## Platform ### get_platform Returns the name of the current system's platform. - Uses `platform.system()` to determine the OS. - Returns one of: `"windows"`, `"macos"`, `"linux"`. ```python from pyloid.utils import get_platform ########## Usage ########## platform_name = get_platform() print(platform_name) # e.g., "windows" ``` **Returns** ## Path Operations ### get_absolute_path Returns the absolute path of the given relative path. ```python from pyloid.utils import get_absolute_path ########## Usage ########## absolute_path = get_absolute_path("assets/icon.ico") print(absolute_path) # e.g., 'C:/Users/aaaap/Documents/pyloid/pyloid/assets/icon.ico' ``` **Parameters** **Returns** ## Networking ### get_free_port Finds and returns an available random network port number from the operating system. - Creates a socket, binds to port `0` (let OS choose), retrieves the port, and closes the socket. - Note: The port may be reassigned to another process after this function returns, so use it quickly. ```python from pyloid.utils import get_free_port ########## Usage ########## port = get_free_port() print(f"Found available port: {port}") # Example: Start a web server on the found port import http.server server = http.server.HTTPServer(('localhost', port), http.server.SimpleHTTPRequestHandler) ``` **Returns** ## Qt Backend ### set_qt_backend Sets the Qt Quick backend to force a specific rendering mode. - Allows changing the Qt Quick rendering backend by setting the `QT_QUICK_BACKEND` environment variable. - Setting it to `'software'` forces software rendering, which can be useful in environments with graphics driver issues or where hardware acceleration is not available. - **Important**: This setting must be applied before the Qt application is initialized. ```python from pyloid.utils import set_qt_backend ########## Usage ########## # Force software rendering (useful for compatibility) set_qt_backend('software') # You can also use other backends like 'opengl' or 'd3d12' if needed # set_qt_backend('opengl') ``` **Production Example** This is typically called at the very beginning of your application, before creating any Pyloid instances: ```python from pyloid.utils import set_qt_backend from pyloid import Pyloid # Set software rendering for better compatibility set_qt_backend('software') app = Pyloid(app_name="MyApp", single_instance=True) # Rest of your application code... ``` **Parameters** **Returns** -------------------------------------------------------------------------------- # API Reference - Pyloid JS ================================================================================ ## File: api/pyloid-js/baseAPI.mdx --- title: BaseAPI --- The `BaseAPI` class provides asynchronous methods to interact with the Pyloid backend via `window.__PYLOID__`. All methods automatically wait for Pyloid initialization before executing. `baseAPI` is an singleton instance of the `BaseAPI` class. --- ## Window Management ### getWindowId Gets the unique identifier for the current window. ```javascript import { baseAPI } from 'pyloid-js'; baseAPI.getWindowId().then((id) => console.log(`Window ID: ${id}`)); ``` **Returns** --- ### getWindowProperties Retrieves properties associated with the current window. ```javascript import { baseAPI } from 'pyloid-js'; baseAPI.getWindowProperties().then((props) => console.log(props)); ``` **Returns** --- ### close Closes the current window. ```javascript import { baseAPI } from 'pyloid-js'; baseAPI.close().then(() => console.log('Window closed.')); ``` **Returns** --- ### hide Hides the current window. ```javascript import { baseAPI } from 'pyloid-js'; baseAPI.hide().then(() => console.log('Window hidden.')); ``` **Returns** --- ### show Shows the current window if it is hidden. ```javascript import { baseAPI } from 'pyloid-js'; baseAPI.show().then(() => console.log('Window shown.')); ``` **Returns** --- ### focus Brings the current window to the foreground and gives it focus. ```javascript import { baseAPI } from 'pyloid-js'; baseAPI.focus().then(() => console.log('Window focused.')); ``` **Returns** --- ### showAndFocus Shows the window (if hidden) and brings it to the foreground with focus. ```javascript import { baseAPI } from 'pyloid-js'; baseAPI.showAndFocus().then(() => console.log('Window shown and focused.')); ``` **Returns** --- ### fullscreen Makes the current window fullscreen. ```javascript import { baseAPI } from 'pyloid-js'; baseAPI.fullscreen().then(() => console.log('Window is now fullscreen.')); ``` **Returns** ### toggleFullscreen Toggles the fullscreen state of the current window. ```javascript import { baseAPI } from 'pyloid-js'; baseAPI.toggleFullscreen().then(() => console.log('Fullscreen toggled.')); ``` **Returns** ### minimize Minimizes the current window. ```javascript import { baseAPI } from 'pyloid-js'; baseAPI.minimize().then(() => console.log('Window minimized.')); ``` **Returns** ### maximize Maximizes the current window. ```javascript import { baseAPI } from 'pyloid-js'; baseAPI.maximize().then(() => console.log('Window maximized.')); ``` **Returns** ### unmaximize Restores the window from a maximized state. ```javascript import { baseAPI } from 'pyloid-js'; baseAPI .unmaximize() .then(() => console.log('Window restored from maximized state.')); ``` **Returns** ### toggleMaximize Toggles the maximized state of the current window. ```javascript import { baseAPI } from 'pyloid-js'; baseAPI.toggleMaximize().then(() => console.log('Maximize toggled.')); ``` **Returns** ### isFullscreen Checks if the current window is in fullscreen mode. ```javascript import { baseAPI } from 'pyloid-js'; baseAPI .isFullscreen() .then((isFullscreen) => console.log(`Is fullscreen: ${isFullscreen}`)); ``` **Returns** ### isMaximized Checks if the current window is maximized. ```javascript import { baseAPI } from 'pyloid-js'; baseAPI .isMaximized() .then((isMaximized) => console.log(`Is maximized: ${isMaximized}`)); ``` **Returns** ### setTitle Sets the title of the current window. ```javascript import { baseAPI } from 'pyloid-js'; baseAPI.setTitle('New Title').then(() => console.log('Title set.')); ``` **Parameters** **Returns** ### setSize Sets the size (width and height) of the current window. ```javascript import { baseAPI } from 'pyloid-js'; baseAPI.setSize(1024, 768).then(() => console.log('Window size set.')); ``` **Parameters** **Returns** ### setPosition Sets the position (x and y coordinates) of the current window. ```javascript import { baseAPI } from 'pyloid-js'; baseAPI.setPosition(100, 100).then(() => console.log('Window position set.')); ``` **Parameters** **Returns** ### setFrame Sets whether the window should have a standard OS frame. ```javascript import { baseAPI } from 'pyloid-js'; baseAPI.setFrame(true).then(() => console.log('Frame set.')); ``` **Parameters** **Returns** ### getFrame Gets the current frame state of the window. ```javascript import { baseAPI } from 'pyloid-js'; baseAPI.getFrame().then((frame) => console.log(`Frame visible: ${frame}`)); ``` **Returns** ### getTitle Gets the current title of the window. ```javascript import { baseAPI } from 'pyloid-js'; baseAPI.getTitle().then((title) => console.log(`Window title: ${title}`)); ``` **Returns** ### getSize Gets the current size (width and height) of the window. ```javascript import { baseAPI } from 'pyloid-js'; baseAPI .getSize() .then((size) => console.log(`Window size: ${size.width}x${size.height}`)); ``` **Returns** ### getPosition Gets the current position (x and y coordinates) of the window. ```javascript import { baseAPI } from 'pyloid-js'; baseAPI .getPosition() .then((position) => console.log(`Window position: (${position.x}, ${position.y})`) ); ``` **Returns** ### setClipboardText Sets the system clipboard text content. ```javascript import { baseAPI } from 'pyloid-js'; baseAPI .setClipboardText('Hello, World!') .then(() => console.log('Clipboard text set.')); ``` **Parameters** **Returns** ### getClipboardText Gets the current text content from the system clipboard. ```javascript import { baseAPI } from 'pyloid-js'; baseAPI .getClipboardText() .then((text) => console.log(`Clipboard text: ${text}`)); ``` **Returns** ### setClipboardImage Sets the system clipboard image content from a file path. ```javascript import { baseAPI } from 'pyloid-js'; baseAPI .setClipboardImage('/path/to/image.png', 'png') .then(() => console.log('Clipboard image set.')); ``` **Parameters** **Returns** ### getClipboardImage Gets the current image content from the system clipboard. ```javascript import { baseAPI } from 'pyloid-js'; baseAPI .getClipboardImage() .then((imageData) => console.log(`Clipboard image data: ${imageData}`)); ``` **Returns** ### quit Quits the entire application. ```javascript import { baseAPI } from 'pyloid-js'; baseAPI.quit().then(() => console.log('Application quit.')); ``` **Returns** ### getPlatform Gets the underlying operating system platform. ```javascript import { baseAPI } from 'pyloid-js'; baseAPI.getPlatform().then((platform) => console.log(`Platform: ${platform}`)); ``` **Returns** ### isProduction Checks if the application is running in production mode. ```javascript import { baseAPI } from 'pyloid-js'; baseAPI .isProduction() .then((isProd) => console.log(`Is production: ${isProd}`)); ``` **Returns** ### getProductionPath Resolves a relative path to an absolute path within the application's production build directory. ```javascript import { baseAPI } from 'pyloid-js'; baseAPI .getProductionPath('assets/image.png') .then((absPath) => console.log(`Absolute path: ${absPath}`)); ``` **Parameters** **Returns** ### getServerUrl Retrieves the server URL. ```javascript import { baseAPI } from 'pyloid-js'; baseAPI.getServerUrl().then((url) => console.log(`server URL: ${url}`)); ``` **Returns** -------------------------------------------------------------------------------- ## File: api/pyloid-js/event.mdx --- title: Event --- This can invoke events from Python to JavaScript. [more guide](/docs/guides/calling-js-from-python). ### Python Backend ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) window = app.create_window(title="My Window") ########## Usage ########## # Invoke the 'hello_event' event with a message window.invoke('hello_event', {'message': 'Hello from Python!'}) ``` ### JavaScript Frontend In JavaScript, you can receive and handle events triggered from Python. You can use the `pyloid-js` library to receive events. ```javascript import { event } from 'pyloid-js'; // Register the event listener event.listen('hello_event', (data) => { console.log('hello_event', data.message); }); // Unregister the event listener event.unlisten('hello_event'); ``` -------------------------------------------------------------------------------- ## File: api/pyloid-js/fetch.mdx --- title: Fetch --- For FastAPI or other HTTP backends, use this [fetch](./fetch) from `pyloid-js`. For PyloidRPC backend, use [rpc](./rpc) instead. The pyloid fetch provides automatic window ID injection and server URL resolution for seamless backend communication. ## Key Features - **Automatic Window ID**: Injects `X-Pyloid-Window-Id` header for request routing - **Server URL Resolution**: Combines relative paths with the Pyloid server URL - **Drop-in Replacement**: Same API as native `fetch()` - works with any HTTP library - **Lazy Initialization**: Automatically waits for Pyloid to be ready ## Basic Usage ### Frontend ```javascript import { fetch } from 'pyloid-js'; // Fetch the 'greet' function to receive a greeting. fetch(`/greet?name=Alice`) .then(response => response.text()) .then(data => console.log(data)); ``` ### Backend 1. Create a server instance 2. Create a start server function 3. Create a setup cors function 4. Create an adapter instance and pass the start and setup cors functions 5. Pass the adapter instance to the server parameter of the Pyloid class if you want to access the pyloid context, you can use the `adapter.get_context(window_id)` function. if you want to check if the request is a pyloid request, you can use the `adapter.is_pyloid(window_id)` function. ```python tab="src-pyloid/server.py" from pyloid_adapter import BaseAdapter, PyloidContext from fastapi import FastAPI from fastapi import Request from fastapi.middleware.cors import CORSMiddleware # 1. Create a server instance app = FastAPI() # 2. Create a start server function def start(host: str, port: int): import uvicorn uvicorn.run(app, host=host, port=port) # 3. Create a setup cors function def setup_cors(): app.add_middleware( CORSMiddleware, allow_origins=['*'], allow_credentials=True, allow_methods=['*'], allow_headers=['*'], ) # 4. Create an adapter instance and pass the start and setup cors functions adapter = BaseAdapter(start, setup_cors) @app.get('/greet') async def greet(name: str): return f'Hello, {name}!' @app.get('/create_window') async def create_window(request: Request): window_id = request.headers.get("X-Pyloid-Window-Id") if adapter.is_pyloid(window_id): print("pyloid request") else: print("not pyloid request") ctx: PyloidContext = adapter.get_context(window_id) win = ctx.pyloid.create_window(title='Google Window') win.load_url('https://www.google.com') win.show_and_focus() ``` ```python tab="src-pyloid/main.py" from pyloid import Pyloid from server import adapter # 5. Pass the adapter instance to the server parameter of the Pyloid class app = Pyloid(app_name="Pyloid-App", single_instance=True, server=adapter) window = app.create_window(title="Pyloid Browser-dev") window.load_url("http://localhost:5173") # Load the local development frontend url window.show_and_focus() app.run() ``` this example is for fastapi backend. you can use any server backend. -------------------------------------------------------------------------------- ## File: api/pyloid-js/ipc.mdx --- title: IPC --- The `ipc` object enables communication between JavaScript and Python via Inter-Process Communication. It allows JavaScript code to call methods defined in [PyloidIPC](/docs/api/pyloid/pyloidipc) classes that are registered with the Pyloid window. --- ## Usage ### Accessing IPC Classes IPC classes registered in Python can be accessed through the `ipc` object using the class name. ```javascript import { ipc } from 'pyloid-js'; // Access the CustomIPC class methods ipc.CustomIPC.echo('Hello, Pyloid!').then(result => { console.log(result); // "Message received in Python: Hello, Pyloid!" }); ``` ### Calling IPC Methods IPC methods return Promises that resolve with the return value from the Python method. ```javascript import { ipc } from 'pyloid-js'; // Call methods with parameters ipc.CustomIPC.add(5, 3).then(sum => { console.log(sum); // 8 }); // Call methods without parameters ipc.CustomIPC.create_window().then(windowId => { console.log(windowId); // "eae338a3-c8cb-4103-852f-404486beea0d" }); ``` --- ## Example ### Python Backend ```python from pyloid import Pyloid from pyloid.ipc import PyloidIPC, Bridge app = Pyloid('Pyloid-App') class CustomIPC(PyloidIPC): @Bridge(str, result=str) def echo(self, message): return f'Message received in Python: {message}' @Bridge(int, int, result=int) def add(self, a, b): return a + b @Bridge(result=str) def create_window(self): win = self.pyloid.create_window(title='Pyloid Browser') win.load_url('https://www.google.com') win.show() win.focus() return win.get_id() # Create main window with IPC window = app.create_window( title='Pyloid Browser', ipc=[CustomIPC()], ) window.load_file('index.html') window.show() window.focus() app.run() ``` ### JavaScript Frontend ```javascript import { ipc } from 'pyloid-js'; // Call IPC methods async function runExample() { try { // Echo message const result = await ipc.CustomIPC.echo('Hello, Pyloid!'); console.log(result); // "Message received in Python: Hello, Pyloid!" // Add numbers const sum = await ipc.CustomIPC.add(5, 3); console.log(sum); // 8 // Create new window const windowId = await ipc.CustomIPC.create_window(); console.log(windowId); // "eae338a3-c8cb-4103-852f-404486beea0d" } catch (error) { console.error('IPC call failed:', error); } } runExample(); ``` --- ## Error Handling IPC calls can fail due to various reasons. Always handle errors appropriately: ```javascript import { ipc } from 'pyloid-js'; ipc.CustomIPC.someMethod('param') .then(result => { console.log('Success:', result); }) .catch(error => { console.error('IPC call failed:', error); }); ``` Or using async/await: ```javascript import { ipc } from 'pyloid-js'; async function callIPC() { try { const result = await ipc.CustomIPC.someMethod('param'); console.log('Success:', result); } catch (error) { console.error('IPC call failed:', error); } } ``` -------------------------------------------------------------------------------- ## File: api/pyloid-js/rpc.mdx --- title: RPC --- For PyloidRPC backend, use this [rpc](./rpc) from `pyloid-js`. For FastAPI or other HTTP backends, use [fetch](./fetch) instead. ### Frontend Calling RPC Functions from JavaScript ```javascript import { rpc } from 'pyloid-js'; // Call the 'greet' RPC function to receive a greeting. rpc .call('greet', { name: 'Alice' }) .then((response) => { console.log(response); // Outputs "Hello, Alice!" }) .catch((error) => { console.error('Error occurred during RPC call:', error); }); ``` ### Backend All RPC functions must be defined as asynchronous (async) functions and registered with the `method()` decorator. Additionally, if you add `ctx` [(RPCContext)](/docs/api/pyloid/pyloidrpc#rpccontext) as the first argument, you can access the current app and window objects. ```python tab="src-pyloid/server.py" from pyloid.rpc import PyloidRPC, RPCContext server = PyloidRPC() @server.method() async def greet(name: str): return f"Hello, {name}!" @server.method() async def create_window(ctx: RPCContext): win = ctx.pyloid.create_window(title="Google Window") win.load_url("https://www.google.com") win.show_and_focus() ``` ```python tab="src-pyloid/main.py" from pyloid import Pyloid from server import server app = Pyloid(app_name="Pyloid-App", single_instance=True, server=server) # server is the PyloidRPC instance window = app.create_window(title="Pyloid Browser-dev") window.load_url("http://localhost:5173") # Load the local development frontend url window.show_and_focus() app.run() ``` -------------------------------------------------------------------------------- # API Reference - Pyloid Builder ================================================================================ ## File: api/pyloid-builder/optimize.mdx --- title: optimize --- The `optimize` function removes unnecessary files from PyInstaller build output based on spec file patterns to reduce application size. --- ## Function Signature ```python def optimize(base_path: str, spec_file: str) -> None: ``` ## Description Optimizes PyInstaller build output by removing unnecessary files and directories based on patterns defined in a spec file. This significantly reduces the final application size by removing unused Qt libraries, translations, and other bloat. The function provides a rich terminal interface with real-time progress tracking, showing: - Current processing status - Space saved - Files and directories removed - Processing time --- ## Parameters ## Spec File Format The spec file uses a simple text format with the following rules: - **Include patterns**: Files/directories to remove (one per line) - **Exclude patterns**: Files to keep (prefixed with `!`) - **Comments**: Lines starting with `#` are ignored - **Empty lines**: Ignored ### Pattern Examples ```text # Remove all Qt3D libraries PySide6/Qt63D* # Remove Qt Charts PySide6/Qt6Charts* # Remove translations but keep English PySide6/translations/qtwebengine_locales/*.pak !PySide6/translations/qtwebengine_locales/en-US.pak # Remove QML files PySide6/qml # Remove debug resources PySide6/resources/qtwebengine_devtools_resources.pak ``` ### Platform-Specific Spec Files Different platforms have different optimization patterns: - **Windows**: `windows_optimize.spec` - **macOS**: `macos_optimize.spec` - **Linux**: `linux_optimize.spec` --- ## Usage Examples ### Basic Usage ```python from pyloid_builder.optimize import optimize # Optimize Windows build optimize('./dist/MyApp/_internal', './src/build/windows_optimize.spec') # Optimize macOS app bundle optimize('./dist/MyApp.app', './src/build/macos_optimize.spec') ``` ### Complete Build Script ```python from pyloid_builder.pyinstaller import pyinstaller from pyloid_builder.optimize import optimize from pyloid.utils import get_platform # Configuration main_script = './src-pyloid/main.py' name = 'pyloid-app' dist_path = './dist' work_path = './build' # Platform-specific settings if get_platform() == 'windows': icon = './src-pyloid/icons/icon.ico' optimize_spec = './src-pyloid/build/windows_optimize.spec' internal_path = f'{dist_path}/{name}/_internal' elif get_platform() == 'macos': icon = './src-pyloid/icons/icon.icns' optimize_spec = './src-pyloid/build/macos_optimize.spec' internal_path = f'{dist_path}/{name}.app' else: # linux icon = './src-pyloid/icons/icon.png' optimize_spec = './src-pyloid/build/linux_optimize.spec' internal_path = f'{dist_path}/{name}/_internal' # Build with PyInstaller pyinstaller( main_script, [ f'--name={name}', f'--distpath={dist_path}', f'--workpath={work_path}', '--clean', '--noconfirm', '--onedir', '--windowed', '--add-data=./src-pyloid/icons/:./src-pyloid/icons/', '--add-data=./dist-front/:./dist-front/', f'--icon={icon}', ], ) # Optimize the build optimize(internal_path, optimize_spec) ``` --- ## Error Handling The function may raise the following exceptions: - **FileNotFoundError**: When spec file is not found - **FileNotFoundError**: When target directory doesn't exist - **OSError**: When file/directory removal fails All errors are displayed in the terminal with detailed messages. -------------------------------------------------------------------------------- ## File: api/pyloid-builder/pyinstaller.mdx --- title: pyinstaller --- The `pyinstaller` function provides a rich terminal interface for building Pyloid applications with PyInstaller, offering real-time build progress tracking and detailed logging. --- ## Function Signature ```python def pyinstaller(scriptname: str, options: List[str]) -> None: ``` ## Description Executes PyInstaller with enhanced visual feedback and progress monitoring. Unlike standard PyInstaller, this function provides: - **Real-time progress display** with build logs - **Rich terminal interface** with panels and colors - **Dynamic layout** that adapts to terminal size - **Error handling** with detailed failure information - **Success/failure indicators** with appropriate styling The interface splits the terminal into two panels: - **Left panel**: Build information (script name, options) - **Right panel**: Live build log with scrolling --- ## Parameters ## Common PyInstaller Options ### Basic Options | Option | Description | Example | |--------|-------------|---------| | `--name` | Application name | `--name=MyApp` | | `--distpath` | Distribution directory | `--distpath=./dist` | | `--workpath` | Working/build directory | `--workpath=./build` | | `--clean` | Clean cache and temporary files | `--clean` | | `--noconfirm` | Replace output directory without asking | `--noconfirm` | ### Build Mode Options | Option | Description | |--------|-------------| | `--onedir` | Create one-folder bundle (default) | | `--windowed` | Hide console window (GUI apps) | ### Data and Resource Options | Option | Description | Example | |--------|-------------|---------| | `--add-data` | Add data files/directories | `--add-data=src/:dest/` | | `--icon` | Set application icon | `--icon=icon.ico` | | `--hidden-import` | Add hidden imports | `--hidden-import=module` | --- ## Usage Examples ### Basic GUI Application ```python from pyloid_builder.pyinstaller import pyinstaller pyinstaller( 'main.py', [ '--name=MyApp', '--onedir', '--windowed', '--clean', '--noconfirm', ] ) ``` ### Complete Pyloid Application ```python from pyloid_builder.pyinstaller import pyinstaller from pyloid.utils import get_platform # Platform-specific icon if get_platform() == 'windows': icon = './icons/icon.ico' elif get_platform() == 'macos': icon = './icons/icon.icns' else: icon = './icons/icon.png' pyinstaller( './src-pyloid/main.py', [ '--name=pyloid-app', '--distpath=./dist', '--workpath=./build', '--clean', '--noconfirm', '--onedir', '--windowed', '--add-data=./src-pyloid/icons/:./src-pyloid/icons/', '--add-data=./dist-front/:./dist-front/', f'--icon={icon}', ] ) ``` --- ## Integration with Optimize The `pyinstaller` function is typically used together with `optimize`: ```python # 1. Build the application pyinstaller('main.py', build_options) # 2. Optimize the output from pyloid_builder.optimize import optimize optimize('./dist/MyApp/_internal', 'optimize.spec') ``` This workflow provides a complete build and optimization pipeline for Pyloid applications. --- ## Platform-Specific Notes ### Windows - Icon format: `.ico` - Executable extension: `.exe` - Console hiding: `--windowed` option ### macOS - Icon format: `.icns` - Bundle structure: `.app` directory - Code signing may be required for distribution ### Linux - Icon format: `.png` - No extension for executables - May require additional system dependencies -------------------------------------------------------------------------------- # Distribution ================================================================================ ## File: distribute/build.py.mdx --- title: build.py --- Build utilities for creating distributable Pyloid applications using PyInstaller with advanced optimization features. --- ## Overview Pyloid provides two main build utilities: 1. **`pyinstaller`**: Enhanced PyInstaller wrapper with rich terminal interface 2. **`optimize`**: Post-build optimization to reduce application size These utilities work together to create optimized, distributable Pyloid applications for all platforms. --- ## Building Applications ### pyinstaller Builds a PyInstaller application for Pyloid with rich terminal interface and real-time progress monitoring. For complete PyInstaller options, see the [official PyInstaller documentation](https://pyinstaller.org/en/stable/usage.html#options). ```python from pyloid_builder.pyinstaller import pyinstaller ########## Usage ########## # Basic build pyinstaller('main.py', ['--onedir', '--windowed']) # Advanced build with multiple options pyinstaller( 'main.py', [ '--name=MyApp', '--onedir', '--windowed', '--icon=icon.ico', '--add-data=assets:assets', ] ) ``` **Parameters** **Returns** ## Optimizing Builds ### optimize Optimizes PyInstaller build output by removing unnecessary files based on spec file patterns to reduce application size. This function only works with `--onedir` builds, not `--onefile` builds. For detailed optimization options, see the [optimize API documentation](./api/pyloid-builder/optimize). ```python from pyloid_builder.optimize import optimize ########## Usage ########## # Basic optimization optimize('./dist/MyApp/_internal', './build/windows_optimize.spec') # Platform-specific optimization import platform if platform.system() == 'Windows': optimize('./dist/MyApp/_internal', './build/windows_optimize.spec') elif platform.system() == 'Darwin': optimize('./dist/MyApp.app', './build/macos_optimize.spec') else: optimize('./dist/MyApp/_internal', './build/linux_optimize.spec') ``` **Parameters** **Returns** ## Build Scripts ### Basic Build Script ```python tab="build.py" from pyloid_builder.pyinstaller import pyinstaller from pyloid.utils import get_platform # Configuration main_script = './src-pyloid/main.py' name = 'pyloid-app' dist_path = './dist' work_path = './build' # Platform-specific icon if get_platform() == 'windows': icon = './src-pyloid/icons/icon.ico' elif get_platform() == 'macos': icon = './src-pyloid/icons/icon.icns' else: icon = './src-pyloid/icons/icon.png' if __name__ == '__main__': # Build with PyInstaller pyinstaller( main_script, [ f'--name={name}', f'--distpath={dist_path}', f'--workpath={work_path}', '--clean', '--noconfirm', '--onedir', '--windowed', '--add-data=./src-pyloid/icons/:./src-pyloid/icons/', '--add-data=./dist-front/:./dist-front/', f'--icon={icon}', ], ) ``` ### Build with Optimization ```python tab="build.py" from pyloid_builder.pyinstaller import pyinstaller from pyloid_builder.optimize import optimize from pyloid.utils import get_platform # Configuration main_script = './src-pyloid/main.py' name = 'pyloid-app' dist_path = './dist' work_path = './build' # Platform-specific settings if get_platform() == 'windows': icon = './src-pyloid/icons/icon.ico' optimize_spec = './src-pyloid/build/windows_optimize.spec' internal_path = f'{dist_path}/{name}/_internal' elif get_platform() == 'macos': icon = './src-pyloid/icons/icon.icns' optimize_spec = './src-pyloid/build/macos_optimize.spec' internal_path = f'{dist_path}/{name}.app' else: # linux icon = './src-pyloid/icons/icon.png' optimize_spec = './src-pyloid/build/linux_optimize.spec' internal_path = f'{dist_path}/{name}/_internal' if __name__ == '__main__': # Step 1: Build with PyInstaller pyinstaller( main_script, [ f'--name={name}', f'--distpath={dist_path}', f'--workpath={work_path}', '--clean', '--noconfirm', '--onedir', '--windowed', '--add-data=./src-pyloid/icons/:./src-pyloid/icons/', '--add-data=./dist-front/:./dist-front/', f'--icon={icon}', ], ) # Step 2: Optimize the build optimize(internal_path, optimize_spec) print(f"✅ {name} built and optimized successfully!") ``` ## Build Options ### Common PyInstaller Options | Option | Description | |--------|-------------| | `--onedir` | Create a single directory bundle (recommended) | | `--windowed` | Create a windowed application (no console) | | `--console` | Create a console application | | `--icon=file.ico` | Set application icon | | `--name=AppName` | Set application name | | `--clean` | Clean cache and temporary files | | `--noconfirm` | Replace output directory without confirmation | | `--add-data=src:dst` | Add additional data files | | `--hidden-import=module` | Include hidden imports | ### Spec File Format Optimization uses spec files that define which files to remove. Create platform-specific spec files: **windows_optimize.spec:** ```text PySide6/translations/*.qm PySide6/translations/qtwebengine_locales/*.pak !PySide6/translations/qtwebengine_locales/en-US.pak PySide6/qml PySide6/Qt63D* PySide6/Qt6Charts* PySide6/Qt6DataVisualization* # ... etc ``` **macos_optimize.spec:** ```text Contents/Frameworks/PySide6/Qt/lib/Qt3D* Contents/Frameworks/PySide6/Qt/lib/QtCharts* Contents/Resources/PySide6/Qt/qml Contents/Resources/PySide6/Qt/translations # ... etc ``` ### Common Optimization Targets | Category | Examples | Purpose | |----------|----------|---------| | **Qt Components** | `Qt63D*`, `Qt6Charts*`, `Qt6Multimedia*` | Remove unused Qt libraries | | **Translations** | `*.qm`, `qtwebengine_locales/*.pak` | Keep only essential locales | | **QML Files** | `qml/` | Remove if not using QML | | **Debug Files** | `*.pdb`, `*_debug.*` | Remove debug symbols | | **Python StdLib** | `tcl/`, `tk/`, `test_*` | Remove unused standard library parts | ### Platform-Specific Considerations **Windows:** - Target: `dist/AppName/_internal/` - Remove: Qt DLLs, debug files, unused translations **macOS:** - Target: `dist/AppName.app/` - Remove: Framework libraries, QML resources, translations **Linux:** - Target: `dist/AppName/_internal/` - Similar to Windows but may include additional system libraries ### Running Builds ```bash tab="npm" npm run build ``` ```bash tab="pnpm" pnpm run build ``` ```bash tab="yarn" yarn run build ``` ```bash tab="bun" bun run build ``` ## Troubleshooting ### PyInstaller Issues **Build fails with import errors:** - Use `--hidden-import` to include missing modules - Check that all dependencies are installed in the build environment **Application won't start:** - Ensure all data files are included with `--add-data` - Check that the main script path is correct - Verify that required DLLs/.so files are not removed during optimization **Large bundle size:** - Use the `optimize` function with appropriate spec files - Review included packages and remove unnecessary ones **Icon not showing:** - Ensure the icon path is correct and the file exists - Use platform-appropriate icon formats (.ico for Windows, .icns for macOS, .png for Linux) ### Optimization Issues **Optimization removes required files:** - Check spec file patterns - use exclude patterns (`!`) to protect important files - Test the application after optimization to ensure it still works - Start with minimal optimization and gradually add more patterns **Spec file not found:** - Ensure spec files exist in the correct location - Check file paths in your build script - Use absolute paths if relative paths cause issues **Optimization takes too long:** - Large applications may take time to scan - Consider excluding large directories from scanning - Use more specific patterns instead of broad wildcards **Application crashes after optimization:** - Some Qt libraries might be required even if not directly used - Check for missing dependencies in error logs - Adjust spec file to be less aggressive ### Platform-Specific Issues **Windows:** - Ensure Visual C++ redistributables are handled correctly - Check that all required DLLs are preserved - Icon format must be .ico **macOS:** - Code signing may be required for distribution - Ensure app bundle structure is maintained - Check Info.plist requirements **Linux:** - System libraries may need to be included - Check for missing .so files - Ensure proper permissions on executable -------------------------------------------------------------------------------- # Guides ================================================================================ ## File: guides/autostart.mdx --- title: Auto Start --- You can use the `app.set_auto_start()` function to set whether the application should start automatically when the user logs in. The [`app_name` of the Pyloid class](/docs/api/pyloid/pyloid#initialization) is used as the key name for auto-start. ```python app.set_auto_start(True) # Enable auto-start app.set_auto_start(False) # Disable auto-start ``` This function takes a boolean value as an argument. If the value is `True`, the application will start automatically when computer loged in. If the value is `False`, the application will not start automatically. ## Notes - `set_auto_start(True)` only works in production environments. - `set_auto_start(False)` works in all environments. - Calling `set_auto_start(True)` in a non-production environment will print a warning message and return `None`. ## Checking Auto-start Status You can use the `app.is_auto_start()` function to check the current auto-start setting status. ```python is_auto_start = app.is_auto_start() print(is_auto_start) # Prints True or False ``` This function returns `True` if auto-start is enabled, and `False` otherwise. ## Using app_name from the Pyloid class The `app_name` defined in the Pyloid class plays an important role in the auto-start feature. This `app_name` is used as a key to identify the application in the operating system's auto-start registry or settings. Therefore, it's important to set the `app_name` to something unique and meaningful. For example: ```python from pyloid import Pyloid app = Pyloid(app_name="MyUniqueApp") app.set_auto_start(True) ``` In this case, the name "MyUniqueApp" is used as the key in the auto-start settings. This allows you to distinguish between multiple applications and manage auto-start individually for each one. -------------------------------------------------------------------------------- ## File: guides/calling-js-from-python.mdx --- title: Calling JavaScript from Python --- Pyloid provides a mechanism for calling JavaScript functions from Python through events. This guide explains how to invoke JavaScript event handlers from Python backend code. ## 1. Event System Overview The event system in Pyloid allows the Python backend to trigger events that can be captured and handled by the JavaScript frontend. This creates a communication channel from the backend to the frontend. ## 2. Invoking Events from Python In the Python backend, you can use the `invoke()` method to trigger events that will be received by the JavaScript frontend: ```python app = Pyloid(app_name="Pyloid-App") window = app.create_window("pyloid-window") # Invoke an event named 'hello_event' with data window.invoke('hello_event', {'message': 'Hello from Python!'}) ``` The first parameter is the event name that JavaScript will listen for, and the second parameter is the data payload to send with the event. The data can be any JSON-serializable object. ## 3. Handling Events in JavaScript In the JavaScript frontend, you need to set up event listeners to capture and respond to events triggered from Python: ```javascript import { event } from 'pyloid-js'; // Register an event listener for 'hello_event' event.listen('hello_event', (data) => { console.log('Received hello_event with message:', data.message); // Handle the event data here }); ``` ## 4. Removing Event Listeners When you no longer need an event listener, you should clean it up to prevent memory leaks: ```javascript import { event } from 'pyloid-js'; // Unregister the event listener event.unlisten('hello_event'); ``` ## Use Cases The event system is useful for various scenarios: - Notifying the frontend of backend state changes - Sending real-time updates from long-running Python processes - Pushing notifications from the backend to the user interface - Coordinating UI updates based on backend processing results ## Notes - Events are one-way communications from Python to JavaScript - For two-way communication, combine events with PyloidRPC or server - Event names should be consistent between Python and JavaScript -------------------------------------------------------------------------------- ## File: guides/calling-python-from-js.mdx --- title: Calling Python from JavaScript --- you can use [PyloidRPC](/docs/api/pyloid-js/rpc) or [server frameworks](/docs/api/pyloid-js/fetch) or [IPC](/docs/api/pyloid/pyloidipc) to call Python functions from JavaScript. -------------------------------------------------------------------------------- ## File: guides/clipboard.mdx --- title: Clipboard --- Pyloid provides easy-to-use clipboard functionality. You can copy text and images to the clipboard or retrieve them from the clipboard. ## Methods [methods here](/docs/api/pyloid/pyloid#clipboard) -------------------------------------------------------------------------------- ## File: guides/desktop-monitor.mdx --- title: Desktop Monitor --- ## Overview You can obtain monitor objects using the `app.get_primary_monitor()` or `app.get_all_monitors()` methods. Through these monitor objects, you can perform various functions and utilize several methods of the `Monitor` object to query or modify the properties and states of the monitor. ## Methods [methods here](/docs/api/pyloid/monitor). -------------------------------------------------------------------------------- ## File: guides/devtools-settings.mdx --- title: DevTools Settings --- Pyloid allows you to configure developer tools in two ways. You can specify them as parameters when creating a window, or use a method to set them after the window has been created. When developer tools are activated, you can open them using the `F12` key. ## 1. Setting as a Parameter When Creating a Window You can set the developer tools using the `dev_tools` parameter when creating a window. The default value for this parameter is `False`. ```python tab="Partial Code" window = app.create_window( title="Pylon Browser", dev_tools=True # Activate developer tools (default is False) ) ``` ```python tab="Full Code" from pyloid import Pyloid app = Pyloid(app_name="Pyloid-App", single_instance=True) window = app.create_window( title="Pyloid Browser", dev_tools=True # Activate developer tools (default is False) ) window.load_url("https://www.example.com") window.show_and_focus() app.run() ``` ## 2. Setting Using a Method You can set the developer tools using the `set_dev_tools()` method after creating a window. ```python tab="Partial Code" window = app.create_window( title="Pyloid Browser", ) window.set_dev_tools(True) # Activate developer tools ``` ```python tab="Full Code" from pyloid import Pyloid app = Pyloid(app_name="Pyloid-App", single_instance=True) window = app.create_window( title="Pyloid Browser", ) window.set_dev_tools(True) # Activate developer tools window.load_url("https://www.example.com") window.show_and_focus() app.run() ``` This method is useful when you want to dynamically change the state of the developer tools based on conditions after creating the window. ## Accessing Developer Tools via F12 Key Setting `dev_tools=True` allows users to open the developer tools by pressing the `F12` key. This is the same method as used in web browsers and provides a familiar way for developers to access the tools. -------------------------------------------------------------------------------- ## File: guides/file-dialog.mdx --- title: File Dialog --- ## Overview This document explains how to open a file dialog and select files or directories. This functionality is implemented using PySide's `QFileDialog` class. This document covers three methods: `open_file_dialog`, `save_file_dialog`, and `select_directory_dialog`. ## Methods [methods here](/docs/api/pyloid/pyloid#file-dialogs). -------------------------------------------------------------------------------- ## File: guides/filewatcher.mdx --- title: File Watcher --- The File Watcher provides functionality to monitor changes in specific files or directories. This allows you to receive automatic notifications when files or directories are modified. ## Basic Usage ### Start Watching a File To monitor changes in a specific file, use the following: ```python tab="Partial Code" result = app.watch_file("path/file.txt") if result: print("File watching started") else: print("Failed to start file watching") ``` ```python tab="Full Code" from pyloid import Pyloid app = Pyloid(app_name="Pyloid-App", single_instance=True) window = app.create_window( title="Pyloid Browser", ) window.load_url("https://www.example.com") window.show_and_focus() result = app.watch_file("/path/file.txt") if result: print("File watching started") else: print("Failed to start file watching") app.run() ``` ### Start Watching a Directory To monitor changes in a specific directory, use the following: ```python tab="Partial Code" result = app.watch_directory("/path/directory") if result: print("Directory watching started") else: print("Failed to start directory watching") ``` ```python tab="Full Code" from pyloid import Pyloid app = Pyloid(app_name="Pyloid-App", single_instance=True) window = app.create_window( title="Pyloid Browser", ) window.load_url("https://www.example.com") window.show_and_focus() result = app.watch_directory("/path/directory") if result: print("Directory watching started") else: print("Failed to start directory watching") app.run() ``` ### Set File Change Callback You can set a callback function to be executed when a file is changed: ```python tab="Partial Code" def on_file_changed(path): print(f"File has been changed: {path}") app.set_file_change_callback(on_file_changed) ``` ```python tab="Full Code" from pyloid import Pyloid app = Pyloid(app_name="Pyloid-App", single_instance=True) window = app.create_window( title="Pyloid Browser", ) window.load_url("https://www.example.com") window.show_and_focus() app.watch_file("/path/file.txt") # Define callback function def on_file_changed(path): print(f"File has been changed: {path}") # Set callback function app.set_file_change_callback(on_file_changed) app.run() ``` ### Set Directory Change Callback You can set a callback function to be executed when a directory is changed: ```python tab="Partial Code" def on_directory_changed(path): print(f"Directory has been changed: {path}") app.set_directory_change_callback(on_directory_changed) ``` ```python tab="Full Code" from pyloid import Pyloid app = Pyloid(app_name="Pyloid-App", single_instance=True) window = app.create_window( title="Pyloid Browser", ) window.load_url("https://www.example.com") window.show_and_focus() app.watch_directory("/path/directory") # Define callback function def on_directory_changed(path): print(f"Directory has been changed: {path}") # Set callback function app.set_directory_change_callback(on_directory_changed) app.run() ``` ### Stop Watching To stop watching a specific file or directory, use the following: ```python tab="Partial Code" result = app.stop_watching("/path/to/file_or_directory") if result: print("Watching stopped successfully") else: print("Failed to stop watching") ``` ```python tab="Full Code" from pyloid import Pyloid app = Pyloid(app_name="Pyloid-App", single_instance=True) window = app.create_window( title="Pyloid Browser", ) window.load_url("https://www.example.com") window.show_and_focus() result = app.stop_watching("/path/to/file_or_directory") if result: print("Watching stopped successfully") else: print("Failed to stop watching") app.run() ``` ### Check Watched Paths To check all currently watched paths (files and directories), use the following: ```python tab="Partial Code" watched_paths = app.get_watched_paths() print("All watched paths:", watched_paths) ``` ```python tab="Full Code" from pyloid import Pyloid app = Pyloid(app_name="Pyloid-App", single_instance=True) window = app.create_window( title="Pyloid Browser", ) window.load_url("https://www.example.com") window.show_and_focus() watched_paths = app.get_watched_paths() print("All watched paths:", watched_paths) app.run() ``` ### Get Only Watched Files ```python tab="Partial Code" watched_files = app.get_watched_files() print("Watched files:", watched_files) ``` ```python tab="Full Code" from pyloid import Pyloid app = Pyloid(app_name="Pyloid-App", single_instance=True) window = app.create_window( title="Pyloid Browser", ) window.load_url("https://www.example.com") window.show_and_focus() watched_files = app.get_watched_files() print("Watched files:", watched_files) app.run() ``` ### Get Only Watched Directories ```python tab="Partial Code" watched_directories = app.get_watched_directories() print("Watched directories:", watched_directories) ``` ```python tab="Full Code" from pyloid import Pyloid app = Pyloid(app_name="Pyloid-App", single_instance=True) window = app.create_window( title="Pyloid Browser", ) window.load_url("https://www.example.com") window.show_and_focus() watched_directories = app.get_watched_directories() print("Watched directories:", watched_directories) app.run() ``` ### Remove All Watched Paths ```python tab="Partial Code" app.remove_all_watched_paths() print("All watched paths have been removed.") ``` ```python tab="Full Code" from pyloid import Pyloid app = Pyloid(app_name="Pyloid-App", single_instance=True) window = app.create_window( title="Pyloid Browser", ) window.load_url("https://www.example.com") window.show_and_focus() # Remove all watched paths app.remove_all_watched_paths() print("All watched paths have been removed.") app.run() ``` ## Usage Example Here's a comprehensive example of using the File Watcher: ```python # Start watching file and directory app.watch_file("/path/to/file1.txt") app.watch_file("/path/to/file2.txt") app.watch_file("/path/to/file3.txt") app.watch_file("/path/to/file4.txt") app.watch_directory("/path/to/directory1") app.watch_directory("/path/to/directory2") app.watch_directory("/path/to/directory3") app.watch_directory("/path/to/directory4") # Define callback functions def on_file_changed(path): print(f"File changed: {path}") def on_directory_changed(path): print(f"Directory changed: {path}") # Set callback functions app.set_file_change_callback(on_file_changed) app.set_directory_change_callback(on_directory_changed) # Check watched paths print("Watched paths:", app.get_watched_paths()) print("Watched files:", app.get_watched_files()) print("Watched directories:", app.get_watched_directories()) # Stop watching a specific path app.stop_watching("/path/to/file1.txt") app.stop_watching("/path/to/file2.txt") app.stop_watching("/path/to/file3.txt") app.stop_watching("/path/to/file4.txt") app.stop_watching("/path/to/directory1") app.stop_watching("/path/to/directory2") app.stop_watching("/path/to/directory3") app.stop_watching("/path/to/directory4") # Remove all watched paths app.remove_all_watched_paths() ``` ## Precautions - The File Watcher uses system resources, so use it only when necessary and clean up properly when finished. - Watching a large number of files or directories can impact system performance, so use caution. - Some file systems or operating systems may not detect certain types of changes. This guide should help you understand the basic usage and advanced features of the File Watcher. If you have any additional questions or need further assistance, please don't hesitate to ask. -------------------------------------------------------------------------------- ## File: guides/keyboard-shotcuts.mdx --- title: Keyboard Shortcuts --- ## Adding and Managing Shortcuts This section explains how to add and manage keyboard shortcuts in a Pyloid application. ### Adding Shortcuts You can add new shortcuts using the `window.add_shortcut()` method. ```python window.add_shortcut("shortcut", lambda: (action1, action2, ...)) ``` **Example** ```python window.add_shortcut("Ctrl+Shift+S", lambda: ( print("Ctrl+Shift+S shortcut was pressed."), )) ``` **Example using a regular function** ```python def handle_shortcut(): print("Ctrl+Shift+F shortcut was pressed.") print("Current time:", datetime.now()) window.add_shortcut("Ctrl+Shift+F", handle_shortcut) ``` ### Removing Shortcuts You can remove existing shortcuts using the `window.remove_shortcut()` method. ```python window.remove_shortcut("") ``` **Example** ```python window.remove_shortcut("Ctrl+Shift+F") ``` ### Viewing All Shortcuts You can view all currently registered shortcuts using the `window.get_all_shortcuts()->Dict` method. **Example** ```python print(window.get_all_shortcuts()) ``` ### Triggering Events You can trigger [JavaScript events](/docs/api/pyloid-js/event) through shortcuts. ```python window.add_shortcut("shortcut", lambda: ( window.invoke('eventName', { "data": 'value' }) )) ``` **Example** ```python window.add_shortcut("Ctrl+Shift+E", lambda: ( print("Ctrl+Shift+E shortcut was pressed."), window.invoke('pythonEvent', { "message": 'Hello from Python!' }) )) ``` -------------------------------------------------------------------------------- ## File: guides/load-webview.mdx --- title: Load Webview --- ### load_url (Load URL) ```python app = Pyloid(app_name="Pyloid-App") window = app.create_window("Pyloid-Window") window.load_url("https://www.example.com") window.show() ``` ### load_file (Load File) ```python app = Pyloid(app_name="Pyloid-App") window = app.create_window("Pyloid-Window") window.load_file("./index.html") window.show() ``` ### load_html (Load HTML) ```python app = Pyloid(app_name="Pyloid-App") window = app.create_window("Pyloid-Window") window.load_html("

Hello, Pyloid!

") window.show() ``` -------------------------------------------------------------------------------- ## File: guides/notification.mdx --- title: Notification --- You can display notifications to users using the `show_notification()` method of Pyloid. ## Methods [methods here](/docs/api/pyloid/pyloid#notification). -------------------------------------------------------------------------------- ## File: guides/position.mdx --- title: Position --- ### 1. Using parameters when creating a window ```python app = Pyloid(app_name="Pyloid-App") window = app.create_window("Pyloid-Window", x=100, y=100) ``` ### 2. Using the set_position method The window position is determined by the `x` and `y` parameters. ```python app = Pyloid(app_name="Pyloid-App") window = app.create_window("Pyloid-Window") window.set_position(x=100, y=100) ``` ### 3. Using the set_position_by_anchor method The window position is determined by the `anchor` parameter. The position is set based on the available screen space (excluding the taskbar). Available anchor positions: - `top` - `left` - `right` - `bottom` - `top-left` - `top-right` - `bottom-left` - `bottom-right` - `center` ```python app = Pyloid(app_name="Pyloid-App") window = app.create_window("Pyloid-Window") window.set_position_by_anchor("center") ``` -------------------------------------------------------------------------------- ## File: guides/production-utils.mdx --- title: Production Utils --- Pyloid provides several utility functions to help with production and development environments, platform detection, and other common tasks. Especially get_production_path is very important. ## Utilities [Utils here](/docs/api/pyloid/utils) -------------------------------------------------------------------------------- ## File: guides/serve-frontend.mdx --- title: Serve Frontend(Static Files) --- Pyloid provides functionality to easily serve web-based UIs. Using the `pyloid_serve` function from the `pyloid.serve` module, you can serve static files from a local HTTP server. The server uses dynamic port allocation by default, automatically finding an available port on your system. ## Basic Usage use [pyloid_serve](/docs/api/pyloid/serve#pyloid_serve) function to serve static files. -------------------------------------------------------------------------------- ## File: guides/splash-screen.mdx --- title: Splash Screen --- Provides splash screen functionality displayed during application loading. ## Basic Usage ### 1. Splash Screen Setup #### Static Image Splash Screen ```python app = Pyloid(app_name="Pyloid-App") window = app.create_window("Splash Screen Example") window.set_static_image_splash_screen(image_path="./assets/loading.png") ``` #### Parameters - `image_path`: Image file path - `close_on_load`: Auto-close on page load completion (default: True) - `stay_on_top`: Always display on top (default: True) - `clickable`: Allow closing by click (default: True) - `position`: Splash screen position (default: "center") - Supported positions: "center", "top-left", "top-right", "bottom-left", "bottom-right" #### GIF Splash Screen ```python window.set_gif_splash_screen(gif_path="./assets/loading.gif") ``` #### Parameters - `gif_path`: GIF file path - `close_on_load`: Auto-close on page load completion (default: True) - `stay_on_top`: Always display on top (default: True) - `clickable`: Allow closing by click (default: True) - `position`: Splash screen position (default: "center") - Supported positions: "center", "top-left", "top-right", "bottom-left", "bottom-right" ### 2. Splash Screen Control #### Manually Close Splash Screen ```python window.close_splash_screen() ``` #### Timer Control Example ```python from pyloid.timer import PyloidTimer # ... assuming window object is already created def close_splash_and_show_main(): window.close_splash_screen() window.show_and_focus() # Create timer manager timer_manager = PyloidTimer() # Close splash screen and show main window after 3 seconds timer_manager.start_single_shot_timer(3000, close_splash_and_show_main) ``` ## Usage Scenarios 1. **Initial Loading Screen** - Loading resources at application start - Database connection - External API initialization 2. **Display During Long Operations** - Large file processing - Network operations - Complex calculations ## Precautions 1. Optimize GIF files with appropriate size and quality 2. Manual splash screen closure required when `close_on_load=False` -------------------------------------------------------------------------------- ## File: guides/timer.mdx --- title: Timer --- `PyloidTimer` is a convenient timer management class based on PySide6's QTimer. It allows you to easily create and manage various types of timers. ## PyloidTimer more info in [PyloidTimer](/docs/api/pyloid/pyloidtimer) -------------------------------------------------------------------------------- ## File: guides/tray.mdx --- title: Tray --- Pyloid makes it easy to implement system tray functionality. This guide explains how to set up a tray icon, handle events, add menu items, animate the icon, and set tooltips. All tray-related features work dynamically, allowing real-time changes even while the app is running. ## Setting the Tray Icon Use the set_tray_icon method to set the tray icon. This method can be called at any time to change the icon: ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) ########## Usage ########## app.set_tray_icon("icons/icon.ico") ``` Note: This method can be called while the app is running, allowing you to change the icon dynamically based on different conditions. ## Animating the Tray Icon You can apply animations to the tray icon. Use the set_tray_icon_animation method to display multiple icon frames sequentially: ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) ########## Usage ########## app.set_tray_icon_animation( [ "icons/frame1.png", "icons/frame2.png", "icons/frame3.png", "icons/frame4.png", ], interval=500, ) ``` This setting can be changed during runtime, and you can revert to a regular icon at any time. ## Setting the Tray Icon Tooltip You can set a tooltip that appears when hovering over the tray icon. Use the set_tray_tooltip method: ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) ########## Usage ########## app.set_tray_tooltip("This is a Pyloid application.") ``` The tooltip can also be dynamically changed at any time during app execution. ## Handling Tray Events You can handle various click events on the tray icon. Use the set_tray_actions method to set event handlers. This setting can also be changed at any time: ```python from pyloid import Pyloid from pyloid.tray import TrayEvent app = Pyloid(app_name="MyApp", single_instance=True) ########## Usage ########## app.set_tray_actions( { TrayEvent.DoubleClick: lambda: print("Tray icon was double-clicked."), TrayEvent.MiddleClick: lambda: print("Tray icon was middle-clicked."), TrayEvent.RightClick: lambda: print("Tray icon was right-clicked."), TrayEvent.LeftClick: lambda: print("Tray icon was left-clicked."), } ) ``` Note: Event handlers can be dynamically added, modified, or removed during app execution. ## Adding and Dynamically Updating Tray Menu Items You can add items to the context menu that appears when right-clicking the tray icon. Use the set_tray_menu_items method to set menu items. This menu configuration can also be changed in real-time: ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) ########## Usage ########## app.set_tray_menu_items( [ {"label": "Show Window", "callback": lambda: app.show_and_focus_main_window()}, {"label": "Exit", "callback": lambda: app.quit()}, ] ) ``` Each menu item is defined as a dictionary with `label` and `callback` keys. Menu items can be dynamically added, modified, or removed while the app is running. Example of dynamically updating the menu: ```python from pyloid import Pyloid app = Pyloid(app_name="MyApp", single_instance=True) ########## Usage ########## def update_menu(): app.set_tray_menu_items( [ { "label": "New Menu 1", "callback": lambda: print("New Menu 1 clicked"), }, { "label": "New Menu 2", "callback": lambda: print("New Menu 2 clicked"), }, {"label": "Exit", "callback": lambda: app.quit()}, ] ) # Update tray menu after 5 seconds timer.start_single_shot_timer(5000, update_menu) ``` ## Production Example Here's a production example implementing tray functionality. It demonstrates that all settings can be changed dynamically for production, you should use the get_production_path function to get the path to the resource file. ```python from pyloid import Pyloid from pyloid.tray import TrayEvent from pyloid.timer import PyloidTimer from pyloid.utils import is_production, get_production_path app = Pyloid("Pyloid-App", single_instance=True) timer = PyloidTimer() # Set the icon and tray icon app.set_icon(get_production_path("icon.ico")) app.set_tray_icon(get_production_path("icon.ico")) # Set the tray actions app.set_tray_actions( { TrayEvent.DoubleClick: lambda: print("Tray icon was double-clicked."), TrayEvent.MiddleClick: lambda: print("Tray icon was middle-clicked."), TrayEvent.RightClick: lambda: print("Tray icon was right-clicked."), TrayEvent.LeftClick: lambda: print("Tray icon was left-clicked."), } ) # Set the tray menu items app.set_tray_menu_items( [ {"label": "Show Window", "callback": lambda: app.show_and_focus_main_window()}, {"label": "Exit", "callback": lambda: app.quit()}, ] ) # Set the tray tooltip app.set_tray_tooltip("This is a Pyloid application.") # Update the tray menu items def update_menu(): app.set_tray_menu_items( [ { "label": "New Menu 1", "callback": lambda: print("New Menu 1 clicked"), }, { "label": "New Menu 2", "callback": lambda: print("New Menu 2 clicked"), }, {"label": "Exit", "callback": lambda: app.quit()}, ] ) # Update the tray icon def update_tray_icon(): # Set tray icon animation app.set_tray_icon_animation( [ get_production_path("frame1.png"), get_production_path("frame2.png"), get_production_path("frame3.png"), get_production_path("frame4.png"), ], interval=500, ) # Update the tray menu after 5 seconds timer.start_single_shot_timer(5000, update_menu) # Start the tray icon animation after 3 seconds timer.start_single_shot_timer(3000, update_tray_icon) # Change the tray icon to static icon after 6 seconds timer.start_single_shot_timer(6000, lambda: app.set_tray_icon("assets/icon.ico")) # Change the tray icon tooltip after 10 seconds timer.start_single_shot_timer(10000, lambda: app.set_tray_tooltip("New tooltip!")) ``` This example demonstrates setting the tray icon, handling events, adding menu items, animating the icon, and setting tooltips. All settings can be changed dynamically while the app is running, allowing you to update tray functionality in real-time as needed. -------------------------------------------------------------------------------- ## File: guides/video.mdx --- title: Video --- Pyloid is based on Qt WebEngine, which **only supports open-source codecs**. This is a policy to avoid patent issues, so proprietary codecs like MP4/H.264 are not supported. When you need to play videos in your web application, you must use videos encoded with open-source codecs. ## Supported Video Codecs The open-source video codecs supported by Pyloid (Qt WebEngine) are: - **VP8** - Used in WebM containers - **VP9** - Used in WebM containers (improved compression over VP8) - **WebM** - Container format using VP8 or VP9 codecs ## Unsupported Video Codecs The following codecs are **not supported** due to patent issues: - **MP4/H.264** - The most widely used codec but protected by patents - **H.265/HEVC** - Successor to H.264 - Other proprietary codecs ## Basic Usage You can play WebM format videos using the HTML5 `