### Install Wine for Cross-Compilation on Linux Source: https://nativephp.com/docs/desktop/2/publishing/building Example commands for installing 32-bit Wine on Debian-based systems to facilitate Windows x64 application builds. ```bash # Example installation of wine for Debian based distributions (Ubuntu) dpkg --add-architecture i386 apt-get -y update apt-get -y install wine32 ``` -------------------------------- ### Run NativePHP Installer Source: https://nativephp.com/docs/desktop/2/getting-started/installation Execute the NativePHP installer to set up your project. This command publishes the service provider, configuration file, and installs Electron dependencies. ```shell php artisan native:install ``` -------------------------------- ### Start a Basic Child Process Source: https://nativephp.com/docs/desktop/2/digging-deeper/child-processes Use the ChildProcess facade to start a new process. Provide a command and a unique alias for management. Processes started this way are non-blocking and continue running in the background. ```php use Native\Desktop\Facades\ChildProcess; ChildProcess::start( cmd: 'tail -f storage/logs/laravel.log', alias: 'tail' ); ``` -------------------------------- ### Quit and Install Update Source: https://nativephp.com/docs/desktop/2/publishing/updating Quit the application and install any downloaded updates. The application will relaunch automatically after installation. ```APIDOC ## Quit and Install Update ### Description Quit the application and install any downloaded updates. The application will relaunch automatically after installation. ### Method ```php use Native\Desktop\Facades\AutoUpdater; AutoUpdater::quitAndInstall(); ``` ### Notes This method is optional. Any successfully downloaded updates will be applied automatically the next time the application starts. ``` -------------------------------- ### Start a Child Process with Command Line Arguments Source: https://nativephp.com/docs/desktop/2/digging-deeper/child-processes Pass command-line arguments to a child process when starting it. The `cmd` parameter accepts either a string or an array of arguments. ```php ChildProcess::start( cmd: ['tail', '-f', 'storage/logs/laravel.log'], alias: 'tail' ); ``` -------------------------------- ### Start a Child Process with Custom Environment Variables Source: https://nativephp.com/docs/desktop/2/digging-deeper/child-processes When starting a child process, you can provide custom environment variables using the `env` parameter. These variables will be available to the child process. ```php ChildProcess::start( cmd: 'tail ...', alias: 'tail', env: [ 'CUSTOM_ENV_VAR' => 'custom value', ] ); ``` -------------------------------- ### Update Composer and Install NativePHP Source: https://nativephp.com/docs/desktop/2/getting-started/upgrade-guide Run `composer update` to fetch the new dependencies, followed by `php artisan native:install` to set up the NativePHP environment. The `native:install` script is automatically registered as a `post-update-cmd`. ```sh composer update php artisan native:install ``` -------------------------------- ### Retrieving All Windows Source: https://nativephp.com/docs/desktop/2/the-basics/windows Gets a collection of all currently open native application windows. ```APIDOC ## Window::all() ### Description Retrieves all currently open native application windows. This method returns a collection of window objects. ### Method `Window::all(): Collection` ### Example ```php foreach (Window::all() as $window) { $window->url(route('home')); } ``` ``` -------------------------------- ### Start and Stop Queue Workers Source: https://nativephp.com/docs/desktop/2/digging-deeper/queues Use `QueueWorker::up()` to start a queue worker with a specific configuration or an alias from your config file. Use `QueueWorker::down()` to stop a worker by its alias. ```php use Native\DTOs\QueueConfig; use Native\Desktop\Facades\QueueWorker; $queueConfig = new QueueConfig(alias: 'manual', queuesToConsume: ['default'], memoryLimit: 1024, timeout: 600, sleep: 5); QueueWorker::up($queueConfig); // Alternatively, if you already have the worker config in your config/nativephp.php file, you may simply use its alias: QueueWorker::up(config: 'manual'); // Later... QueueWorker::down(alias: 'manual'); ``` -------------------------------- ### Quit and Install Update Source: https://nativephp.com/docs/desktop/2/publishing/updating Call the `quitAndInstall` method on the `AutoUpdater` facade to close the application and apply any downloaded updates. The application will automatically relaunch. ```php use Native\Desktop\Facades\AutoUpdater; AutoUpdater::quitAndInstall(); ``` -------------------------------- ### Get Setting with Default Value Source: https://nativephp.com/docs/desktop/2/the-basics/settings Provide a default value to the `get` method, which will be returned if the setting key is not found. This can be a static value or a closure. ```php $value = Settings::get('key', 'default'); ``` ```php $value = Settings::get('key', function () { return 'default'; }); ``` -------------------------------- ### Install NativePHP Desktop Package Source: https://nativephp.com/docs/desktop/2/getting-started/installation Install the NativePHP desktop package using Composer. This command adds all necessary classes, commands, and interfaces for your application to work with the Electron runtime. ```shell composer require nativephp/desktop ``` -------------------------------- ### Register Global Hotkeys in NativeAppServiceProvider Source: https://nativephp.com/docs/desktop/2/the-basics/global-hotkeys Register global hotkeys within the `boot` method of your `NativeAppServiceProvider`. This ensures hotkeys are available when the application starts. ```php namespace App\Providers; use Native\Desktop\Facades\GlobalShortcut; class NativeAppServiceProvider { public function boot(): void { GlobalShortcut::key('CmdOrCtrl+Shift+A') ->event("App\Events\MyShortcutEvent::class") ->register(); // Additional code, such as registering a menu, opening windows, etc. } } ``` -------------------------------- ### Get a Setting Value Source: https://nativephp.com/docs/desktop/2/the-basics/settings Retrieve a setting's value using its key with the `get` method. If the setting does not exist, `null` is returned by default. ```php $value = Settings::get('key'); ``` -------------------------------- ### Retrieve All Windows Source: https://nativephp.com/docs/desktop/2/the-basics/windows Get a collection of all currently open windows. This allows you to iterate through and manipulate each window. ```php foreach (Window::all() as $window) { $window->url(route('home')); } ``` -------------------------------- ### Start NativePHP Development Server Source: https://nativephp.com/docs/desktop/2/getting-started/installation Run your Laravel application in a native desktop window using the NativePHP development server. Ensure your application runs correctly in the browser first to address potential exceptions. ```shell php artisan native:run ``` -------------------------------- ### Start Vite Development Server Source: https://nativephp.com/docs/desktop/2/getting-started/development When using Vite, run this command in a separate terminal session to enable hot reloading of your application's assets. Ensure the Vite script tag is included in your views. ```shell npm run dev ``` -------------------------------- ### Accessing Bundled Files with Storage Facade Source: https://nativephp.com/docs/desktop/2/digging-deeper/files Use the Storage facade with the 'extras' disk to get the absolute path to a bundled file. The 'extras' disk is read-only and files are overwritten on update. ```php use Illuminate\Support\Facades\Storage; $toolPath = Storage::disk('extras')->path('my-tool.exe'); ``` -------------------------------- ### Start a Persistent Child Process Source: https://nativephp.com/docs/desktop/2/digging-deeper/child-processes Mark a child process as `persistent` to ensure it automatically restarts if it crashes. This behavior is similar to process managers like `supervisord`. ```php ChildProcess::start( cmd: ['tail', '-f', 'logs/laravel.log'], alias: 'tail', persistent: true ); ``` -------------------------------- ### Handle Notification Clicks with References Source: https://nativephp.com/docs/desktop/2/the-basics/notifications Associate notifications with specific data using custom references and handle click events. This example shows how to link a post to its notification and open the post's URL when the notification is clicked. ```php use App\Events\PostNotificationClicked; use App\Models\Post; Post::recentlyCreated() ->get() ->each(function(Post $post) { Notification::title('New post: ' . $post->title) ->reference($post->id) ->event(PostNotificationClicked::class) ->show(); }); Event::listen(PostNotificationClicked::class, function (PostNotificationClicked $event) { $post = Post::findOrFail($event->reference); Window::open()->url($post->url); }); ``` -------------------------------- ### Start a Child Process with Custom Working Directory Source: https://nativephp.com/docs/desktop/2/digging-deeper/child-processes Specify a custom current working directory (cwd) for a child process by passing the path to the `$cwd` parameter. This is useful when the command relies on relative paths within a specific directory. ```php ChildProcess::start( cmd: ['tail', '-f', 'logs/laravel.log'], alias: 'tail', cwd: storage_path() ); ``` -------------------------------- ### Get Current System Theme Source: https://nativephp.com/docs/desktop/2/the-basics/system Detect the user's operating system theme preference (light, dark, or system default) to adapt the application's UI accordingly. ```php $theme = System::theme(); // $theme => SystemThemesEnum::LIGHT, SystemThemesEnum::DARK or SystemThemesEnum::SYSTEM ``` -------------------------------- ### Import the App Facade Source: https://nativephp.com/docs/desktop/2/the-basics/application Add this to the top of your file to use the App facade. ```php use Native\Desktop\Facades\App; ``` -------------------------------- ### Get All Displays Information Source: https://nativephp.com/docs/desktop/2/the-basics/screens Retrieves an array containing details for each physical display connected to the system. This includes bounds, size, and work area information. Note that internal laptop screens may not be included if the laptop lid is closed. ```php use Native\Desktop\Facades\Screen; $screens = Screen::displays(); [ 0 => [ 'bounds' => [ 'x' => 0, 'y' => 0, 'width' => 2560, 'height' => 1440, ], 'detected' => true, 'id' => 2026675401, 'internal' => false, 'label' => 'U3277WB', 'size' => [ 'width' => 2560, 'height' => 1440, ], 'workArea' => [ 'x' => 0, 'y' => 25, 'width' => 2560, 'height' => 1345, ], // ... ], // ... ] ``` -------------------------------- ### Create Application Menu Source: https://nativephp.com/docs/desktop/2/the-basics/application-menu Create and register a new application menu by passing predefined menu items as arguments to `Menu::create()`. This method should be called within the `boot` method of your `NativeAppServiceProvider`. ```php namespace App\Providers; use Native\Desktop\Facades\Menu; use Native\Desktop\Facades\Window; class NativeAppServiceProvider { public function boot(): void { Menu::create( Menu::app(), // Only on macOS Menu::file(), Menu::edit(), Menu::view(), Menu::window(), ); Window::open(); } } ``` -------------------------------- ### Import Clipboard Facade Source: https://nativephp.com/docs/desktop/2/the-basics/clipboard Import the Clipboard facade to use its methods. ```php use Native\Desktop\Facades\Clipboard; ``` -------------------------------- ### Import Shell Facade Source: https://nativephp.com/docs/desktop/2/the-basics/shell Add this to the top of your file to use the Shell facade. ```php use Native\Desktop\Facades\Shell; ``` -------------------------------- ### Using Bundled Tools with ChildProcess Source: https://nativephp.com/docs/desktop/2/digging-deeper/files Execute bundled tools using the ChildProcess facade after obtaining their path via the Storage facade. Ensure the tool is placed in the 'extras/' directory. ```php use Illuminate\Support\Facades\Storage; use Native\Desktop\Facades\ChildProcess; // Get the path to a bundled executable $toolPath = Storage::disk('extras')->path('my-tool.sh'); ChildProcess::start( cmd: $toolPath, alias: 'my-tool' ); ``` -------------------------------- ### Focus the App Source: https://nativephp.com/docs/desktop/2/the-basics/application Use the `focus` method to bring the application's window to the front. Behavior varies by OS. ```php App::focus(); ``` -------------------------------- ### Import System Facade Source: https://nativephp.com/docs/desktop/2/the-basics/system Import the System facade to access its methods for system-level operations. ```php use Native\Desktop\Facades\System; ``` -------------------------------- ### Get System Idle Time Source: https://nativephp.com/docs/desktop/2/the-basics/power-monitor Retrieves the number of seconds the system has been idle. ```APIDOC ## Get System Idle Time ### Description Retrieves the total number of seconds the system has been idle. ### Method `getSystemIdleTime()` ### Returns - `int` - The number of seconds the system has been idle. ### Example ```php use Native\Desktop\Facades\PowerMonitor; $seconds = PowerMonitor::getSystemIdleTime(); ``` ``` -------------------------------- ### Retrieving the Current Window Source: https://nativephp.com/docs/desktop/2/the-basics/windows Gets the currently focused native application window object. ```APIDOC ## Window::current() ### Description Retrieves the currently focused native application window. This method returns an object containing details about the window. ### Method `Window::current(): object` ### Response Properties - **id** (string) - The ID of the window. - **title** (string) - The title of the window. - **width** (int) - The width of the window. - **height** (int) - The height of the window. - **x** (int) - The x position of the window. - **y** (int) - The y position of the window. - **alwaysOnTop** (bool) - Whether the window is always on top. ### Example ```php $currentWindow = Window::current(); ``` ``` -------------------------------- ### Advanced Window Instance Assertions Source: https://nativephp.com/docs/desktop/2/testing/windows This advanced snippet demonstrates how to mock a window instance and assert specific method calls like `route`, `transparent`, `height`, `width`, `minHeight`, and `minWidth`. It requires `Mockery` and specific NativePHP Desktop classes. ```php use Illuminate\Support\Facades\Http; use Native\Desktop\Facades\Window; use Native\Desktop\Windows\Window as WindowImplementation; use Mockery; #[ Framework\Attributes\Test] public function example(): void { Http::fake(); Window::fake(); Window::alwaysReturnWindows([ $mockWindow = Mockery::mock(WindowImplementation::class)->makePartial(), ]); $mockWindow->shouldReceive('route')->once()->with('action')->andReturnSelf(); $mockWindow->shouldReceive('transparent')->once()->andReturnSelf(); $mockWindow->shouldReceive('height')->once()->with(500)->andReturnSelf(); $mockWindow->shouldReceive('width')->once()->with(775)->andReturnSelf(); $mockWindow->shouldReceive('minHeight')->once()->with(500)->andReturnSelf(); $mockWindow->shouldReceive('minWidth')->once()->with(775)->andReturnSelf(); $this->get(route('action')); } ``` -------------------------------- ### Open a New Window Source: https://nativephp.com/docs/desktop/2/the-basics/windows Use the Window facade to open a new native application window. You can specify dimensions and an optional unique identifier. If no ID is provided, it defaults to 'main'. ```php namespace App\Providers; use Native\Desktop\Facades\Window; class NativeAppServiceProvider { public function boot(): void { Window::open() ->width(800) ->height(800); } } ``` -------------------------------- ### Get Notification Reference Source: https://nativephp.com/docs/desktop/2/the-basics/notifications Retrieve the reference property of a notification after it has been created. This can be used for tracking. ```php $notification = Notification::title('Hello from NativePHP')->show(); $notification->reference; ``` -------------------------------- ### Default NativeAppServiceProvider Source: https://nativephp.com/docs/desktop/2/the-basics/app-lifecycle This is the default `NativeAppServiceProvider` published by NativePHP. Use the `boot` method to open windows or register global shortcuts. Implement `ProvidesPhpIni` to set PHP configuration directives. ```php namespace App\Providers; use Native\Desktop\Facades\Window; use Native\Desktop\Contracts\ProvidesPhpIni; class NativeAppServiceProvider implements ProvidesPhpIni { /** * Executed once the native application has been booted. * Use this method to open windows, register global shortcuts, etc. */ public function boot(): void { Window::open(); } /** * Return an array of php.ini directives to be set. */ public function phpIni(): array { return [ ]; } } ``` -------------------------------- ### Create Default Application Menu Source: https://nativephp.com/docs/desktop/2/the-basics/application-menu Use `Menu::default()` as a shortcut to create a standard application menu containing File, Edit, View, and Window items. This replaces the need to manually list each default menu. ```php // Instead of... Menu::create( Menu::app(), Menu::file(), Menu::edit(), Menu::view(), Menu::window(), ); // You can just write... Menu::default(); ``` -------------------------------- ### Get current app version Source: https://nativephp.com/docs/desktop/2/the-basics/application Retrieves the current application version, which is defined in the `config/nativephp.php` file. ```APIDOC ## Current Version ### Description Retrieves the current application version, as defined in the `config/nativephp.php` file. ### Method `App::version()` ``` -------------------------------- ### Configuring Alert Buttons Source: https://nativephp.com/docs/desktop/2/the-basics/alerts Define custom buttons for the alert and get the user's selection. ```APIDOC ## Configuring Alert Buttons ### Description Allows you to define custom buttons for the alert. The `show()` method returns the index of the clicked button. ### Method ```php Alert::new()->buttons(array $buttons) ``` ### Parameters #### Request Body - **buttons** (array) - An array of strings representing the button labels. ### Request Example ```php use Native\Desktop\Facades\Alert; $clickedButtonIndex = Alert::new() ->buttons(['Yes', 'No', 'Maybe']) ->show('Do you like pizza?'); // $clickedButtonIndex will be 0 for 'Yes', 1 for 'No', 2 for 'Maybe' ``` ### Response #### Success Response (200) - **return value** (int) - The index of the button clicked by the user. ``` -------------------------------- ### Import Alert Facade Source: https://nativephp.com/docs/desktop/2/the-basics/alerts Import the Alert facade to use its methods for creating native alerts. ```php use Native\Desktop\Facades\Alert; ``` -------------------------------- ### Get All Running Child Processes Source: https://nativephp.com/docs/desktop/2/digging-deeper/child-processes Retrieve an array of all currently running `Native\Desktop\ChildProcess` instances managed by NativePHP. ```php $processes = ChildProcess::all(); ``` -------------------------------- ### Create Menu Bar with Initial Label Source: https://nativephp.com/docs/desktop/2/the-basics/menu-bar Set an initial text label for the menu bar when it is first created. ```php MenuBar::create() ->label('Status: Online'); ``` -------------------------------- ### Locale Information Source: https://nativephp.com/docs/desktop/2/the-basics/application Provides methods to get the application's locale, country code, and system-wide locale settings. ```APIDOC ## Locale information ### Description Provides methods to access the system's localization information. ### Methods - `App::getLocale()`: Returns the locale used by the app (e.g., "de", "fr-FR"). - `App::getLocaleCountryCode()`: Returns the user's system country code (e.g., "US", "DE"). Returns an empty string if detection fails. - `App::getSystemLocale()`: Returns the system-wide locale setting (e.g., "it-IT", "de-DE"). ``` -------------------------------- ### Seed Database with Sample Data Source: https://nativephp.com/docs/desktop/2/digging-deeper/databases Populate your development database with sample data using configured Database Seeders. ```shell php artisan native:seed ``` -------------------------------- ### Get Current App Version Source: https://nativephp.com/docs/desktop/2/the-basics/application Retrieve the current application version defined in `config/nativephp.php` using the `version` method. ```php $version = App::version(); ``` -------------------------------- ### Opening Windows Source: https://nativephp.com/docs/desktop/2/the-basics/windows Opens a new native application window. You can specify dimensions and a unique ID for the window. If no ID is provided, it defaults to 'main'. ```APIDOC ## Window::open() ### Description Opens a new native application window. By default, it opens the root URL of your application. You can specify a unique identifier to distinguish between multiple windows. ### Method `Window::open(string $id = 'main')` ### Parameters #### Path Parameters - **id** (string) - Optional - A unique identifier for the window. Defaults to 'main'. ### Example ```php Window::open() ->width(800) ->height(800); Window::open('settings') ->route('settings') ->width(800) ->height(800); ``` ``` -------------------------------- ### Get Current Thermal State Source: https://nativephp.com/docs/desktop/2/the-basics/power-monitor Retrieves the current thermal state of the system, returning an enum value of `ThermalStatesEnum`. ```APIDOC ## Get Current Thermal State ### Description Retrieves the current thermal state of the system. ### Method `getCurrentThermalState()` ### Returns - `ThermalStatesEnum` - An enum value representing the current thermal state (e.g., UNKNOWN, NOMINAL, FAIR, SERIOUS, CRITICAL). ### Example ```php use Native\Desktop\Enums\ThermalStatesEnum; use Native\Desktop\Facades\PowerMonitor; $thermalState = PowerMonitor::getCurrentThermalState(); if ($state === ThermalStatesEnum::CRITICAL) { // Wow, the CPU is running hot! } ``` ``` -------------------------------- ### Get Current Thermal State Source: https://nativephp.com/docs/desktop/2/the-basics/power-monitor Obtain the current thermal state of the system. Returns an enum value of `ThermalStatesEnum`. ```php use Native\Desktop\Enums\ThermalStatesEnum; use Native\Desktop\Facades\PowerMonitor; $thermalState = PowerMonitor::getCurrentThermalState(); if ($state === ThermalStatesEnum::CRITICAL) { // Wow, the CPU is running hot! } ``` -------------------------------- ### Get System Idle Time Source: https://nativephp.com/docs/desktop/2/the-basics/power-monitor Retrieve the number of seconds the system has been idle. Requires importing the `PowerMonitor` facade. ```php use Native\Desktop\Facades\PowerMonitor; $seconds = PowerMonitor::getSystemIdleTime(); ``` -------------------------------- ### Import Settings Facade Source: https://nativephp.com/docs/desktop/2/the-basics/settings Import the Settings facade to access its methods for managing application settings. ```php use Native\Desktop\Facades\Settings; ``` -------------------------------- ### Show Hidden Files Source: https://nativephp.com/docs/desktop/2/the-basics/dialogs Include hidden files (those starting with a dot) in the dialog's view by using the `withHiddenFiles()` method. ```php Dialog::new() ->withHiddenFiles() ->open(); ``` -------------------------------- ### Open File Dialog Source: https://nativephp.com/docs/desktop/2/the-basics/dialogs Use the `open()` method to display a native file selection dialog. The return value is the selected file path, an array of paths, or null. ```php Dialog::new() ->title('Select a file') ->open(); ``` -------------------------------- ### Import Menu Facade Source: https://nativephp.com/docs/desktop/2/the-basics/application-menu Import the Menu facade to access its methods for menu creation and configuration. ```php use Native\Desktop\Facades\Menu; ``` -------------------------------- ### Get System Idle State Source: https://nativephp.com/docs/desktop/2/the-basics/power-monitor Checks if the system is idle. It expects a threshold in seconds and returns an enum value of `SystemIdleStatesEnum`. ```APIDOC ## Get System Idle State ### Description Checks if the system is idle based on a provided threshold. ### Method `getSystemIdleState(int $threshold)` ### Parameters #### Arguments - **threshold** (int) - Required - The number of seconds the system must be idle before it is considered idle. ### Returns - `SystemIdleStatesEnum` - An enum value representing the system's idle state (e.g., ACTIVE, IDLE, LOCKED, UNKNOWN). ### Example ```php use Native\Desktop\Enums\SystemIdleStatesEnum; use Native\Desktop\Facades\PowerMonitor; $state = PowerMonitor::getSystemIdleState(60); if ($state === SystemIdleStatesEnum::IDLE) { // The system is idle! } ``` ``` -------------------------------- ### Set Application Theme Source: https://nativephp.com/docs/desktop/2/the-basics/system Override the system's theme preference and set the application's theme to light, dark, or system default. Setting to SYSTEM resets to OS default. ```php System::theme(SystemThemesEnum::DARK); ``` -------------------------------- ### Get Locale Information Source: https://nativephp.com/docs/desktop/2/the-basics/application Access locale details like the app's locale, country code, and system locale. Useful for localization. ```php App::getLocale(); // e.g. "de", "fr-FR" App::getLocaleCountryCode(); // e.g. "US", "DE" App::getSystemLocale(); // e.g. "it-IT", "de-DE" ``` -------------------------------- ### Import Dialog Facade Source: https://nativephp.com/docs/desktop/2/the-basics/dialogs Import the `Dialog` facade to access its methods for creating native dialogs. ```php use Native\Desktop\Dialog; ``` -------------------------------- ### Seed User Database on First App Run Source: https://nativephp.com/docs/desktop/2/publishing/building Run this code within your application's boot process to seed the user's database if it hasn't been seeded already. This ensures initial data is available. ```php use App\Models\Config; use Illuminate\Support\Facades\Artisan; if (Config::where('seeded', true)->count() === 1) { Artisan::call('db:seed'); } ``` -------------------------------- ### Retrieve Current Window Source: https://nativephp.com/docs/desktop/2/the-basics/windows Get an object representing the currently focused window. This object contains properties like ID, title, dimensions, and position. ```php $currentWindow = Window::current(); ``` -------------------------------- ### Get App Badge Count (macOS/Linux) Source: https://nativephp.com/docs/desktop/2/the-basics/application Retrieve the current app badge count by calling `badgeCount` without arguments. Only available on macOS and Linux. ```php $badgeCount = App::badgeCount(); ``` -------------------------------- ### Relaunch the App Source: https://nativephp.com/docs/desktop/2/the-basics/application Use the `relaunch` method to quit and restart the application. ```php App::relaunch(); ``` -------------------------------- ### Get a Single Running Child Process by Alias Source: https://nativephp.com/docs/desktop/2/digging-deeper/child-processes Retrieve a specific running child process instance using its alias. This returns a `Native\Desktop\ChildProcess` object. ```php $tail = ChildProcess::get('tail'); ``` -------------------------------- ### Run Database Migrations Source: https://nativephp.com/docs/desktop/2/digging-deeper/databases Use this command to migrate your development database. It functions identically to Laravel's `migrate` command. ```shell php artisan native:migrate ``` -------------------------------- ### Show File in Folder Source: https://nativephp.com/docs/desktop/2/the-basics/shell Opens the specified file path in the user's default file manager. ```php Shell::showInFolder($path); ``` -------------------------------- ### Get Cursor Position Source: https://nativephp.com/docs/desktop/2/the-basics/screens The `cursorPosition` method returns an object with the `x` and `y` coordinates of the mouse cursor's current absolute position relative to the primary display. ```APIDOC ## Get Cursor Position ### Description Retrieves the current absolute coordinates of the mouse cursor. ### Method ```php Screen::cursorPosition() ``` ### Response Example ```json { "x": 627, "y": 168 } ``` ``` -------------------------------- ### Import Notification Facade Source: https://nativephp.com/docs/desktop/2/the-basics/notifications Import the Notification facade to use its methods for sending system notifications. ```php use Native\Desktop\Facades\Notification; ``` -------------------------------- ### Get System Time Zone Source: https://nativephp.com/docs/desktop/2/the-basics/system Retrieve the current time zone identifier from the operating system. This helps in displaying dates and times accurately without manual user input. ```php $timezone = System::timezone(); // $timezone => 'Europe/London' ``` -------------------------------- ### Fake and Assert Window Behavior Source: https://nativephp.com/docs/desktop/2/testing/windows Use this snippet to fake window and HTTP requests, then assert that windows were opened, closed, or hidden. It requires the `Native Desktop Facades Window` and `Illuminate Support Facades Http` namespaces. ```php use Native\Desktop\Facades\Window; use Illuminate\Support\Facades\Http; #[ Framework\Attributes\Test] public function example(): void { Http::fake(); Window::fake(); $this->get('/whatever-action'); Window::assertOpened(fn (string $windowId) => Str::startsWith($windowId, ['window-name'])); Window::assertClosed('window-name'); Window::assertHidden('window-name'); } ``` -------------------------------- ### Get Cursor Position Source: https://nativephp.com/docs/desktop/2/the-basics/screens Fetches the current absolute coordinates of the mouse cursor. The position is relative to the top-left corner of the primary display and can be positive or negative, especially on secondary displays. ```php use Native\Desktop\Facades\Screen; $position = Screen::cursorPosition(); (object) [ 'x' => 627, 'y' => 168, ] ``` -------------------------------- ### Relaunch the app Source: https://nativephp.com/docs/desktop/2/the-basics/application The `relaunch` method quits the current application instance and then relaunches it. ```APIDOC ## Relaunch the app ### Description Quits the application and then relaunches it. ### Method `App::relaunch()` ``` -------------------------------- ### Listen for Child Process Messages in JavaScript Source: https://nativephp.com/docs/desktop/2/digging-deeper/child-processes Listen for `MessageReceived` events on the frontend after the `native:init` event. This example appends received data from processes aliased as 'tail' to a container element. ```javascript window.addEventListener('native:init', () => { Native.on('Native\Desktop\Events\ChildProcess\MessageReceived', (event) => { if (event.alias === 'tail') { container.append(event.data) } }) // }) ``` -------------------------------- ### Open File with Default Application Source: https://nativephp.com/docs/desktop/2/the-basics/shell Attempts to open the specified file path using the default application for its type. Returns an empty string on success or an error message on failure. ```php $result = Shell::openFile($path); ``` -------------------------------- ### Create Menu Bar with Dock Icon Source: https://nativephp.com/docs/desktop/2/the-basics/menu-bar Integrate a menu bar into an application that already uses windows. This option ensures the dock icon remains visible. ```php namespace App\Providers; use Native\Desktop\Facades\MenuBar; class NativeAppServiceProvider { public function boot(): void { MenuBar::create() ->showDockIcon(); } } ``` -------------------------------- ### Handle Notification Action Button Clicks Source: https://nativephp.com/docs/desktop/2/the-basics/notifications Listen for the `NotificationActionClicked` event to determine which action button was pressed. The event provides an `$index` property (starting from 0) corresponding to the button's order. ```php use Native\Desktop\Events\Notifications\NotificationActionClicked; Notification::title('Do you accept?') ->addAction('Accept') // This action will be $index = 0 ->addAction('Decline') // This action will be $index = 1 ->show(); Event::listen(NotificationActionClicked::class, function (NotificationActionClicked $event) { if ($event->index === 0) { // 'Accept' clicked } elseif ($event->index === 1) { // 'Decline' clicked } }); ``` -------------------------------- ### Create Window Menu Source: https://nativephp.com/docs/desktop/2/the-basics/application-menu Generate the default Window menu, offering standard window management actions like Minimize and Zoom. The default label is 'Window'. ```php Menu::create( Menu::app(), Menu::window() ); ``` -------------------------------- ### Get All Displays Source: https://nativephp.com/docs/desktop/2/the-basics/screens The `displays` method returns an array containing information about all physical displays connected to the system. This includes details like screen bounds, dimensions, and whether the display is internal or detected. ```APIDOC ## Get All Displays ### Description Retrieves an array of display objects, each representing a physical screen connected to the computer. ### Method ```php Screen::displays() ``` ### Response Example ```json [ { "bounds": { "x": 0, "y": 0, "width": 2560, "height": 1440 }, "detected": true, "id": 2026675401, "internal": false, "label": "U3277WB", "size": { "width": 2560, "height": 1440 }, "workArea": { "x": 0, "y": 25, "width": 2560, "height": 1345 } } ] ``` ``` -------------------------------- ### Show Context Menu Programmatically Source: https://nativephp.com/docs/desktop/2/the-basics/menu-bar Programmatically display the context menu associated with the menu bar icon. ```APIDOC ## Opening a Context Menu You can programmatically display the context menu that has been configured for your Menu Bar app using the `showContextMenu()` method. This method will show the same context menu that appears when a user clicks on the Menu Bar app. ```php MenuBar::showContextMenu(); ``` This is useful when you want to trigger the context menu from within your application logic, such as in response to a keyboard shortcut, button click, or other application events. ``` -------------------------------- ### Listen to Native Events in Livewire (Class Name) Source: https://nativephp.com/docs/desktop/2/digging-deeper/broadcasting Use the `#[On]` attribute with the `native:` prefix and the event's class name (::class) for a more convenient way to listen for native events in Livewire. ```php use Native\Desktop\Events\Windows\WindowBlurred; use Native\Desktop\Events\Windows\WindowFocused; class AppSettings extends Component { public $windowFocused = true; #[On('native:'.WindowFocused::class)] public function windowFocused() { $this->windowFocused = true; } #[On('native:'.WindowBlurred::class)] public function windowBlurred() { $this->windowFocused = false; } } ``` -------------------------------- ### Create a Custom Application Menu with Submenus Source: https://nativephp.com/docs/desktop/2/the-basics/application-menu Use `Menu::make()` to construct a custom menu instance that can be nested within other menus to create submenus. ```php Menu::create( Menu::app(), Menu::make( Menu::link('https://nativephp.com', 'Documentation'), )->label('My Submenu') ); ``` -------------------------------- ### Allow Multiple File Selections Source: https://nativephp.com/docs/desktop/2/the-basics/dialogs Enable the selection of multiple files by calling the `multiple()` method. This changes the return type of `open()` to an array of file paths. ```php $files = Dialog::new() ->multiple() ->open(); ``` -------------------------------- ### Open Save Dialog Source: https://nativephp.com/docs/desktop/2/the-basics/dialogs Use the `save()` method to prompt the user for a file path to save. This method returns the chosen path but does not perform the save operation. ```php Dialog::new() ->title('Save a file') ->save(); ``` -------------------------------- ### Set and Get App Badge Count (macOS and Linux) Source: https://nativephp.com/docs/desktop/2/the-basics/application Manages the application's badge count, which appears on the dock icon (macOS) or Unity launcher (Linux). Supports setting a count, removing it (setting to 0), and retrieving the current count. ```APIDOC ## App Badge Count (macOS and Linux) ### Description Manages the app's badge count. On macOS, it shows on the dock icon. On Linux, it only works for the Unity launcher. This feature is available on macOS and Linux. ### Methods - `App::badgeCount(int $count)`: Sets the badge count. Use `0` to remove it. - `App::badgeCount()`: Retrieves the current badge count. ``` -------------------------------- ### Open Folder Dialog Source: https://nativephp.com/docs/desktop/2/the-basics/dialogs Use the `folders()` method to configure the dialog specifically for selecting directories instead of files. ```php Dialog::new() ->folders() ->open(); ``` -------------------------------- ### Open Specific Route in Window Source: https://nativephp.com/docs/desktop/2/the-basics/windows Opens the root URL of your application, specifying a route name to load. Ensure the route exists in your application. ```php Window::open() ->route('home'); ``` -------------------------------- ### Add Fullscreen Menu Item Source: https://nativephp.com/docs/desktop/2/the-basics/application-menu Enable fullscreen mode for the application window by adding a fullscreen item using `Menu::fullscreen()`. This functionality depends on the window being fullscreen-able. ```php Menu::make() Menu::fullscreen('Supersize me!'), ); ``` -------------------------------- ### Open Window in Full Screen Source: https://nativephp.com/docs/desktop/2/the-basics/windows Opens the window directly in Full Screen Mode. ```php Window::open()->fullscreen(); ``` -------------------------------- ### Menu Bar Window Sizing Source: https://nativephp.com/docs/desktop/2/the-basics/menu-bar Set the default size of the menu bar window using width() and height() methods. ```APIDOC ## Menu Bar Window Sizing The default size of the menu bar window is **400x400 pixels**. You may use the `width()` and `height()` methods to specify the size of the window that will be opened when the user clicks on the menu bar icon. ```php MenuBar::create() ->width(800) ->height(600); ``` ``` -------------------------------- ### Configure Environment Key Cleanup Source: https://nativephp.com/docs/desktop/2/getting-started/env-files Specify environment keys to be removed from the .env file when bundling for production. Wildcards can be used to match multiple keys. ```php /** * A list of environment keys that should be removed from the * .env file when the application is bundled for production. * You may use wildcards to match multiple keys. */ 'cleanup_env_keys' => [ 'AWS_*', 'DO_SPACES_*', '*_SECRET', 'NATIVEPHP_UPDATER_PATH', 'NATIVEPHP_APPLE_ID', 'NATIVEPHP_APPLE_ID_PASS', 'NATIVEPHP_APPLE_TEAM_ID', ] ``` -------------------------------- ### Run a NativePHP Build Source: https://nativephp.com/docs/desktop/2/publishing/publishing Execute this command to build your application for the current platform and architecture. Ensure your app version is updated in the .env file before running. ```shell php artisan native:publish ``` -------------------------------- ### Set Window Position Source: https://nativephp.com/docs/desktop/2/the-basics/windows Sets the initial position of the window on the screen using X and Y coordinates. ```php Window::open() ->position(100, 100); ``` -------------------------------- ### Set Window Dimensions Source: https://nativephp.com/docs/desktop/2/the-basics/windows Sets the initial width and height of the window in pixels. ```php Window::open() ->width(800) ->height(800); ``` -------------------------------- ### Check PHP Version (Production Build - Windows) Source: https://nativephp.com/docs/desktop/2/getting-started/debugging Verify the PHP version used in production builds on Windows. This command checks the bundled PHP executable within the application's distribution. ```shell C:\path\to\your\app\dist\win-unpacked\resources\app.asar.unpacked\resources\php\php.exe -v ``` -------------------------------- ### Open at Login (macOS and Windows) Source: https://nativephp.com/docs/desktop/2/the-basics/application Controls whether the application automatically opens on system login. Supports enabling, disabling, and checking the current status. This feature is available on macOS and Windows. ```APIDOC ## Open at login (macOS and Windows) ### Description Configures whether the application should open automatically when the user logs in. Available on macOS and Windows. ### Methods - `App::openAtLogin(bool $open)`: Sets the 'open at login' preference. Pass `true` to enable, `false` to disable. - `App::openAtLogin()`: Checks if the app is set to open at login. Returns a boolean. ``` -------------------------------- ### Configure Pre- and Post-Build Commands Source: https://nativephp.com/docs/desktop/2/publishing/building Add these hooks to your `config/nativephp.php` file to run commands before or after the build process, useful for asset compilation. ```php [ 'npm run build', 'php artisan optimize', ], 'postbuild' => [ 'npm run release', ], // ... ]; ``` -------------------------------- ### Configure Webpage Features Source: https://nativephp.com/docs/desktop/2/the-basics/windows Control web page features by passing a `webPreferences` configuration array to `webPreferences()`. Note that `sandbox`, `preload`, and `contextIsolation` are locked for security. ```php Window::open() ->webPreferences([ 'nodeIntegration' => true, 'spellcheck' => true, 'backgroundThrottling' => true, ]); ``` ```php [ 'sandbox' => false, // locked 'preload' => '{preload-path}', // locked 'contextIsolation' => true, // locked 'spellcheck' => false, 'nodeIntegration' => false, 'backgroundThrottling' => false, ] ``` -------------------------------- ### Execute Artisan Commands with ChildProcess Source: https://nativephp.com/docs/desktop/2/digging-deeper/child-processes Conveniently run Artisan commands as child processes. Provide the command name and an alias for easy reference. ```php ChildProcess::artisan('smtp:serve', alias: 'smtp-server'); ``` -------------------------------- ### Cut, Copy, and Paste Source: https://nativephp.com/docs/desktop/2/the-basics/application-menu Add standard cut, copy, and paste actions to your menu using `Menu::cut()`, `Menu::copy()`, and `Menu::paste()`. These are alternatives if the default Edit menu is not included. ```APIDOC ## Cut, Copy, and Paste ### Description Provides standard cut, copy, and paste functionality, typically used when the default Edit menu is omitted. ### Methods - `Menu::cut()` - `Menu::copy()` - `Menu::paste()` ### Usage Example ```php Menu::make( Menu::cut(), Menu::copy(), Menu::paste() ); ``` **Note:** These are best suited for standard text input fields. For complex workflows, implement custom logic. ``` -------------------------------- ### Fake NativePHP Window Testing Source: https://nativephp.com/docs/desktop/2/testing/basics Use `Window::fake()` to replace the real window implementation with a fake one for testing. This allows you to assert window interactions without running the full Electron application. ```php use Native\Desktop\Facades\Window; #[ PHPUnit\Framework\Attributes\Test] public function example(): void { Window::fake(); $this->get('/whatever-action'); Window::assertOpened('window-name'); } ``` -------------------------------- ### Show File in Folder Source: https://nativephp.com/docs/desktop/2/the-basics/shell Opens the specified file path in the user's default file manager (e.g., File Explorer, Finder). ```APIDOC ## Shell::showInFolder ### Description Opens the given file path in the user's default file manager. ### Method ```php Shell::showInFolder(string $path) ``` ### Parameters #### Path Parameters - **path** (string) - Required - The path to the file to show. ``` -------------------------------- ### Fullscreen Source: https://nativephp.com/docs/desktop/2/the-basics/application-menu Allow users to enter fullscreen mode for the currently focused window using the `Menu::fullscreen()` method. This functionality is dependent on the window being fullscreen-able. ```APIDOC ## Fullscreen ### Description Adds an item to the menu that attempts to enter fullscreen mode for the active window. ### Method - `Menu::fullscreen(string $label)` ### Parameters - `label` (string): The text displayed for the fullscreen menu item. ### Usage Example ```php Menu::make( Menu::fullscreen('Supersize me!') ); ``` ``` -------------------------------- ### Compress PHP Binary for Windows Source: https://nativephp.com/docs/desktop/2/digging-deeper/php-binaries Use PowerShell to compress the PHP executable into a zip file with the specified naming convention for Windows. ```powershell powershell Compress-Archive -Path "php.exe" -DestinationPath "php-[PHP_MAJOR_VERSION].[PHP_MINOR_VERSION].zip" ``` -------------------------------- ### Run NativePHP Build Source: https://nativephp.com/docs/desktop/2/publishing/building Execute the build command to compile your application for the current platform and architecture. ```shell php artisan native:build ``` -------------------------------- ### Listen for Menu Bar Click Event Source: https://nativephp.com/docs/desktop/2/the-basics/menu-bar Attach a custom event to be fired when the menu bar icon is clicked, providing details about the click event. ```php MenuBar::create()->event(MenuBarClicked::class); class MenuBarClicked { public function __construct(public array $combo, public array $bounds, public array $position) { // $combo - details of any combo keys pressed when the click occurred // $bounds - the current absolute bounds of the menu bar icon at the time of the event // $position - the absolute cursor position at the time of the event } } ``` -------------------------------- ### Configure Menu Bar Route Source: https://nativephp.com/docs/desktop/2/the-basics/menu-bar Specify a named route to open when the menu bar is clicked. Defaults to the application's root URL. ```php MenuBar::create() ->route('home'); ``` -------------------------------- ### Open Multiple Windows with Identifiers Source: https://nativephp.com/docs/desktop/2/the-basics/windows Open multiple distinct windows by providing unique identifiers to the `Window::open()` method. This allows for individual management of each window. ```php Window::open('home') ->width(800) ->height(800); Window::open('settings') ->route('settings') ->width(800) ->height(800); ``` -------------------------------- ### Configure Menu Bar URL Source: https://nativephp.com/docs/desktop/2/the-basics/menu-bar Set a specific absolute URL to open when the menu bar is clicked. ```php MenuBar::create() ->url('https://google.com'); ``` -------------------------------- ### Focus the app Source: https://nativephp.com/docs/desktop/2/the-basics/application Brings the application to the foreground. Behavior varies by OS: focuses the first window on Linux and Windows, and makes the app active on macOS. ```APIDOC ## Focus the app ### Description Brings the application to the foreground. On Linux, it focuses on the first visible window. On macOS, it makes the application the active one. On Windows, it focuses on the application's first window. ### Method `App::focus()` ``` -------------------------------- ### Listen to Native Events with JavaScript Source: https://nativephp.com/docs/desktop/2/digging-deeper/broadcasting Use `window.Native.on()` within a `native:init` handler to listen for native and custom events. The `payload` and `event` are passed to the callback. ```javascript window.addEventListener('native:init', () => { Native.on('Native\Desktop\Events\Windows\WindowBlurred', (payload, event) => { // }) // }) ``` -------------------------------- ### Configure Azure Trusted Signing for Windows Source: https://nativephp.com/docs/desktop/2/publishing/building Set these environment variables in your `.env` file to enable Azure Trusted Signing for code signing your Windows builds. ```dotenv # Azure AD authentication AZURE_TENANT_ID=your-tenant-id AZURE_CLIENT_ID=your-client-id AZURE_CLIENT_SECRET=your-client-secret # Azure Trusted Signing configuration # This is the CommonName (CN) value - your full name or company name # as entered in the Identity Validation Request form NATIVEPHP_AZURE_PUBLISHER_NAME=your-publisher-name # The endpoint URL for the Azure region where your certificate is stored NATIVEPHP_AZURE_ENDPOINT=https://eus.codesigning.azure.net/ # The name of your certificate profile (NOT the Trusted Signing Account) NATIVEPHP_AZURE_CERTIFICATE_PROFILE_NAME=your-certificate-profile # Your Trusted Signing Account name (NOT the app registration display name) # This is the account name shown in Azure Trusted Signing, not your login name NATIVEPHP_AZURE_CODE_SIGNING_ACCOUNT_NAME=your-code-signing-account ``` -------------------------------- ### Show Only Context Menu Source: https://nativephp.com/docs/desktop/2/the-basics/menu-bar Use this method to configure the menu bar to only display the context menu when the menu bar icon is clicked, instead of opening a window. ```php MenuBar::onlyShowContextMenu(); ``` -------------------------------- ### Recreate Application Menu Source: https://nativephp.com/docs/desktop/2/the-basics/application-menu Update the application menu dynamically by calling `Menu::create()` again with a new menu structure. This is useful for context-sensitive menus based on application state or window focus. ```php Menu::create( Menu::app(), Menu::file(), Menu::edit(), Menu::view(), Menu::window(), ); ``` -------------------------------- ### Create App Menu Source: https://nativephp.com/docs/desktop/2/the-basics/application-menu Generate the default macOS application menu, which includes items like About, Services, and Quit. This menu is typically used as the first item in the application's menu bar. ```php Menu::create( Menu::app(), ); ``` -------------------------------- ### Enable/Disable Open at Login (macOS/Windows) Source: https://nativephp.com/docs/desktop/2/the-basics/application Control whether the application opens automatically at login. Available on macOS and Windows. ```php App::openAtLogin(true); App::openAtLogin(false); ```