### Pyloid Build Configuration Example
Source: https://github.com/pyloid/docs/blob/main/getting-started/create-pyloid-app.md
An example of a `build_config.json` file showing how icon formats are automatically set based on the operating system.
```json
{
"iconFormat": {
"windows": ".ico",
"macos": ".icns",
"linux": ".png"
}
}
```
--------------------------------
### Running a Pyloid Project with bun
Source: https://github.com/pyloid/docs/blob/main/getting-started/create-pyloid-app.md
These commands navigate to the project directory, install dependencies, and start the development server using bun.
```bash
cd project-name
bun run setup
bun run dev
```
--------------------------------
### Complete RPC Example
Source: https://github.com/pyloid/docs/blob/main/api/python-backend/rpc.md
A complete example that shows how to set up an RPC server with the static file server. It includes initializing RPC, defining an RPC method, initializing Pyloid, creating a window with RPC enabled, loading the frontend, and starting the application.
```Python
from pyloid import Pyloid
from pyloid.rpc import PyloidRPC, RPCContext
from pyloid.serve import pyloid_serve
# Initialize RPC
rpc = PyloidRPC()
@rpc.method()
async def get_window_info(ctx: RPCContext):
return {
"id": ctx.window.get_id(),
"window_title": ctx.window.get_title(),
"size": ctx.window.get_size(),
"position": ctx.window.get_position(),
"url": ctx.window.get_url(),
"is_fullscreen": ctx.window.is_fullscreen(),
#...
}
# Initialize Pyloid
app = Pyloid("My Pyloid App")
if is_production():
url = pyloid_serve("dist-front")
else:
url = "http://localhost:5173"
# Create window with RPC enabled
window = app.create_window(
title="My App Window",
rpc=rpc # Pass the RPC instance to enable it for this window
)
# Load the frontend
window.load_url(url)
window.show_and_focus()
# Start the application (this will start the event loop)
app.run()
```
--------------------------------
### Complete Pyloid Tray Example
Source: https://github.com/pyloid/docs/blob/main/guides/tray.md
A comprehensive example demonstrating Pyloid's tray functionality, including setting icons, handling events, managing menu items, and dynamic updates. It shows how to configure the tray icon and its associated actions and menus.
```Python
import os
from pyloid import PyloidApp, TrayEvent, is_production, get_production_path, PyloidTimer
app = PyloidApp("Pyloid-App", single_instance=True)
timer = PyloidTimer()
if (is_production()):
app.set_icon(os.path.join(get_production_path(), "icon.ico"))
app.set_tray_icon(os.path.join(get_production_path(), "icon.ico"))
else:
app.set_icon("assets/icon.ico")
app.set_tray_icon("assets/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."),
}
)
app.set_tray_menu_items(
[
{"label": "Show Window", "callback": lambda: app.show_and_focus_main_window()},
{"label": "Exit", "callback": lambda: app.quit()},
]
)
# Set tray icon tooltip
app.set_tray_tooltip("This is a Pyloid application.")
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()},
]
)
def update_tray_icon():
# Set tray icon animation
app.set_tray_icon_animation(
[
"assets/frame1.png",
"assets/frame2.png",
"assets/frame3.png",
"assets/frame4.png",
],
interval=500,
)
```
--------------------------------
### Running a Pyloid Project with npm
Source: https://github.com/pyloid/docs/blob/main/getting-started/create-pyloid-app.md
These commands navigate to the project directory, install dependencies, and start the development server using npm.
```bash
cd project-name
npm run setup
npm run dev
```
--------------------------------
### Run Pyloid Project Development
Source: https://github.com/pyloid/docs/blob/main/getting-started/create-pyloid-app.md
Commands to navigate into the project directory, set up dependencies, and start the development server for a Pyloid project using various package managers.
```bash
cd project-name
npm run setup
npm run dev
```
```bash
cd project-name
pnpm run setup
pnpm run dev
```
```bash
cd project-name
yarn run setup
yarn run dev
```
```bash
cd project-name
bun run setup
bun run dev
```
--------------------------------
### Install Node.js on Linux using nvm
Source: https://github.com/pyloid/docs/blob/main/getting-started/prerequisites.md
Installs Node.js on Linux distributions using Node Version Manager (nvm). This method ensures compatibility with Pyloid's requirements (Node.js v18+).
```bash
sudo apt update
sudo apt install curl
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.1/install.sh | bash
source ~/.bashrc
nvm install --lts
```
--------------------------------
### Install uv Package Manager
Source: https://github.com/pyloid/docs/blob/main/getting-started/prerequisites.md
Installs the 'uv' package installer and environment manager using pip. This is a prerequisite for Pyloid installation.
```bash
pip install uv
```
--------------------------------
### Running a Pyloid Project with pnpm
Source: https://github.com/pyloid/docs/blob/main/getting-started/create-pyloid-app.md
These commands navigate to the project directory, install dependencies, and start the development server using pnpm.
```bash
cd project-name
pnpm run setup
pnpm run dev
```
--------------------------------
### Running a Pyloid Project with yarn
Source: https://github.com/pyloid/docs/blob/main/getting-started/create-pyloid-app.md
These commands navigate to the project directory, install dependencies, and start the development server using yarn.
```bash
cd project-name
yarn run setup
yarn run dev
```
--------------------------------
### Start Periodic Timer
Source: https://github.com/pyloid/docs/blob/main/guides/timer.md
Shows how to start a timer that repeatedly executes a given function at a specified interval. Includes examples for both partial and full application context.
```Python
def print_hello():
print("Hello!")
# Start a timer that prints "Hello!" every 2 seconds
timer_id = timer_manager.start_periodic_timer(2000, print_hello)
```
```Python
from pyloid.timer import PyloidTimer
from pyloid import Pyloid
# Create a PyloidTimer instance
app = Pyloid(app_name="Pyloid-App")
timer_manager = PyloidTimer()
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()
```
--------------------------------
### Full Code for Periodic Timer
Source: https://github.com/pyloid/docs/blob/main/guides/timer.md
This complete example shows how to create a `PyloidTimer` instance, define a counter and a function to increment it, and start a periodic timer that executes the function every 1000 milliseconds. It includes the necessary imports and the `app.run()` call to start the Pyloid application. Requires the `pyloid` and `pyloid.timer` modules.
```python
from pyloid.timer import PyloidTimer
from pyloid import Pyloid
# Create a PyloidTimer instance
app = Pyloid(app_name="Pyloid-App")
timer_manager = PyloidTimer()
counter = 0
def count():
global counter
counter += 1
print(f"Counter: {counter}")
timer_id = timer_manager.start_periodic_timer(1000, count)
app.run()
```
--------------------------------
### Serve Static Files with Pyloid
Source: https://github.com/pyloid/docs/blob/main/guides/serve-frontend.md
Demonstrates how to serve static files from a specified directory using Pyloid's `pyloid_serve` function. This example initializes a Pyloid app, starts the server, and loads the provided URL into a new window.
```Python
from pyloid import Pyloid
from pyloid.serve import pyloid_serve
app = Pyloid("Pyloid-App")
url = pyloid_serve("dist-front") # Serve static files from dist-front folder
window = app.create_window("Pyloid-App")
window.load_url(url)
window.show_and_focus()
```
--------------------------------
### Complete Pyloid Application with RPC and Static File Serving
Source: https://github.com/pyloid/docs/blob/main/api/python-backend/rpc.md
A comprehensive example demonstrating the setup of a Pyloid application with PyloidRPC enabled for a window. It includes registering an RPC method to retrieve window information and serving frontend static files.
```Python
from pyloid import Pyloid
from pyloid.rpc import PyloidRPC, RPCContext
from pyloid.serve import pyloid_serve
# Initialize RPC
rpc = PyloidRPC()
@rpc.method()
async def get_window_info(ctx: RPCContext):
return {
"id": ctx.window.get_id(),
"window_title": ctx.window.get_title(),
"size": ctx.window.get_size(),
"position": ctx.window.get_position(),
"url": ctx.window.get_url(),
"is_fullscreen": ctx.window.is_fullscreen(),
#...
}
# Initialize Pyloid
app = Pyloid("My Pyloid App")
if is_production():
url = pyloid_serve("dist-front")
else:
url = "http://localhost:5173"
# Create window with RPC enabled
window = app.create_window(
title="My App Window",
rpc=rpc # Pass the RPC instance to enable it for this window
)
# Load the frontend
window.load_url(url)
window.show_and_focus()
# Start the application (this will start the event loop)
app.run()
```
--------------------------------
### Create Symbolic Links for Libraries on Raspberry Pi5 OS
Source: https://github.com/pyloid/docs/blob/main/getting-started/prerequisites.md
Creates necessary symbolic links for libwebp and libtiff libraries on Raspberry Pi5 OS. These links are required for Pyloid to function correctly.
```bash
sudo ln -s /usr/lib/aarch64-linux-gnu/libwebp.so.7 /usr/lib/aarch64-linux-gnu/libwebp.so.6
sudo ln -s /usr/lib/aarch64-linux-gnu/libtiff.so.6 /usr/lib/aarch64-linux-gnu/libtiff.so.5
```
--------------------------------
### All Example
Source: https://github.com/pyloid/docs/blob/main/api/python-backend/store.md
Demonstrates retrieving all keys from the store. Requires a Store instance.
```python
store = app.store("store.json")
store.set("key1", "value1")
store.set("key2", "value2")
keys = store.all()
print(keys) # ['key1', 'key2']
```
--------------------------------
### Install Node.js on macOS using Homebrew
Source: https://github.com/pyloid/docs/blob/main/getting-started/prerequisites.md
Installs Node.js on macOS using the Homebrew package manager. Node.js version 18 or higher is required for Pyloid.
```bash
brew install node
```
--------------------------------
### Start Single-Shot Timer
Source: https://github.com/pyloid/docs/blob/main/guides/timer.md
Illustrates how to create a timer that executes a function only once after a specified delay. Provides examples in partial and full code contexts.
```Python
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)
```
```Python
from pyloid.timer import PyloidTimer
from pyloid import Pyloid
# Create a PyloidTimer instance
app = Pyloid(app_name="Pyloid-App")
timer_manager = PyloidTimer()
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()
```
--------------------------------
### Usage Example: Getting Window Title with baseAPI
Source: https://github.com/pyloid/docs/blob/main/api/javascript-frontend/baseAPI.md
Demonstrates how to import and use the baseAPI to get the title of the application window. The title is then printed to the console.
```javascript
import { baseAPI } from 'pyloid-js';
// Get the title of the window and print it to the console
baseAPI.getTitle().then(title => console.log(title));
```
--------------------------------
### Save Example
Source: https://github.com/pyloid/docs/blob/main/api/python-backend/store.md
Demonstrates saving the store's data to the file. Requires a Store instance.
```python
store = app.store("store.json")
store.set("key", "value")
store.save() # True
```
--------------------------------
### Pyoid Timer Examples for Tray Icon
Source: https://github.com/pyloid/docs/blob/main/guides/tray.md
Demonstrates using Pyoid's timer functionality to schedule updates for a system tray icon. This includes updating the menu, animating the icon, and changing its tooltip after specified delays.
```Python
import timer
import app
# Update tray menu after 5 seconds
timer.start_single_shot_timer(5000, update_menu)
# Start tray icon animation after 3 seconds
timer.start_single_shot_timer(3000, update_tray_icon)
# Change tray icon to static icon after 6 seconds
timer.start_single_shot_timer(6000, lambda: app.set_tray_icon("assets/icon.ico"))
# Change tray icon tooltip after 10 seconds
timer.start_single_shot_timer(10000, lambda: app.set_tray_tooltip("New tooltip!"))
```
--------------------------------
### Pyloid File Watcher Usage Example
Source: https://github.com/pyloid/docs/blob/main/guides/filewatcher.md
A comprehensive example demonstrating the usage of the Pyloid File Watcher, including watching files and directories, setting callbacks, checking watched paths, stopping specific watches, and removing all watched paths.
```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()
```
--------------------------------
### Pyloid App Name for Auto Start
Source: https://github.com/pyloid/docs/blob/main/guides/autostart.md
Demonstrates setting a unique `app_name` for the Pyloid application, which is used as the key in system auto-start settings.
```Python
from pyloid import Pyloid
app = Pyloid(app_name="MyUniqueApp")
app.set_auto_start(True)
```
--------------------------------
### Purge Example
Source: https://github.com/pyloid/docs/blob/main/api/python-backend/store.md
Demonstrates purging all data from the store. Requires a Store instance.
```python
store = app.store("store.json")
store.set("key1", "value1")
store.set("key2", "value2")
store.purge() # True
print(store.all()) # []
```
--------------------------------
### Listening for Custom Event - JavaScript Example
Source: https://github.com/pyloid/docs/blob/main/api/python-backend/browserwindow.md
Example of listening for a custom event in JavaScript that was invoked from Python.
```JavaScript
import { event } from 'pyloid-js';
event.listen('customEvent', (data) => {
console.log(data.message);
});
```
--------------------------------
### Start Periodic Timer with Function
Source: https://github.com/pyloid/docs/blob/main/guides/timer.md
This snippet demonstrates how to start a periodic timer using a standard function. It initializes a counter and defines a function `count` that increments the counter and prints its value. The `start_periodic_timer` method is then used to schedule the `count` function to run every 1000 milliseconds. Requires a `PyloidTimer` instance and a function to be executed periodically.
```python
counter = 0
def count():
global counter
counter += 1
print(f"Counter: {counter}")
timer_id = timer_manager.start_periodic_timer(1000, count)
```
--------------------------------
### Running the Application - Python
Source: https://github.com/pyloid/docs/blob/main/api/python-backend/pyloid.md
Starts the application's event loop, making the application interactive.
```python
app.run()
```
--------------------------------
### Complete Example: Circular Semi-Transparent Window
Source: https://github.com/pyloid/docs/blob/main/guides/window-radius-and-transparent.md
This complete example demonstrates creating a circular, semi-transparent window using Pyloid, HTML, and CSS. It includes setting the border radius, transparency, and drag region.
```python
from pyloid import Pyloid
app = Pyloid(app_name="pyloid-app")
window = app.create_window(
"border-radius and transparent", frame=False, width=500, height=500
)
html = """
Hello World!
"""
window.load_html(html)
window.show_and_focus()
app.run()
```
--------------------------------
### Configure Pyloid Auto Start
Source: https://github.com/pyloid/docs/blob/main/guides/autostart.md
Enables or disables the automatic startup of the Pyloid application when a user logs in. The `app_name` is used as the key for this setting.
```Python
app.set_auto_start(True) # Enable auto-start
app.set_auto_start(False) # Disable auto-start
```
--------------------------------
### Complete Pyloid Window Example
Source: https://github.com/pyloid/docs/blob/main/guides/window-radius-and-transparent.md
A comprehensive example combining frameless window creation, CSS for circular shape and semi-transparency, and the drag region attribute for a fully customized Pyloid window.
```python
from pyloid import Pyloid
app = Pyloid(app_name="pyloid-app")
window = app.create_window(
"border-radius and transparent", frame=False, width=500, height=500
)
html = """
Hello World!
""
window.load_html(html)
window.show_and_focus()
app.run()
```
--------------------------------
### Initialize PyloidTimer
Source: https://github.com/pyloid/docs/blob/main/guides/timer.md
Demonstrates the basic initialization of the PyloidTimer class, which serves as the central manager for all timer operations.
```Python
from pyloid.timer import PyloidTimer
timer_manager = PyloidTimer()
```
--------------------------------
### Run the App
Source: https://github.com/pyloid/docs/blob/main/api/python-backend/pyloid.md
Starts the Pyloid application's event loop. This function does not return any value.
```Python
app.run()
```
--------------------------------
### Getting All Shortcuts - Python
Source: https://github.com/pyloid/docs/blob/main/api/python-backend/browserwindow.md
Returns all shortcuts registered to the window as a dictionary.
```Python
def get_all_shortcuts(self) -> dict:
```
--------------------------------
### Get All Keys
Source: https://github.com/pyloid/docs/blob/main/api/python-backend/store.md
Returns a list of all keys stored in the database. Requires a Store instance.
```python
store.all() -> List[str]
```
--------------------------------
### Get Remaining Timer Time
Source: https://github.com/pyloid/docs/blob/main/guides/timer.md
Shows how to retrieve the remaining time in milliseconds before a timer fires. Includes examples for partial and full code setups.
```Python
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.")
```
```Python
from pyloid.timer import PyloidTimer
from pyloid import Pyloid
# Create a PyloidTimer instance
app = Pyloid(app_name="Pyloid-App")
timer_manager = PyloidTimer()
# Start a timer
timer_id = timer_manager.start_periodic_timer(2000, lambda: print("Hello!"))
# Check remaining time
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()
```
--------------------------------
### Start Precise Periodic Timer
Source: https://github.com/pyloid/docs/blob/main/guides/timer.md
Starts a precise periodic timer with a specified interval and a callback function. This is useful for tasks that require accurate execution timing.
```python
from pyloid.timer import PyloidTimer
from pyloid import Pyloid
# Create a PyloidTimer instance
app = Pyloid(app_name="Pyloid-App")
timer_manager = PyloidTimer()
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()
```
--------------------------------
### Basic PyloidRPC Setup and Method Registration
Source: https://github.com/pyloid/docs/blob/main/api/python-backend/rpc.md
Demonstrates how to initialize PyloidRPC, register a simple asynchronous method, and register a method that utilizes the RPCContext for accessing application objects like windows.
```Python
from pyloid.rpc import PyloidRPC, RPCContext
# Create an RPC instance
rpc = PyloidRPC()
# Register a simple RPC method
@rpc.method()
async def greet(name: str):
return f"Hello, {name}!"
# Register a method that uses context
@rpc.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()
```
--------------------------------
### Start Periodic Timer with Lambda Function
Source: https://github.com/pyloid/docs/blob/main/guides/timer.md
Starts a periodic timer with a specified interval and a callback function, demonstrated using a simple counter increment. This showcases using functions as callbacks for timed events.
```python
from pyloid.timer import PyloidTimer
from pyloid import Pyloid
# Create a PyloidTimer instance
app = Pyloid(app_name="Pyloid-App")
timer_manager = PyloidTimer()
counter = 0
def count():
global counter
counter += 1
print(f"Counter: {counter}")
timer_id = timer_manager.start_periodic_timer(1000, count)
app.run()
```
--------------------------------
### Usage Example: Setting Window Size with baseAPI
Source: https://github.com/pyloid/docs/blob/main/api/javascript-frontend/baseAPI.md
Demonstrates how to use the baseAPI to set the size of the application window. The setSize method takes width and height as arguments.
```javascript
// Set the size of the window to 1024x768
baseAPI.setSize(1024, 768).then(() => console.log('Window size set.'));
```
--------------------------------
### Create Pyloid App with Package Managers
Source: https://github.com/pyloid/docs/blob/main/getting-started/create-pyloid-app.md
Command to create a new Pyloid project using different package managers like npm, pnpm, yarn, and bun.
```bash
npm create pyloid-app@latest
```
```bash
pnpm create pyloid-app@latest
```
```bash
yarn create pyloid-app@latest
```
```bash
bun create pyloid-app@latest
```
--------------------------------
### Creating a Pyloid App with bun
Source: https://github.com/pyloid/docs/blob/main/getting-started/create-pyloid-app.md
This command uses bun to create a new Pyloid application. It initializes a new project with the latest version of the create-pyloid-app package.
```bash
bun create pyloid-app@latest
```
--------------------------------
### Stop Timer
Source: https://github.com/pyloid/docs/blob/main/guides/timer.md
Demonstrates how to stop an active timer using its unique identifier. Includes examples for both partial and full code scenarios.
```Python
# Stop a timer using its ID
timer_manager.stop_timer(timer_id)
```
```Python
from pyloid.timer import PyloidTimer
from pyloid import Pyloid
# Create a PyloidTimer instance
app = Pyloid(app_name="Pyloid-App")
timer_manager = PyloidTimer()
# Start a timer
timer_id = timer_manager.start_periodic_timer(2000, lambda: print("Hello!"))
# Stop a timer using its ID
timer_manager.stop_timer(timer_id)
app.run()
```
--------------------------------
### Pyloid Store Class Instantiation
Source: https://github.com/pyloid/docs/blob/main/api/python-backend/store.md
Demonstrates how to create an instance of the Store class from a Pyloid app. The store is initialized with a file path for persistent storage.
```Python
from src.pyloid.pyloid import Pyloid
app = Pyloid(app_name="Pyloid-App")
store = app.store("store.json")
```
--------------------------------
### Change Timer Interval
Source: https://github.com/pyloid/docs/blob/main/guides/timer.md
Demonstrates how to dynamically change the interval of an existing periodic timer. Examples are provided for partial and full code contexts.
```Python
# Change the timer interval to 3 seconds
timer_manager.set_interval(timer_id, 3000)
```
```Python
from pyloid.timer import PyloidTimer
from pyloid import Pyloid
# Create a PyloidTimer instance
app = Pyloid(app_name="Pyloid-App")
timer_manager = PyloidTimer()
# Start a timer
timer_id = timer_manager.start_periodic_timer(1000, lambda: print("Hello!"))
# Change the timer interval to 3 seconds
timer_manager.set_interval(timer_id, 3000)
app.run()
```
--------------------------------
### Check Timer Activity
Source: https://github.com/pyloid/docs/blob/main/guides/timer.md
Provides code to check if a specific timer is currently active or has been stopped. Examples are shown for partial and full code contexts.
```Python
if timer_manager.is_timer_active(timer_id):
print("The timer is still running.")
else:
print("The timer has stopped.")
```
```Python
from pyloid.timer import PyloidTimer
from pyloid import Pyloid
# Create a PyloidTimer instance
app = Pyloid(app_name="Pyloid-App")
timer_manager = PyloidTimer()
# Start a timer
timer_id = timer_manager.start_periodic_timer(2000, lambda: print("Hello!"))
# Check if the timer is active
if timer_manager.is_timer_active(timer_id):
print("The timer is still running.")
else:
print("The timer has stopped.")
app.run()
```
--------------------------------
### Showing and Focusing Window - Python
Source: https://github.com/pyloid/docs/blob/main/api/python-backend/browserwindow.md
Shows the BrowserWindow and gives it focus.
```Python
def show_and_focus(self) -> None:
```
--------------------------------
### Get Virtual Monitor Size
Source: https://github.com/pyloid/docs/blob/main/guides/desktop-monitor.md
Returns the virtual size (width, height) which represents the combined dimensions of all monitors in a multi-monitor setup. The output is a dictionary.
```Python
app = Pyloid("Pyloid-App")
monitor = app.get_primary_monitor()
virtual_size = monitor.virtual_size()
print("Virtual Size:", virtual_size)
```
--------------------------------
### Get Virtual Monitor Geometry
Source: https://github.com/pyloid/docs/blob/main/guides/desktop-monitor.md
Retrieves the virtual geometry (x, y, width, height) which represents the combined area of all monitors in a multi-monitor setup. Returns a dictionary.
```Python
app = Pyloid("Pyloid-App")
monitor = app.get_primary_monitor()
virtual_geometry = monitor.virtual_geometry()
print("Virtual Geometry:", virtual_geometry)
```
--------------------------------
### Pyloid BrowserWindow Methods
Source: https://github.com/pyloid/docs/blob/main/api/python-backend/browserwindow.md
Provides methods for managing browser windows, including loading content, setting properties, and controlling window behavior.
```APIDOC
BrowserWindow:
load_file(file_path: str) -> None
Loads a local HTML file into the web view.
Parameters:
file_path (str): Path to the HTML file to load
load_url(url: str) -> None
Loads the specified URL into the window.
Parameters:
url (str): URL to load
set_title(title: str) -> None
Sets the title of the window.
Parameters:
title (str): New window title
set_size(width: int, height: int) -> None
Sets the size of the window.
Parameters:
width (int): New window width
height (int): New window height
set_position(x: int, y: int) -> None
Sets the position of the window.
Parameters:
x (int): New x-coordinate
y (int): New y-coordinate
set_frame(frame: bool) -> None
Sets whether to show the window frame.
Parameters:
frame (bool): Whether to show the frame
set_context_menu(context_menu: bool) -> None
Sets whether to enable the context menu.
Parameters:
context_menu (bool): Whether to enable the context menu
set_dev_tools(enable: bool) -> None
Sets whether to enable developer tools.
Parameters:
enable (bool): Whether to enable developer tools
open_dev_tools() -> None
Opens the developer tools window.
get_window_properties() -> dict
Returns the properties of the window.
Returns: dict: A dictionary containing the window properties
get_id() -> str
Returns the ID of the window.
Returns: str: The window ID
hide() -> None
Hides the window.
show() -> None
Shows the window.
focus() -> None
Gives focus to the window.
show_and_focus() -> None
Shows the window and gives it focus.
close() -> None
Closes the window.
toggle_fullscreen() -> None
Toggles fullscreen mode.
minimize() -> None
Minimizes the window.
maximize() -> None
Maximizes the window.
unmaximize() -> None
Restores the window to its previous size.
capture(save_path: str) -> Optional[str]
Captures the current window.
Parameters:
save_path (str): Path to save the captured image
Returns:
Optional[str]: Path to the saved image or None if failed
add_shortcut(key_sequence: str, callback: Callable) -> QShortcut
Adds a keyboard shortcut to the window.
Parameters:
key_sequence (str): Shortcut key sequence (e.g., "Ctrl+C")
callback (Callable): Function to execute when the shortcut is pressed
Returns:
QShortcut: The created QShortcut object
remove_shortcut(key_sequence: str) -> None
Removes a keyboard shortcut from the window.
Parameters:
key_sequence (str): Shortcut key sequence to remove
get_all_shortcuts() -> dict
Returns all shortcuts registered to the window.
Returns:
dict: A dictionary containing shortcut sequences and their QShortcut objects
invoke(event_name: str, data: Optional[Dict] = None) -> None
Invokes an event to the JavaScript side.
Parameters:
event_name (str): Name of the event
data (dict, optional): Data to be sent with the event (default is None)
```
--------------------------------
### Showing Window - Python
Source: https://github.com/pyloid/docs/blob/main/api/python-backend/browserwindow.md
Shows the BrowserWindow.
```Python
def show(self) -> None:
```
--------------------------------
### Create Pyloid App with bun
Source: https://github.com/pyloid/docs/blob/main/README.md
This snippet shows the command to create a Pyloid application using bun, a new, fast JavaScript runtime, package manager, and bundler. It initializes a project with the latest pyloid-app.
```bash
bun create pyloid-app@latest
```
--------------------------------
### Pyloid Base API: Window Sizing (Fullscreen, Maximize, Minimize)
Source: https://github.com/pyloid/docs/blob/main/api/javascript-frontend/baseAPI.md
Methods to control the window's size and display state, including fullscreen, maximize, minimize, and toggling these states. All operations return promises.
```javascript
fullscreen()
- Makes the current window fullscreen.
- Returns: Promise - A promise that resolves when the fullscreen operation is initiated.
- Example:
baseAPI.fullscreen().then(() => console.log('Window is now fullscreen.'));
toggleFullscreen()
- Toggles the fullscreen state of the current window.
- Returns: Promise - A promise that resolves when the toggle operation is initiated.
- Example:
baseAPI.toggleFullscreen().then(() => console.log('Fullscreen toggled.'));
minimize()
- Minimizes the current window.
- Returns: Promise - A promise that resolves when the minimize operation is initiated.
- Example:
baseAPI.minimize().then(() => console.log('Window minimized.'));
maximize()
- Maximizes the current window.
- Returns: Promise - A promise that resolves when the maximize operation is initiated.
- Example:
baseAPI.maximize().then(() => console.log('Window maximized.'));
unmaximize()
- Restores the window from a maximized state.
- Returns: Promise - A promise that resolves when the unmaximize operation is initiated.
- Example:
baseAPI.unmaximize().then(() => console.log('Window restored from maximized state.'));
toggleMaximize()
- Toggles the maximized state of the current window.
- Returns: Promise - A promise that resolves when the toggle operation is initiated.
- Example:
baseAPI.toggleMaximize().then(() => console.log('Maximize toggled.'));
```
--------------------------------
### Opening Developer Tools - Python
Source: https://github.com/pyloid/docs/blob/main/api/python-backend/browserwindow.md
Opens the developer tools window for the BrowserWindow.
```Python
def open_dev_tools(self) -> None:
```
--------------------------------
### Pyloid Base API: Window Management (Close, Hide, Show, Focus)
Source: https://github.com/pyloid/docs/blob/main/api/javascript-frontend/baseAPI.md
Provides methods to manage the window's state, including closing, hiding, showing, and focusing. All operations return promises that resolve when the action is initiated.
```javascript
close()
- Closes the current window.
- Returns: Promise - A promise that resolves when the close operation is initiated.
- Example:
baseAPI.close().then(() => console.log('Window closed.'));
hide()
- Hides the current window.
- Returns: Promise - A promise that resolves when the hide operation is initiated.
- Example:
baseAPI.hide().then(() => console.log('Window hidden.'));
show()
- Shows the current window if it is hidden.
- Returns: Promise - A promise that resolves when the show operation is initiated.
- Example:
baseAPI.show().then(() => console.log('Window shown.'));
focus()
- Brings the current window to the foreground and gives it focus.
- Returns: Promise - A promise that resolves when the focus operation is initiated.
- Example:
baseAPI.focus().then(() => console.log('Window focused.'));
showAndFocus()
- Shows the window (if hidden) and brings it to the foreground with focus.
- Returns: Promise - A promise that resolves when the operation is initiated.
- Example:
baseAPI.showAndFocus().then(() => console.log('Window shown and focused.'));
```
--------------------------------
### Invoking Custom Event - Python Example
Source: https://github.com/pyloid/docs/blob/main/api/python-backend/browserwindow.md
Example of invoking a custom event from Python to JavaScript using the invoke method.
```Python
app = Pyloid(app_name="Pyloid-App")
window = app.create_window("pyloid-window")
window.invoke("customEvent", {"message": "Hello, Pyloid!"})
```
--------------------------------
### Getting Window Title with BaseAPI in JavaScript
Source: https://github.com/pyloid/docs/blob/main/api/javascript-frontend/baseAPI.md
Gets the current title of the window using the baseAPI. Returns a promise that resolves with the window title string.
```javascript
baseAPI.getTitle().then(title => console.log(`Window title: ${title}`));
```
--------------------------------
### Pyloid Initialization
Source: https://github.com/pyloid/docs/blob/main/api/python-backend/pyloid.md
Initializes the Pyloid application. Supports setting an application name and enforcing a single running instance.
```Python
from pyloid import Pyloid
app = Pyloid(app_name="MyApp", single_instance=True)
```
--------------------------------
### Getting Clipboard Text with BaseAPI in JavaScript
Source: https://github.com/pyloid/docs/blob/main/api/javascript-frontend/baseAPI.md
Gets the current text content from the system clipboard using the baseAPI. Returns a promise that resolves with the clipboard text.
```javascript
baseAPI.getClipboardText().then(text => console.log(`Clipboard text: ${text}`));
```
--------------------------------
### Create Pyloid App with pnpm
Source: https://github.com/pyloid/docs/blob/main/README.md
This snippet demonstrates creating a Pyloid application using pnpm, a fast, reliable, and efficient Node.js package manager. It initializes a new project with the latest pyloid-app.
```bash
pnpm create pyloid-app@latest
```
--------------------------------
### Pyloid Clipboard Operations
Source: https://github.com/pyloid/docs/blob/main/api/python-backend/pyloid.md
Provides functionality to interact with the system clipboard for both text and image data. Supports setting and getting text, and setting and getting image data.
```Python
app.set_clipboard_text("Copied text")
text = app.get_clipboard_text()
app.set_clipboard_image("image.png")
img = app.get_clipboard_image()
```
--------------------------------
### Getting Clipboard Image with BaseAPI in JavaScript
Source: https://github.com/pyloid/docs/blob/main/api/javascript-frontend/baseAPI.md
Gets the current image content from the system clipboard using the baseAPI. Returns a promise that resolves with the clipboard image data.
```javascript
baseAPI.getClipboardImage().then(imageData => console.log(`Clipboard image data: ${imageData}`));
```
--------------------------------
### Check Pyloid Auto Start Status
Source: https://github.com/pyloid/docs/blob/main/guides/autostart.md
Checks the current auto-start setting for the Pyloid application. Returns `True` if auto-start is enabled, `False` otherwise.
```Python
is_auto_start = app.is_auto_start()
print(is_auto_start)
```
--------------------------------
### Pyloid Serve Function Signature and Details
Source: https://github.com/pyloid/docs/blob/main/guides/serve-frontend.md
Provides the function signature for `pyloid_serve`, detailing its parameters (`directory`, `port`) and the return type (`str`). It explains the purpose of each parameter, including dynamic port allocation.
```APIDOC
pyloid_serve(directory: str, port: Optional[int] = None) -> str
Parameters:
- directory (str): Path to the static file directory to serve
- port (int, optional): Server port (default: None - will use dynamic port allocation to automatically find an available port)
Returns:
- str: URL of the started server (e.g. "http://127.0.0.1:65421")
```
--------------------------------
### Store API Usage - Python
Source: https://github.com/pyloid/docs/blob/main/api/python-backend/pyloid.md
Demonstrates how to use the Store API to persist settings to a JSON file. It shows how to create a store, set a value, and retrieve it.
```python
store = app.store("settings.json")
store.set("theme", "dark")
print(store.get("theme"))
```
--------------------------------
### Getting Window Position with BaseAPI in JavaScript
Source: https://github.com/pyloid/docs/blob/main/api/javascript-frontend/baseAPI.md
Gets the current position (x and y coordinates) of the window using the baseAPI. Returns a promise that resolves with an object containing the x and y coordinates.
```javascript
baseAPI.getPosition().then(position => console.log(`Window position: (${position.x}, ${position.y})`));
```
--------------------------------
### Getting Window Size with BaseAPI in JavaScript
Source: https://github.com/pyloid/docs/blob/main/api/javascript-frontend/baseAPI.md
Gets the current size (width and height) of the window using the baseAPI. Returns a promise that resolves with an object containing the width and height.
```javascript
baseAPI.getSize().then(size => console.log(`Window size: ${size.width}x${size.height}`));
```
--------------------------------
### Clipboard Image Operations
Source: https://github.com/pyloid/docs/blob/main/api/javascript-frontend/baseAPI.md
Allows setting and getting image content from the system clipboard. Setting an image requires a file path and format, while getting returns image data. Both are asynchronous.
```APIDOC
setClipboardImage(imagePath: string, format: string): Promise
Sets the system clipboard image content from a file path.
Parameters:
imagePath: The path to the image file.
format: The format of the image (e.g., 'png', 'jpeg').
getClipboardImage(): Promise
Gets the current image content from the system clipboard.
Returns: A promise that resolves with the clipboard image data.
```
```javascript
baseAPI.setClipboardImage('/path/to/image.png', 'png').then(() => console.log('Clipboard image set.'));
baseAPI.getClipboardImage().then(imageData => console.log(`Clipboard image data: ${imageData}`));
```
--------------------------------
### Create Window with Position Parameters
Source: https://github.com/pyloid/docs/blob/main/guides/position.md
Demonstrates how to specify the initial x and y coordinates when creating a new Pyloid window.
```Python
app = Pyloid(app_name="Pyloid-App")
window = app.create_window("Pyloid-Window", x=100, y=100)
```