### Example: Install Python Dependencies with Pinokio Source: https://github.com/pinokiocomputer/pinokio/blob/main/README.md This JSON snippet demonstrates how to install Python dependencies using 'uv pip' within a specified path and virtual environment. It ensures isolated execution and dependency management. ```json { "method": "shell.run", "params": { "message": "uv pip install -r requirements.txt", "path": "server", "venv": "venv" } } ``` -------------------------------- ### Configure Application Settings with Electron-Store Source: https://context7.com/pinokiocomputer/pinokio/llms.txt This Javascript code snippet sets up an application configuration system using 'electron-store' for persistent storage. It defines various configuration values like URLs for newsfeeds, profiles, and application discovery, along with application version and agent type. It also demonstrates basic usage of the store for getting and setting values. Dependencies include 'electron-store' and './package.json'. ```javascript const Store = require('electron-store') const packagejson = require("./package.json") const store = new Store() const config = { newsfeed: (gitRemote) => { return `https://pinokiocomputer.github.io/home/item?uri=${gitRemote}&display=feed` }, profile: (gitRemote) => { return `https://pinokiocomputer.github.io/home/item?uri=${gitRemote}&display=profile` }, site: "https://pinokiocomputer.github.io/home", discover_dark: "https://pinokiocomputer.github.io/home/app?theme=dark", discover_light: "https://pinokiocomputer.github.io/home/app", portal: "https://pinokiocomputer.github.io/home/portal", docs: "https://pinokiocomputer.github.io/program.pinokio.computer", agent: "electron", version: packagejson.version, store } // Usage const mode = config.store.get("mode") || "full" config.store.set("theme", "dark") module.exports = config ``` -------------------------------- ### Inspector Mode for Debugging (Electron IPC - JavaScript) Source: https://context7.com/pinokiocomputer/pinokio/llms.txt Enables interactive element inspection for debugging web applications within iframes. It uses Electron's IPC (Inter-Process Communication) to bridge communication between the main process and renderer. This snippet includes setup for both preload scripts and the main process, along with a usage example in the renderer. ```javascript const { ipcMain } = require('electron') // In preload.js - Expose API to renderer window.electronAPI = { startInspector: (payload) => ipcRenderer.invoke('pinokio:start-inspector', payload), stopInspector: () => ipcRenderer.invoke('pinokio:stop-inspector'), captureScreenshot: (request) => ipcRenderer.invoke('pinokio:capture-screenshot-debug', { screenshotRequest: request }) } // In main process - Handle inspector requests ipcMain.handle('pinokio:start-inspector', async (event, payload = {}) => { try { const targetFrame = selectTargetFrame(event.sender, payload) if (!targetFrame) { throw new Error('Unable to locate iframe to inspect.') } // Inject inspector code into target frame await targetFrame.executeJavaScript(buildInspectorInjection(), true) event.sender.send('pinokio:inspector-started', { frameUrl: targetFrame.url }) return { ok: true } } catch (error) { event.sender.send('pinokio:inspector-error', { message: error.message }) throw error } }) // Usage in renderer document.getElementById('inspector-button').addEventListener('click', async () => { try { await window.electronAPI.startInspector({ frameUrl: 'http://localhost:3000', frameIndex: 0 }) } catch (error) { console.error('Failed to start inspector:', error) } }) ``` -------------------------------- ### Initialize Pinokio Application with Daemon Source: https://context7.com/pinokiocomputer/pinokio/llms.txt This snippet demonstrates how to initialize the Pinokio application and integrate with the `pinokiod` daemon. It handles application startup events like quitting, restarting, and refreshing, and includes functionality to clear browser cache. This requires the 'electron' and 'pinokiod' packages. ```javascript const { app } = require('electron') const Pinokiod = require("pinokiod") const config = require('./config') const pinokiod = new Pinokiod(config) app.whenReady().then(async () => { try { await pinokiod.start({ onquit: () => { app.quit() }, onrestart: () => { app.relaunch() app.exit() }, onrefresh: (payload) => { // Update UI theme colors updateThemeColors(payload) }, browser: { clearCache: async () => { await session.defaultSession.clearStorageData() } } }) PORT = pinokiod.port createWindow(PORT) } catch (error) { console.error('Failed to start pinokiod', error) showStartupError({ error }) } }) ``` -------------------------------- ### Minimal Mode with System Tray (Electron - JavaScript) Source: https://context7.com/pinokiocomputer/pinokio/llms.txt Configures Pinokio to run in the background with system tray integration. It hides the dock icon on macOS, creates a context menu for the tray, and opens the application in the browser upon startup. Requires Electron, path, and nativeImage modules. ```javascript const { app, Tray, Menu, shell, nativeImage } = require('electron') const path = require('path') app.whenReady().then(async () => { await pinokiod.start({ onquit: () => app.quit(), onrestart: () => { app.relaunch(); app.exit() } }) const rootUrl = `http://localhost:${pinokiod.port}` // Hide dock icon on macOS if (process.platform === 'darwin') app.dock.hide() // Create system tray const iconPath = path.resolve(__dirname, "assets/icon_small.png") let icon = nativeImage.createFromPath(iconPath) icon = icon.resize({ height: 24, width: 24 }) const tray = new Tray(icon) const contextMenu = Menu.buildFromTemplate([ { label: 'Open in Browser', click: () => shell.openExternal(rootUrl) }, { label: 'Restart', click: () => { app.relaunch(); app.exit() } }, { label: 'Quit', click: () => app.quit() } ]) tray.setToolTip('Pinokio') tray.setContextMenu(contextMenu) tray.on('click', () => tray.popUpContextMenu(contextMenu)) // Open browser automatically shell.openExternal(rootUrl) }) ``` -------------------------------- ### Create and Manage Electron Browser Window Source: https://context7.com/pinokiocomputer/pinokio/llms.txt This code defines a function to create the main browser window for the Pinokio application. It configures window appearance, size, and web preferences, including native window open, context isolation, and preload script integration. It utilizes 'electron', 'electron-window-state', and 'path' modules. ```javascript const { BrowserWindow, session } = require('electron') const path = require('path') const windowStateKeeper = require('electron-window-state') const createWindow = (port) => { let mainWindowState = windowStateKeeper({ defaultWidth: 1000, defaultHeight: 800 }) const mainWindow = new BrowserWindow({ titleBarStyle: "hidden", titleBarOverlay: { color: "#1a1a1a", symbolColor: "#ffffff", height: 40 }, x: mainWindowState.x, y: mainWindowState.y, width: mainWindowState.width, height: mainWindowState.height, minWidth: 190, webPreferences: { session: session.fromPartition('temp-window-' + Date.now()), webSecurity: false, nativeWindowOpen: true, contextIsolation: false, nodeIntegrationInSubFrames: true, preload: path.join(__dirname, 'preload.js') } }) const root_url = `http://localhost:${port}` mainWindow.loadURL(root_url) mainWindowState.manage(mainWindow) return mainWindow } ``` -------------------------------- ### Handle Custom Protocol for Deep Linking Source: https://context7.com/pinokiocomputer/pinokio/llms.txt This snippet configures the application to handle the `pinokio://` custom protocol for deep linking. It ensures single instance locking and defines handlers for 'second-instance' and 'open-url' events to load new windows with the provided deep link path. This requires 'electron' and 'path' modules. ```javascript const { app, BrowserWindow } = require('electron') const path = require('path') // Set as default protocol client if (process.defaultApp) { app.setAsDefaultProtocolClient('pinokio', process.execPath, [path.resolve(process.argv[1])]) } else { app.setAsDefaultProtocolClient('pinokio') } // Handle single instance lock const gotTheLock = app.requestSingleInstanceLock() if (gotTheLock) { app.on('second-instance', (event, argv) => { // Extract pinokio:// URL from arguments const url = [...argv].reverse().find(arg => typeof arg === 'string' && arg.startsWith('pinokio:') ) if (url) { const path = url.replace(/pinokio:[\/]+/, "") loadNewWindow(`${root_url}/pinokio/${path}`, PORT) } }) app.on('open-url', (event, url) => { const path = url.replace(/pinokio:[\/]+/, "") loadNewWindow(`${root_url}/pinokio/${path}`, PORT) }) } ``` -------------------------------- ### Auto-Update System (Electron-Updater - JavaScript) Source: https://context7.com/pinokiocomputer/pinokio/llms.txt Implements an automatic update system for the application using electron-updater. It checks for available updates, prompts the user to download, displays a progress bar during download, and requests a restart to apply the update. Dependencies include electron-updater, electron's dialog, and electron-progressbar. ```javascript const { autoUpdater } = require("electron-updater") const { dialog } = require('electron') const ProgressBar = require('electron-progressbar') class Updater { run(mainWindow) { let progressBar = null autoUpdater.autoDownload = false autoUpdater.on('update-available', (info) => { dialog.showMessageBox(mainWindow, { type: 'question', buttons: ['Yes', 'No'], title: 'Update Available', message: `Version ${info.version} is available. Download now?` }).then(result => { if (result.response === 0) { progressBar = new ProgressBar({ indeterminate: false, text: "Downloading update…", detail: "Please wait…", browserWindow: { parent: mainWindow, modal: true, width: 400, height: 120 } }) autoUpdater.downloadUpdate() } }) }) autoUpdater.on("download-progress", (progress) => { if (progressBar && !progressBar.isCompleted()) { progressBar.value = Math.floor(progress.percent) progressBar.detail = `Downloaded ${Math.round(progress.percent)}%` } }) autoUpdater.on("update-downloaded", (info) => { if (progressBar) { progressBar.setCompleted() progressBar = null } dialog.showMessageBox(mainWindow, { type: "info", buttons: ["Restart Now", "Later"], title: "Update Ready", message: "Restart to apply updates?" }).then((result) => { if (result.response === 0) { autoUpdater.quitAndInstall() } }) }) autoUpdater.checkForUpdates() } } module.exports = Updater ``` -------------------------------- ### Manage Browser Window Lifecycle in Electron Source: https://context7.com/pinokiocomputer/pinokio/llms.txt This Javascript code snippet handles browser window lifecycle events in an Electron application. It manages navigation, preventing navigation to external hosts unless explicitly opened. It also configures window open handlers to either open external links in the default browser or allow internal links with specific window options. Dependencies include 'shell' and 'path' from Electron, and URL parsing. ```javascript function attachWindowHandlers(webContents, root_url) { // Track first navigation webContents.on('will-navigate', (event, url) => { if (!webContents.opened) { webContents.opened = true } else { const host = new URL(url).host const localhost = new URL(root_url).host if (host !== localhost) { event.preventDefault() shell.openExternal(url) } } }) // Handle new window requests webContents.setWindowOpenHandler((config) => { const url = config.url const features = config.features const origin = new URL(url).origin if (features === "browser") { shell.openExternal(url) return { action: 'deny' } } if (origin === root_url) { return { action: 'allow', outlivesOpener: true, overrideBrowserWindowOptions: { width: 1000, height: 800, titleBarStyle: "hidden", webPreferences: { webSecurity: false, contextIsolation: false, preload: path.join(__dirname, 'preload.js') } } } } shell.openExternal(url) return { action: 'deny' } }) } ``` -------------------------------- ### Pinokio UI State Management with JavaScript Source: https://github.com/pinokiocomputer/pinokio/blob/main/splash.html This JavaScript code manages the Pinokio application's UI state based on URL parameters. It handles displaying messages, error states, and log paths. It relies on the browser's `URLSearchParams` API and DOM manipulation. Input is derived from URL query parameters. ```javascript const params = new URLSearchParams(window.location.search) const state = params.get('state') || 'loading' const message = params.get('message') || 'Starting Pinokio…' const detail = params.get('detail') const logPath = params.get('log') const icon = params.get('icon') if (icon) { const logo = document.getElementById('logo') if (logo) { logo.src = icon } } document.getElementById('title').textContent = message if (state === 'error') { document.body.classList.add('error') const friendly = detail && detail.trim().length > 0 ? detail : 'Please review the Pinokio logs for more information.' document.getElementById('loader').hidden = true const detailEl = document.getElementById('detail') detailEl.textContent = friendly detailEl.hidden = false const hintEl = document.getElementById('hint') hintEl.textContent = logPath ? `Logs: ${logPath}` : 'Logs: ~/.pinokio/logs/stdout.txt' hintEl.hidden = false document.getElementById('subtitle').textContent = 'Something stopped Pinokio from starting.' } else { document.getElementById('subtitle').textContent = 'This should only take a moment.' } ``` -------------------------------- ### Pinokio UI Styling with CSS Source: https://github.com/pinokiocomputer/pinokio/blob/main/splash.html This CSS code styles the Pinokio application's user interface, defining styles for the body, cards, logo, text elements, and a loader animation. It also includes styles for error states. No external dependencies are required. ```css html, body { width: 100%; height: 100%; margin: 0; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; background: #ffffff; color: #111827; } body { display: flex; align-items: center; justify-content: center; overflow: hidden; } .card { width: min(360px, 90vw); padding: 32px; text-align: center; display: flex; flex-direction: column; align-items: center; gap: 8px; max-height: calc(100vh - 40px); overflow: hidden; } .logo { width: 48px; height: 48px; margin: 0 auto 20px; } .title { margin: 0 0 6px; font-size: 16px; font-weight: 600; } .subtitle { margin: 0; opacity: 0.85; line-height: 1.4; font-size: 13px; } .hint { font-size: 12px; opacity: 0.7; margin: 16px 0 0; word-break: break-word; } .loader { width: 60px; height: 2px; margin: 24px auto; background: rgba(17, 24, 39, 0.08); overflow: hidden; position: relative; } .loader::after { content: ""; position: absolute; top: 0; left: -30%; width: 30%; height: 100%; background: #111827; animation: slide 1.2s ease-in-out infinite; } .detail { padding: 14px 16px; border-radius: 12px; border: 1px solid rgba(17, 24, 39, 0.08); font-size: 12px; text-align: left; white-space: pre-wrap; margin-top: 16px; max-height: 160px; overflow-y: auto; background: rgba(249, 250, 251, 0.8); width: 100%; } body.error .subtitle { color: #b91c1c; } body.error .loader { display: none; } @keyframes slide { 0% { left: -30%; } 50% { left: 100%; } 100% { left: 100%; } } ``` -------------------------------- ### Manipulate Web Requests with Electron Source: https://context7.com/pinokiocomputer/pinokio/llms.txt This Javascript code snippet demonstrates how to manipulate web requests within an Electron application. It removes the 'X-Frame-Options' header and modifies the 'Content-Security-Policy' to allow iframe embedding. It also cleans the User-Agent header to remove specific application identifiers. Dependencies include the 'electron' module. ```javascript const { session } = require('electron') function setupWebRequestHandlers(webContents) { // Remove X-Frame-Options to allow iframe embedding webContents.session.webRequest.onHeadersReceived((details, callback) => { if (details.responseHeaders["X-Frame-Options"]) { delete details.responseHeaders["X-Frame-Options"] } if (details.responseHeaders["x-frame-options"]) { delete details.responseHeaders["x-frame-options"] } // Remove frame-ancestors from CSP let csp = details.responseHeaders["Content-Security-Policy"] || details.responseHeaders["content-security-policy"] if (csp) { const new_csp = csp.map(c => c.replaceAll(/frame-ancestors[^;]+;?/gi, "")) details.responseHeaders["Content-Security-Policy"] = new_csp } callback({ responseHeaders: details.responseHeaders }) }) // Clean User-Agent header webContents.session.webRequest.onBeforeSendHeaders((details, callback) => { let ua = details.requestHeaders['User-Agent'] if (ua) { ua = ua.replace(/ pinokio\/[0-9.]+/i, '') ua = ua.replace(/Electron\/.+ /i, '') details.requestHeaders['User-Agent'] = ua } callback({ cancel: false, requestHeaders: details.requestHeaders }) }) } ``` -------------------------------- ### Handle Form Submission and Cancel Button Click in JavaScript Source: https://github.com/pinokiocomputer/pinokio/blob/main/prompt.html This snippet demonstrates how to add event listeners to a form and a cancel button using JavaScript. The form submission listener prevents default actions and sends the input value 'val' to the electron API before closing the window. The cancel button listener also prevents default actions and closes the window. It relies on the DOM being fully loaded and the presence of elements with IDs 'cancel' and 'val', as well as a 'form' element. It also assumes the existence of `window.electronAPI`. ```javascript document.addEventListener("DOMContentLoaded" () => { document.querySelector("#cancel").addEventListener("click", (e) => { debugger e.preventDefault() e.stopPropagation() window.close() }) document.querySelector("form").addEventListener("submit", (e) => { e.preventDefault() e.stopPropagation() debugger window.electronAPI.send('prompt-response', document.querySelector("#val").value) window.close() }) }) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.