Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1e91b7aa27 | ||
|
|
eb4b101f45 | ||
|
|
290e524901 | ||
|
|
4b010925ed | ||
|
|
910001f0e1 | ||
|
|
61628b1864 | ||
|
|
1a79ffd855 | ||
|
|
5423239e62 | ||
|
|
44a4fa9d2d | ||
|
|
26494e6844 | ||
|
|
4f8a9c307c | ||
|
|
a3860ebd69 | ||
|
|
b3a787d03d | ||
|
|
41e4c2d434 | ||
|
|
77cb962e6f | ||
|
|
c85055a222 | ||
|
|
81b4c30aa2 | ||
|
|
e6d8c537f2 | ||
|
|
0c51c1c1ff | ||
|
|
45ea309f3b |
+193
-17
@@ -48,44 +48,220 @@ If you are running Linux with a graphical user interface (Wayland or X11), you s
|
||||
|
||||
## Features
|
||||
**Minimal features** are designed to run on any system without issues:
|
||||
|
||||
- A webview kiosk window launched in fullscreen mode and loading the specified `--web-url` website should not cause any problems.
|
||||
- When connecting to an internal HTTPS site with a self-signed certificate, ensure the specified FQDN matches. Using the `--ignore-certificate-errors` flag is [not recommended](https://github.com/leukipp/touchkio/issues/76) for browsing external sites.
|
||||
|
||||
**Extended features** become available when the `--mqtt-*` arguments are provided and the hardware is supported:
|
||||
|
||||
- The following commands are currently implemented to modify the display status. Make sure that one of these works for your display when you run it directly on the terminal, otherwise the MQTT switch will not work either.
|
||||
- `wlopm --[on,off] \*` (Raspberry Pi OS, Wayland)
|
||||
- `kscreen-doctor --dpms [on,off]` (Debian KDE, Wayland)
|
||||
- `xset dpms force [on,off]` (Generic, X11)
|
||||
- If your hardware is not fully compatible there should be no crashes, but you may miss some sensors.
|
||||
- On some Debian based systems (e.g. Ubuntu GNOME), the display status control is only available when using X11 (`xset`).
|
||||
- There are certain HDMI screens (e.g. Viewsonic) where the display status command doesn't work as expected.
|
||||
- The screen [immediately turns on again](https://github.com/leukipp/touchkio/issues/38), which may be caused by incompatible HDMI cables being used.
|
||||
- On Raspberry Pi OS the display command may fail with `ERROR: Setting power mode for output '[DSI-*,HDMI-*]' failed`.
|
||||
- This can happen if you have `wayvnc` running for remote access and is caused by a [known bug](https://github.com/leukipp/touchkio/issues/78).
|
||||
- Certain commands from the MQTT integration may require elevated privileges to work correctly.
|
||||
- Ensure that your local user has the [necessary permissions](https://github.com/leukipp/touchkio/issues/39) to run `sudo` without being prompted for a password.
|
||||
|
||||
Hardware support is verified during application startup and can be seen in the terminal or in the log file under the `Supported` section.
|
||||
Hardware support is verified during application startup and can be checked in the terminal or in the log file under the `Supported` section.
|
||||
The necessary requirements for MQTT sensors to work are listed here:
|
||||
| Name | Requirements | References |
|
||||
| -------------------- | ----------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- |
|
||||
| -------------------- | ------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------ |
|
||||
| App (Update) | Requires `sudo` rights, `.deb` install and `touchkio.service` running . | [#70](https://github.com/leukipp/touchkio/issues/70), [#77](https://github.com/leukipp/touchkio/issues/77) |
|
||||
| Display (Status) | Working `wlopm`, `kscreen-doctor` or `xset` command. | [#38](https://github.com/leukipp/touchkio/issues/38), [#57](https://github.com/leukipp/touchkio/issues/57) |
|
||||
| Display (Brightness) | Device under `/sys/class/backlight/*/brightness` exists. | [#30](https://github.com/leukipp/touchkio/issues/30), [#32](https://github.com/leukipp/touchkio/issues/32) |
|
||||
| Display (Brightness) | Requires `sudo` rights, device under `/sys/class/backlight/*/brightness` exists or working `ddcutil` command. | [#30](https://github.com/leukipp/touchkio/issues/30), [#101](https://github.com/leukipp/touchkio/issues/101) |
|
||||
| Keyboard | Raspberry Pi OS (Wayland) with `squeekboard` running. | [#7](https://github.com/leukipp/touchkio/issues/7), [#85](https://github.com/leukipp/touchkio/issues/85) |
|
||||
| Battery | Device under `/sys/class/power_supply/*/capacity` exists. | [#33](https://github.com/leukipp/touchkio/issues/33) |
|
||||
| Volume | Device (non-dummy) `pactl get-default-sink` exists. | [#82](https://github.com/leukipp/touchkio/issues/82) |
|
||||
| Reboot | Requires password-less `sudo` rights. | [#39](https://github.com/leukipp/touchkio/issues/39) |
|
||||
| Shutdown | Requires password-less `sudo` rights. | [#39](https://github.com/leukipp/touchkio/issues/39) |
|
||||
|
||||
## FAQ
|
||||
|
||||
### Operating System
|
||||
|
||||
<details><summary>I have installed Ubuntu GNOME.</summary>
|
||||
|
||||
- On some Debian based systems (e.g. Ubuntu GNOME), the display status control is only available when using X11 (`xset`).
|
||||
- GNOME is the least supported window manager.
|
||||
- It's recommended to switch to KDE wayland, if you want better support for display status control (`kscreen-doctor`).
|
||||
|
||||
</details>
|
||||
|
||||
<details><summary>I have installed Raspberry Pi OS on a RPI3.</summary>
|
||||
|
||||
- Raspberry Pi 3 devices have produced a bunch of issues in the past.
|
||||
- [RPI 3B wayland rendering issue](ttps://github.com/leukipp/touchkio/issues/104).
|
||||
- [RPI 3b+ thermostat card issue](https://github.com/leukipp/touchkio/issues/17).
|
||||
- [Webpage cards don't work (Pi3b+)](https://github.com/leukipp/touchkio/issues/24).
|
||||
- It looks like the GPU is not properly supported by Electron.
|
||||
- Running `touchkio --disable-gpu` may improve the situation, but upgrading the hardware is the best solution.
|
||||
|
||||
</details>
|
||||
|
||||
<details><summary>I want to update APT packages automatically.</summary>
|
||||
|
||||
- The **Package Upgrades** MQTT sensor will show if `apt` package upgrades are available, but updates are [intentionally](https://github.com/leukipp/touchkio/issues/7) not triggered by TouchKio.
|
||||
- It's recommended to keep your system up to date for security and compatibility, as TouchKio primarily supports the latest OS versions.
|
||||
- Consider configuring `sudo apt install unattended-upgrades` for automatic updates.
|
||||
|
||||
</details>
|
||||
|
||||
### Display
|
||||
|
||||
<details><summary>Display status can't be controlled through MQTT.</summary>
|
||||
|
||||
- The following commands are currently implemented to modify the display status. Make sure that one of these works for your display when you run it directly on the terminal, otherwise the MQTT switch will not work either.
|
||||
- `wlopm --[on,off] \*` (Raspberry Pi OS, Wayland)
|
||||
- `kscreen-doctor --dpms [on,off]` (Debian KDE, Wayland)
|
||||
- `xset dpms force [on,off]` (Generic, X11)
|
||||
|
||||
</details>
|
||||
|
||||
<details><summary>Display brightness can't be controlled through MQTT.</summary>
|
||||
|
||||
- Have a look at the [features](https://github.com/leukipp/touchkio/blob/main/HARDWARE.md#features) section to check if all requirements are fulfilled.
|
||||
- The **Display** MQTT control is a light entity with brightness support. So make sure to to [click on the entity](https://github.com/leukipp/touchkio/issues/75) to check for brightness support.
|
||||
- HDMI screens typically do not offer brightness control out of the box, so additional setup steps are required.
|
||||
- Brightness support for [ddcutil](https://github.com/leukipp/touchkio/issues/101#issuecomment-3521247263) is build-in and checked on application startup.
|
||||
- Alternatively installing [ddcci-driver-linux](https://github.com/leukipp/touchkio/issues/132#issue-3659009749) or [ddcci-dkms](https://github.com/leukipp/touchkio/issues/101#issuecomment-3571523927) may also work.
|
||||
|
||||
</details>
|
||||
|
||||
<details><summary>Turning HDMI screen off via MQTT causes it to turn back on.</summary>
|
||||
|
||||
- There are certain HDMI screens (e.g. Viewsonic) where the MQTT display status command doesn't work as expected.
|
||||
- The screen [immediately turns on again](https://github.com/leukipp/touchkio/issues/38), which may be caused by incompatible HDMI cables being used.
|
||||
|
||||
</details>
|
||||
|
||||
### Touch
|
||||
|
||||
<details><summary>Automated screen blanking on inactivity.</summary>
|
||||
|
||||
- You can use Raspberry Pi's build-in [screen blanking](https://www.raspberrypi.com/documentation/computers/configuration.html#screen-blanking-3) functionality, however, if the screen is turned on through Home Assistant after being automatically turned off, it will remain on indefinitely.
|
||||
- It's recommended to either use the built-in screen blanking feature or implement a Home Assistant [automation](https://www.home-assistant.io/docs/automation/basics) (e.g. presence detection or **Last Active** MQTT sensor) to manage the screen status.
|
||||
|
||||
</details>
|
||||
|
||||
<details><summary>Touch in multitouch mode not waking the screen.</summary>
|
||||
|
||||
- It's recommended to use **Mouse Emulation** for touch screens, otherwise touch based [screen wake-up](https://github.com/leukipp/touchkio/issues/127) from display off state will fail, especially if build-in [screen blanking](https://www.raspberrypi.com/documentation/computers/configuration.html#screen-blanking-3) is disabled.
|
||||
|
||||
</details>
|
||||
|
||||
<details><summary>Touch events may propagate through a display that is turned off.</summary>
|
||||
|
||||
- It's recommended to use **Mouse Emulation** for touch screens, otherwise Home Assistant actions could be triggered [unintentionally](https://github.com/leukipp/touchkio/issues/61) on touch.
|
||||
|
||||
</details>
|
||||
|
||||
### Network
|
||||
|
||||
<details><summary>Connecting via https/mqtts with a self-signed certificate.</summary>
|
||||
|
||||
- When connecting to a service with a [custom certificate](https://github.com/leukipp/touchkio/issues/42#issuecomment-3041870215), ensure the specified FQDN matches.
|
||||
- Using the `--ignore-certificate-errors` flag is [not recommended](https://github.com/leukipp/touchkio/issues/76) for browsing external sites.
|
||||
|
||||
</details>
|
||||
|
||||
<details><summary>Local DNS entries in /etc/hosts are ignored.</summary>
|
||||
|
||||
- Electron bypasses the system resolver stack, ignoring `/etc/hosts` and local DNS servers.
|
||||
- To use the system resolver, modify `~/.config/systemd/user/touchkio.service` to disable these features:
|
||||
```bash
|
||||
ExecStart=/usr/bin/touchkio --disable-features=UseDNSHttps,AsyncDns
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
<details><summary>During VNC access the display turns gray.</summary>
|
||||
|
||||
- On Raspberry Pi OS the display command may fail with `ERROR: Setting power mode for output '[DSI-*,HDMI-*]' failed`.
|
||||
- This can happen if you have `wayvnc` running for remote access and is caused by a [known bug](https://github.com/leukipp/touchkio/issues/78).
|
||||
|
||||
</details>
|
||||
|
||||
### Media
|
||||
|
||||
<details><summary>I need Music and Voice Assistant.</summary>
|
||||
|
||||
- Not planned, look for [alternatives](https://github.com/leukipp/touchkio/issues/88#issuecomment-3366659265).
|
||||
|
||||
</details>
|
||||
|
||||
<details><summary>I need a camera stream from the device.</summary>
|
||||
|
||||
- Not planned, look for [alternatives](https://github.com/leukipp/touchkio/issues/130#issuecomment-3591770594).
|
||||
|
||||
</details>
|
||||
|
||||
<details><summary>I need additional MQTT entities to control hardware.</summary>
|
||||
|
||||
- Not planned, look for [alternatives](https://github.com/leukipp/touchkio/issues/138#issuecomment-3591784725).
|
||||
|
||||
</details>
|
||||
|
||||
### Dependencies
|
||||
|
||||
<details><summary>Some of the MQTT controls are missing.</summary>
|
||||
|
||||
- Certain [features](https://github.com/leukipp/touchkio/blob/main/HARDWARE.md#features) from the MQTT integration may require elevated privileges to work correctly.
|
||||
- Test if your local user has the [necessary permissions](https://github.com/leukipp/touchkio/issues/39) to run `sudo -n true` without being [prompted for a password](https://github.com/leukipp/touchkio/issues/116#issuecomment-3471566411).
|
||||
|
||||
</details>
|
||||
|
||||
<details><summary>The ddcutil command doesn't seem to be used.</summary>
|
||||
|
||||
- Currently `ddcutil` is only used for brightness control of HDMI screens.
|
||||
- Make sure that your screen is supporting [continuous](https://github.com/leukipp/touchkio/issues/101#issuecomment-3521247263) adjustments of brightness values.
|
||||
|
||||
</details>
|
||||
|
||||
<details><summary>The on-screen keyboard doesn't automatically pop-out.</summary>
|
||||
|
||||
- Most of the available on-screen keyboards will not render above any [fullscreen window](https://forums.raspberrypi.com/viewtopic.php?p=2327148).
|
||||
- There is a [workaround](https://github.com/leukipp/touchkio/issues/85) for `squeekboard`, which will only work on Raspberry Pi OS.
|
||||
- If the on-screen keyboard still doesn't [automatically pop-out](https://github.com/leukipp/touchkio/issues/4) when entering a text field inside the webview you can use the side [widget](https://github.com/leukipp/touchkio/issues/16) to toggle the visibility.
|
||||
|
||||
</details>
|
||||
|
||||
### Errors
|
||||
|
||||
<details><summary>Terminal is full with "ERROR:gbm_wrapper.cc" messages.</summary>
|
||||
|
||||
- On the terminal you may see some _ERROR:gbm_wrapper.cc_ messages.
|
||||
- This appears to be a [known issue](https://github.com/electron/electron/issues/42322) that currently lacks a fix, but the webview still works.
|
||||
|
||||
</details>
|
||||
|
||||
<details><summary>CPU and RAM usage increases without reason.</summary>
|
||||
|
||||
- This was [especially observed](https://github.com/leukipp/touchkio/issues/123) when the screen is permanently on and renders a dashboard with interactive elements (e.g. custom lovelace cards).
|
||||
- Switching to another **Page Url** or turning the **Display** off during idle times improves resource usage.
|
||||
- Alternatively a timed **Refresh** of the webview via MQTT can also help.
|
||||
|
||||
</details>
|
||||
|
||||
<details><summary>Error message "GPU Process abnormal-exit".</summary>
|
||||
|
||||
- _GPU Process abnormal-exit (code 512)_ means that the Electron GPU process crashed, probably caused by some issues inside the webview.
|
||||
- Disabling the GPU via `touchkio --disable-gpu` may help.
|
||||
|
||||
</details>
|
||||
|
||||
<details><summary>Error message "Render Process killed".</summary>
|
||||
|
||||
- _Render Process killed (code 9)_ will lead to a temporary [white screen](https://github.com/leukipp/touchkio/issues/115).
|
||||
- The problem likely stems from Electron’s calculated RAM limit (~2GB) and the dashboard using too much memory.
|
||||
- Although there are flags to [increase the limit](https://github.com/leukipp/touchkio/issues/36#issuecomment-3406441947), a standard webview shouldn’t require that much RAM.
|
||||
|
||||
</details>
|
||||
|
||||
## Contributions
|
||||
In case your hardware is not listed above don't worry, give it a try.
|
||||
Running `touchkio --web-url=https://demo.home-assistant.io` will most likely just work.
|
||||
The only problems that may arise are when controlling the display via the Home Assistant integration.
|
||||
|
||||
There is a possibility to test `pre-releases` if you would like to try upcoming versions before the official release is published.
|
||||
These early builds are available to a smaller group of users who have chosen to take part in testing.
|
||||
|
||||
If you are interested in long-term testing, check out the related [help request](https://github.com/leukipp/touchkio/issues/96).
|
||||
When a [pre-release](https://github.com/leukipp/touchkio/releases) is available and you want to test it on-demand, run:
|
||||
```bash
|
||||
bash <(wget -qO- https://raw.githubusercontent.com/leukipp/touchkio/main/install.sh) update early
|
||||
```
|
||||
|
||||
- If you encounter any problems, please create a new [issue](https://github.com/leukipp/touchkio/issues).
|
||||
- If you encounter any problems and are able to fix it yourself, feel free to create a [pull request](https://github.com/leukipp/touchkio/pulls).
|
||||
- If everything works as expected and your hardware is not yet listed, you are welcome to [report](https://github.com/leukipp/touchkio/issues/12) it or create a [pull request](https://github.com/leukipp/touchkio/pulls).
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
# TouchKio
|
||||

|
||||

|
||||

|
||||

|
||||
[](https://github.com/leukipp/touchkio/actions)
|
||||
[](https://github.com/leukipp/touchkio/releases)
|
||||
[](https://github.com/leukipp/touchkio/releases)
|
||||
[](https://github.com/leukipp/touchkio/releases)
|
||||
[](https://github.com/sponsors/leukipp)
|
||||
|
||||
**TouchKio** is a Node.js application that utilizes Electron to create a kiosk mode window specifically designed for a Home Assistant dashboard.
|
||||
@@ -27,10 +27,11 @@ Moreover, the device running the **kiosk application** also offers several **Hom
|
||||
- [x] Toggle the on-screen keyboard.
|
||||
- [x] Touch display power and brightness.
|
||||
- [x] Manage kiosk window status and zoom.
|
||||
- [x] Screenshot image of the kiosk webview.
|
||||
- [x] Show network interfaces and addresses.
|
||||
- [x] List all available system package upgrades.
|
||||
- [x] Multi-webpage switching and url navigation.
|
||||
- [x] Audio volume control for connected devices.
|
||||
- [x] Volume control for connected audio outputs.
|
||||
- [x] Execute system reboot and shutdown commands.
|
||||
- [x] Monitor battery, temperature, processor and memory usage.
|
||||
|
||||
@@ -51,11 +52,12 @@ This setup allows seamless communication between your kiosk device and Home Assi
|
||||
For a comprehensive guide on setting up MQTT with Home Assistant, please refer to the official documentation available here: https://www.home-assistant.io/integrations/mqtt.
|
||||
|
||||
## Installation
|
||||
On the first run of the application, you may encounter a **setup procedure** and the Home Assistant **login screen**.
|
||||
On the first run of the application, you will encounter a **setup procedure (CLI)** and the Home Assistant **login screen (UI)**.
|
||||
It's recommended to create a dedicated Home Assistant user (local access only) for your kiosk device.
|
||||
|
||||
You might also need a physical keyboard or remote VNC access to input these credentials once.
|
||||
If your hardware is [supported](https://github.com/leukipp/touchkio/blob/main/HARDWARE.md) you may be able to activate the on-screen keyboard using the side [widget](https://github.com/leukipp/touchkio/issues/16).
|
||||
After the first login the Home Assistant credentials should be stored inside the `~/.config/touchkio/Cache` folder.
|
||||
|
||||
#### Option 1 - The easy way
|
||||
Run this command to download and install the latest **.deb** (arm64 or x64) release.
|
||||
@@ -236,15 +238,17 @@ The Raspberry Pi's **build-in on-screen keyboard** named `squeekboard` (it squea
|
||||
The kiosk application interacts with squeekboard via the `D-Bus` object path `/sm/puri/OSK0`, enabling the keyboard to be hidden or shown based on **MQTT** user input or system events.
|
||||
|
||||
The Raspberry Pi's **build-in screen blanking** function uses the command `swayidle -w timeout 600 'wlopm --off \*' resume 'wlopm --on \*' &` inside `~/.config/labwc/autostart` to blank the screen after **10 minutes**.
|
||||
The `wlopm --off \*` command changes the `bl_power` value to **4**, when setting the value to **0** the screen will turn on again.
|
||||
The `wlopm --off \*` command changes the `/sys/class/backlight/*/bl_power` value to **4**, when setting the value to **0** the screen will turn on again.
|
||||
However, `swayidle` still seems to consider the screen to be off and as a result it will not turn off again unless there is some interaction in the meantime.
|
||||
|
||||
When using the MQTT integration, the kiosk application must be able to **detect changes** made on the **device** itself.
|
||||
I managed to achieve this for the `brightness` file by implementing a simple `fs.watch(..)` file listener.
|
||||
However, I found that it **never triggered** for the `bl_power` file.
|
||||
I managed to achieve this for the `/sys/class/backlight/*/brightness` file by implementing a simple `fs.watch(..)` file listener.
|
||||
However, I found that it **never triggered** for the `/sys/class/backlight/*/bl_power` or the `/sys/class/drm/*/dpms` file.
|
||||
Although the file content changes, none of the filesystem listeners where fired.
|
||||
This could be due to `swayidle`/`wlopm` performing write actions at a deeper level that are not detectable by file listeners.
|
||||
As a result, I went for a **polling solution**, checking the state of the `brightness` and `dpms` file **every second** for any changes.
|
||||
|
||||
As a result, I went for a **polling solution**, checking the state of the `/sys/class/backlight/*/brightness` and `/sys/class/drm/*/dpms` file **every second** for any changes.
|
||||
In case `ddcutil` is installed the file `~/.config/touchkio/Cache/Brightness.vcp` will be written/monitored to support brightness support for HDMI screens.
|
||||
While I understand this is not ideal, it's necessary to ensure proper functionality.
|
||||
|
||||
The display power status and brightness can be adjusted via the MQTT integration.
|
||||
@@ -269,22 +273,17 @@ This adjustment provides a user experience similar to that of a proper mobile de
|
||||
</div></details>
|
||||
|
||||
## Issues
|
||||
Please review the [hardware](https://github.com/leukipp/touchkio/blob/main/HARDWARE.md) documentation first if you encounter any problems.
|
||||
### Please review the hardware [FAQ](https://github.com/leukipp/touchkio/blob/main/HARDWARE.md#faq) section first if you encounter any issues.
|
||||
|
||||
**Known Issues** that are by-design or for which there isn't a solution so far:
|
||||
- You can use Raspberry Pi's build-in [screen blanking](https://www.raspberrypi.com/documentation/computers/configuration.html#screen-blanking-3) functionality, however, if the screen is turned on through Home Assistant after being automatically turned off, it will remain on indefinitely.
|
||||
- It's recommended to either use the built-in screen blanking feature or implement a Home Assistant [automation](https://www.home-assistant.io/docs/automation/basics) (e.g. presence detection) to manage the screen status.
|
||||
- An active VNC session can also interfere with the display state, you can find details about this in the features [section](https://github.com/leukipp/touchkio/blob/main/HARDWARE.md#features).
|
||||
- When using a Raspberry Pi, the on-screen keyboard doesn't [automatically pop-out](https://github.com/leukipp/touchkio/issues/4) when entering a text field inside the webview.
|
||||
- As a current workaround you can use the side [widget](https://github.com/leukipp/touchkio/issues/16) to toggle the keyboard visibility.
|
||||
- There is also an [experimental feature](https://github.com/leukipp/touchkio/issues/85) that uses a special Electron flag to address this problem.
|
||||
- On the terminal you may see some _ERROR:gbm_wrapper.cc_ messages.
|
||||
- This appears to be a [known issue](https://github.com/electron/electron/issues/42322) that currently lacks a fix, but the webview still works.
|
||||
|
||||
For debugging, stop the service and launch `touchkio` directly on the terminal to monitor the log output in real-time.
|
||||
For basic debugging **(TouchKio)**, stop the service and launch `touchkio` directly on the terminal to monitor the log output in real-time.
|
||||
This output is also written into `~/.config/touchkio/logs/main.log` for review.
|
||||
|
||||
If you encounter any problems, please [create an issue](https://github.com/leukipp/touchkio/issues) and include the output of `touchkio --version`, additional information's about your system (such as operating system, hardware, etc.) and any relevant log files.
|
||||
For extended logging **(Electron)** you can run `touchkio --enable-logging`, which will write an additional log file into `~/.config/touchkio/logs/electron.log`.
|
||||
Refer to the [--log-level=[0-3]](https://www.electronjs.org/docs/latest/api/command-line-switches#--log-leveln) and [--v=[0-3]](https://www.electronjs.org/docs/latest/api/command-line-switches#--vlog_level) options to adjust the logging verbosity.
|
||||
|
||||
If you need to debug the webview **(Chrome DevTools)** use `touchkio --app-debug`.
|
||||
|
||||
In case of undocumented problems, please [create an issue](https://github.com/leukipp/touchkio/issues) and include the output of `touchkio --version`, additional information about your system (such as operating system, hardware, etc.), and any relevant log files.
|
||||
|
||||
## Credits
|
||||
[Inspired by](https://www.jeffgeerling.com/blog/2024/home-assistant-and-carplay-pi-touch-display-2) the one and only Raspberry Pi Master, Jeff Geerling ([@geerlingguy](https://github.com/geerlingguy)).
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
<!doctype html>
|
||||
<html>
|
||||
<head>
|
||||
<meta http-equiv="Content-Security-Policy" content="default-src 'unsafe-inline'" />
|
||||
<style>
|
||||
[data-theme="dark"] {
|
||||
--primary-color: rgba(225, 225, 225, 1);
|
||||
|
||||
+29
-6
@@ -1,9 +1,22 @@
|
||||
<!doctype html>
|
||||
<html>
|
||||
<head>
|
||||
<meta http-equiv="Content-Security-Policy" content="default-src 'unsafe-inline'" />
|
||||
<style>
|
||||
[data-theme="dark"] {
|
||||
--background-color: rgba(225, 225, 225, 0.15);
|
||||
--previous-cursor: w-resize;
|
||||
--next-cursor: e-resize;
|
||||
}
|
||||
[data-theme="light"] {
|
||||
--background-color: rgba(33, 33, 33, 0.15);
|
||||
--previous-cursor: w-resize;
|
||||
--next-cursor: e-resize;
|
||||
}
|
||||
[data-theme="hidden"] {
|
||||
--background-color: rgba(0, 0, 0, 0);
|
||||
--previous-cursor: none;
|
||||
--next-cursor: none;
|
||||
}
|
||||
::-webkit-scrollbar {
|
||||
display: none;
|
||||
@@ -26,24 +39,31 @@
|
||||
width: 100vw;
|
||||
height: 100vh;
|
||||
list-style-type: none;
|
||||
background: var(--background-color);
|
||||
}
|
||||
li {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
li:not(.disabled) #previous {
|
||||
cursor: var(--previous-cursor);
|
||||
}
|
||||
li:not(.disabled) #next {
|
||||
cursor: var(--next-cursor);
|
||||
}
|
||||
button {
|
||||
width: 100vw;
|
||||
height: 50vh;
|
||||
border: none;
|
||||
cursor: not-allowed;
|
||||
background-color: transparent;
|
||||
}
|
||||
#previous {
|
||||
cursor: w-resize;
|
||||
button:not(:active) {
|
||||
transition: background-color 500ms step-end;
|
||||
}
|
||||
#next {
|
||||
cursor: e-resize;
|
||||
menu:has(button:active) button {
|
||||
background-color: var(--background-color);
|
||||
transition-duration: 0ms;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
@@ -61,13 +81,16 @@
|
||||
|
||||
const registerSendEvents = () => {
|
||||
document.querySelectorAll("button").forEach((button) => {
|
||||
button.addEventListener("click", (e) => {
|
||||
button.addEventListener("pointerdown", (e) => {
|
||||
ipcRenderer.send("button-click", { id: e.target.id });
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
const registerReceiveEvents = () => {
|
||||
ipcRenderer.on("button-disabled", (e, button) => {
|
||||
document.getElementById(button.id).parentNode.classList.toggle("disabled", button.disabled);
|
||||
});
|
||||
ipcRenderer.on("data-theme", (e, data) => {
|
||||
document.documentElement.setAttribute("data-theme", data.theme);
|
||||
});
|
||||
|
||||
+2
-1
@@ -1,6 +1,7 @@
|
||||
<!doctype html>
|
||||
<html>
|
||||
<head>
|
||||
<meta http-equiv="Content-Security-Policy" content="default-src 'unsafe-inline'" />
|
||||
<style>
|
||||
[data-theme="dark"] {
|
||||
--primary-color: rgba(229, 229, 229, 1);
|
||||
@@ -99,7 +100,7 @@
|
||||
</head>
|
||||
<body>
|
||||
<header>
|
||||
<h1 id="title"></h1>
|
||||
<h1 id="title">TouchKio</h1>
|
||||
</header>
|
||||
<menu>
|
||||
<li>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
<!doctype html>
|
||||
<html>
|
||||
<head>
|
||||
<meta http-equiv="Content-Security-Policy" content="default-src 'unsafe-inline'" />
|
||||
<style>
|
||||
[data-theme="dark"] {
|
||||
--primary-color: rgba(225, 225, 225, 1);
|
||||
|
||||
@@ -6,13 +6,14 @@ const integration = require("./js/integration");
|
||||
const hardware = require("./js/hardware");
|
||||
const webview = require("./js/webview");
|
||||
const log = require("electron-log");
|
||||
const { app } = require("electron");
|
||||
const { app, powerMonitor } = require("electron");
|
||||
const Events = require("events");
|
||||
|
||||
global.APP = global.APP || {};
|
||||
global.ARGS = global.ARGS || {};
|
||||
global.EVENTS = global.EVENTS || new Events();
|
||||
|
||||
// Check display environment variable
|
||||
if (!process.env.DISPLAY) {
|
||||
console.error(`\n$DISPLAY variable not set to run the GUI application, are you connected via SSH?\n`);
|
||||
console.error(`If you have installed the service use:`);
|
||||
@@ -22,6 +23,18 @@ if (!process.env.DISPLAY) {
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// Delete electron log file
|
||||
const elog = path.join(app.getPath("logs"), "electron.log");
|
||||
try {
|
||||
if (fs.existsSync(elog)) {
|
||||
fs.unlinkSync(elog);
|
||||
}
|
||||
console.debug = () => {};
|
||||
} catch (error) {
|
||||
console.error("Failed to delete electron log file:", error.message);
|
||||
}
|
||||
app.commandLine.appendSwitch("log-file", elog);
|
||||
|
||||
/**
|
||||
* This promise resolves when the app has finished initializing,
|
||||
* allowing to safely create browser windows and perform other
|
||||
@@ -38,11 +51,18 @@ app.whenReady().then(async () => {
|
||||
args.mqtt_password = "*".repeat((args.mqtt_password || "").length);
|
||||
}
|
||||
console.info(`Arguments: ${JSON.stringify(args, null, 2)}`);
|
||||
process.stdout.write("\n");
|
||||
|
||||
// Chained init functions
|
||||
const chained = [webview.init, hardware.init, integration.init];
|
||||
for (const init of chained) {
|
||||
const chained = [
|
||||
["webview.js", webview.init],
|
||||
["hardware.js", hardware.init],
|
||||
["integration.js", integration.init],
|
||||
];
|
||||
for (const [name, init] of chained) {
|
||||
console.debug(`${name}: init()`);
|
||||
if (!(await init())) {
|
||||
console.debug(`${name}: init() --> aborted`);
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -67,6 +87,7 @@ const initApp = async () => {
|
||||
APP.path = app.getAppPath();
|
||||
APP.icon = path.join(app.getAppPath(), "img", "icon.png");
|
||||
APP.log = path.join(app.getPath("logs"), "main.log");
|
||||
APP.cache = path.join(app.getPath("userData"), "Cache");
|
||||
APP.config = app.getPath("userData");
|
||||
|
||||
// Set additional update infos
|
||||
@@ -75,6 +96,7 @@ const initApp = async () => {
|
||||
url: `https://api.github.com/repos/${packageJson.author}/${packageJson.name}/releases`,
|
||||
latest: null,
|
||||
};
|
||||
APP.issues = `https://github.com/${packageJson.author}/${packageJson.name}/issues`;
|
||||
APP.scripts = {
|
||||
install: `https://raw.githubusercontent.com/${packageJson.author}/${packageJson.name}/main/install.sh`,
|
||||
};
|
||||
@@ -91,6 +113,32 @@ const initApp = async () => {
|
||||
return app.exit(1);
|
||||
}
|
||||
|
||||
// Register app quit events
|
||||
app.on("before-quit", () => {
|
||||
APP.exiting = true;
|
||||
});
|
||||
app.on("will-quit", (e) => {
|
||||
e.preventDefault();
|
||||
process.exitCode = process.exitCode !== 0 ? 1 : 0;
|
||||
const level = process.exitCode === 0 ? "warn" : "error";
|
||||
console[level](`${APP.title} Terminated (${process.exitCode})`);
|
||||
app.exit(process.exitCode);
|
||||
});
|
||||
|
||||
// Register process exit events
|
||||
["SIGINT", "SIGTERM", "SIGQUIT", "SIGTRAP", "exit"].forEach((signal) => {
|
||||
process.on(signal, () => {
|
||||
process.exitCode = 0;
|
||||
APP.exiting = true;
|
||||
app.quit();
|
||||
});
|
||||
});
|
||||
powerMonitor.on("shutdown", () => {
|
||||
process.exitCode = 0;
|
||||
APP.exiting = true;
|
||||
app.quit();
|
||||
});
|
||||
|
||||
return true;
|
||||
};
|
||||
|
||||
@@ -106,6 +154,9 @@ const initArgs = async () => {
|
||||
let argsFilePath = path.join(APP.config, "Arguments.json");
|
||||
let argsFileExists = fs.existsSync(argsFilePath);
|
||||
|
||||
let argsFileHashPath = path.join(APP.cache, "Arguments.hash");
|
||||
let argsFileHashExists = fs.existsSync(argsFileHashPath);
|
||||
|
||||
// Show version and release info
|
||||
if ("help" in args || "version" in args) {
|
||||
let build = "";
|
||||
@@ -138,6 +189,16 @@ const initArgs = async () => {
|
||||
if (!Array.isArray(args.web_url)) {
|
||||
args.web_url = args.web_url.split(",").map((url) => url.trim());
|
||||
}
|
||||
|
||||
// Calculate arguments hash
|
||||
const argsFileHash = crypto.createHash("sha256").update(JSON.stringify(args)).digest("hex");
|
||||
const argsUpdated = argsFileHashExists && argsFileHash !== fs.readFileSync(argsFileHashPath, "utf8");
|
||||
if (argsUpdated && !("app_reset" in args)) {
|
||||
args.app_reset = "arguments";
|
||||
}
|
||||
fs.writeFileSync(argsFileHashPath, argsFileHash);
|
||||
|
||||
// Set global arguments
|
||||
ARGS = args;
|
||||
|
||||
return true;
|
||||
@@ -154,20 +215,41 @@ const initLog = async () => {
|
||||
fs.unlinkSync(APP.log);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to delete log file:", error.message);
|
||||
console.error("Failed to delete main log file:", error.message);
|
||||
}
|
||||
|
||||
// Overwrite console log
|
||||
APP.logs = [];
|
||||
// Set log level and path
|
||||
const level = "enable_logging" in ARGS ? "silly" : "app_debug" in ARGS ? "debug" : "verbose";
|
||||
log.transports.file.level = level;
|
||||
log.transports.console.level = level;
|
||||
log.transports.file.resolvePathFn = () => {
|
||||
return APP.log;
|
||||
};
|
||||
|
||||
// Catch unhandled errors
|
||||
log.errorHandler.startCatching({
|
||||
showDialog: false,
|
||||
onError({ error }) {
|
||||
console.error(`Uncaught Error: ${error.message} (${error.stack})`);
|
||||
app.exit(1);
|
||||
onError({ error, versions }) {
|
||||
if (!error?.message?.includes("Object has been destroyed")) {
|
||||
const build = { ...APP.build, ...versions };
|
||||
const whoopsie = "💥 Whoopsie!";
|
||||
const section2 = `# Description\n- Hardware information?\n- How to reproduce?\n- Additional logs?\n`;
|
||||
const section3 = `# Error\n\`\`\`bash\n${new Date().toISOString()}: ${error.stack}\n\`\`\`\n`;
|
||||
const section4 = `# Application\n\`\`\`json\n${JSON.stringify(build, null, 2)}\n\`\`\`\n`;
|
||||
const title = encodeURIComponent(`${whoopsie} - ${error}`);
|
||||
const body = encodeURIComponent(`${section2}\n${section3}\n${section4}`);
|
||||
console.error(`${whoopsie} -`, error, build);
|
||||
console.info(`🪲 Report issue --> ${APP.issues}/new?title=${title}&body=${body}`);
|
||||
}
|
||||
app.quit();
|
||||
},
|
||||
});
|
||||
|
||||
// Emit console log
|
||||
APP.logs = [];
|
||||
log.hooks.push((message, transport, type) => {
|
||||
const text = message.data.join(" ");
|
||||
const data = message.data.map((d) => (typeof d === "object" ? String(d?.message) || JSON.stringify(d) : String(d)));
|
||||
const text = data.filter((s) => s && s.trim()).join(" ");
|
||||
if (!text.startsWith("(node:") && type === "console") {
|
||||
APP.logs.unshift({
|
||||
time: message.date,
|
||||
@@ -181,10 +263,10 @@ const initLog = async () => {
|
||||
}
|
||||
return message;
|
||||
});
|
||||
log.transports.file.resolvePathFn = () => {
|
||||
return APP.log;
|
||||
};
|
||||
|
||||
// Overwrite console log
|
||||
Object.assign(console, log.functions);
|
||||
console.silly("Welcome To The Jungle!");
|
||||
|
||||
return true;
|
||||
};
|
||||
|
||||
+216
-61
@@ -15,14 +15,14 @@ global.HARDWARE = global.HARDWARE || {
|
||||
},
|
||||
display: {
|
||||
status: {
|
||||
value: null,
|
||||
path: null,
|
||||
command: null,
|
||||
value: {},
|
||||
},
|
||||
brightness: {
|
||||
value: null,
|
||||
path: null,
|
||||
max: null,
|
||||
command: null,
|
||||
value: {},
|
||||
},
|
||||
},
|
||||
keyboard: {
|
||||
@@ -52,7 +52,8 @@ const init = async () => {
|
||||
HARDWARE.display.status.path = getDisplayStatusPath();
|
||||
HARDWARE.display.status.command = getDisplayStatusCommand();
|
||||
HARDWARE.display.brightness.path = getDisplayBrightnessPath();
|
||||
HARDWARE.display.brightness.max = getDisplayBrightnessMax();
|
||||
HARDWARE.display.brightness.command = getDisplayBrightnessCommand();
|
||||
HARDWARE.display.brightness.value.max = getDisplayBrightnessMax();
|
||||
HARDWARE.audio.device = getAudioDevice();
|
||||
HARDWARE.support = checkSupport();
|
||||
HARDWARE.initialized = true;
|
||||
@@ -86,22 +87,35 @@ const init = async () => {
|
||||
// Show hardware infos
|
||||
process.stdout.write("\n");
|
||||
const unsupported = "unsupported";
|
||||
console.info(`Battery Level [${HARDWARE.battery.level.path || unsupported}]:`, `${getBatteryLevel() || unsupported}`);
|
||||
const batteryLevel = `${getBatteryLevel()} (sysfs)`;
|
||||
const batteryLevelInfo = HARDWARE.support.batteryLevel ? batteryLevel : unsupported;
|
||||
console.info(
|
||||
`Display Status [${HARDWARE.display.status.path || unsupported}]:`,
|
||||
`${getDisplayStatus() || unsupported} (${HARDWARE.display.status.command || unsupported})`,
|
||||
`Battery Level [${HARDWARE.support.batteryLevel ? HARDWARE.battery.level.path : unsupported}]:`,
|
||||
batteryLevelInfo,
|
||||
);
|
||||
const displayStatus = `${getDisplayStatus()} (${HARDWARE.display.status.command})`;
|
||||
const displayStatusInfo = HARDWARE.support.displayStatus ? displayStatus : unsupported;
|
||||
console.info(
|
||||
`Display Brightness [${HARDWARE.display.brightness.path || unsupported}]:`,
|
||||
`${getDisplayBrightness() || unsupported}`,
|
||||
`Display Status [${HARDWARE.support.displayStatus ? HARDWARE.display.status.path : unsupported}]:`,
|
||||
displayStatusInfo,
|
||||
);
|
||||
const displayBrightness = `${getDisplayBrightness()} (${HARDWARE.display.brightness.command || "sysfs"})`;
|
||||
const displayBrightnessInfo = HARDWARE.support.displayBrightness ? displayBrightness : unsupported;
|
||||
console.info(
|
||||
`Display Brightness [${HARDWARE.support.displayBrightness ? HARDWARE.display.brightness.path || "ddc://vcp/feature/0x10" : unsupported}]:`,
|
||||
displayBrightnessInfo,
|
||||
);
|
||||
const audioVolume = `${getAudioVolume()} (pactl)`;
|
||||
const audioVolumeInfo = HARDWARE.support.audioVolume ? audioVolume : unsupported;
|
||||
console.info(
|
||||
`Audio Volume [${HARDWARE.support.audioVolume ? HARDWARE.audio.device : unsupported}]:`,
|
||||
`${getAudioVolume() || unsupported}`,
|
||||
audioVolumeInfo,
|
||||
);
|
||||
const keyboardVisibility = `${getKeyboardVisibility()} (squeekboard)`;
|
||||
const keyboardVisibilityInfo = HARDWARE.support.keyboardVisibility ? keyboardVisibility : unsupported;
|
||||
console.info(
|
||||
`Keyboard Visibility [${HARDWARE.support.keyboardVisibility ? "squeekboard" : unsupported}]:`,
|
||||
`${getKeyboardVisibility() || unsupported}`,
|
||||
`Keyboard Visibility [${HARDWARE.support.keyboardVisibility ? "dbus://sm/puri/OSK0" : unsupported}]:`,
|
||||
keyboardVisibilityInfo,
|
||||
);
|
||||
process.stdout.write("\n");
|
||||
|
||||
@@ -135,9 +149,9 @@ const init = async () => {
|
||||
});
|
||||
}
|
||||
|
||||
// Check for display changes
|
||||
// Monitor display changes (1s)
|
||||
setDisplayStatus("ON", () => {
|
||||
interval(update, 1000);
|
||||
interval(update, 1 * 1000);
|
||||
});
|
||||
|
||||
return true;
|
||||
@@ -151,23 +165,65 @@ const update = async () => {
|
||||
return;
|
||||
}
|
||||
|
||||
// Display status has changed
|
||||
// Check if display status has changed
|
||||
if (HARDWARE.support.displayStatus) {
|
||||
const status = (await fsp.readFile(`${HARDWARE.display.status.path}/dpms`, "utf8")).trim();
|
||||
if (status !== HARDWARE.display.status.value) {
|
||||
console.info("Update Display Status:", getDisplayStatus());
|
||||
HARDWARE.display.status.value = status;
|
||||
let displayStatusChanged = false;
|
||||
|
||||
// Use sysfs dpms path if available
|
||||
if (HARDWARE.display.status.path) {
|
||||
const power = await readFile(path.join(HARDWARE.display.status.path, "dpms"), false);
|
||||
const powerChanged = !!power && power !== HARDWARE.display.status.value.power;
|
||||
|
||||
// Update internal status values
|
||||
HARDWARE.display.status.value.power = power;
|
||||
displayStatusChanged |= powerChanged;
|
||||
}
|
||||
|
||||
// Use sysfs status path if available
|
||||
if (HARDWARE.display.status.path) {
|
||||
const connection = await readFile(path.join(HARDWARE.display.status.path, "status"), false);
|
||||
const connectionChanged = !!connection && connection !== HARDWARE.display.status.value.connection;
|
||||
|
||||
// Update internal status values
|
||||
HARDWARE.display.status.value.connection = connection;
|
||||
displayStatusChanged |= connectionChanged;
|
||||
}
|
||||
|
||||
// Emit display event if changed
|
||||
if (displayStatusChanged) {
|
||||
EVENTS.emit("updateDisplay");
|
||||
console.info("Update Display Status:", getDisplayStatus());
|
||||
}
|
||||
}
|
||||
|
||||
// Display brightness has changed
|
||||
// Check if display brightness has changed
|
||||
if (HARDWARE.support.displayBrightness) {
|
||||
const brightness = (await fsp.readFile(`${HARDWARE.display.brightness.path}/brightness`, "utf8")).trim();
|
||||
if (brightness !== HARDWARE.display.brightness.value) {
|
||||
console.info("Update Display Brightness:", getDisplayBrightness());
|
||||
HARDWARE.display.brightness.value = brightness;
|
||||
let displayBrightnessChanged = false;
|
||||
|
||||
// Use cache brightness path if available
|
||||
if (HARDWARE.display.brightness.command) {
|
||||
const brightness = await readFile(path.join(APP.cache, "Brightness.vcp"), false);
|
||||
const brightnessChanged = !!brightness && brightness !== HARDWARE.display.brightness.value.brightness;
|
||||
|
||||
// Update internal brightness values
|
||||
HARDWARE.display.brightness.value.brightness = brightness;
|
||||
displayBrightnessChanged |= brightnessChanged;
|
||||
}
|
||||
|
||||
// Use sysfs brightness path if available
|
||||
if (HARDWARE.display.brightness.path) {
|
||||
const brightness = await readFile(path.join(HARDWARE.display.brightness.path, "brightness"), false);
|
||||
const brightnessChanged = !!brightness && brightness !== HARDWARE.display.brightness.value.brightness;
|
||||
|
||||
// Update internal brightness values
|
||||
HARDWARE.display.brightness.value.brightness = brightness;
|
||||
displayBrightnessChanged |= brightnessChanged;
|
||||
}
|
||||
|
||||
// Emit display event if changed
|
||||
if (displayBrightnessChanged) {
|
||||
EVENTS.emit("updateDisplay");
|
||||
console.info("Update Display Brightness:", getDisplayBrightness());
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -230,22 +286,26 @@ const sessionDesktop = () => {
|
||||
* @returns {Object} Returns support object with boolean values.
|
||||
*/
|
||||
const checkSupport = () => {
|
||||
const battery = HARDWARE.battery.level;
|
||||
const status = HARDWARE.display.status;
|
||||
const brightness = HARDWARE.display.brightness;
|
||||
const audio = HARDWARE.audio.device;
|
||||
const keyboard = processRuns("squeekboard");
|
||||
const service = serviceRuns(APP.name);
|
||||
const sudo = sudoRights();
|
||||
const deb = APP.build.maker === "deb";
|
||||
const service = serviceRuns(APP.name);
|
||||
const keyboard = processRuns("squeekboard");
|
||||
const release = APP.build.maker === "deb";
|
||||
|
||||
const audioDevice = !!HARDWARE.audio.device;
|
||||
const batteryPath = !!HARDWARE.battery.level.path;
|
||||
const statusPath = !!HARDWARE.display.status.path;
|
||||
const statusCommand = !!HARDWARE.display.status.command;
|
||||
const brightnessPath = !!HARDWARE.display.brightness.path && !!HARDWARE.display.brightness.value.max;
|
||||
const brightnessCommand = !!HARDWARE.display.brightness.command && !!HARDWARE.display.brightness.value.max;
|
||||
|
||||
return {
|
||||
batteryLevel: !!battery.path,
|
||||
displayStatus: !!status.path && !!status.command,
|
||||
displayBrightness: sudo && !!brightness.path && !!brightness.max,
|
||||
batteryLevel: batteryPath,
|
||||
displayStatus: statusPath && statusCommand,
|
||||
displayBrightness: sudo && statusPath && statusCommand && (brightnessPath || brightnessCommand),
|
||||
keyboardVisibility: keyboard,
|
||||
audioVolume: !!audio,
|
||||
audioVolume: audioDevice,
|
||||
sudoRights: sudo,
|
||||
appUpdate: service && sudo && deb,
|
||||
appUpdate: service && sudo && release,
|
||||
};
|
||||
};
|
||||
|
||||
@@ -397,9 +457,12 @@ const getProcessorTemperature = () => {
|
||||
if (!fs.existsSync(typeFile) || !fs.existsSync(tempFile)) {
|
||||
continue;
|
||||
}
|
||||
const type = fs.readFileSync(typeFile, "utf8").trim();
|
||||
const type = readFile(typeFile);
|
||||
if (["cpu-thermal", "x86_pkg_temp", "k10temp", "acpitz", "cpu"].includes(type)) {
|
||||
return parseFloat(fs.readFileSync(tempFile, "utf8").trim()) / 1000;
|
||||
const temp = readFile(tempFile);
|
||||
if (temp) {
|
||||
return parseFloat(temp) / 1000;
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
@@ -431,7 +494,7 @@ const getBatteryLevel = () => {
|
||||
if (!HARDWARE.support.batteryLevel) {
|
||||
return null;
|
||||
}
|
||||
const capacity = fs.readFileSync(`${HARDWARE.battery.level.path}/capacity`, "utf8").trim();
|
||||
const capacity = readFile(`${HARDWARE.battery.level.path}/capacity`);
|
||||
if (capacity) {
|
||||
return parseFloat(capacity);
|
||||
}
|
||||
@@ -450,7 +513,7 @@ const getDisplayStatusPath = () => {
|
||||
if (!fs.existsSync(statusFile)) {
|
||||
continue;
|
||||
}
|
||||
const content = fs.readFileSync(statusFile, "utf8").trim();
|
||||
const content = readFile(statusFile);
|
||||
if (content === "connected") {
|
||||
return path.join(drm, card);
|
||||
}
|
||||
@@ -478,7 +541,6 @@ const getDisplayStatusCommand = () => {
|
||||
return map.command;
|
||||
}
|
||||
}
|
||||
console.warn("No display command available");
|
||||
return null;
|
||||
};
|
||||
|
||||
@@ -567,23 +629,62 @@ const getDisplayBrightnessPath = () => {
|
||||
};
|
||||
|
||||
/**
|
||||
* Gets the maximum display brightness value using `/sys/class/backlight/.../max_brightness`.
|
||||
* Gets the available display brightness command checking for `ddcutil`.
|
||||
*
|
||||
* @returns {number|null} The brightness maximum value or null if an error occurs.
|
||||
* @returns {string|null} The display brightness command or null if nothing was found.
|
||||
*/
|
||||
const getDisplayBrightnessMax = () => {
|
||||
if (!HARDWARE.display.brightness.path) {
|
||||
return null;
|
||||
const getDisplayBrightnessCommand = () => {
|
||||
const type = HARDWARE.session.type;
|
||||
const desktop = HARDWARE.session.desktop;
|
||||
const mapping = {
|
||||
wayland: [{ command: "ddcutil", desktops: ["*"] }],
|
||||
x11: [{ command: "ddcutil", desktops: ["*"] }],
|
||||
}[type];
|
||||
for (const map of mapping || []) {
|
||||
if (sudoRights() && commandExists(map.command) && map.desktops.some((d) => d === "*" || desktop.includes(d))) {
|
||||
HARDWARE.display.brightness.path = null;
|
||||
switch (map.command) {
|
||||
case "ddcutil":
|
||||
const output = execSyncCommand("sudo", ["ddcutil", "capabilities"]);
|
||||
if (output && output.includes("Feature: 10")) {
|
||||
fs.writeFileSync(path.join(APP.cache, "Brightness.vcp"), "");
|
||||
return map.command;
|
||||
}
|
||||
break;
|
||||
default:
|
||||
return map.command;
|
||||
}
|
||||
}
|
||||
const max = fs.readFileSync(`${HARDWARE.display.brightness.path}/max_brightness`, "utf8").trim();
|
||||
if (max) {
|
||||
return parseInt(max, 10);
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Gets the current display brightness level using `/sys/class/backlight/.../brightness`.
|
||||
* Gets the maximum display brightness value using `/sys/class/backlight/.../max_brightness` or `ddcutil getvcp 10`.
|
||||
*
|
||||
* @returns {number|null} The brightness maximum value or null if an error occurs.
|
||||
*/
|
||||
const getDisplayBrightnessMax = () => {
|
||||
switch (HARDWARE.display.brightness.command) {
|
||||
case "ddcutil":
|
||||
const output = execSyncCommand("sudo", ["ddcutil", "getvcp", "10", "--brief"]);
|
||||
const match = output ? output.match(/VCP 10 C (\d+) (\d+)/) : null;
|
||||
if (match) {
|
||||
return parseInt(match[2], 10);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
if (HARDWARE.display.brightness.path) {
|
||||
const max = readFile(path.join(HARDWARE.display.brightness.path, "max_brightness"));
|
||||
if (max) {
|
||||
return parseInt(max, 10);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Gets the current display brightness level using `/sys/class/backlight/.../brightness` or `ddcutil getvcp 10`.
|
||||
*
|
||||
* @returns {number|null} The brightness level as a percentage or null if an error occurs.
|
||||
*/
|
||||
@@ -591,16 +692,27 @@ const getDisplayBrightness = () => {
|
||||
if (!HARDWARE.support.displayBrightness) {
|
||||
return null;
|
||||
}
|
||||
const brightness = fs.readFileSync(`${HARDWARE.display.brightness.path}/brightness`, "utf8").trim();
|
||||
switch (HARDWARE.display.brightness.command) {
|
||||
case "ddcutil":
|
||||
const output = execSyncCommand("sudo", ["ddcutil", "getvcp", "10", "--brief"]);
|
||||
const match = output ? output.match(/VCP 10 C (\d+) (\d+)/) : null;
|
||||
if (match) {
|
||||
return parseInt(match[1], 10);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
if (HARDWARE.display.brightness.path) {
|
||||
const brightness = readFile(path.join(HARDWARE.display.brightness.path, "brightness"));
|
||||
if (brightness) {
|
||||
const max = HARDWARE.display.brightness.max || 1;
|
||||
const max = HARDWARE.display.brightness.value.max || 1;
|
||||
return Math.max(1, Math.min(Math.round((parseInt(brightness, 10) / max) * 100), 100));
|
||||
}
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Sets the display brightness level using `/sys/class/backlight/.../brightness`.
|
||||
* Sets the display brightness level using `/sys/class/backlight/.../brightness` or `ddcutil setvcp 10`.
|
||||
*
|
||||
* This function takes a brightness value between 1 to 100 percent,
|
||||
* maps it to the proper range and writes it to the system.
|
||||
@@ -618,11 +730,23 @@ const setDisplayBrightness = (brightness, callback = null) => {
|
||||
if (typeof callback === "function") callback(null, "Invalid brightness");
|
||||
return;
|
||||
}
|
||||
const max = HARDWARE.display.brightness.max || 1;
|
||||
switch (HARDWARE.display.brightness.command) {
|
||||
case "ddcutil":
|
||||
execAsyncCommand("sudo", ["ddcutil", "setvcp", "10", `${brightness}`], (reply, error) => {
|
||||
if (!error) {
|
||||
fs.writeFileSync(path.join(APP.cache, "Brightness.vcp"), `${brightness}`);
|
||||
}
|
||||
if (typeof callback === "function") callback(reply, error);
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (HARDWARE.display.brightness.path) {
|
||||
const max = HARDWARE.display.brightness.value.max || 1;
|
||||
const value = Math.max(1, Math.min(Math.round((brightness / 100) * max), max));
|
||||
const proc = execAsyncCommand("sudo", ["tee", `${HARDWARE.display.brightness.path}/brightness`], callback);
|
||||
const proc = execAsyncCommand("sudo", ["tee", path.join(HARDWARE.display.brightness.path, "brightness")], callback);
|
||||
proc.stdin.write(value.toString());
|
||||
proc.stdin.end();
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -657,7 +781,7 @@ const getAudioVolume = () => {
|
||||
}
|
||||
const match = volume.match(/\/(\s*(\d+)%)/);
|
||||
if (match) {
|
||||
return Math.max(0, Math.min(100, mute.includes("yes") ? 0 : parseInt(match[2])));
|
||||
return Math.max(0, Math.min(100, mute.includes("yes") ? 0 : parseInt(match[2], 10)));
|
||||
}
|
||||
return null;
|
||||
};
|
||||
@@ -831,10 +955,11 @@ const commandExists = (name) => {
|
||||
*/
|
||||
const execSyncCommand = (cmd, args) => {
|
||||
try {
|
||||
console.debug(`hardware.js: execSyncCommand(${[cmd, ...args].join(" ")})`);
|
||||
const output = cpr.execSync([cmd, ...args].join(" "), { encoding: "utf8" });
|
||||
return output.trim().replace(/\0/g, "");
|
||||
} catch (error) {
|
||||
console.error(`Execute Sync: '${[cmd, ...args].join(" ")}' --> ${error.message}`);
|
||||
console.error(`Execute Sync: '${[cmd, ...args].join(" ")}' --> ${error.message}`.trim());
|
||||
}
|
||||
return null;
|
||||
};
|
||||
@@ -848,6 +973,7 @@ const execSyncCommand = (cmd, args) => {
|
||||
* @returns {Object} The spawned process object.
|
||||
*/
|
||||
const execAsyncCommand = (cmd, args, callback = null) => {
|
||||
console.debug(`hardware.js: execAsyncCommand(${[cmd, ...args].join(" ")})`);
|
||||
let errorOutput = "";
|
||||
let successOutput = "";
|
||||
let proc = cpr.spawn(cmd, args);
|
||||
@@ -883,6 +1009,7 @@ const execAsyncCommand = (cmd, args, callback = null) => {
|
||||
* @returns {Object} The spawned process object.
|
||||
*/
|
||||
const execScriptCommand = (cmd, args, callback = null) => {
|
||||
console.debug(`hardware.js: execScriptCommand(${[cmd, ...args].join(" ")})`);
|
||||
let progress = 1;
|
||||
let proc = cpr.spawn(cmd, args);
|
||||
if (typeof callback === "function") callback(progress, null);
|
||||
@@ -902,7 +1029,7 @@ const execScriptCommand = (cmd, args, callback = null) => {
|
||||
for (const line of lines.split("\n").filter(Boolean)) {
|
||||
const matches = line.match(/(\d{1,3})%/g);
|
||||
if (matches) {
|
||||
const match = Math.max(...matches.map((p) => parseInt(p)));
|
||||
const match = Math.max(...matches.map((p) => parseInt(p, 10)));
|
||||
const percent = Math.floor(match / 10) * 10;
|
||||
if (percent > 10 && percent > progress) {
|
||||
progress = percent;
|
||||
@@ -931,7 +1058,8 @@ const execScriptCommand = (cmd, args, callback = null) => {
|
||||
* @param {Function} callback - A callback function that receives the output or error.
|
||||
* @returns {Object} The spawned process object.
|
||||
*/
|
||||
const commandMonitor = (cmd, args, callback) => {
|
||||
const commandMonitor = (cmd, args, callback = null) => {
|
||||
console.debug(`hardware.js: commandMonitor(${[cmd, ...args].join(" ")})`);
|
||||
const proc = cpr.spawn(cmd, args);
|
||||
proc.stdout.on("data", (data) => {
|
||||
if (data) {
|
||||
@@ -955,9 +1083,10 @@ const commandMonitor = (cmd, args, callback) => {
|
||||
* @param {Function} callback - A callback function that receives the changed property.
|
||||
* @returns {Object} The spawned process object.
|
||||
*/
|
||||
const dbusMonitor = (path, callback) => {
|
||||
const dbusMonitor = (path, callback = null) => {
|
||||
const cmd = "dbus-monitor";
|
||||
const args = [`interface='org.freedesktop.DBus.Properties',member='PropertiesChanged',path='${path}'`];
|
||||
console.debug(`hardware.js: dbusMonitor(${[cmd, ...args].join(" ")})`);
|
||||
const proc = cpr.spawn(cmd, args);
|
||||
proc.stdout.on("data", (data) => {
|
||||
try {
|
||||
@@ -1006,6 +1135,7 @@ const dbusCall = (path, method, values, callback = null) => {
|
||||
const dest = `${iface} ${path} ${iface}.${method} ${values.join(" ")}`;
|
||||
const args = ["--print-reply", "--type=method_call", `--dest=${dest}`];
|
||||
try {
|
||||
console.debug(`hardware.js: dbusCall(${[cmd, ...args].join(" ")})`);
|
||||
const output = cpr.execSync([cmd, ...args].join(" ").trim(), { encoding: "utf8" });
|
||||
if (typeof callback === "function") callback(output.trim().replace(/\0/g, ""), null);
|
||||
} catch (error) {
|
||||
@@ -1014,6 +1144,31 @@ const dbusCall = (path, method, values, callback = null) => {
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Reads file content synchronously or asynchronously from the filesystem.
|
||||
*
|
||||
* @param {string} path - Path of the file.
|
||||
* @param {boolean} sync - If true, reads the file synchronously, otherwise asynchronously.
|
||||
* @returns {string|null|Promise<string|null>} The file content or null if an error occurs.
|
||||
*/
|
||||
const readFile = (path, sync = true) => {
|
||||
if (!sync) {
|
||||
return fsp
|
||||
.readFile(path, "utf8")
|
||||
.then((content) => content.trim())
|
||||
.catch((error) => {
|
||||
console.error(`Read File ${path} Async:`, error.message);
|
||||
return null;
|
||||
});
|
||||
}
|
||||
try {
|
||||
return fs.readFileSync(path, "utf8").trim();
|
||||
} catch (error) {
|
||||
console.error(`Read File ${path} Sync:`, error.message);
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Helper function for asynchronous interval calls.
|
||||
*
|
||||
@@ -1026,7 +1181,7 @@ const interval = (callback, ms) => {
|
||||
try {
|
||||
await callback();
|
||||
} catch (error) {
|
||||
console.error("Interval Callback:", error.message);
|
||||
console.error("Interval Async:", error.message);
|
||||
}
|
||||
run();
|
||||
}, ms);
|
||||
|
||||
+57
-16
@@ -94,6 +94,7 @@ const init = async () => {
|
||||
initLastActive();
|
||||
|
||||
// Init client diagnostic
|
||||
initScreenshot();
|
||||
initHeartbeat();
|
||||
initErrors();
|
||||
initVersion();
|
||||
@@ -102,14 +103,21 @@ const init = async () => {
|
||||
INTEGRATION.initialized = true;
|
||||
|
||||
// Register global events
|
||||
EVENTS.on("updateApp", updateApp);
|
||||
EVENTS.on("updateStatus", updateKiosk);
|
||||
EVENTS.on("updateVolume", updateVolume);
|
||||
EVENTS.on("updateKeyboard", updateKeyboard);
|
||||
EVENTS.on("updatePage", () => {
|
||||
updatePageNumber();
|
||||
updatePageZoom();
|
||||
updatePageUrl();
|
||||
updateTheme();
|
||||
});
|
||||
EVENTS.on("updateDisplay", () => {
|
||||
updateDisplay();
|
||||
updateLastActive();
|
||||
});
|
||||
EVENTS.on("updateStatus", updateKiosk);
|
||||
EVENTS.on("updateTheme", updateTheme);
|
||||
EVENTS.on("updateVolume", updateVolume);
|
||||
EVENTS.on("updateKeyboard", updateKeyboard);
|
||||
EVENTS.on("updateScreenshot", updateScreenshot);
|
||||
EVENTS.on("consoleLog", updateErrors);
|
||||
})
|
||||
.on("error", (error) => {
|
||||
@@ -139,7 +147,6 @@ const init = async () => {
|
||||
if (APP.exiting) {
|
||||
return;
|
||||
}
|
||||
updateApp();
|
||||
updatePackageUpgrades();
|
||||
}, 3600 * 1000);
|
||||
|
||||
@@ -153,11 +160,8 @@ const update = async () => {
|
||||
if (!INTEGRATION.initialized || APP.exiting) {
|
||||
return;
|
||||
}
|
||||
console.debug("integration.js: update()");
|
||||
|
||||
// Update client sensors
|
||||
updatePageNumber();
|
||||
updatePageZoom();
|
||||
updatePageUrl();
|
||||
updateNetworkAddress();
|
||||
updateUpTime();
|
||||
updateLastActive();
|
||||
@@ -180,6 +184,7 @@ const removeConfig = (type, config) => {
|
||||
}
|
||||
const path = config.unique_id.replace(`${INTEGRATION.node}_`, "");
|
||||
const root = `${INTEGRATION.discovery}/${type}/${INTEGRATION.node}/${path}/config`;
|
||||
console.debug(`integration.js: removeConfig(${path})`);
|
||||
return INTEGRATION.client.publish(root, JSON.stringify({}), { qos: 1, retain: true });
|
||||
};
|
||||
|
||||
@@ -196,6 +201,7 @@ const publishConfig = (type, config) => {
|
||||
}
|
||||
const path = config.unique_id.replace(`${INTEGRATION.node}_`, "");
|
||||
const root = `${INTEGRATION.discovery}/${type}/${INTEGRATION.node}/${path}/config`;
|
||||
console.debug(`integration.js: publishConfig(${path})`);
|
||||
return INTEGRATION.client.publish(root, JSON.stringify(config), { qos: 1, retain: true });
|
||||
};
|
||||
|
||||
@@ -421,7 +427,7 @@ const initTheme = () => {
|
||||
publishConfig("select", config)
|
||||
.on("message", (topic, message) => {
|
||||
if (topic === config.command_topic) {
|
||||
const theme = message.toString();
|
||||
const theme = message.toString().toLowerCase();
|
||||
console.verbose("Set Application Theme:", theme);
|
||||
WEBVIEW.theme.set(theme);
|
||||
}
|
||||
@@ -448,10 +454,12 @@ const initDisplay = () => {
|
||||
unique_id: `${INTEGRATION.node}_display`,
|
||||
command_topic: `${root}/power/set`,
|
||||
state_topic: `${root}/power/state`,
|
||||
supported_color_modes: ["onoff"],
|
||||
icon: "mdi:monitor-shimmer",
|
||||
platform: "light",
|
||||
device: INTEGRATION.device,
|
||||
...(HARDWARE.support.displayBrightness && {
|
||||
supported_color_modes: ["brightness"],
|
||||
brightness_command_topic: `${root}/brightness/set`,
|
||||
brightness_state_topic: `${root}/brightness/state`,
|
||||
brightness_scale: 100,
|
||||
@@ -496,8 +504,8 @@ const initDisplay = () => {
|
||||
const updateDisplay = async () => {
|
||||
const status = hardware.getDisplayStatus();
|
||||
const brightness = hardware.getDisplayBrightness();
|
||||
publishState("display/power", status);
|
||||
publishState("display/brightness", brightness);
|
||||
publishState("display/power", status);
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -607,10 +615,12 @@ const initPageNumber = () => {
|
||||
.on("message", (topic, message) => {
|
||||
if (topic === config.command_topic) {
|
||||
const number = parseInt(message, 10);
|
||||
if (WEBVIEW.viewActive && number) {
|
||||
console.verbose("Set Page Number:", number);
|
||||
WEBVIEW.viewActive = number || 1;
|
||||
WEBVIEW.viewActive = number;
|
||||
EVENTS.emit("updateView");
|
||||
}
|
||||
}
|
||||
})
|
||||
.subscribe(config.command_topic);
|
||||
updatePageNumber();
|
||||
@@ -647,10 +657,12 @@ const initPageZoom = () => {
|
||||
.on("message", (topic, message) => {
|
||||
if (topic === config.command_topic) {
|
||||
const zoom = parseInt(message, 10);
|
||||
if (WEBVIEW.viewActive && zoom) {
|
||||
console.verbose("Set Page Zoom:", zoom);
|
||||
WEBVIEW.views[WEBVIEW.viewActive || 1].webContents.setZoomFactor(zoom / 100.0);
|
||||
WEBVIEW.zoom.set(zoom);
|
||||
EVENTS.emit("updateView");
|
||||
}
|
||||
}
|
||||
})
|
||||
.subscribe(config.command_topic);
|
||||
updatePageZoom();
|
||||
@@ -660,7 +672,7 @@ const initPageZoom = () => {
|
||||
* Updates the page zoom via the mqtt connection.
|
||||
*/
|
||||
const updatePageZoom = async () => {
|
||||
const pageZoom = Math.round(WEBVIEW.views[WEBVIEW.viewActive || 1].webContents.getZoomFactor() * 100.0);
|
||||
const pageZoom = WEBVIEW.zoom.get();
|
||||
publishState("page_zoom", pageZoom);
|
||||
};
|
||||
|
||||
@@ -683,8 +695,10 @@ const initPageUrl = () => {
|
||||
.on("message", (topic, message) => {
|
||||
if (topic === config.command_topic) {
|
||||
const url = message.toString();
|
||||
if (WEBVIEW.viewActive && url) {
|
||||
console.verbose("Set Page Url:", url);
|
||||
WEBVIEW.views[WEBVIEW.viewActive || 1].webContents.loadURL(url);
|
||||
WEBVIEW.views[WEBVIEW.viewActive].webContents.loadURL(url);
|
||||
}
|
||||
}
|
||||
})
|
||||
.subscribe(config.command_topic);
|
||||
@@ -698,7 +712,7 @@ const updatePageUrl = async () => {
|
||||
const defaultUrl = WEBVIEW.viewUrls[WEBVIEW.viewActive || 1];
|
||||
const currentUrl = WEBVIEW.views[WEBVIEW.viewActive || 1].webContents.getURL();
|
||||
const pageUrl = !currentUrl || currentUrl.startsWith("data:") ? defaultUrl : currentUrl;
|
||||
publishState("page_url", pageUrl);
|
||||
publishState("page_url", pageUrl.length < 255 ? pageUrl : null);
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -1040,6 +1054,33 @@ const updateLastActive = async () => {
|
||||
publishAttributes("last_active", tracker);
|
||||
};
|
||||
|
||||
/**
|
||||
* Initializes the page screenshot.
|
||||
*/
|
||||
const initScreenshot = () => {
|
||||
const root = `${INTEGRATION.root}/screenshot`;
|
||||
const config = {
|
||||
name: "Screenshot",
|
||||
unique_id: `${INTEGRATION.node}_screenshot`,
|
||||
image_topic: `${root}/state`,
|
||||
image_encoding: "b64",
|
||||
content_type: "image/png",
|
||||
entity_category: "diagnostic",
|
||||
icon: "mdi:image-area",
|
||||
device: INTEGRATION.device,
|
||||
};
|
||||
publishConfig("image", config);
|
||||
updateScreenshot();
|
||||
};
|
||||
|
||||
/**
|
||||
* Updates the page screenshot via the mqtt connection.
|
||||
*/
|
||||
const updateScreenshot = async () => {
|
||||
const screenshot = WEBVIEW.tracker.screenshot;
|
||||
publishState("screenshot", screenshot);
|
||||
};
|
||||
|
||||
/**
|
||||
* Initializes the heartbeat sensor.
|
||||
*/
|
||||
|
||||
+396
-109
@@ -29,6 +29,7 @@ global.WEBVIEW = global.WEBVIEW || {
|
||||
widget: {
|
||||
focused: null,
|
||||
},
|
||||
screenshot: null,
|
||||
},
|
||||
};
|
||||
|
||||
@@ -46,69 +47,108 @@ const init = async () => {
|
||||
console.error("Please provide the '--web-url' parameter with http(s)");
|
||||
return app.quit();
|
||||
}
|
||||
session.defaultSession.clearCache();
|
||||
|
||||
// Clear cache and storage
|
||||
await session.defaultSession.clearCache();
|
||||
if (ARGS.app_reset === "storage") {
|
||||
await session.defaultSession.clearStorageData();
|
||||
}
|
||||
|
||||
// Parse arguments
|
||||
const debug = "app_debug" in ARGS;
|
||||
const widget = ARGS.web_widget ? ARGS.web_widget === "true" : true;
|
||||
const zoom = !isNaN(parseFloat(ARGS.web_zoom)) ? parseFloat(ARGS.web_zoom) : 1.25;
|
||||
const theme = ["light", "dark"].includes(ARGS.web_theme) ? ARGS.web_theme : "dark";
|
||||
const urls = [loaderHtml(40, 1.0, theme)].concat(ARGS.web_url);
|
||||
const zoom = (!isNaN(parseFloat(ARGS.web_zoom)) ? parseFloat(ARGS.web_zoom) : 1.25) * 100;
|
||||
const urls = [loaderHtml(40, 1.0, theme), ...ARGS.web_url];
|
||||
|
||||
// Init global properties
|
||||
WEBVIEW.viewActive = 0;
|
||||
WEBVIEW.viewUrls = urls;
|
||||
WEBVIEW.viewZoom = zoom;
|
||||
WEBVIEW.statusEnabled = true;
|
||||
// Init global controls
|
||||
WEBVIEW.statusEnabled = !debug;
|
||||
WEBVIEW.pagerEnabled = widget;
|
||||
WEBVIEW.widgetEnabled = widget;
|
||||
WEBVIEW.navigationEnabled = widget;
|
||||
|
||||
// Init global theme
|
||||
// Init global views
|
||||
WEBVIEW.views = [];
|
||||
WEBVIEW.viewUrls = urls;
|
||||
WEBVIEW.viewActive = 0;
|
||||
|
||||
// Init global display
|
||||
const display = screen.getPrimaryDisplay();
|
||||
WEBVIEW.display = display ? display.workAreaSize : {};
|
||||
if (!WEBVIEW.display.width || !WEBVIEW.display.height) {
|
||||
WEBVIEW.display = { width: 800, height: 600 };
|
||||
}
|
||||
|
||||
// Init global theme manager
|
||||
WEBVIEW.theme = {
|
||||
set: (name) => {
|
||||
nativeTheme.themeSource = name.toLowerCase();
|
||||
set: function (value) {
|
||||
const theme = value.toLowerCase();
|
||||
nativeTheme.themeSource = theme;
|
||||
if (typeof this.callback === "function") this.callback();
|
||||
},
|
||||
get: () => {
|
||||
get: function () {
|
||||
return nativeTheme.shouldUseDarkColors ? "dark" : "light";
|
||||
},
|
||||
toggle: () => {
|
||||
nativeTheme.themeSource = nativeTheme.shouldUseDarkColors ? "light" : "dark";
|
||||
toggle: function () {
|
||||
this.set(nativeTheme.shouldUseDarkColors ? "light" : "dark");
|
||||
},
|
||||
register: () => {
|
||||
nativeTheme.on("updated", () => {
|
||||
const theme = WEBVIEW.theme.get();
|
||||
WEBVIEW.statusTheme = theme;
|
||||
WEBVIEW.widgetTheme = theme;
|
||||
WEBVIEW.navigationTheme = theme;
|
||||
if (WEBVIEW.initialized) {
|
||||
resizeView();
|
||||
}
|
||||
EVENTS.emit("updateTheme");
|
||||
});
|
||||
reset: function () {
|
||||
this.set(this.default);
|
||||
},
|
||||
store: function () {
|
||||
cookieStore("web-theme", this.get());
|
||||
},
|
||||
init: function (value, callback) {
|
||||
this.callback = callback;
|
||||
this.default = value;
|
||||
this.reset();
|
||||
},
|
||||
};
|
||||
WEBVIEW.theme.register();
|
||||
WEBVIEW.theme.set(theme);
|
||||
|
||||
// Init global root window
|
||||
WEBVIEW.display = screen.getPrimaryDisplay().workAreaSize;
|
||||
// Init global zoom manager
|
||||
WEBVIEW.zoom = {
|
||||
set: function (value) {
|
||||
const zoom = Math.max(0.25, Math.min(4.0, value / 100.0));
|
||||
WEBVIEW.views[WEBVIEW.viewActive].webContents.setZoomFactor(zoom);
|
||||
if (typeof this.callback === "function") this.callback();
|
||||
},
|
||||
get: function () {
|
||||
const zoom = WEBVIEW.views[WEBVIEW.viewActive].webContents.getZoomFactor();
|
||||
return Math.round(zoom * 100.0);
|
||||
},
|
||||
minus: function () {
|
||||
this.set(Math.floor((this.get() - 1) / 10) * 10);
|
||||
},
|
||||
plus: function () {
|
||||
this.set(Math.ceil((this.get() + 1) / 10) * 10);
|
||||
},
|
||||
reset: function () {
|
||||
this.set(this.default);
|
||||
},
|
||||
store: function () {
|
||||
cookieStore("web-zoom", this.get());
|
||||
},
|
||||
init: function (value, callback) {
|
||||
this.callback = callback;
|
||||
this.default = value;
|
||||
this.reset();
|
||||
},
|
||||
};
|
||||
|
||||
// Init root window
|
||||
WEBVIEW.window = new BaseWindow({
|
||||
title: APP.title,
|
||||
icon: APP.icon,
|
||||
fullscreen: !debug,
|
||||
autoHideMenuBar: true,
|
||||
frame: debug || !WEBVIEW.statusEnabled,
|
||||
width: Math.floor(WEBVIEW.display.width * 0.9),
|
||||
height: Math.floor(WEBVIEW.display.height * 0.9),
|
||||
frame: !WEBVIEW.statusEnabled,
|
||||
width: Math.floor(WEBVIEW.display.width * 0.85),
|
||||
height: Math.floor(WEBVIEW.display.height * 0.75),
|
||||
minWidth: 136,
|
||||
minHeight: 136,
|
||||
});
|
||||
WEBVIEW.window.setMenuBarVisibility(false);
|
||||
|
||||
// Init global webview
|
||||
WEBVIEW.views = [];
|
||||
urls.forEach((url, i) => {
|
||||
WEBVIEW.viewUrls.forEach((url, i) => {
|
||||
const view = new WebContentsView({
|
||||
webPreferences: {
|
||||
nodeIntegration: false,
|
||||
@@ -172,6 +212,12 @@ const init = async () => {
|
||||
WEBVIEW.window.contentView.addChildView(WEBVIEW.navigation);
|
||||
WEBVIEW.navigation.webContents.loadFile(path.join(APP.path, "html", "navigation.html"));
|
||||
|
||||
// Init global layout
|
||||
const { width, height, x, y } = WEBVIEW.window.getBounds();
|
||||
console.info(`Open Window: ${width}x${height}+${x}+${y}`);
|
||||
WEBVIEW.theme.init(theme, updateTheme);
|
||||
WEBVIEW.zoom.init(zoom, updateZoom);
|
||||
|
||||
// Register global events
|
||||
await windowEvents();
|
||||
await widgetEvents();
|
||||
@@ -190,18 +236,61 @@ const update = async () => {
|
||||
if (!WEBVIEW.initialized || APP.exiting) {
|
||||
return;
|
||||
}
|
||||
console.debug("webview.js: update()");
|
||||
|
||||
// Update window status
|
||||
updateStatus();
|
||||
|
||||
// Update pager status
|
||||
updatePager();
|
||||
|
||||
// Update widget status
|
||||
updateWidget();
|
||||
|
||||
// Update navigation status
|
||||
updateNavigation();
|
||||
};
|
||||
|
||||
// Update integration sensor
|
||||
integration.update();
|
||||
/**
|
||||
* Updates the application theme.
|
||||
*/
|
||||
const updateTheme = () => {
|
||||
if (APP.exiting) {
|
||||
return;
|
||||
}
|
||||
const theme = WEBVIEW.theme.get();
|
||||
|
||||
// Update controls theme
|
||||
WEBVIEW.statusTheme = theme;
|
||||
WEBVIEW.pagerTheme = theme;
|
||||
WEBVIEW.widgetTheme = theme;
|
||||
WEBVIEW.navigationTheme = theme;
|
||||
WEBVIEW.window.setMenuBarVisibility(false);
|
||||
|
||||
// Update application theme
|
||||
WEBVIEW.theme.store();
|
||||
if (WEBVIEW.initialized) {
|
||||
console.info("Update Application Theme:", theme);
|
||||
resizeView();
|
||||
}
|
||||
EVENTS.emit("updatePage");
|
||||
};
|
||||
|
||||
/**
|
||||
* Updates the page zoom.
|
||||
*/
|
||||
const updateZoom = () => {
|
||||
if (APP.exiting) {
|
||||
return;
|
||||
}
|
||||
const zoom = WEBVIEW.zoom.get();
|
||||
|
||||
// Update page zoom
|
||||
WEBVIEW.zoom.store();
|
||||
if (WEBVIEW.initialized) {
|
||||
console.info("Update Page Zoom:", zoom);
|
||||
}
|
||||
EVENTS.emit("updatePage");
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -211,7 +300,10 @@ const updateView = () => {
|
||||
if (!WEBVIEW.viewActive) {
|
||||
return;
|
||||
}
|
||||
const url = WEBVIEW.views[WEBVIEW.viewActive].webContents.getURL();
|
||||
const view = WEBVIEW.views[WEBVIEW.viewActive];
|
||||
const url = view.webContents.getURL();
|
||||
|
||||
// Build window title
|
||||
const host = url.startsWith("data:") ? "whoopsie" : new URL(url).host;
|
||||
const title = `${APP.title} - ${host} (${WEBVIEW.viewActive})`;
|
||||
const previous = WEBVIEW.window.getTitle();
|
||||
@@ -227,6 +319,24 @@ const updateView = () => {
|
||||
WEBVIEW.views.forEach((view, i) => {
|
||||
view.setVisible(i === WEBVIEW.viewActive);
|
||||
});
|
||||
|
||||
// Update stored theme and zoom
|
||||
cookieStore("web-theme").then((value) => {
|
||||
if (value && value !== WEBVIEW.theme.get()) {
|
||||
WEBVIEW.theme.set(value);
|
||||
}
|
||||
});
|
||||
cookieStore("web-zoom").then((value) => {
|
||||
if (value && value !== WEBVIEW.zoom.get()) {
|
||||
WEBVIEW.zoom.set(value);
|
||||
}
|
||||
});
|
||||
|
||||
// Update webview screenshot
|
||||
captureView(1000).then(() => {
|
||||
EVENTS.emit("updateScreenshot");
|
||||
});
|
||||
EVENTS.emit("updatePage");
|
||||
update();
|
||||
};
|
||||
|
||||
@@ -254,16 +364,25 @@ const updateStatus = () => {
|
||||
EVENTS.emit("updateStatus");
|
||||
};
|
||||
|
||||
/**
|
||||
* Updates the pager control.
|
||||
*/
|
||||
const updatePager = () => {
|
||||
// Disable pager buttons
|
||||
WEBVIEW.pager.webContents.send("button-disabled", {
|
||||
id: "previous",
|
||||
disabled: WEBVIEW.viewActive <= 1,
|
||||
});
|
||||
WEBVIEW.pager.webContents.send("button-disabled", {
|
||||
id: "next",
|
||||
disabled: WEBVIEW.viewActive >= WEBVIEW.viewUrls.length - 1,
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Updates the widget control.
|
||||
*/
|
||||
const updateWidget = () => {
|
||||
// Hide status button
|
||||
WEBVIEW.widget.webContents.send("button-hidden", {
|
||||
id: "fullscreen",
|
||||
hidden: !WEBVIEW.statusEnabled,
|
||||
});
|
||||
|
||||
// Hide keyboard button
|
||||
WEBVIEW.widget.webContents.send("button-hidden", {
|
||||
id: "keyboard",
|
||||
@@ -281,6 +400,9 @@ const updateWidget = () => {
|
||||
* Updates the navigation control.
|
||||
*/
|
||||
const updateNavigation = () => {
|
||||
if (!WEBVIEW.viewActive) {
|
||||
return;
|
||||
}
|
||||
const view = WEBVIEW.views[WEBVIEW.viewActive];
|
||||
const defaultUrl = WEBVIEW.viewUrls[WEBVIEW.viewActive];
|
||||
const currentUrl = view.webContents.getURL();
|
||||
@@ -319,11 +441,11 @@ const updateNavigation = () => {
|
||||
// Disable zoom buttons
|
||||
WEBVIEW.navigation.webContents.send("button-disabled", {
|
||||
id: "minus",
|
||||
disabled: view.webContents.getZoomFactor().toFixed(2) <= 0.25,
|
||||
disabled: WEBVIEW.zoom.get() <= 25,
|
||||
});
|
||||
WEBVIEW.navigation.webContents.send("button-disabled", {
|
||||
id: "plus",
|
||||
disabled: view.webContents.getZoomFactor().toFixed(2) >= 4.0,
|
||||
disabled: WEBVIEW.zoom.get() >= 400,
|
||||
});
|
||||
|
||||
// Disable history buttons
|
||||
@@ -402,26 +524,31 @@ const toggleStatus = (force = null) => {
|
||||
* Decreases page zoom on the active webview.
|
||||
*/
|
||||
const zoomMinus = () => {
|
||||
const view = WEBVIEW.views[WEBVIEW.viewActive];
|
||||
const zoom = view.webContents.getZoomFactor() - 0.1;
|
||||
view.webContents.setZoomFactor(Math.max(0.25, Math.round(zoom * 10) / 10));
|
||||
update();
|
||||
if (!WEBVIEW.viewActive) {
|
||||
return;
|
||||
}
|
||||
WEBVIEW.zoom.minus();
|
||||
updateView();
|
||||
};
|
||||
|
||||
/**
|
||||
* Increases page zoom on the active webview.
|
||||
*/
|
||||
const zoomPlus = () => {
|
||||
const view = WEBVIEW.views[WEBVIEW.viewActive];
|
||||
const zoom = view.webContents.getZoomFactor() + 0.1;
|
||||
view.webContents.setZoomFactor(Math.min(4.0, Math.round(zoom * 10) / 10));
|
||||
update();
|
||||
if (!WEBVIEW.viewActive) {
|
||||
return;
|
||||
}
|
||||
WEBVIEW.zoom.plus();
|
||||
updateView();
|
||||
};
|
||||
|
||||
/**
|
||||
* Navigates backward in the history of the active webview.
|
||||
*/
|
||||
const historyBackward = () => {
|
||||
if (!WEBVIEW.viewActive) {
|
||||
return;
|
||||
}
|
||||
const view = WEBVIEW.views[WEBVIEW.viewActive];
|
||||
if (view.webContents.navigationHistory.canGoBack()) {
|
||||
view.webContents.navigationHistory.goBack();
|
||||
@@ -432,6 +559,9 @@ const historyBackward = () => {
|
||||
* Navigates forward in the history of the active webview.
|
||||
*/
|
||||
const historyForward = () => {
|
||||
if (!WEBVIEW.viewActive) {
|
||||
return;
|
||||
}
|
||||
const view = WEBVIEW.views[WEBVIEW.viewActive];
|
||||
if (view.webContents.navigationHistory.canGoForward()) {
|
||||
view.webContents.navigationHistory.goForward();
|
||||
@@ -442,7 +572,12 @@ const historyForward = () => {
|
||||
* Activates the previous webview page.
|
||||
*/
|
||||
const previousView = () => {
|
||||
if (WEBVIEW.viewActive > 1) WEBVIEW.viewActive--;
|
||||
if (!WEBVIEW.viewActive) {
|
||||
return;
|
||||
}
|
||||
if (WEBVIEW.viewActive > 1) {
|
||||
WEBVIEW.viewActive--;
|
||||
}
|
||||
updateView();
|
||||
};
|
||||
|
||||
@@ -450,7 +585,12 @@ const previousView = () => {
|
||||
* Activates the next webview page.
|
||||
*/
|
||||
const nextView = () => {
|
||||
if (WEBVIEW.viewActive < WEBVIEW.views.length - 1) WEBVIEW.viewActive++;
|
||||
if (!WEBVIEW.viewActive) {
|
||||
return;
|
||||
}
|
||||
if (WEBVIEW.viewActive < WEBVIEW.views.length - 1) {
|
||||
WEBVIEW.viewActive++;
|
||||
}
|
||||
updateView();
|
||||
};
|
||||
|
||||
@@ -458,12 +598,21 @@ const nextView = () => {
|
||||
* Reloads the default url and settings on the active webview.
|
||||
*/
|
||||
const homeView = () => {
|
||||
if (!WEBVIEW.viewActive) {
|
||||
return;
|
||||
}
|
||||
const view = WEBVIEW.views[WEBVIEW.viewActive];
|
||||
const defaultUrl = WEBVIEW.viewUrls[WEBVIEW.viewActive];
|
||||
const currentUrl = view.webContents.getURL();
|
||||
|
||||
// Reset log history
|
||||
// Clear logs, cache and history
|
||||
APP.logs = [];
|
||||
view.webContents.session.clearCache();
|
||||
view.webContents.navigationHistory.clear();
|
||||
|
||||
// Reset page zoom and theme
|
||||
WEBVIEW.zoom.reset();
|
||||
WEBVIEW.theme.reset();
|
||||
|
||||
// Reload the default url or refresh the page
|
||||
if (currentUrl != defaultUrl) {
|
||||
@@ -471,25 +620,22 @@ const homeView = () => {
|
||||
} else {
|
||||
view.webContents.reloadIgnoringCache();
|
||||
}
|
||||
|
||||
// Reset page zoom and history
|
||||
view.webContents.setZoomFactor(WEBVIEW.viewZoom);
|
||||
setTimeout(() => {
|
||||
view.webContents.navigationHistory.clear();
|
||||
update();
|
||||
}, 2000);
|
||||
};
|
||||
|
||||
/**
|
||||
* Reloads the current url on the active webview.
|
||||
*/
|
||||
const reloadView = () => {
|
||||
if (!WEBVIEW.viewActive) {
|
||||
return;
|
||||
}
|
||||
const view = WEBVIEW.views[WEBVIEW.viewActive];
|
||||
const defaultUrl = WEBVIEW.viewUrls[WEBVIEW.viewActive];
|
||||
const currentUrl = view.webContents.getURL();
|
||||
|
||||
// Reset log history
|
||||
// Clear logs and cache
|
||||
APP.logs = [];
|
||||
view.webContents.session.clearCache();
|
||||
|
||||
// Reload the default url or refresh the page
|
||||
if (currentUrl.startsWith("data:")) {
|
||||
@@ -497,7 +643,6 @@ const reloadView = () => {
|
||||
} else {
|
||||
view.webContents.reloadIgnoringCache();
|
||||
}
|
||||
update();
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -511,7 +656,8 @@ const resizeView = () => {
|
||||
const widget = { width: 60, height: 200 };
|
||||
|
||||
// Update view size
|
||||
WEBVIEW.views.forEach((view) => {
|
||||
WEBVIEW.views.forEach((view, i) => {
|
||||
console.debug(`webview.js: resizeView(${i})`);
|
||||
view.setBounds({
|
||||
x: 0,
|
||||
y: status.height,
|
||||
@@ -529,7 +675,7 @@ const resizeView = () => {
|
||||
height: pager.height - status.height - navigation.height,
|
||||
});
|
||||
WEBVIEW.pager.webContents.send("data-theme", {
|
||||
theme: "hidden",
|
||||
theme: WEBVIEW.viewUrls.length > 2 ? WEBVIEW.pagerTheme : "hidden",
|
||||
});
|
||||
}
|
||||
|
||||
@@ -571,16 +717,18 @@ const resizeView = () => {
|
||||
theme: WEBVIEW.navigationTheme,
|
||||
});
|
||||
}
|
||||
|
||||
// Update webview screenshot
|
||||
captureView(1000).then(() => {
|
||||
EVENTS.emit("updateScreenshot");
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Register window events and handler.
|
||||
*/
|
||||
const windowEvents = async () => {
|
||||
// Handle window resize events
|
||||
WEBVIEW.window.on("ready-to-show", resizeView);
|
||||
WEBVIEW.window.on("resize", resizeView);
|
||||
resizeView();
|
||||
console.debug("webview.js: windowEvents()");
|
||||
|
||||
// Handle window status updates
|
||||
WEBVIEW.window.setStatus = async (status) => {
|
||||
@@ -625,6 +773,7 @@ const windowEvents = async () => {
|
||||
}
|
||||
break;
|
||||
case "Terminated":
|
||||
process.exitCode = 0;
|
||||
app.quit();
|
||||
break;
|
||||
}
|
||||
@@ -640,6 +789,10 @@ const windowEvents = async () => {
|
||||
WEBVIEW.window.on("enter-full-screen", WEBVIEW.window.onStatus);
|
||||
WEBVIEW.window.on("leave-full-screen", WEBVIEW.window.onStatus);
|
||||
|
||||
// Handle window resize events
|
||||
WEBVIEW.window.on("resize", resizeView);
|
||||
resizeView();
|
||||
|
||||
// Handle global shortcut events
|
||||
globalShortcut.register("Control+Left", () => {
|
||||
previousView();
|
||||
@@ -660,8 +813,8 @@ const windowEvents = async () => {
|
||||
historyForward();
|
||||
});
|
||||
|
||||
// Check for window touch events (1s)
|
||||
setInterval(() => {
|
||||
// Check for window touch events (every full 1s)
|
||||
interval(() => {
|
||||
if (APP.exiting) {
|
||||
return;
|
||||
}
|
||||
@@ -676,7 +829,7 @@ const windowEvents = async () => {
|
||||
}
|
||||
toggleNavigation("OFF");
|
||||
}
|
||||
}, 1000);
|
||||
}, 1 * 1000);
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -686,6 +839,7 @@ const widgetEvents = async () => {
|
||||
if (!WEBVIEW.widgetEnabled) {
|
||||
return;
|
||||
}
|
||||
console.debug("webview.js: widgetEvents()");
|
||||
|
||||
// Handle widget focus events
|
||||
WEBVIEW.widget.webContents.on("focus", () => {
|
||||
@@ -704,6 +858,7 @@ const widgetEvents = async () => {
|
||||
theme: WEBVIEW.widgetTheme,
|
||||
});
|
||||
WEBVIEW.tracker.widget.focused = true;
|
||||
console.debug("webview.js: widgetEvents(widget-focus)");
|
||||
});
|
||||
|
||||
// Handle widget blur events
|
||||
@@ -722,12 +877,17 @@ const widgetEvents = async () => {
|
||||
theme: "hidden",
|
||||
});
|
||||
WEBVIEW.tracker.widget.focused = false;
|
||||
console.debug("webview.js: widgetEvents(widget-blur)");
|
||||
});
|
||||
|
||||
// Handle widget button click events
|
||||
ipcMain.on("button-click", (e, button) => {
|
||||
console.debug(`webview.js: widgetEvents(button-click-${button.id})`);
|
||||
WEBVIEW.tracker.pointer.time = new Date();
|
||||
switch (button.id) {
|
||||
case "fullscreen":
|
||||
WEBVIEW.window.setStatus(WEBVIEW.tracker.window.status === "Fullscreen" ? "Framed" : "Fullscreen");
|
||||
break;
|
||||
case "theme":
|
||||
WEBVIEW.theme.toggle();
|
||||
break;
|
||||
@@ -748,14 +908,13 @@ const statusEvents = async () => {
|
||||
if (!WEBVIEW.statusEnabled) {
|
||||
return;
|
||||
}
|
||||
console.debug("webview.js: statusEvents()");
|
||||
|
||||
// Handle status button click events
|
||||
ipcMain.on("button-click", (e, button) => {
|
||||
console.debug(`webview.js: statusEvents(button-click-${button.id})`);
|
||||
WEBVIEW.tracker.pointer.time = new Date();
|
||||
switch (button.id) {
|
||||
case "fullscreen":
|
||||
WEBVIEW.window.setStatus(WEBVIEW.tracker.window.status === "Fullscreen" ? "Framed" : "Fullscreen");
|
||||
break;
|
||||
case "minimize":
|
||||
WEBVIEW.window.setStatus("Minimized");
|
||||
break;
|
||||
@@ -790,10 +949,12 @@ const navigationEvents = async () => {
|
||||
if (!WEBVIEW.navigationEnabled) {
|
||||
return;
|
||||
}
|
||||
console.debug("webview.js: navigationEvents()");
|
||||
|
||||
// Handle input blur events
|
||||
let selected = false;
|
||||
ipcMain.on("input-blur", (e, input) => {
|
||||
console.debug(`webview.js: navigationEvents(input-blur-${input.id})`);
|
||||
switch (input.id) {
|
||||
case "url":
|
||||
if (selected) {
|
||||
@@ -809,6 +970,7 @@ const navigationEvents = async () => {
|
||||
|
||||
// Handle input focus events
|
||||
ipcMain.on("input-focus", (e, input) => {
|
||||
console.debug(`webview.js: navigationEvents(input-focus-${input.id})`);
|
||||
WEBVIEW.tracker.pointer.time = new Date();
|
||||
switch (input.id) {
|
||||
case "url":
|
||||
@@ -826,6 +988,8 @@ const navigationEvents = async () => {
|
||||
|
||||
// Handle input enter events
|
||||
ipcMain.on("input-enter", (e, input) => {
|
||||
console.debug(`webview.js: navigationEvents(input-enter-${input.id})`);
|
||||
WEBVIEW.tracker.pointer.time = new Date();
|
||||
switch (input.id) {
|
||||
case "url":
|
||||
let url = input.text.trim();
|
||||
@@ -842,6 +1006,7 @@ const navigationEvents = async () => {
|
||||
|
||||
// Handle navigation button click events
|
||||
ipcMain.on("button-click", (e, button) => {
|
||||
console.debug(`webview.js: navigationEvents(button-click-${button.id})`);
|
||||
WEBVIEW.tracker.pointer.time = new Date();
|
||||
switch (button.id) {
|
||||
case "home":
|
||||
@@ -877,6 +1042,29 @@ const navigationEvents = async () => {
|
||||
*/
|
||||
const viewEvents = async () => {
|
||||
const ready = [];
|
||||
|
||||
const loaded = (i) => {
|
||||
if (WEBVIEW.viewActive) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Set window status to fullscreen
|
||||
if (i === 0 && !("app_debug" in ARGS)) {
|
||||
WEBVIEW.window.setStatus("Fullscreen");
|
||||
}
|
||||
|
||||
// Hide loader and show first view
|
||||
const done = ready.length >= WEBVIEW.views.length;
|
||||
if (done) {
|
||||
WEBVIEW.viewActive = 1;
|
||||
updateView();
|
||||
}
|
||||
console.debug(`webview.js: viewEvents(${i},loaded-${ready.length}/${WEBVIEW.views.length})`);
|
||||
|
||||
return done;
|
||||
};
|
||||
|
||||
// Handle events per webview
|
||||
WEBVIEW.views.forEach((view, i) => {
|
||||
// Enable webview touch emulation
|
||||
view.webContents.debugger.attach("1.1");
|
||||
@@ -892,32 +1080,33 @@ const viewEvents = async () => {
|
||||
});
|
||||
|
||||
// Update webview layout
|
||||
view.webContents.once("dom-ready", () => {
|
||||
console.debug(`webview.js: viewEvents(${i},dom-ready)`);
|
||||
if ("app_reset" in ARGS) {
|
||||
cookieStore("web-theme", WEBVIEW.theme.default, view);
|
||||
cookieStore("web-zoom", WEBVIEW.zoom.default, view);
|
||||
}
|
||||
ready.push(i);
|
||||
});
|
||||
view.webContents.on("dom-ready", () => {
|
||||
view.webContents.insertCSS("::-webkit-scrollbar { display: none; }");
|
||||
if (ready.length < WEBVIEW.views.length) {
|
||||
view.webContents.setZoomFactor(WEBVIEW.viewZoom);
|
||||
ready.push(i);
|
||||
}
|
||||
});
|
||||
|
||||
// Webview fully loaded
|
||||
view.webContents.on("did-finish-load", () => {
|
||||
if (WEBVIEW.viewActive === 0 && ready.length === WEBVIEW.views.length) {
|
||||
nextView();
|
||||
}
|
||||
console.debug(`webview.js: viewEvents(${i},did-finish-load)`);
|
||||
if ("app_debug" in ARGS) {
|
||||
setTimeout(() => {
|
||||
view.webContents.openDevTools();
|
||||
}, 2000);
|
||||
}
|
||||
loaded(i);
|
||||
});
|
||||
|
||||
// Webview not loaded
|
||||
view.webContents.on("did-fail-load", (e, code, text, url, mainframe) => {
|
||||
if (mainframe) {
|
||||
if (WEBVIEW.viewActive === 0 && ready.length === WEBVIEW.views.length) {
|
||||
nextView();
|
||||
}
|
||||
console.debug(`webview.js: viewEvents(${i},did-fail-load)`);
|
||||
switch (code) {
|
||||
case -3:
|
||||
console.warn(`Load Warning: ${url}, ERR_ABORTED (${code})`);
|
||||
@@ -926,35 +1115,44 @@ const viewEvents = async () => {
|
||||
console.error(`Load Error: ${url}, ${text} (${code})`);
|
||||
view.webContents.loadURL(errorHtml(code, text, url, WEBVIEW.theme.get()));
|
||||
}
|
||||
loaded(i);
|
||||
}
|
||||
});
|
||||
|
||||
// Webview url changed
|
||||
view.webContents.on("did-navigate", () => {
|
||||
console.debug(`webview.js: viewEvents(${i},did-navigate)`);
|
||||
updateView();
|
||||
});
|
||||
view.webContents.on("did-navigate-in-page", (e, url, mainframe) => {
|
||||
if (mainframe) {
|
||||
console.debug(`webview.js: viewEvents(${i},did-navigate-in-page)`);
|
||||
updateView();
|
||||
}
|
||||
});
|
||||
view.webContents.on("did-navigate", () => {
|
||||
updateView();
|
||||
});
|
||||
|
||||
// Handle webview mouse events
|
||||
view.webContents.on("before-mouse-event", (e, mouse) => {
|
||||
const now = new Date();
|
||||
const then = WEBVIEW.tracker.pointer.time;
|
||||
const delta = (now - then) / 1000;
|
||||
|
||||
// Check mouse event type
|
||||
switch (mouse.type) {
|
||||
case "mouseMove":
|
||||
const posNew = { x: mouse.globalX, y: mouse.globalY };
|
||||
const posNew = { x: Math.round(mouse.globalX), y: Math.round(mouse.globalY) };
|
||||
if (posNew.x < 0 || posNew.y < 0) {
|
||||
break;
|
||||
}
|
||||
// Update last active on pointer position change
|
||||
console.debug(`webview.js: viewEvents(${i},${mouse.type}-${posNew.x}-${posNew.y})`);
|
||||
|
||||
// Update tracker pointer time and position
|
||||
const posOld = WEBVIEW.tracker.pointer.position;
|
||||
if (posOld.x !== posNew.x || posOld.y !== posNew.y) {
|
||||
WEBVIEW.tracker.pointer.time = now;
|
||||
WEBVIEW.tracker.pointer.position = posNew;
|
||||
|
||||
// Update last active on pointer position change
|
||||
if (delta > 30) {
|
||||
console.info("Update Last Active");
|
||||
integration.update();
|
||||
@@ -962,15 +1160,18 @@ const viewEvents = async () => {
|
||||
}
|
||||
break;
|
||||
case "mouseDown":
|
||||
console.debug(`webview.js: viewEvents(${i},${mouse.type}-${mouse.button})`);
|
||||
switch (mouse.button) {
|
||||
case "left":
|
||||
const off = WEBVIEW.tracker.display.off > WEBVIEW.tracker.display.on;
|
||||
console.debug(`webview.js: viewEvents(${i},display-${off ? "off" : "on"})`);
|
||||
|
||||
// Ignore touch event if display was off
|
||||
if (WEBVIEW.tracker.display.off > WEBVIEW.tracker.display.on) {
|
||||
if (off) {
|
||||
console.verbose("Display Touch Event: Ignored");
|
||||
e.preventDefault();
|
||||
}
|
||||
|
||||
// Turn display on if it was off
|
||||
if (hardware.getDisplayStatus() === "OFF") {
|
||||
hardware.setDisplayStatus("ON");
|
||||
}
|
||||
break;
|
||||
@@ -991,6 +1192,8 @@ const viewEvents = async () => {
|
||||
* Register app events and handler.
|
||||
*/
|
||||
const appEvents = async () => {
|
||||
console.debug("webview.js: appEvents()");
|
||||
|
||||
// Handle global events
|
||||
EVENTS.on("reloadView", reloadView);
|
||||
EVENTS.on("updateView", updateView);
|
||||
@@ -1026,24 +1229,40 @@ const appEvents = async () => {
|
||||
WEBVIEW.window.focus();
|
||||
});
|
||||
|
||||
// Handle exit events
|
||||
app.on("before-quit", () => {
|
||||
APP.exiting = true;
|
||||
console.warn(`${APP.title} Terminated`);
|
||||
// Handle crash events
|
||||
app.on("render-process-gone", (e, wc, details) => {
|
||||
const url = wc.getURL() || "Unknown";
|
||||
if (!url.startsWith("data:")) {
|
||||
console.error(`Render Process ${details.reason} (code ${details.exitCode}): ${url}`);
|
||||
}
|
||||
reloadView();
|
||||
});
|
||||
app.on("child-process-gone", (e, details) => {
|
||||
const name = details.name || details.serviceName || "Unknown";
|
||||
console.error(`${details.type} Process ${details.reason} (code ${details.exitCode}): ${name}`);
|
||||
});
|
||||
process.on("SIGINT", app.quit);
|
||||
|
||||
// Webview initialized
|
||||
WEBVIEW.initialized = true;
|
||||
// Update latest screenshot (every full 1min)
|
||||
interval(() => {
|
||||
if (APP.exiting) {
|
||||
return;
|
||||
}
|
||||
captureView(5000).then(() => {
|
||||
EVENTS.emit("updateScreenshot");
|
||||
});
|
||||
}, 60 * 1000);
|
||||
|
||||
// Check for latest release infos (2h)
|
||||
setInterval(() => {
|
||||
// Check latest release (every full 2h)
|
||||
interval(() => {
|
||||
if (APP.exiting) {
|
||||
return;
|
||||
}
|
||||
latestRelease();
|
||||
}, 7200 * 1000);
|
||||
await latestRelease();
|
||||
latestRelease();
|
||||
|
||||
// Webview initialized
|
||||
WEBVIEW.initialized = true;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -1051,7 +1270,7 @@ const appEvents = async () => {
|
||||
*/
|
||||
const latestRelease = async () => {
|
||||
try {
|
||||
const response = await axios.get(APP.releases.url, { timeout: 10000 });
|
||||
const response = await axios.get(APP.releases.url, { timeout: 20000 });
|
||||
const release = response?.data?.find((item) => {
|
||||
return !item.draft && (!item.prerelease || "app_early" in ARGS);
|
||||
});
|
||||
@@ -1062,6 +1281,7 @@ const latestRelease = async () => {
|
||||
summary: release.body || " ",
|
||||
url: release.html_url || " ",
|
||||
};
|
||||
EVENTS.emit("updateApp");
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn("Github Error:", error.message);
|
||||
@@ -1084,7 +1304,7 @@ const onlineStatus = (url, interval = 1000, timeout = 60000) => {
|
||||
try {
|
||||
if (!url.startsWith("data:")) {
|
||||
const agent = new https.Agent({ rejectUnauthorized: !("ignore_certificate_errors" in ARGS) });
|
||||
await axios.get(url, { httpsAgent: agent, timeout: 10000 });
|
||||
await axios.get(url, { httpsAgent: agent, timeout: 20000 });
|
||||
}
|
||||
resolve(true);
|
||||
} catch (error) {
|
||||
@@ -1105,6 +1325,59 @@ const onlineStatus = (url, interval = 1000, timeout = 60000) => {
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Stores, retrieves or deletes a cookie from the active webview.
|
||||
*
|
||||
* @param {string} key - The key of the webview cookie.
|
||||
* @param {string|number} value - The value of the webview cookie.
|
||||
* @param {WebContentsView} view - The webview that stores the cookie.
|
||||
* @returns {Promise<string|number>} The value of the webview cookie.
|
||||
*/
|
||||
const cookieStore = async (key, value, view = WEBVIEW.views[WEBVIEW.viewActive]) => {
|
||||
const url = view ? view.webContents.getURL() : null;
|
||||
if (!url || url.startsWith("data:")) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Use origin session cookies
|
||||
const name = `${APP.name}-${key}`;
|
||||
const origin = new URL(url).origin;
|
||||
const cookies = view.webContents.session.cookies;
|
||||
const expires = Math.floor(Date.now() / 1000) + 3600 * 24 * 365;
|
||||
|
||||
// Delete cookie if value is null
|
||||
if (value === null) {
|
||||
await cookies.remove(origin, name);
|
||||
return null;
|
||||
}
|
||||
|
||||
// Write cookie if value is provided
|
||||
if (value !== undefined) {
|
||||
await cookies.set({ url: origin, name: name, value: `${value}`, expirationDate: expires });
|
||||
return value;
|
||||
}
|
||||
|
||||
// Read cookie if no value is provided
|
||||
const cookie = (await cookies.get({ url: origin, name: name }))[0] || {};
|
||||
return !isNaN(Number(cookie.value)) ? Number(cookie.value) : cookie.value;
|
||||
};
|
||||
|
||||
/**
|
||||
* Captures a webview screenshot as a base64 image.
|
||||
*
|
||||
* @param {number} wait - The time to wait before capturing in milliseconds.
|
||||
* @param {WebContentsView} view - The webview that captures the page.
|
||||
* @returns {Promise<string|null>} The base64 image of the captured page or null if failed.
|
||||
*/
|
||||
const captureView = async (wait, view = WEBVIEW.views[WEBVIEW.viewActive]) => {
|
||||
await new Promise((r) => setTimeout(r, wait));
|
||||
const image = await view.webContents.capturePage();
|
||||
const dataUrl = image.toDataURL();
|
||||
const dataString = dataUrl.replace(/^data:image\/\w+;base64,/, "").trim();
|
||||
WEBVIEW.tracker.screenshot = dataString || WEBVIEW.tracker.screenshot;
|
||||
return WEBVIEW.tracker.screenshot;
|
||||
};
|
||||
|
||||
/**
|
||||
* Generates a html template for a spinning loader.
|
||||
*
|
||||
@@ -1203,6 +1476,20 @@ const errorHtml = (code, text, url, theme) => {
|
||||
return `data:text/html;charset=utf-8,${encodeURIComponent(html)}`;
|
||||
};
|
||||
|
||||
/**
|
||||
* Interval function that runs at interval boundaries.
|
||||
*
|
||||
* @param {Function} callback - The function to execute.
|
||||
* @param {number} ms - The interval time in milliseconds.
|
||||
*/
|
||||
const interval = (callback, ms) => {
|
||||
const delay = ms - (Date.now() % ms);
|
||||
setTimeout(() => {
|
||||
callback();
|
||||
setInterval(callback, ms);
|
||||
}, delay);
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
init,
|
||||
update,
|
||||
|
||||
+7
-7
@@ -4,7 +4,7 @@
|
||||
"description": "Home Assistant Touch Kiosk",
|
||||
"homepage": "https://github.com/leukipp/touchkio",
|
||||
"author": "leukipp",
|
||||
"version": "1.4.0",
|
||||
"version": "1.4.1",
|
||||
"license": "MIT",
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
@@ -15,16 +15,16 @@
|
||||
"printWidth": 120
|
||||
},
|
||||
"devDependencies": {
|
||||
"@electron-forge/cli": "^7.10.0",
|
||||
"@electron-forge/maker-deb": "^7.10.0",
|
||||
"@electron-forge/maker-zip": "^7.10.0",
|
||||
"@electron-forge/publisher-github": "^7.10.0",
|
||||
"electron": "^38.2.2",
|
||||
"@electron-forge/cli": "^7.10.2",
|
||||
"@electron-forge/maker-deb": "^7.10.2",
|
||||
"@electron-forge/maker-zip": "^7.10.2",
|
||||
"@electron-forge/publisher-github": "^7.10.2",
|
||||
"electron": "^39.2.4",
|
||||
"jszip": "^3.10.1",
|
||||
"prettier": "^3.6.2"
|
||||
},
|
||||
"dependencies": {
|
||||
"axios": "^1.12.2",
|
||||
"axios": "^1.13.2",
|
||||
"electron-log": "^5.4.3",
|
||||
"mqtt": "^5.14.1"
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user