mirror of https://github.com/jetkvm/kvm.git
Compare commits
45 Commits
release/0.
...
main
Author | SHA1 | Date |
---|---|---|
|
fe127ed41c | |
|
3e7d8fb0f5 | |
|
0d7f47c109 | |
|
254c001572 | |
|
6f037a832d | |
|
ccba27cedd | |
|
cf9c6e5cc8 | |
|
ffeaf8cced | |
|
a1ed28c676 | |
|
1674a6666c | |
|
772527849f | |
|
19871517ec | |
|
b822b73a03 | |
|
58ade3b551 | |
|
3cc119c646 | |
|
c494cf26ef | |
|
4bfbc66ea7 | |
|
0636cc9aff | |
|
4f6026e182 | |
|
89f3bc8c40 | |
|
91171d9bf7 | |
|
0d955a8d95 | |
|
a40d26ab9b | |
|
9bd587b52e | |
|
7ef9a7ba93 | |
|
bfbc1a5a57 | |
|
abb4350316 | |
|
52825da68d | |
|
9d2abd9fb0 | |
|
52dd675e52 | |
|
e95e30e48c | |
|
eaa58492ab | |
|
f4bb47c544 | |
|
a7693df92c | |
|
8d77d75294 | |
|
718b343713 | |
|
1f7c5c94d8 | |
|
55d7f22c47 | |
|
a28676cd94 | |
|
2ec061b3a8 | |
|
7e64a529f8 | |
|
1b5062c504 | |
|
c1d771cced | |
|
019934d33e | |
|
0c5c69f2d3 |
|
@ -9,6 +9,19 @@
|
|||
},
|
||||
"mounts": [
|
||||
"source=${localEnv:HOME}/.ssh,target=/home/vscode/.ssh,type=bind,consistency=cached"
|
||||
]
|
||||
],
|
||||
"customizations": {
|
||||
"vscode": {
|
||||
"extensions": [
|
||||
"bradlc.vscode-tailwindcss",
|
||||
"GitHub.vscode-pull-request-github",
|
||||
"dbaeumer.vscode-eslint",
|
||||
"golang.go",
|
||||
"ms-vscode.makefile-tools",
|
||||
"esbenp.prettier-vscode",
|
||||
"github.vscode-github-actions"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -0,0 +1,3 @@
|
|||
{
|
||||
"tailwindCSS.classFunctions": ["cva", "cx"]
|
||||
}
|
4
Makefile
4
Makefile
|
@ -2,8 +2,8 @@ BRANCH ?= $(shell git rev-parse --abbrev-ref HEAD)
|
|||
BUILDDATE ?= $(shell date -u +%FT%T%z)
|
||||
BUILDTS ?= $(shell date -u +%s)
|
||||
REVISION ?= $(shell git rev-parse HEAD)
|
||||
VERSION_DEV := 0.4.4-dev$(shell date +%Y%m%d%H%M)
|
||||
VERSION := 0.4.3
|
||||
VERSION_DEV ?= 0.4.6-dev$(shell date +%Y%m%d%H%M)
|
||||
VERSION ?= 0.4.5
|
||||
|
||||
PROMETHEUS_TAG := github.com/prometheus/common/version
|
||||
KVM_PKG_NAME := github.com/jetkvm/kvm
|
||||
|
|
22
cloud.go
22
cloud.go
|
@ -51,34 +51,34 @@ var (
|
|||
)
|
||||
metricCloudConnectionEstablishedTimestamp = promauto.NewGauge(
|
||||
prometheus.GaugeOpts{
|
||||
Name: "jetkvm_cloud_connection_established_timestamp",
|
||||
Name: "jetkvm_cloud_connection_established_timestamp_seconds",
|
||||
Help: "The timestamp when the cloud connection was established",
|
||||
},
|
||||
)
|
||||
metricConnectionLastPingTimestamp = promauto.NewGaugeVec(
|
||||
prometheus.GaugeOpts{
|
||||
Name: "jetkvm_connection_last_ping_timestamp",
|
||||
Name: "jetkvm_connection_last_ping_timestamp_seconds",
|
||||
Help: "The timestamp when the last ping response was received",
|
||||
},
|
||||
[]string{"type", "source"},
|
||||
)
|
||||
metricConnectionLastPingReceivedTimestamp = promauto.NewGaugeVec(
|
||||
prometheus.GaugeOpts{
|
||||
Name: "jetkvm_connection_last_ping_received_timestamp",
|
||||
Name: "jetkvm_connection_last_ping_received_timestamp_seconds",
|
||||
Help: "The timestamp when the last ping request was received",
|
||||
},
|
||||
[]string{"type", "source"},
|
||||
)
|
||||
metricConnectionLastPingDuration = promauto.NewGaugeVec(
|
||||
prometheus.GaugeOpts{
|
||||
Name: "jetkvm_connection_last_ping_duration",
|
||||
Name: "jetkvm_connection_last_ping_duration_seconds",
|
||||
Help: "The duration of the last ping response",
|
||||
},
|
||||
[]string{"type", "source"},
|
||||
)
|
||||
metricConnectionPingDuration = promauto.NewHistogramVec(
|
||||
prometheus.HistogramOpts{
|
||||
Name: "jetkvm_connection_ping_duration",
|
||||
Name: "jetkvm_connection_ping_duration_seconds",
|
||||
Help: "The duration of the ping response",
|
||||
Buckets: []float64{
|
||||
0.1, 0.5, 1, 10,
|
||||
|
@ -88,28 +88,28 @@ var (
|
|||
)
|
||||
metricConnectionTotalPingSentCount = promauto.NewCounterVec(
|
||||
prometheus.CounterOpts{
|
||||
Name: "jetkvm_connection_total_ping_sent",
|
||||
Name: "jetkvm_connection_ping_sent_total",
|
||||
Help: "The total number of pings sent to the connection",
|
||||
},
|
||||
[]string{"type", "source"},
|
||||
)
|
||||
metricConnectionTotalPingReceivedCount = promauto.NewCounterVec(
|
||||
prometheus.CounterOpts{
|
||||
Name: "jetkvm_connection_total_ping_received",
|
||||
Name: "jetkvm_connection_ping_received_total",
|
||||
Help: "The total number of pings received from the connection",
|
||||
},
|
||||
[]string{"type", "source"},
|
||||
)
|
||||
metricConnectionSessionRequestCount = promauto.NewCounterVec(
|
||||
prometheus.CounterOpts{
|
||||
Name: "jetkvm_connection_session_total_requests",
|
||||
Name: "jetkvm_connection_session_requests_total",
|
||||
Help: "The total number of session requests received",
|
||||
},
|
||||
[]string{"type", "source"},
|
||||
)
|
||||
metricConnectionSessionRequestDuration = promauto.NewHistogramVec(
|
||||
prometheus.HistogramOpts{
|
||||
Name: "jetkvm_connection_session_request_duration",
|
||||
Name: "jetkvm_connection_session_request_duration_seconds",
|
||||
Help: "The duration of session requests",
|
||||
Buckets: []float64{
|
||||
0.1, 0.5, 1, 10,
|
||||
|
@ -119,7 +119,7 @@ var (
|
|||
)
|
||||
metricConnectionLastSessionRequestTimestamp = promauto.NewGaugeVec(
|
||||
prometheus.GaugeOpts{
|
||||
Name: "jetkvm_connection_last_session_request_timestamp",
|
||||
Name: "jetkvm_connection_last_session_request_timestamp_seconds",
|
||||
Help: "The timestamp of the last session request",
|
||||
},
|
||||
[]string{"type", "source"},
|
||||
|
@ -133,7 +133,7 @@ var (
|
|||
)
|
||||
metricCloudConnectionFailureCount = promauto.NewCounter(
|
||||
prometheus.CounterOpts{
|
||||
Name: "jetkvm_cloud_connection_failure_count",
|
||||
Name: "jetkvm_cloud_connection_failure_total",
|
||||
Help: "The number of times the cloud connection has failed",
|
||||
},
|
||||
)
|
||||
|
|
|
@ -85,6 +85,7 @@ type Config struct {
|
|||
HashedPassword string `json:"hashed_password"`
|
||||
LocalAuthToken string `json:"local_auth_token"`
|
||||
LocalAuthMode string `json:"localAuthMode"` //TODO: fix it with migration
|
||||
LocalLoopbackOnly bool `json:"local_loopback_only"`
|
||||
WakeOnLanDevices []WakeOnLanDevice `json:"wake_on_lan_devices"`
|
||||
KeyboardMacros []KeyboardMacro `json:"keyboard_macros"`
|
||||
KeyboardLayout string `json:"keyboard_layout"`
|
||||
|
@ -110,7 +111,7 @@ var defaultConfig = &Config{
|
|||
ActiveExtension: "",
|
||||
KeyboardMacros: []KeyboardMacro{},
|
||||
DisplayRotation: "270",
|
||||
KeyboardLayout: "en-US",
|
||||
KeyboardLayout: "en_US",
|
||||
DisplayMaxBrightness: 64,
|
||||
DisplayDimAfterSec: 120, // 2 minutes
|
||||
DisplayOffAfterSec: 1800, // 30 minutes
|
||||
|
|
15
display.go
15
display.go
|
@ -339,10 +339,18 @@ func startBacklightTickers() {
|
|||
return
|
||||
}
|
||||
|
||||
if dimTicker == nil && config.DisplayDimAfterSec != 0 {
|
||||
// Stop existing tickers to prevent multiple active instances on repeated calls
|
||||
if dimTicker != nil {
|
||||
dimTicker.Stop()
|
||||
}
|
||||
|
||||
if offTicker != nil {
|
||||
offTicker.Stop()
|
||||
}
|
||||
|
||||
if config.DisplayDimAfterSec != 0 {
|
||||
displayLogger.Info().Msg("dim_ticker has started")
|
||||
dimTicker = time.NewTicker(time.Duration(config.DisplayDimAfterSec) * time.Second)
|
||||
defer dimTicker.Stop()
|
||||
|
||||
go func() {
|
||||
for { //nolint:staticcheck
|
||||
|
@ -354,10 +362,9 @@ func startBacklightTickers() {
|
|||
}()
|
||||
}
|
||||
|
||||
if offTicker == nil && config.DisplayOffAfterSec != 0 {
|
||||
if config.DisplayOffAfterSec != 0 {
|
||||
displayLogger.Info().Msg("off_ticker has started")
|
||||
offTicker = time.NewTicker(time.Duration(config.DisplayOffAfterSec) * time.Second)
|
||||
defer offTicker.Stop()
|
||||
|
||||
go func() {
|
||||
for { //nolint:staticcheck
|
||||
|
|
|
@ -95,16 +95,27 @@ func (t *TimeSync) queryMultipleHttp(urls []string, timeout time.Duration) (now
|
|||
} else if errors.Is(err, context.Canceled) {
|
||||
metricHttpCancelCount.WithLabelValues(url).Inc()
|
||||
metricHttpTotalCancelCount.Inc()
|
||||
results <- nil
|
||||
} else {
|
||||
scopedLogger.Warn().
|
||||
Str("error", err.Error()).
|
||||
Int("status", status).
|
||||
Msg("failed to query HTTP server")
|
||||
results <- nil
|
||||
}
|
||||
}(url)
|
||||
}
|
||||
|
||||
return <-results
|
||||
for range urls {
|
||||
result := <-results
|
||||
if result == nil {
|
||||
continue
|
||||
}
|
||||
now = result
|
||||
return
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
func queryHttpTime(
|
||||
|
|
|
@ -14,44 +14,44 @@ var (
|
|||
)
|
||||
metricTimeSyncCount = promauto.NewCounter(
|
||||
prometheus.CounterOpts{
|
||||
Name: "jetkvm_timesync_count",
|
||||
Name: "jetkvm_timesync_total",
|
||||
Help: "The number of times the timesync has been run",
|
||||
},
|
||||
)
|
||||
metricTimeSyncSuccessCount = promauto.NewCounter(
|
||||
prometheus.CounterOpts{
|
||||
Name: "jetkvm_timesync_success_count",
|
||||
Name: "jetkvm_timesync_success_total",
|
||||
Help: "The number of times the timesync has been successful",
|
||||
},
|
||||
)
|
||||
metricRTCUpdateCount = promauto.NewCounter( //nolint:unused
|
||||
prometheus.CounterOpts{
|
||||
Name: "jetkvm_timesync_rtc_update_count",
|
||||
Name: "jetkvm_timesync_rtc_update_total",
|
||||
Help: "The number of times the RTC has been updated",
|
||||
},
|
||||
)
|
||||
metricNtpTotalSuccessCount = promauto.NewCounter(
|
||||
prometheus.CounterOpts{
|
||||
Name: "jetkvm_timesync_ntp_total_success_count",
|
||||
Name: "jetkvm_timesync_ntp_total_success_total",
|
||||
Help: "The total number of successful NTP requests",
|
||||
},
|
||||
)
|
||||
metricNtpTotalRequestCount = promauto.NewCounter(
|
||||
prometheus.CounterOpts{
|
||||
Name: "jetkvm_timesync_ntp_total_request_count",
|
||||
Name: "jetkvm_timesync_ntp_total_request_total",
|
||||
Help: "The total number of NTP requests sent",
|
||||
},
|
||||
)
|
||||
metricNtpSuccessCount = promauto.NewCounterVec(
|
||||
prometheus.CounterOpts{
|
||||
Name: "jetkvm_timesync_ntp_success_count",
|
||||
Name: "jetkvm_timesync_ntp_success_total",
|
||||
Help: "The number of successful NTP requests",
|
||||
},
|
||||
[]string{"url"},
|
||||
)
|
||||
metricNtpRequestCount = promauto.NewCounterVec(
|
||||
prometheus.CounterOpts{
|
||||
Name: "jetkvm_timesync_ntp_request_count",
|
||||
Name: "jetkvm_timesync_ntp_request_total",
|
||||
Help: "The number of NTP requests sent to the server",
|
||||
},
|
||||
[]string{"url"},
|
||||
|
@ -83,39 +83,39 @@ var (
|
|||
|
||||
metricHttpTotalSuccessCount = promauto.NewCounter(
|
||||
prometheus.CounterOpts{
|
||||
Name: "jetkvm_timesync_http_total_success_count",
|
||||
Name: "jetkvm_timesync_http_total_success_total",
|
||||
Help: "The total number of successful HTTP requests",
|
||||
},
|
||||
)
|
||||
metricHttpTotalRequestCount = promauto.NewCounter(
|
||||
prometheus.CounterOpts{
|
||||
Name: "jetkvm_timesync_http_total_request_count",
|
||||
Name: "jetkvm_timesync_http_total_request_total",
|
||||
Help: "The total number of HTTP requests sent",
|
||||
},
|
||||
)
|
||||
metricHttpTotalCancelCount = promauto.NewCounter(
|
||||
prometheus.CounterOpts{
|
||||
Name: "jetkvm_timesync_http_total_cancel_count",
|
||||
Name: "jetkvm_timesync_http_total_cancel_total",
|
||||
Help: "The total number of HTTP requests cancelled",
|
||||
},
|
||||
)
|
||||
metricHttpSuccessCount = promauto.NewCounterVec(
|
||||
prometheus.CounterOpts{
|
||||
Name: "jetkvm_timesync_http_success_count",
|
||||
Name: "jetkvm_timesync_http_success_total",
|
||||
Help: "The number of successful HTTP requests",
|
||||
},
|
||||
[]string{"url"},
|
||||
)
|
||||
metricHttpRequestCount = promauto.NewCounterVec(
|
||||
prometheus.CounterOpts{
|
||||
Name: "jetkvm_timesync_http_request_count",
|
||||
Name: "jetkvm_timesync_http_request_total",
|
||||
Help: "The number of HTTP requests sent to the server",
|
||||
},
|
||||
[]string{"url"},
|
||||
)
|
||||
metricHttpCancelCount = promauto.NewCounterVec(
|
||||
prometheus.CounterOpts{
|
||||
Name: "jetkvm_timesync_http_cancel_count",
|
||||
Name: "jetkvm_timesync_http_cancel_total",
|
||||
Help: "The number of HTTP requests cancelled",
|
||||
},
|
||||
[]string{"url"},
|
||||
|
|
|
@ -5,6 +5,7 @@ import (
|
|||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"time"
|
||||
|
||||
"github.com/fsnotify/fsnotify"
|
||||
|
@ -149,6 +150,12 @@ func (c *DHCPClient) loadLeaseFile() error {
|
|||
}
|
||||
|
||||
isFirstLoad := c.lease == nil
|
||||
|
||||
// Skip processing if lease hasn't changed to avoid unnecessary wake-ups.
|
||||
if reflect.DeepEqual(c.lease, lease) {
|
||||
return nil
|
||||
}
|
||||
|
||||
c.lease = lease
|
||||
|
||||
if lease.IPAddress == nil {
|
||||
|
|
|
@ -1,8 +1,11 @@
|
|||
package usbgadget
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"reflect"
|
||||
"time"
|
||||
)
|
||||
|
||||
var keyboardConfig = gadgetConfigItem{
|
||||
|
@ -36,6 +39,7 @@ var keyboardReportDesc = []byte{
|
|||
0x81, 0x03, /* INPUT (Cnst,Var,Abs) */
|
||||
0x95, 0x05, /* REPORT_COUNT (5) */
|
||||
0x75, 0x01, /* REPORT_SIZE (1) */
|
||||
|
||||
0x05, 0x08, /* USAGE_PAGE (LEDs) */
|
||||
0x19, 0x01, /* USAGE_MINIMUM (Num Lock) */
|
||||
0x29, 0x05, /* USAGE_MAXIMUM (Kana) */
|
||||
|
@ -54,23 +58,155 @@ var keyboardReportDesc = []byte{
|
|||
0xc0, /* END_COLLECTION */
|
||||
}
|
||||
|
||||
func (u *UsbGadget) keyboardWriteHidFile(data []byte) error {
|
||||
if u.keyboardHidFile == nil {
|
||||
var err error
|
||||
u.keyboardHidFile, err = os.OpenFile("/dev/hidg0", os.O_RDWR, 0666)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to open hidg0: %w", err)
|
||||
const (
|
||||
hidReadBufferSize = 8
|
||||
// https://www.usb.org/sites/default/files/documents/hid1_11.pdf
|
||||
// https://www.usb.org/sites/default/files/hut1_2.pdf
|
||||
KeyboardLedMaskNumLock = 1 << 0
|
||||
KeyboardLedMaskCapsLock = 1 << 1
|
||||
KeyboardLedMaskScrollLock = 1 << 2
|
||||
KeyboardLedMaskCompose = 1 << 3
|
||||
KeyboardLedMaskKana = 1 << 4
|
||||
ValidKeyboardLedMasks = KeyboardLedMaskNumLock | KeyboardLedMaskCapsLock | KeyboardLedMaskScrollLock | KeyboardLedMaskCompose | KeyboardLedMaskKana
|
||||
)
|
||||
|
||||
// Synchronization between LED states and CAPS LOCK, NUM LOCK, SCROLL LOCK,
|
||||
// COMPOSE, and KANA events is maintained by the host and NOT the keyboard. If
|
||||
// using the keyboard descriptor in Appendix B, LED states are set by sending a
|
||||
// 5-bit absolute report to the keyboard via a Set_Report(Output) request.
|
||||
type KeyboardState struct {
|
||||
NumLock bool `json:"num_lock"`
|
||||
CapsLock bool `json:"caps_lock"`
|
||||
ScrollLock bool `json:"scroll_lock"`
|
||||
Compose bool `json:"compose"`
|
||||
Kana bool `json:"kana"`
|
||||
}
|
||||
|
||||
func getKeyboardState(b byte) KeyboardState {
|
||||
// should we check if it's the correct usage page?
|
||||
return KeyboardState{
|
||||
NumLock: b&KeyboardLedMaskNumLock != 0,
|
||||
CapsLock: b&KeyboardLedMaskCapsLock != 0,
|
||||
ScrollLock: b&KeyboardLedMaskScrollLock != 0,
|
||||
Compose: b&KeyboardLedMaskCompose != 0,
|
||||
Kana: b&KeyboardLedMaskKana != 0,
|
||||
}
|
||||
}
|
||||
|
||||
func (u *UsbGadget) updateKeyboardState(b byte) {
|
||||
u.keyboardStateLock.Lock()
|
||||
defer u.keyboardStateLock.Unlock()
|
||||
|
||||
if b&^ValidKeyboardLedMasks != 0 {
|
||||
u.log.Trace().Uint8("b", b).Msg("contains invalid bits, ignoring")
|
||||
return
|
||||
}
|
||||
|
||||
newState := getKeyboardState(b)
|
||||
if reflect.DeepEqual(u.keyboardState, newState) {
|
||||
return
|
||||
}
|
||||
u.log.Info().Interface("old", u.keyboardState).Interface("new", newState).Msg("keyboardState updated")
|
||||
u.keyboardState = newState
|
||||
|
||||
if u.onKeyboardStateChange != nil {
|
||||
(*u.onKeyboardStateChange)(newState)
|
||||
}
|
||||
}
|
||||
|
||||
func (u *UsbGadget) SetOnKeyboardStateChange(f func(state KeyboardState)) {
|
||||
u.onKeyboardStateChange = &f
|
||||
}
|
||||
|
||||
func (u *UsbGadget) GetKeyboardState() KeyboardState {
|
||||
u.keyboardStateLock.Lock()
|
||||
defer u.keyboardStateLock.Unlock()
|
||||
|
||||
return u.keyboardState
|
||||
}
|
||||
|
||||
func (u *UsbGadget) listenKeyboardEvents() {
|
||||
var path string
|
||||
if u.keyboardHidFile != nil {
|
||||
path = u.keyboardHidFile.Name()
|
||||
}
|
||||
l := u.log.With().Str("listener", "keyboardEvents").Str("path", path).Logger()
|
||||
l.Trace().Msg("starting")
|
||||
|
||||
go func() {
|
||||
buf := make([]byte, hidReadBufferSize)
|
||||
for {
|
||||
select {
|
||||
case <-u.keyboardStateCtx.Done():
|
||||
l.Info().Msg("context done")
|
||||
return
|
||||
default:
|
||||
l.Trace().Msg("reading from keyboard")
|
||||
if u.keyboardHidFile == nil {
|
||||
u.logWithSupression("keyboardHidFileNil", 100, &l, nil, "keyboardHidFile is nil")
|
||||
// show the error every 100 times to avoid spamming the logs
|
||||
time.Sleep(time.Second)
|
||||
continue
|
||||
}
|
||||
// reset the counter
|
||||
u.resetLogSuppressionCounter("keyboardHidFileNil")
|
||||
|
||||
n, err := u.keyboardHidFile.Read(buf)
|
||||
if err != nil {
|
||||
u.logWithSupression("keyboardHidFileRead", 100, &l, err, "failed to read")
|
||||
continue
|
||||
}
|
||||
u.resetLogSuppressionCounter("keyboardHidFileRead")
|
||||
|
||||
l.Trace().Int("n", n).Bytes("buf", buf).Msg("got data from keyboard")
|
||||
if n != 1 {
|
||||
l.Trace().Int("n", n).Msg("expected 1 byte, got")
|
||||
continue
|
||||
}
|
||||
u.updateKeyboardState(buf[0])
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
func (u *UsbGadget) openKeyboardHidFile() error {
|
||||
if u.keyboardHidFile != nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
var err error
|
||||
u.keyboardHidFile, err = os.OpenFile("/dev/hidg0", os.O_RDWR, 0666)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to open hidg0: %w", err)
|
||||
}
|
||||
|
||||
if u.keyboardStateCancel != nil {
|
||||
u.keyboardStateCancel()
|
||||
}
|
||||
|
||||
u.keyboardStateCtx, u.keyboardStateCancel = context.WithCancel(context.Background())
|
||||
u.listenKeyboardEvents()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (u *UsbGadget) OpenKeyboardHidFile() error {
|
||||
return u.openKeyboardHidFile()
|
||||
}
|
||||
|
||||
func (u *UsbGadget) keyboardWriteHidFile(data []byte) error {
|
||||
if err := u.openKeyboardHidFile(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err := u.keyboardHidFile.Write(data)
|
||||
if err != nil {
|
||||
u.log.Error().Err(err).Msg("failed to write to hidg0")
|
||||
u.logWithSupression("keyboardWriteHidFile", 100, u.log, err, "failed to write to hidg0")
|
||||
u.keyboardHidFile.Close()
|
||||
u.keyboardHidFile = nil
|
||||
return err
|
||||
}
|
||||
|
||||
u.resetLogSuppressionCounter("keyboardWriteHidFile")
|
||||
return nil
|
||||
}
|
||||
|
||||
|
|
|
@ -12,7 +12,7 @@ var absoluteMouseConfig = gadgetConfigItem{
|
|||
configPath: []string{"hid.usb1"},
|
||||
attrs: gadgetAttributes{
|
||||
"protocol": "2",
|
||||
"subclass": "1",
|
||||
"subclass": "0",
|
||||
"report_length": "6",
|
||||
},
|
||||
reportDesc: absoluteMouseCombinedReportDesc,
|
||||
|
@ -75,11 +75,12 @@ func (u *UsbGadget) absMouseWriteHidFile(data []byte) error {
|
|||
|
||||
_, err := u.absMouseHidFile.Write(data)
|
||||
if err != nil {
|
||||
u.log.Error().Err(err).Msg("failed to write to hidg1")
|
||||
u.logWithSupression("absMouseWriteHidFile", 100, u.log, err, "failed to write to hidg1")
|
||||
u.absMouseHidFile.Close()
|
||||
u.absMouseHidFile = nil
|
||||
return err
|
||||
}
|
||||
u.resetLogSuppressionCounter("absMouseWriteHidFile")
|
||||
return nil
|
||||
}
|
||||
|
||||
|
|
|
@ -65,11 +65,12 @@ func (u *UsbGadget) relMouseWriteHidFile(data []byte) error {
|
|||
|
||||
_, err := u.relMouseHidFile.Write(data)
|
||||
if err != nil {
|
||||
u.log.Error().Err(err).Msg("failed to write to hidg2")
|
||||
u.logWithSupression("relMouseWriteHidFile", 100, u.log, err, "failed to write to hidg2")
|
||||
u.relMouseHidFile.Close()
|
||||
u.relMouseHidFile = nil
|
||||
return err
|
||||
}
|
||||
u.resetLogSuppressionCounter("relMouseWriteHidFile")
|
||||
return nil
|
||||
}
|
||||
|
||||
|
|
|
@ -3,6 +3,7 @@
|
|||
package usbgadget
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path"
|
||||
"sync"
|
||||
|
@ -59,6 +60,11 @@ type UsbGadget struct {
|
|||
relMouseHidFile *os.File
|
||||
relMouseLock sync.Mutex
|
||||
|
||||
keyboardState KeyboardState
|
||||
keyboardStateLock sync.Mutex
|
||||
keyboardStateCtx context.Context
|
||||
keyboardStateCancel context.CancelFunc
|
||||
|
||||
enabledDevices Devices
|
||||
|
||||
strictMode bool // only intended for testing for now
|
||||
|
@ -70,7 +76,11 @@ type UsbGadget struct {
|
|||
tx *UsbGadgetTransaction
|
||||
txLock sync.Mutex
|
||||
|
||||
onKeyboardStateChange *func(state KeyboardState)
|
||||
|
||||
log *zerolog.Logger
|
||||
|
||||
logSuppressionCounter map[string]int
|
||||
}
|
||||
|
||||
const configFSPath = "/sys/kernel/config"
|
||||
|
@ -96,23 +106,30 @@ func newUsbGadget(name string, configMap map[string]gadgetConfigItem, enabledDev
|
|||
config = &Config{isEmpty: true}
|
||||
}
|
||||
|
||||
keyboardCtx, keyboardCancel := context.WithCancel(context.Background())
|
||||
|
||||
g := &UsbGadget{
|
||||
name: name,
|
||||
kvmGadgetPath: path.Join(gadgetPath, name),
|
||||
configC1Path: path.Join(gadgetPath, name, "configs/c.1"),
|
||||
configMap: configMap,
|
||||
customConfig: *config,
|
||||
configLock: sync.Mutex{},
|
||||
keyboardLock: sync.Mutex{},
|
||||
absMouseLock: sync.Mutex{},
|
||||
relMouseLock: sync.Mutex{},
|
||||
txLock: sync.Mutex{},
|
||||
enabledDevices: *enabledDevices,
|
||||
lastUserInput: time.Now(),
|
||||
log: logger,
|
||||
name: name,
|
||||
kvmGadgetPath: path.Join(gadgetPath, name),
|
||||
configC1Path: path.Join(gadgetPath, name, "configs/c.1"),
|
||||
configMap: configMap,
|
||||
customConfig: *config,
|
||||
configLock: sync.Mutex{},
|
||||
keyboardLock: sync.Mutex{},
|
||||
absMouseLock: sync.Mutex{},
|
||||
relMouseLock: sync.Mutex{},
|
||||
txLock: sync.Mutex{},
|
||||
keyboardStateCtx: keyboardCtx,
|
||||
keyboardStateCancel: keyboardCancel,
|
||||
keyboardState: KeyboardState{},
|
||||
enabledDevices: *enabledDevices,
|
||||
lastUserInput: time.Now(),
|
||||
log: logger,
|
||||
|
||||
strictMode: config.strictMode,
|
||||
|
||||
logSuppressionCounter: make(map[string]int),
|
||||
|
||||
absMouseAccumulatedWheelY: 0,
|
||||
}
|
||||
if err := g.Init(); err != nil {
|
||||
|
|
|
@ -6,6 +6,8 @@ import (
|
|||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/rs/zerolog"
|
||||
)
|
||||
|
||||
func joinPath(basePath string, paths []string) string {
|
||||
|
@ -78,3 +80,27 @@ func compareFileContent(oldContent []byte, newContent []byte, looserMatch bool)
|
|||
|
||||
return false
|
||||
}
|
||||
|
||||
func (u *UsbGadget) logWithSupression(counterName string, every int, logger *zerolog.Logger, err error, msg string, args ...interface{}) {
|
||||
if _, ok := u.logSuppressionCounter[counterName]; !ok {
|
||||
u.logSuppressionCounter[counterName] = 0
|
||||
} else {
|
||||
u.logSuppressionCounter[counterName]++
|
||||
}
|
||||
|
||||
l := logger.With().Int("counter", u.logSuppressionCounter[counterName]).Logger()
|
||||
|
||||
if u.logSuppressionCounter[counterName]%every == 0 {
|
||||
if err != nil {
|
||||
l.Error().Err(err).Msgf(msg, args...)
|
||||
} else {
|
||||
l.Error().Msgf(msg, args...)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (u *UsbGadget) resetLogSuppressionCounter(counterName string) {
|
||||
if _, ok := u.logSuppressionCounter[counterName]; !ok {
|
||||
u.logSuppressionCounter[counterName] = 0
|
||||
}
|
||||
}
|
||||
|
|
|
@ -0,0 +1,55 @@
|
|||
package websecure
|
||||
|
||||
import (
|
||||
"os"
|
||||
"testing"
|
||||
)
|
||||
|
||||
var (
|
||||
fixtureEd25519Certificate = `-----BEGIN CERTIFICATE-----
|
||||
MIIBQDCB86ADAgECAhQdB4qB6dV0/u1lwhJofQgkmjjV1zAFBgMrZXAwLzELMAkG
|
||||
A1UEBhMCREUxIDAeBgNVBAMMF2VkMjU1MTktdGVzdC5qZXRrdm0uY29tMB4XDTI1
|
||||
MDUyMzEyNTkyN1oXDTI3MDQyMzEyNTkyN1owLzELMAkGA1UEBhMCREUxIDAeBgNV
|
||||
BAMMF2VkMjU1MTktdGVzdC5qZXRrdm0uY29tMCowBQYDK2VwAyEA9tLyoulJn7Ev
|
||||
bf8kuD1ZGdA092773pCRjFEDKpXHonyjITAfMB0GA1UdDgQWBBRkmrVMfsLY57iy
|
||||
r/0POP0S4QxCADAFBgMrZXADQQBfTRvqavLHDYQiKQTgbGod+Yn+fIq2lE584+1U
|
||||
C4wh9peIJDFocLBEAYTQpEMKxa4s0AIRxD+a7aCS5oz0e/0I
|
||||
-----END CERTIFICATE-----`
|
||||
|
||||
fixtureEd25519PrivateKey = `-----BEGIN PRIVATE KEY-----
|
||||
MC4CAQAwBQYDK2VwBCIEIKV08xUsLRHBfMXqZwxVRzIbViOp8G7aQGjPvoRFjujB
|
||||
-----END PRIVATE KEY-----`
|
||||
|
||||
certStore *CertStore
|
||||
certSigner *SelfSigner
|
||||
)
|
||||
|
||||
func TestMain(m *testing.M) {
|
||||
tlsStorePath, err := os.MkdirTemp("", "jktls.*")
|
||||
if err != nil {
|
||||
defaultLogger.Fatal().Err(err).Msg("failed to create temp directory")
|
||||
}
|
||||
|
||||
certStore = NewCertStore(tlsStorePath, nil)
|
||||
certStore.LoadCertificates()
|
||||
|
||||
certSigner = NewSelfSigner(
|
||||
certStore,
|
||||
nil,
|
||||
"ci.jetkvm.com",
|
||||
"JetKVM",
|
||||
"JetKVM",
|
||||
"JetKVM",
|
||||
)
|
||||
|
||||
m.Run()
|
||||
|
||||
os.RemoveAll(tlsStorePath)
|
||||
}
|
||||
|
||||
func TestSaveEd25519Certificate(t *testing.T) {
|
||||
err, _ := certStore.ValidateAndSaveCertificate("ed25519-test.jetkvm.com", fixtureEd25519Certificate, fixtureEd25519PrivateKey, true)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to save certificate: %v", err)
|
||||
}
|
||||
}
|
|
@ -2,6 +2,7 @@ package websecure
|
|||
|
||||
import (
|
||||
"crypto/ecdsa"
|
||||
"crypto/ed25519"
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
"crypto/tls"
|
||||
|
@ -37,11 +38,15 @@ func keyToFile(cert *tls.Certificate, filename string) error {
|
|||
if e != nil {
|
||||
return fmt.Errorf("failed to marshal EC private key: %v", e)
|
||||
}
|
||||
|
||||
keyBlock = pem.Block{
|
||||
Type: "EC PRIVATE KEY",
|
||||
Bytes: b,
|
||||
}
|
||||
case ed25519.PrivateKey:
|
||||
keyBlock = pem.Block{
|
||||
Type: "ED25519 PRIVATE KEY",
|
||||
Bytes: k,
|
||||
}
|
||||
default:
|
||||
return fmt.Errorf("unknown private key type: %T", k)
|
||||
}
|
||||
|
|
22
jsonrpc.go
22
jsonrpc.go
|
@ -1006,6 +1006,25 @@ func setKeyboardMacros(params KeyboardMacrosParams) (interface{}, error) {
|
|||
return nil, nil
|
||||
}
|
||||
|
||||
func rpcGetLocalLoopbackOnly() (bool, error) {
|
||||
return config.LocalLoopbackOnly, nil
|
||||
}
|
||||
|
||||
func rpcSetLocalLoopbackOnly(enabled bool) error {
|
||||
// Check if the setting is actually changing
|
||||
if config.LocalLoopbackOnly == enabled {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Update the setting
|
||||
config.LocalLoopbackOnly = enabled
|
||||
if err := SaveConfig(); err != nil {
|
||||
return fmt.Errorf("failed to save config: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
var rpcHandlers = map[string]RPCHandler{
|
||||
"ping": {Func: rpcPing},
|
||||
"reboot": {Func: rpcReboot, Params: []string{"force"}},
|
||||
|
@ -1017,6 +1036,7 @@ var rpcHandlers = map[string]RPCHandler{
|
|||
"setNetworkSettings": {Func: rpcSetNetworkSettings, Params: []string{"settings"}},
|
||||
"renewDHCPLease": {Func: rpcRenewDHCPLease},
|
||||
"keyboardReport": {Func: rpcKeyboardReport, Params: []string{"modifier", "keys"}},
|
||||
"getKeyboardLedState": {Func: rpcGetKeyboardLedState},
|
||||
"absMouseReport": {Func: rpcAbsMouseReport, Params: []string{"x", "y", "buttons"}},
|
||||
"relMouseReport": {Func: rpcRelMouseReport, Params: []string{"dx", "dy", "buttons"}},
|
||||
"wheelReport": {Func: rpcWheelReport, Params: []string{"wheelY"}},
|
||||
|
@ -1082,4 +1102,6 @@ var rpcHandlers = map[string]RPCHandler{
|
|||
"setKeyboardLayout": {Func: rpcSetKeyboardLayout, Params: []string{"layout"}},
|
||||
"getKeyboardMacros": {Func: getKeyboardMacros},
|
||||
"setKeyboardMacros": {Func: setKeyboardMacros, Params: []string{"params"}},
|
||||
"getLocalLoopbackOnly": {Func: rpcGetLocalLoopbackOnly},
|
||||
"setLocalLoopbackOnly": {Func: rpcSetLocalLoopbackOnly, Params: []string{"enabled"}},
|
||||
}
|
||||
|
|
99
native.go
99
native.go
|
@ -8,6 +8,7 @@ import (
|
|||
"io"
|
||||
"net"
|
||||
"os"
|
||||
"os/exec"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
|
@ -41,6 +42,11 @@ var ongoingRequests = make(map[int32]chan *CtrlResponse)
|
|||
|
||||
var lock = &sync.Mutex{}
|
||||
|
||||
var (
|
||||
nativeCmd *exec.Cmd
|
||||
nativeCmdLock = &sync.Mutex{}
|
||||
)
|
||||
|
||||
func CallCtrlAction(action string, params map[string]interface{}) (*CtrlResponse, error) {
|
||||
lock.Lock()
|
||||
defer lock.Unlock()
|
||||
|
@ -129,16 +135,26 @@ func StartNativeSocketServer(socketPath string, handleClient func(net.Conn), isC
|
|||
scopedLogger.Info().Msg("server listening")
|
||||
|
||||
go func() {
|
||||
conn, err := listener.Accept()
|
||||
listener.Close()
|
||||
if err != nil {
|
||||
scopedLogger.Warn().Err(err).Msg("failed to accept socket")
|
||||
for {
|
||||
conn, err := listener.Accept()
|
||||
|
||||
if err != nil {
|
||||
scopedLogger.Warn().Err(err).Msg("failed to accept socket")
|
||||
continue
|
||||
}
|
||||
if isCtrl {
|
||||
// check if the channel is closed
|
||||
select {
|
||||
case <-ctrlClientConnected:
|
||||
scopedLogger.Debug().Msg("ctrl client reconnected")
|
||||
default:
|
||||
close(ctrlClientConnected)
|
||||
scopedLogger.Debug().Msg("first native ctrl socket client connected")
|
||||
}
|
||||
}
|
||||
|
||||
go handleClient(conn)
|
||||
}
|
||||
if isCtrl {
|
||||
close(ctrlClientConnected)
|
||||
scopedLogger.Debug().Msg("first native ctrl socket client connected")
|
||||
}
|
||||
handleClient(conn)
|
||||
}()
|
||||
|
||||
return listener
|
||||
|
@ -235,6 +251,51 @@ func handleVideoClient(conn net.Conn) {
|
|||
}
|
||||
}
|
||||
|
||||
func startNativeBinaryWithLock(binaryPath string) (*exec.Cmd, error) {
|
||||
nativeCmdLock.Lock()
|
||||
defer nativeCmdLock.Unlock()
|
||||
|
||||
cmd, err := startNativeBinary(binaryPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
nativeCmd = cmd
|
||||
return cmd, nil
|
||||
}
|
||||
|
||||
func restartNativeBinary(binaryPath string) error {
|
||||
time.Sleep(10 * time.Second)
|
||||
// restart the binary
|
||||
nativeLogger.Info().Msg("restarting jetkvm_native binary")
|
||||
cmd, err := startNativeBinary(binaryPath)
|
||||
if err != nil {
|
||||
nativeLogger.Warn().Err(err).Msg("failed to restart binary")
|
||||
}
|
||||
nativeCmd = cmd
|
||||
return err
|
||||
}
|
||||
|
||||
func superviseNativeBinary(binaryPath string) error {
|
||||
nativeCmdLock.Lock()
|
||||
defer nativeCmdLock.Unlock()
|
||||
|
||||
if nativeCmd == nil || nativeCmd.Process == nil {
|
||||
return restartNativeBinary(binaryPath)
|
||||
}
|
||||
|
||||
err := nativeCmd.Wait()
|
||||
|
||||
if err == nil {
|
||||
nativeLogger.Info().Err(err).Msg("jetkvm_native binary exited with no error")
|
||||
} else if exiterr, ok := err.(*exec.ExitError); ok {
|
||||
nativeLogger.Warn().Int("exit_code", exiterr.ExitCode()).Msg("jetkvm_native binary exited with error")
|
||||
} else {
|
||||
nativeLogger.Warn().Err(err).Msg("jetkvm_native binary exited with unknown error")
|
||||
}
|
||||
|
||||
return restartNativeBinary(binaryPath)
|
||||
}
|
||||
|
||||
func ExtractAndRunNativeBin() error {
|
||||
binaryPath := "/userdata/jetkvm/bin/jetkvm_native"
|
||||
if err := ensureBinaryUpdated(binaryPath); err != nil {
|
||||
|
@ -246,12 +307,28 @@ func ExtractAndRunNativeBin() error {
|
|||
return fmt.Errorf("failed to make binary executable: %w", err)
|
||||
}
|
||||
// Run the binary in the background
|
||||
cmd, err := startNativeBinary(binaryPath)
|
||||
cmd, err := startNativeBinaryWithLock(binaryPath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to start binary: %w", err)
|
||||
}
|
||||
|
||||
//TODO: add auto restart
|
||||
// check if the binary is still running every 10 seconds
|
||||
go func() {
|
||||
for {
|
||||
select {
|
||||
case <-appCtx.Done():
|
||||
nativeLogger.Info().Msg("stopping native binary supervisor")
|
||||
return
|
||||
default:
|
||||
err := superviseNativeBinary(binaryPath)
|
||||
if err != nil {
|
||||
nativeLogger.Warn().Err(err).Msg("failed to supervise native binary")
|
||||
time.Sleep(1 * time.Second) // Add a short delay to prevent rapid successive calls
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
go func() {
|
||||
<-appCtx.Done()
|
||||
nativeLogger.Info().Int("pid", cmd.Process.Pid).Msg("killing process")
|
||||
|
|
|
@ -21,6 +21,7 @@ func networkStateChanged() {
|
|||
|
||||
// always restart mDNS when the network state changes
|
||||
if mDNS != nil {
|
||||
_ = mDNS.SetListenOptions(config.NetworkConfig.GetMDNSMode())
|
||||
_ = mDNS.SetLocalNames([]string{
|
||||
networkState.GetHostname(),
|
||||
networkState.GetFQDN(),
|
||||
|
@ -54,14 +55,6 @@ func initNetwork() error {
|
|||
OnConfigChange: func(networkConfig *network.NetworkConfig) {
|
||||
config.NetworkConfig = networkConfig
|
||||
networkStateChanged()
|
||||
|
||||
if mDNS != nil {
|
||||
_ = mDNS.SetListenOptions(networkConfig.GetMDNSMode())
|
||||
_ = mDNS.SetLocalNames([]string{
|
||||
networkState.GetHostname(),
|
||||
networkState.GetFQDN(),
|
||||
}, true)
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
|
|
24
terminal.go
24
terminal.go
|
@ -1,6 +1,7 @@
|
|||
package kvm
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"os"
|
||||
|
@ -55,18 +56,23 @@ func handleTerminalChannel(d *webrtc.DataChannel) {
|
|||
return
|
||||
}
|
||||
if msg.IsString {
|
||||
var size TerminalSize
|
||||
err := json.Unmarshal([]byte(msg.Data), &size)
|
||||
if err == nil {
|
||||
err = pty.Setsize(ptmx, &pty.Winsize{
|
||||
Rows: uint16(size.Rows),
|
||||
Cols: uint16(size.Cols),
|
||||
})
|
||||
maybeJson := bytes.TrimSpace(msg.Data)
|
||||
// Cheap check to see if this resembles JSON
|
||||
if len(maybeJson) > 1 && maybeJson[0] == '{' && maybeJson[len(maybeJson)-1] == '}' {
|
||||
var size TerminalSize
|
||||
err := json.Unmarshal(maybeJson, &size)
|
||||
if err == nil {
|
||||
return
|
||||
err = pty.Setsize(ptmx, &pty.Winsize{
|
||||
Rows: uint16(size.Rows),
|
||||
Cols: uint16(size.Cols),
|
||||
})
|
||||
if err == nil {
|
||||
scopedLogger.Info().Int("rows", size.Rows).Int("cols", size.Cols).Msg("Set terminal size")
|
||||
return
|
||||
}
|
||||
}
|
||||
scopedLogger.Warn().Err(err).Msg("Failed to parse terminal size")
|
||||
}
|
||||
scopedLogger.Warn().Err(err).Msg("Failed to parse terminal size")
|
||||
}
|
||||
_, err := ptmx.Write(msg.Data)
|
||||
if err != nil {
|
||||
|
|
|
@ -262,7 +262,23 @@ export default function Actionbar({
|
|||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* {useSettingsStore().actionBarCtrlAltDel && (
|
||||
<div className="hidden lg:block">
|
||||
<Button
|
||||
size="XS"
|
||||
theme="light"
|
||||
text="Ctrl + Alt + Del"
|
||||
LeadingIcon={FaLock}
|
||||
onClick={() => {
|
||||
sendKeyboardEvent(
|
||||
[keys["Delete"]],
|
||||
[modifiers["ControlLeft"], modifiers["AltLeft"]],
|
||||
);
|
||||
setTimeout(resetKeyboardState, 100);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)} */}
|
||||
<div>
|
||||
<Button
|
||||
size="XS"
|
||||
|
|
|
@ -1,12 +1,12 @@
|
|||
import {
|
||||
ExclamationTriangleIcon,
|
||||
CheckCircleIcon,
|
||||
ExclamationTriangleIcon,
|
||||
InformationCircleIcon,
|
||||
} from "@heroicons/react/24/outline";
|
||||
|
||||
import { cx } from "@/cva.config";
|
||||
import { Button } from "@/components/Button";
|
||||
import Modal from "@/components/Modal";
|
||||
import { cx } from "@/cva.config";
|
||||
|
||||
type Variant = "danger" | "success" | "warning" | "info";
|
||||
|
||||
|
@ -14,7 +14,7 @@ interface ConfirmDialogProps {
|
|||
open: boolean;
|
||||
onClose: () => void;
|
||||
title: string;
|
||||
description: string;
|
||||
description: React.ReactNode;
|
||||
variant?: Variant;
|
||||
confirmText?: string;
|
||||
cancelText?: string | null;
|
||||
|
@ -84,8 +84,8 @@ export function ConfirmDialog({
|
|||
>
|
||||
<Icon aria-hidden="true" className={cx("size-6", iconClass)} />
|
||||
</div>
|
||||
<div className="mt-3 text-center sm:ml-4 sm:mt-0 sm:text-left">
|
||||
<h2 className="text-lg font-bold leading-tight text-black dark:text-white">
|
||||
<div className="mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left">
|
||||
<h2 className="text-lg leading-tight font-bold text-black dark:text-white">
|
||||
{title}
|
||||
</h2>
|
||||
<div className="mt-2 text-sm leading-snug text-slate-600 dark:text-slate-400">
|
||||
|
@ -111,4 +111,4 @@ export function ConfirmDialog({
|
|||
</div>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
}
|
|
@ -28,6 +28,7 @@ export default function InfoBar() {
|
|||
const rpcDataChannel = useRTCStore(state => state.rpcDataChannel);
|
||||
|
||||
const settings = useSettingsStore();
|
||||
const showPressedKeys = useSettingsStore(state => state.showPressedKeys);
|
||||
|
||||
useEffect(() => {
|
||||
if (!rpcDataChannel) return;
|
||||
|
@ -36,9 +37,9 @@ export default function InfoBar() {
|
|||
console.log(`Error on DataChannel '${rpcDataChannel.label}': ${e}`);
|
||||
}, [rpcDataChannel]);
|
||||
|
||||
const isCapsLockActive = useHidStore(state => state.isCapsLockActive);
|
||||
const isNumLockActive = useHidStore(state => state.isNumLockActive);
|
||||
const isScrollLockActive = useHidStore(state => state.isScrollLockActive);
|
||||
const keyboardLedState = useHidStore(state => state.keyboardLedState);
|
||||
const keyboardLedStateSyncAvailable = useHidStore(state => state.keyboardLedStateSyncAvailable);
|
||||
const keyboardLedSync = useSettingsStore(state => state.keyboardLedSync);
|
||||
|
||||
const isTurnServerInUse = useRTCStore(state => state.isTurnServerInUse);
|
||||
|
||||
|
@ -97,19 +98,21 @@ export default function InfoBar() {
|
|||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex items-center gap-x-1">
|
||||
<span className="text-xs font-semibold">Keys:</span>
|
||||
<h2 className="text-xs">
|
||||
{[
|
||||
...activeKeys.map(
|
||||
x => Object.entries(keys).filter(y => y[1] === x)[0][0],
|
||||
),
|
||||
activeModifiers.map(
|
||||
x => Object.entries(modifiers).filter(y => y[1] === x)[0][0],
|
||||
),
|
||||
].join(", ")}
|
||||
</h2>
|
||||
</div>
|
||||
{showPressedKeys && (
|
||||
<div className="flex items-center gap-x-1">
|
||||
<span className="text-xs font-semibold">Keys:</span>
|
||||
<h2 className="text-xs">
|
||||
{[
|
||||
...activeKeys.map(
|
||||
x => Object.entries(keys).filter(y => y[1] === x)[0][0],
|
||||
),
|
||||
activeModifiers.map(
|
||||
x => Object.entries(modifiers).filter(y => y[1] === x)[0][0],
|
||||
),
|
||||
].join(", ")}
|
||||
</h2>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center divide-x first:divide-l divide-slate-800/20 dark:divide-slate-300/20">
|
||||
|
@ -118,10 +121,24 @@ export default function InfoBar() {
|
|||
Relayed by Cloudflare
|
||||
</div>
|
||||
)}
|
||||
|
||||
{keyboardLedStateSyncAvailable ? (
|
||||
<div
|
||||
className={cx(
|
||||
"shrink-0 p-1 px-1.5 text-xs",
|
||||
keyboardLedSync !== "browser"
|
||||
? "text-black dark:text-white"
|
||||
: "text-slate-800/20 dark:text-slate-300/20",
|
||||
)}
|
||||
title={"Your keyboard LED state is managed by" + (keyboardLedSync === "browser" ? " the browser" : " the host")}
|
||||
>
|
||||
{keyboardLedSync === "browser" ? "Browser" : "Host"}
|
||||
</div>
|
||||
) : null}
|
||||
<div
|
||||
className={cx(
|
||||
"shrink-0 p-1 px-1.5 text-xs",
|
||||
isCapsLockActive
|
||||
keyboardLedState?.caps_lock
|
||||
? "text-black dark:text-white"
|
||||
: "text-slate-800/20 dark:text-slate-300/20",
|
||||
)}
|
||||
|
@ -131,7 +148,7 @@ export default function InfoBar() {
|
|||
<div
|
||||
className={cx(
|
||||
"shrink-0 p-1 px-1.5 text-xs",
|
||||
isNumLockActive
|
||||
keyboardLedState?.num_lock
|
||||
? "text-black dark:text-white"
|
||||
: "text-slate-800/20 dark:text-slate-300/20",
|
||||
)}
|
||||
|
@ -141,13 +158,23 @@ export default function InfoBar() {
|
|||
<div
|
||||
className={cx(
|
||||
"shrink-0 p-1 px-1.5 text-xs",
|
||||
isScrollLockActive
|
||||
keyboardLedState?.scroll_lock
|
||||
? "text-black dark:text-white"
|
||||
: "text-slate-800/20 dark:text-slate-300/20",
|
||||
)}
|
||||
>
|
||||
Scroll Lock
|
||||
</div>
|
||||
{keyboardLedState?.compose ? (
|
||||
<div className="shrink-0 p-1 px-1.5 text-xs">
|
||||
Compose
|
||||
</div>
|
||||
) : null}
|
||||
{keyboardLedState?.kana ? (
|
||||
<div className="shrink-0 p-1 px-1.5 text-xs">
|
||||
Kana
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
|
|
@ -61,9 +61,9 @@ function Terminal({
|
|||
dataChannel,
|
||||
type,
|
||||
}: {
|
||||
title: string;
|
||||
dataChannel: RTCDataChannel;
|
||||
type: AvailableTerminalTypes;
|
||||
readonly title: string;
|
||||
readonly dataChannel: RTCDataChannel;
|
||||
readonly type: AvailableTerminalTypes;
|
||||
}) {
|
||||
const enableTerminal = useUiStore(state => state.terminalType == type);
|
||||
const setTerminalType = useUiStore(state => state.setTerminalType);
|
||||
|
|
|
@ -10,7 +10,7 @@ import LoadingSpinner from "@components/LoadingSpinner";
|
|||
import Card, { GridCard } from "@components/Card";
|
||||
|
||||
interface OverlayContentProps {
|
||||
children: React.ReactNode;
|
||||
readonly children: React.ReactNode;
|
||||
}
|
||||
function OverlayContent({ children }: OverlayContentProps) {
|
||||
return (
|
||||
|
@ -23,7 +23,7 @@ function OverlayContent({ children }: OverlayContentProps) {
|
|||
}
|
||||
|
||||
interface LoadingOverlayProps {
|
||||
show: boolean;
|
||||
readonly show: boolean;
|
||||
}
|
||||
|
||||
export function LoadingVideoOverlay({ show }: LoadingOverlayProps) {
|
||||
|
@ -57,8 +57,8 @@ export function LoadingVideoOverlay({ show }: LoadingOverlayProps) {
|
|||
}
|
||||
|
||||
interface LoadingConnectionOverlayProps {
|
||||
show: boolean;
|
||||
text: string;
|
||||
readonly show: boolean;
|
||||
readonly text: string;
|
||||
}
|
||||
export function LoadingConnectionOverlay({ show, text }: LoadingConnectionOverlayProps) {
|
||||
return (
|
||||
|
@ -91,8 +91,8 @@ export function LoadingConnectionOverlay({ show, text }: LoadingConnectionOverla
|
|||
}
|
||||
|
||||
interface ConnectionErrorOverlayProps {
|
||||
show: boolean;
|
||||
setupPeerConnection: () => Promise<void>;
|
||||
readonly show: boolean;
|
||||
readonly setupPeerConnection: () => Promise<void>;
|
||||
}
|
||||
|
||||
export function ConnectionFailedOverlay({
|
||||
|
@ -153,7 +153,7 @@ export function ConnectionFailedOverlay({
|
|||
}
|
||||
|
||||
interface PeerConnectionDisconnectedOverlay {
|
||||
show: boolean;
|
||||
readonly show: boolean;
|
||||
}
|
||||
|
||||
export function PeerConnectionDisconnectedOverlay({
|
||||
|
@ -207,8 +207,8 @@ export function PeerConnectionDisconnectedOverlay({
|
|||
}
|
||||
|
||||
interface HDMIErrorOverlayProps {
|
||||
show: boolean;
|
||||
hdmiState: string;
|
||||
readonly show: boolean;
|
||||
readonly hdmiState: string;
|
||||
}
|
||||
|
||||
export function HDMIErrorOverlay({ show, hdmiState }: HDMIErrorOverlayProps) {
|
||||
|
@ -310,8 +310,8 @@ export function HDMIErrorOverlay({ show, hdmiState }: HDMIErrorOverlayProps) {
|
|||
}
|
||||
|
||||
interface NoAutoplayPermissionsOverlayProps {
|
||||
show: boolean;
|
||||
onPlayClick: () => void;
|
||||
readonly show: boolean;
|
||||
readonly onPlayClick: () => void;
|
||||
}
|
||||
|
||||
export function NoAutoplayPermissionsOverlay({
|
||||
|
@ -361,7 +361,7 @@ export function NoAutoplayPermissionsOverlay({
|
|||
}
|
||||
|
||||
interface PointerLockBarProps {
|
||||
show: boolean;
|
||||
readonly show: boolean;
|
||||
}
|
||||
|
||||
export function PointerLockBar({ show }: PointerLockBarProps) {
|
||||
|
@ -369,10 +369,10 @@ export function PointerLockBar({ show }: PointerLockBarProps) {
|
|||
<AnimatePresence mode="wait">
|
||||
{show ? (
|
||||
<motion.div
|
||||
className="absolute -top-[36px] left-0 right-0 z-20 bg-white"
|
||||
initial={{ y: 20, opacity: 0, zIndex: 0 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
exit={{ y: 43, zIndex: 0 }}
|
||||
className="flex w-full items-center justify-between bg-transparent"
|
||||
initial={{ opacity: 0, zIndex: 0 }}
|
||||
animate={{ opacity: 1, zIndex: 20 }}
|
||||
exit={{ opacity: 0, zIndex: 0 }}
|
||||
transition={{ duration: 0.5, ease: "easeInOut", delay: 0.5 }}
|
||||
>
|
||||
<div>
|
||||
|
|
|
@ -1,7 +1,8 @@
|
|||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import Keyboard from "react-simple-keyboard";
|
||||
import { useShallow } from "zustand/react/shallow";
|
||||
import { ChevronDownIcon } from "@heroicons/react/16/solid";
|
||||
import { motion, AnimatePresence } from "framer-motion";
|
||||
import { AnimatePresence, motion } from "framer-motion";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import Keyboard from "react-simple-keyboard";
|
||||
|
||||
import Card from "@components/Card";
|
||||
// eslint-disable-next-line import/order
|
||||
|
@ -9,12 +10,12 @@ import { Button } from "@components/Button";
|
|||
|
||||
import "react-simple-keyboard/build/css/index.css";
|
||||
|
||||
import { useHidStore, useUiStore } from "@/hooks/stores";
|
||||
import { cx } from "@/cva.config";
|
||||
import { keys, modifiers, keyDisplayMap } from "@/keyboardMappings";
|
||||
import useKeyboard from "@/hooks/useKeyboard";
|
||||
import DetachIconRaw from "@/assets/detach-icon.svg";
|
||||
import AttachIconRaw from "@/assets/attach-icon.svg";
|
||||
import DetachIconRaw from "@/assets/detach-icon.svg";
|
||||
import { cx } from "@/cva.config";
|
||||
import { useHidStore, useSettingsStore, useUiStore } from "@/hooks/stores";
|
||||
import useKeyboard from "@/hooks/useKeyboard";
|
||||
import { keyDisplayMap, keys, modifiers } from "@/keyboardMappings";
|
||||
|
||||
export const DetachIcon = ({ className }: { className?: string }) => {
|
||||
return <img src={DetachIconRaw} alt="Detach Icon" className={className} />;
|
||||
|
@ -40,7 +41,17 @@ function KeyboardWrapper() {
|
|||
const [isDragging, setIsDragging] = useState(false);
|
||||
const [position, setPosition] = useState({ x: 0, y: 0 });
|
||||
const [newPosition, setNewPosition] = useState({ x: 0, y: 0 });
|
||||
const isCapsLockActive = useHidStore(state => state.isCapsLockActive);
|
||||
|
||||
const isCapsLockActive = useHidStore(useShallow(state => state.keyboardLedState?.caps_lock));
|
||||
|
||||
// HID related states
|
||||
const keyboardLedStateSyncAvailable = useHidStore(state => state.keyboardLedStateSyncAvailable);
|
||||
const keyboardLedSync = useSettingsStore(state => state.keyboardLedSync);
|
||||
const isKeyboardLedManagedByHost = useMemo(() =>
|
||||
keyboardLedSync !== "browser" && keyboardLedStateSyncAvailable,
|
||||
[keyboardLedSync, keyboardLedStateSyncAvailable],
|
||||
);
|
||||
|
||||
const setIsCapsLockActive = useHidStore(state => state.setIsCapsLockActive);
|
||||
|
||||
const startDrag = useCallback((e: MouseEvent | TouchEvent) => {
|
||||
|
@ -157,14 +168,16 @@ function KeyboardWrapper() {
|
|||
toggleLayout();
|
||||
|
||||
if (isCapsLockActive) {
|
||||
setIsCapsLockActive(false);
|
||||
if (!isKeyboardLedManagedByHost) {
|
||||
setIsCapsLockActive(false);
|
||||
}
|
||||
sendKeyboardEvent([keys["CapsLock"]], []);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Handle caps lock state change
|
||||
if (isKeyCaps) {
|
||||
if (isKeyCaps && !isKeyboardLedManagedByHost) {
|
||||
setIsCapsLockActive(!isCapsLockActive);
|
||||
}
|
||||
|
||||
|
@ -183,7 +196,7 @@ function KeyboardWrapper() {
|
|||
|
||||
setTimeout(resetKeyboardState, 100);
|
||||
},
|
||||
[isCapsLockActive, sendKeyboardEvent, resetKeyboardState, setIsCapsLockActive],
|
||||
[isCapsLockActive, isKeyboardLedManagedByHost, sendKeyboardEvent, resetKeyboardState, setIsCapsLockActive],
|
||||
);
|
||||
|
||||
const virtualKeyboard = useHidStore(state => state.isVirtualKeyboardEnabled);
|
||||
|
|
|
@ -1,23 +1,22 @@
|
|||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { useResizeObserver } from "usehooks-ts";
|
||||
|
||||
import VirtualKeyboard from "@components/VirtualKeyboard";
|
||||
import Actionbar from "@components/ActionBar";
|
||||
import MacroBar from "@/components/MacroBar";
|
||||
import InfoBar from "@components/InfoBar";
|
||||
import notifications from "@/notifications";
|
||||
import useKeyboard from "@/hooks/useKeyboard";
|
||||
import { useJsonRpc } from "@/hooks/useJsonRpc";
|
||||
import { cx } from "@/cva.config";
|
||||
import { keys, modifiers } from "@/keyboardMappings";
|
||||
import {
|
||||
useHidStore,
|
||||
useMouseStore,
|
||||
useRTCStore,
|
||||
useSettingsStore,
|
||||
useUiStore,
|
||||
useVideoStore,
|
||||
} from "@/hooks/stores";
|
||||
import { keys, modifiers } from "@/keyboardMappings";
|
||||
import { cx } from "@/cva.config";
|
||||
import VirtualKeyboard from "@components/VirtualKeyboard";
|
||||
import Actionbar from "@components/ActionBar";
|
||||
import MacroBar from "@/components/MacroBar";
|
||||
import InfoBar from "@components/InfoBar";
|
||||
import useKeyboard from "@/hooks/useKeyboard";
|
||||
import { useJsonRpc } from "@/hooks/useJsonRpc";
|
||||
import notifications from "@/notifications";
|
||||
|
||||
import {
|
||||
HDMIErrorOverlay,
|
||||
|
@ -47,6 +46,23 @@ export default function WebRTCVideo() {
|
|||
clientHeight: videoClientHeight,
|
||||
} = useVideoStore();
|
||||
|
||||
// Video enhancement settings
|
||||
const videoSaturation = useSettingsStore(state => state.videoSaturation);
|
||||
const videoBrightness = useSettingsStore(state => state.videoBrightness);
|
||||
const videoContrast = useSettingsStore(state => state.videoContrast);
|
||||
|
||||
// HID related states
|
||||
const keyboardLedStateSyncAvailable = useHidStore(state => state.keyboardLedStateSyncAvailable);
|
||||
const keyboardLedSync = useSettingsStore(state => state.keyboardLedSync);
|
||||
const isKeyboardLedManagedByHost = useMemo(() =>
|
||||
keyboardLedSync !== "browser" && keyboardLedStateSyncAvailable,
|
||||
[keyboardLedSync, keyboardLedStateSyncAvailable],
|
||||
);
|
||||
|
||||
const setIsNumLockActive = useHidStore(state => state.setIsNumLockActive);
|
||||
const setIsCapsLockActive = useHidStore(state => state.setIsCapsLockActive);
|
||||
const setIsScrollLockActive = useHidStore(state => state.setIsScrollLockActive);
|
||||
|
||||
// RTC related states
|
||||
const peerConnection = useRTCStore(state => state.peerConnection);
|
||||
|
||||
|
@ -55,12 +71,9 @@ export default function WebRTCVideo() {
|
|||
const hdmiError = ["no_lock", "no_signal", "out_of_range"].includes(hdmiState);
|
||||
const isVideoLoading = !isPlaying;
|
||||
|
||||
// Keyboard related states
|
||||
const { setIsNumLockActive, setIsCapsLockActive, setIsScrollLockActive } =
|
||||
useHidStore();
|
||||
const [blockWheelEvent, setBlockWheelEvent] = useState(false);
|
||||
|
||||
// Misc states and hooks
|
||||
const disableVideoFocusTrap = useUiStore(state => state.disableVideoFocusTrap);
|
||||
const [send] = useJsonRpc();
|
||||
|
||||
// Video-related
|
||||
|
@ -98,32 +111,77 @@ export default function WebRTCVideo() {
|
|||
);
|
||||
|
||||
// Pointer lock and keyboard lock related
|
||||
const isPointerLockPossible = window.location.protocol === "https:";
|
||||
|
||||
const isPointerLockPossible = window.location.protocol === "https:" || window.location.hostname === "localhost";
|
||||
const isFullscreenEnabled = document.fullscreenEnabled;
|
||||
|
||||
const checkNavigatorPermissions = useCallback(async (permissionName: string) => {
|
||||
const name = permissionName as PermissionName;
|
||||
const { state } = await navigator.permissions.query({ name });
|
||||
return state === "granted";
|
||||
if (!navigator.permissions || !navigator.permissions.query) {
|
||||
return false; // if can't query permissions, assume NOT granted
|
||||
}
|
||||
|
||||
try {
|
||||
const name = permissionName as PermissionName;
|
||||
const { state } = await navigator.permissions.query({ name });
|
||||
return state === "granted";
|
||||
} catch {
|
||||
// ignore errors
|
||||
}
|
||||
return false; // if query fails, assume NOT granted
|
||||
}, []);
|
||||
|
||||
const requestPointerLock = useCallback(async () => {
|
||||
if (document.pointerLockElement) return;
|
||||
if (!isPointerLockPossible
|
||||
|| videoElm.current === null
|
||||
|| document.pointerLockElement) return;
|
||||
|
||||
const isPointerLockGranted = await checkNavigatorPermissions("pointer-lock");
|
||||
|
||||
if (isPointerLockGranted && settings.mouseMode === "relative") {
|
||||
videoElm.current?.requestPointerLock();
|
||||
try {
|
||||
await videoElm.current.requestPointerLock();
|
||||
} catch {
|
||||
// ignore errors
|
||||
}
|
||||
}
|
||||
}, [checkNavigatorPermissions, settings.mouseMode]);
|
||||
}, [checkNavigatorPermissions, isPointerLockPossible, settings.mouseMode]);
|
||||
|
||||
const requestKeyboardLock = useCallback(async () => {
|
||||
if (videoElm.current === null) return;
|
||||
|
||||
const isKeyboardLockGranted = await checkNavigatorPermissions("keyboard-lock");
|
||||
|
||||
if (isKeyboardLockGranted && "keyboard" in navigator) {
|
||||
try {
|
||||
// @ts-expect-error - keyboard lock is not supported in all browsers
|
||||
await navigator.keyboard.lock();
|
||||
} catch {
|
||||
// ignore errors
|
||||
}
|
||||
}
|
||||
}, [checkNavigatorPermissions]);
|
||||
|
||||
const releaseKeyboardLock = useCallback(async () => {
|
||||
if (videoElm.current === null || document.fullscreenElement !== videoElm.current) return;
|
||||
|
||||
if ("keyboard" in navigator) {
|
||||
try {
|
||||
// @ts-expect-error - keyboard unlock is not supported in all browsers
|
||||
await navigator.keyboard.unlock();
|
||||
} catch {
|
||||
// ignore errors
|
||||
}
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isPointerLockPossible || !videoElm.current) return;
|
||||
|
||||
const handlePointerLockChange = () => {
|
||||
if (document.pointerLockElement) {
|
||||
notifications.success("Pointer lock Enabled, hold escape to exit");
|
||||
notifications.success("Pointer lock Enabled, press escape to unlock");
|
||||
setIsPointerLockActive(true);
|
||||
} else {
|
||||
notifications.success("Pointer lock disabled");
|
||||
notifications.success("Pointer lock Disabled");
|
||||
setIsPointerLockActive(false);
|
||||
}
|
||||
};
|
||||
|
@ -136,27 +194,39 @@ export default function WebRTCVideo() {
|
|||
return () => {
|
||||
abortController.abort();
|
||||
};
|
||||
}, [isPointerLockPossible, videoElm]);
|
||||
}, [isPointerLockPossible]);
|
||||
|
||||
const requestFullscreen = useCallback(async () => {
|
||||
videoElm.current?.requestFullscreen({
|
||||
navigationUI: "show",
|
||||
});
|
||||
if (!isFullscreenEnabled || !videoElm.current) return;
|
||||
|
||||
// we do not care about pointer lock if it's for fullscreen
|
||||
// per https://wicg.github.io/keyboard-lock/#system-key-press-handler
|
||||
// If keyboard lock is activated after fullscreen is already in effect, then the user my
|
||||
// see multiple messages about how to exit fullscreen. For this reason, we recommend that
|
||||
// developers call lock() before they enter fullscreen:
|
||||
await requestKeyboardLock();
|
||||
await requestPointerLock();
|
||||
|
||||
const isKeyboardLockGranted = await checkNavigatorPermissions("keyboard-lock");
|
||||
if (isKeyboardLockGranted) {
|
||||
if ("keyboard" in navigator) {
|
||||
// @ts-expect-error - keyboard lock is not supported in all browsers
|
||||
await navigator.keyboard.lock();
|
||||
await videoElm.current.requestFullscreen({
|
||||
navigationUI: "show",
|
||||
});
|
||||
}, [isFullscreenEnabled, requestKeyboardLock, requestPointerLock]);
|
||||
|
||||
// setup to release the keyboard lock anytime the fullscreen ends
|
||||
useEffect(() => {
|
||||
if (!videoElm.current) return;
|
||||
|
||||
const handleFullscreenChange = () => {
|
||||
if (!document.fullscreenElement) {
|
||||
releaseKeyboardLock();
|
||||
}
|
||||
}
|
||||
}, [requestPointerLock, checkNavigatorPermissions]);
|
||||
};
|
||||
|
||||
document.addEventListener("fullscreenchange ", handleFullscreenChange);
|
||||
}, [releaseKeyboardLock]);
|
||||
|
||||
// Mouse-related
|
||||
const calcDelta = (pos: number) => (Math.abs(pos) < 10 ? pos * 2 : pos);
|
||||
|
||||
const sendRelMouseMovement = useCallback(
|
||||
(x: number, y: number, buttons: number) => {
|
||||
if (settings.mouseMode !== "relative") return;
|
||||
|
@ -171,18 +241,13 @@ export default function WebRTCVideo() {
|
|||
const relMouseMoveHandler = useCallback(
|
||||
(e: MouseEvent) => {
|
||||
if (settings.mouseMode !== "relative") return;
|
||||
if (isPointerLockActive === false && isPointerLockPossible === true) return;
|
||||
if (isPointerLockActive === false && isPointerLockPossible) return;
|
||||
|
||||
// Send mouse movement
|
||||
const { buttons } = e;
|
||||
sendRelMouseMovement(e.movementX, e.movementY, buttons);
|
||||
},
|
||||
[
|
||||
isPointerLockActive,
|
||||
isPointerLockPossible,
|
||||
sendRelMouseMovement,
|
||||
settings.mouseMode,
|
||||
],
|
||||
[isPointerLockActive, isPointerLockPossible, sendRelMouseMovement, settings.mouseMode],
|
||||
);
|
||||
|
||||
const sendAbsMouseMovement = useCallback(
|
||||
|
@ -236,18 +301,16 @@ export default function WebRTCVideo() {
|
|||
const { buttons } = e;
|
||||
sendAbsMouseMovement(x, y, buttons);
|
||||
},
|
||||
[
|
||||
sendAbsMouseMovement,
|
||||
videoClientHeight,
|
||||
videoClientWidth,
|
||||
videoWidth,
|
||||
videoHeight,
|
||||
settings.mouseMode,
|
||||
],
|
||||
[settings.mouseMode, videoClientWidth, videoClientHeight, videoWidth, videoHeight, sendAbsMouseMovement],
|
||||
);
|
||||
|
||||
const mouseWheelHandler = useCallback(
|
||||
(e: WheelEvent) => {
|
||||
|
||||
if (settings.scrollThrottling && blockWheelEvent) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Determine if the wheel event is an accel scroll value
|
||||
const isAccel = Math.abs(e.deltaY) >= 100;
|
||||
|
||||
|
@ -255,7 +318,7 @@ export default function WebRTCVideo() {
|
|||
const accelScrollValue = e.deltaY / 100;
|
||||
|
||||
// Calculate the no accel scroll value
|
||||
const noAccelScrollValue = e.deltaY > 0 ? 1 : e.deltaY < 0 ? -1 : 0;
|
||||
const noAccelScrollValue = Math.sign(e.deltaY);
|
||||
|
||||
// Get scroll value
|
||||
const scrollValue = isAccel ? accelScrollValue : noAccelScrollValue;
|
||||
|
@ -267,8 +330,14 @@ export default function WebRTCVideo() {
|
|||
const invertedScrollValue = -clampedScrollValue;
|
||||
|
||||
send("wheelReport", { wheelY: invertedScrollValue });
|
||||
|
||||
// Apply blocking delay based of throttling settings
|
||||
if (settings.scrollThrottling && !blockWheelEvent) {
|
||||
setBlockWheelEvent(true);
|
||||
setTimeout(() => setBlockWheelEvent(false), settings.scrollThrottling);
|
||||
}
|
||||
},
|
||||
[send],
|
||||
[send, blockWheelEvent, settings],
|
||||
);
|
||||
|
||||
const resetMousePosition = useCallback(() => {
|
||||
|
@ -348,16 +417,11 @@ export default function WebRTCVideo() {
|
|||
let code = e.code;
|
||||
const key = e.key;
|
||||
|
||||
// if (document.activeElement?.id !== "videoFocusTrap") {
|
||||
// console.log("KEYUP: Not focusing on the video", document.activeElement);
|
||||
// return;
|
||||
// }
|
||||
|
||||
// console.log(document.activeElement);
|
||||
|
||||
setIsNumLockActive(e.getModifierState("NumLock"));
|
||||
setIsCapsLockActive(e.getModifierState("CapsLock"));
|
||||
setIsScrollLockActive(e.getModifierState("ScrollLock"));
|
||||
if (!isKeyboardLedManagedByHost) {
|
||||
setIsNumLockActive(e.getModifierState("NumLock"));
|
||||
setIsCapsLockActive(e.getModifierState("CapsLock"));
|
||||
setIsScrollLockActive(e.getModifierState("ScrollLock"));
|
||||
}
|
||||
|
||||
if (code == "IntlBackslash" && ["`", "~"].includes(key)) {
|
||||
code = "Backquote";
|
||||
|
@ -388,11 +452,12 @@ export default function WebRTCVideo() {
|
|||
sendKeyboardEvent([...new Set(newKeys)], [...new Set(newModifiers)]);
|
||||
},
|
||||
[
|
||||
handleModifierKeys,
|
||||
sendKeyboardEvent,
|
||||
isKeyboardLedManagedByHost,
|
||||
setIsNumLockActive,
|
||||
setIsCapsLockActive,
|
||||
setIsScrollLockActive,
|
||||
handleModifierKeys,
|
||||
sendKeyboardEvent,
|
||||
],
|
||||
);
|
||||
|
||||
|
@ -401,9 +466,11 @@ export default function WebRTCVideo() {
|
|||
e.preventDefault();
|
||||
const prev = useHidStore.getState();
|
||||
|
||||
setIsNumLockActive(e.getModifierState("NumLock"));
|
||||
setIsCapsLockActive(e.getModifierState("CapsLock"));
|
||||
setIsScrollLockActive(e.getModifierState("ScrollLock"));
|
||||
if (!isKeyboardLedManagedByHost) {
|
||||
setIsNumLockActive(e.getModifierState("NumLock"));
|
||||
setIsCapsLockActive(e.getModifierState("CapsLock"));
|
||||
setIsScrollLockActive(e.getModifierState("ScrollLock"));
|
||||
}
|
||||
|
||||
// Filtering out the key that was just released (keys[e.code])
|
||||
const newKeys = prev.activeKeys.filter(k => k !== keys[e.code]).filter(Boolean);
|
||||
|
@ -417,22 +484,25 @@ export default function WebRTCVideo() {
|
|||
sendKeyboardEvent([...new Set(newKeys)], [...new Set(newModifiers)]);
|
||||
},
|
||||
[
|
||||
handleModifierKeys,
|
||||
sendKeyboardEvent,
|
||||
isKeyboardLedManagedByHost,
|
||||
setIsNumLockActive,
|
||||
setIsCapsLockActive,
|
||||
setIsScrollLockActive,
|
||||
handleModifierKeys,
|
||||
sendKeyboardEvent,
|
||||
],
|
||||
);
|
||||
|
||||
const videoKeyUpHandler = useCallback((e: KeyboardEvent) => {
|
||||
if (!videoElm.current) return;
|
||||
|
||||
// In fullscreen mode in chrome & safari, the space key is used to pause/play the video
|
||||
// there is no way to prevent this, so we need to simply force play the video when it's paused.
|
||||
// Fix only works in chrome based browsers.
|
||||
if (e.code === "Space") {
|
||||
if (videoElm.current?.paused == true) {
|
||||
if (videoElm.current.paused) {
|
||||
console.log("Force playing video");
|
||||
videoElm.current?.play();
|
||||
videoElm.current.play();
|
||||
}
|
||||
}
|
||||
}, []);
|
||||
|
@ -441,7 +511,6 @@ export default function WebRTCVideo() {
|
|||
(mediaStream: MediaStream) => {
|
||||
if (!videoElm.current) return;
|
||||
const videoElmRefValue = videoElm.current;
|
||||
// console.log("Adding stream to video element", videoElmRefValue);
|
||||
videoElmRefValue.srcObject = mediaStream;
|
||||
updateVideoSizeStore(videoElmRefValue);
|
||||
},
|
||||
|
@ -457,7 +526,6 @@ export default function WebRTCVideo() {
|
|||
peerConnection.addEventListener(
|
||||
"track",
|
||||
(e: RTCTrackEvent) => {
|
||||
// console.log("Adding stream to video element");
|
||||
addStreamToVideoElm(e.streams[0]);
|
||||
},
|
||||
{ signal },
|
||||
|
@ -473,7 +541,6 @@ export default function WebRTCVideo() {
|
|||
useEffect(
|
||||
function updateVideoStream() {
|
||||
if (!mediaStream) return;
|
||||
console.log("Updating video stream from mediaStream");
|
||||
// We set the as early as possible
|
||||
addStreamToVideoElm(mediaStream);
|
||||
},
|
||||
|
@ -495,9 +562,6 @@ export default function WebRTCVideo() {
|
|||
document.addEventListener("keydown", keyDownHandler, { signal });
|
||||
document.addEventListener("keyup", keyUpHandler, { signal });
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-expect-error
|
||||
window.clearKeys = () => sendKeyboardEvent([], []);
|
||||
window.addEventListener("blur", resetKeyboardState, { signal });
|
||||
document.addEventListener("visibilitychange", resetKeyboardState, { signal });
|
||||
|
||||
|
@ -505,7 +569,7 @@ export default function WebRTCVideo() {
|
|||
abortController.abort();
|
||||
};
|
||||
},
|
||||
[keyDownHandler, keyUpHandler, resetKeyboardState, sendKeyboardEvent],
|
||||
[keyDownHandler, keyUpHandler, resetKeyboardState],
|
||||
);
|
||||
|
||||
// Setup Video Event Listeners
|
||||
|
@ -527,38 +591,42 @@ export default function WebRTCVideo() {
|
|||
abortController.abort();
|
||||
};
|
||||
},
|
||||
[
|
||||
absMouseMoveHandler,
|
||||
resetMousePosition,
|
||||
onVideoPlaying,
|
||||
mouseWheelHandler,
|
||||
videoKeyUpHandler,
|
||||
],
|
||||
[onVideoPlaying, videoKeyUpHandler],
|
||||
);
|
||||
|
||||
// Setup Absolute Mouse Events
|
||||
// Setup Mouse Events
|
||||
useEffect(
|
||||
function setAbsoluteMouseModeEventListeners() {
|
||||
function setMouseModeEventListeners() {
|
||||
const videoElmRefValue = videoElm.current;
|
||||
if (!videoElmRefValue) return;
|
||||
|
||||
if (settings.mouseMode !== "absolute") return;
|
||||
const isRelativeMouseMode = (settings.mouseMode === "relative");
|
||||
|
||||
const abortController = new AbortController();
|
||||
const signal = abortController.signal;
|
||||
|
||||
videoElmRefValue.addEventListener("mousemove", absMouseMoveHandler, { signal });
|
||||
videoElmRefValue.addEventListener("pointerdown", absMouseMoveHandler, { signal });
|
||||
videoElmRefValue.addEventListener("pointerup", absMouseMoveHandler, { signal });
|
||||
videoElmRefValue.addEventListener("mousemove", isRelativeMouseMode ? relMouseMoveHandler : absMouseMoveHandler, { signal });
|
||||
videoElmRefValue.addEventListener("pointerdown", isRelativeMouseMode ? relMouseMoveHandler : absMouseMoveHandler, { signal });
|
||||
videoElmRefValue.addEventListener("pointerup", isRelativeMouseMode ? relMouseMoveHandler :absMouseMoveHandler, { signal });
|
||||
videoElmRefValue.addEventListener("wheel", mouseWheelHandler, {
|
||||
signal,
|
||||
passive: true,
|
||||
});
|
||||
|
||||
// Reset the mouse position when the window is blurred or the document is hidden
|
||||
const local = resetMousePosition;
|
||||
window.addEventListener("blur", local, { signal });
|
||||
document.addEventListener("visibilitychange", local, { signal });
|
||||
if (isRelativeMouseMode) {
|
||||
videoElmRefValue.addEventListener("click",
|
||||
() => {
|
||||
if (isPointerLockPossible && !isPointerLockActive && !document.pointerLockElement) {
|
||||
requestPointerLock();
|
||||
}
|
||||
},
|
||||
{ signal },
|
||||
);
|
||||
} else {
|
||||
// Reset the mouse position when the window is blurred or the document is hidden
|
||||
window.addEventListener("blur", resetMousePosition, { signal });
|
||||
document.addEventListener("visibilitychange", resetMousePosition, { signal });
|
||||
}
|
||||
|
||||
const preventContextMenu = (e: MouseEvent) => e.preventDefault();
|
||||
videoElmRefValue.addEventListener("contextmenu", preventContextMenu, { signal });
|
||||
|
||||
|
@ -566,65 +634,18 @@ export default function WebRTCVideo() {
|
|||
abortController.abort();
|
||||
};
|
||||
},
|
||||
[absMouseMoveHandler, mouseWheelHandler, resetMousePosition, settings.mouseMode],
|
||||
[absMouseMoveHandler, isPointerLockActive, isPointerLockPossible, mouseWheelHandler, relMouseMoveHandler, requestPointerLock, resetMousePosition, settings.mouseMode],
|
||||
);
|
||||
|
||||
// Setup Relative Mouse Events
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
useEffect(
|
||||
function setupRelativeMouseEventListeners() {
|
||||
if (settings.mouseMode !== "relative") return;
|
||||
// Relative mouse mode should only be active if the pointer lock is active and Pointer Lock is possible
|
||||
|
||||
const videoElmRefValue = videoElm.current;
|
||||
if (!videoElmRefValue) return;
|
||||
|
||||
const abortController = new AbortController();
|
||||
const signal = abortController.signal;
|
||||
|
||||
videoElmRefValue.addEventListener("mousemove", relMouseMoveHandler, { signal });
|
||||
videoElmRefValue.addEventListener("pointerdown", relMouseMoveHandler, { signal });
|
||||
videoElmRefValue.addEventListener("pointerup", relMouseMoveHandler, { signal });
|
||||
videoElmRefValue.addEventListener(
|
||||
"click",
|
||||
() => {
|
||||
if (isPointerLockPossible && !document.pointerLockElement) {
|
||||
requestPointerLock();
|
||||
}
|
||||
},
|
||||
{ signal },
|
||||
);
|
||||
videoElmRefValue.addEventListener("wheel", mouseWheelHandler, {
|
||||
signal,
|
||||
passive: true,
|
||||
});
|
||||
|
||||
const preventContextMenu = (e: MouseEvent) => e.preventDefault();
|
||||
videoElmRefValue.addEventListener("contextmenu", preventContextMenu, { signal });
|
||||
|
||||
return () => {
|
||||
abortController.abort();
|
||||
};
|
||||
},
|
||||
[
|
||||
settings.mouseMode,
|
||||
relMouseMoveHandler,
|
||||
mouseWheelHandler,
|
||||
disableVideoFocusTrap,
|
||||
requestPointerLock,
|
||||
isPointerLockPossible,
|
||||
isPointerLockActive,
|
||||
],
|
||||
);
|
||||
|
||||
const hasNoAutoPlayPermissions = useMemo(() => {
|
||||
if (peerConnection?.connectionState !== "connected") return false;
|
||||
if (isPlaying) return false;
|
||||
if (hdmiError) return false;
|
||||
if (videoHeight === 0 || videoWidth === 0) return false;
|
||||
return true;
|
||||
}, [peerConnection?.connectionState, isPlaying, hdmiError, videoHeight, videoWidth]);
|
||||
}, [hdmiError, isPlaying, peerConnection?.connectionState, videoHeight, videoWidth]);
|
||||
|
||||
const showPointerLockBar = useMemo(() => {
|
||||
if (settings.mouseMode !== "relative") return false;
|
||||
|
@ -634,15 +655,7 @@ export default function WebRTCVideo() {
|
|||
if (!isPlaying) return false;
|
||||
if (videoHeight === 0 || videoWidth === 0) return false;
|
||||
return true;
|
||||
}, [
|
||||
settings.mouseMode,
|
||||
isPointerLockPossible,
|
||||
isPointerLockActive,
|
||||
isVideoLoading,
|
||||
isPlaying,
|
||||
videoHeight,
|
||||
videoWidth,
|
||||
]);
|
||||
}, [isPlaying, isPointerLockActive, isPointerLockPossible, isVideoLoading, settings.mouseMode, videoHeight, videoWidth]);
|
||||
|
||||
return (
|
||||
<div className="grid h-full w-full grid-rows-(--grid-layout)">
|
||||
|
@ -672,10 +685,10 @@ export default function WebRTCVideo() {
|
|||
<div className="relative grow overflow-hidden">
|
||||
<div className="flex h-full flex-col">
|
||||
<div className="grid grow grid-rows-(--grid-bodyFooter) overflow-hidden">
|
||||
{/* In relative mouse mode and under https, we enable the pointer lock, and to do so we need a bar to show the user to click on the video to enable mouse control */}
|
||||
<PointerLockBar show={showPointerLockBar} />
|
||||
<div className="relative mx-4 my-2 flex items-center justify-center overflow-hidden">
|
||||
<div className="relative flex h-full w-full items-center justify-center">
|
||||
{/* In relative mouse mode and under https, we enable the pointer lock, and to do so we need a bar to show the user to click on the video to enable mouse control */}
|
||||
<PointerLockBar show={showPointerLockBar} />
|
||||
<video
|
||||
ref={videoElm}
|
||||
autoPlay={true}
|
||||
|
@ -686,6 +699,9 @@ export default function WebRTCVideo() {
|
|||
playsInline
|
||||
disablePictureInPicture
|
||||
controlsList="nofullscreen"
|
||||
style={{
|
||||
filter: `saturate(${videoSaturation}) brightness(${videoBrightness}) contrast(${videoContrast})`,
|
||||
}}
|
||||
className={cx(
|
||||
"max-h-full min-h-[384px] max-w-full min-w-[512px] bg-black/50 object-contain transition-all duration-1000",
|
||||
{
|
||||
|
|
|
@ -39,11 +39,11 @@ export default function PasteModal() {
|
|||
state => state.setKeyboardLayout,
|
||||
);
|
||||
|
||||
// this ensures we always get the original en-US if it hasn't been set yet
|
||||
// this ensures we always get the original en_US if it hasn't been set yet
|
||||
const safeKeyboardLayout = useMemo(() => {
|
||||
if (keyboardLayout && keyboardLayout.length > 0)
|
||||
return keyboardLayout;
|
||||
return "en-US";
|
||||
return "en_US";
|
||||
}, [keyboardLayout]);
|
||||
|
||||
useEffect(() => {
|
||||
|
@ -131,7 +131,7 @@ export default function PasteModal() {
|
|||
}}
|
||||
>
|
||||
<div>
|
||||
<div className="w-full" onKeyUp={e => e.stopPropagation()}>
|
||||
<div className="w-full" onKeyUp={e => e.stopPropagation()} onKeyDown={e => e.stopPropagation()}>
|
||||
<TextAreaWithLabel
|
||||
ref={TextAreaRef}
|
||||
label="Paste from host"
|
||||
|
|
|
@ -283,6 +283,8 @@ export const useVideoStore = create<VideoState>(set => ({
|
|||
},
|
||||
}));
|
||||
|
||||
export type KeyboardLedSync = "auto" | "browser" | "host";
|
||||
|
||||
interface SettingsState {
|
||||
isCursorHidden: boolean;
|
||||
setCursorVisibility: (enabled: boolean) => void;
|
||||
|
@ -305,6 +307,26 @@ interface SettingsState {
|
|||
|
||||
keyboardLayout: string;
|
||||
setKeyboardLayout: (layout: string) => void;
|
||||
|
||||
actionBarCtrlAltDel: boolean;
|
||||
setActionBarCtrlAltDel: (enabled: boolean) => void;
|
||||
|
||||
keyboardLedSync: KeyboardLedSync;
|
||||
setKeyboardLedSync: (sync: KeyboardLedSync) => void;
|
||||
|
||||
scrollThrottling: number;
|
||||
setScrollThrottling: (value: number) => void;
|
||||
|
||||
showPressedKeys: boolean;
|
||||
setShowPressedKeys: (show: boolean) => void;
|
||||
|
||||
// Video enhancement settings
|
||||
videoSaturation: number;
|
||||
setVideoSaturation: (value: number) => void;
|
||||
videoBrightness: number;
|
||||
setVideoBrightness: (value: number) => void;
|
||||
videoContrast: number;
|
||||
setVideoContrast: (value: number) => void;
|
||||
}
|
||||
|
||||
export const useSettingsStore = create(
|
||||
|
@ -336,6 +358,26 @@ export const useSettingsStore = create(
|
|||
|
||||
keyboardLayout: "en-US",
|
||||
setKeyboardLayout: layout => set({ keyboardLayout: layout }),
|
||||
|
||||
actionBarCtrlAltDel: false,
|
||||
setActionBarCtrlAltDel: enabled => set({ actionBarCtrlAltDel: enabled }),
|
||||
|
||||
keyboardLedSync: "auto",
|
||||
setKeyboardLedSync: sync => set({ keyboardLedSync: sync }),
|
||||
|
||||
scrollThrottling: 0,
|
||||
setScrollThrottling: value => set({ scrollThrottling: value }),
|
||||
|
||||
showPressedKeys: true,
|
||||
setShowPressedKeys: show => set({ showPressedKeys: show }),
|
||||
|
||||
// Video enhancement settings with default values (1.0 = normal)
|
||||
videoSaturation: 1.0,
|
||||
setVideoSaturation: value => set({ videoSaturation: value }),
|
||||
videoBrightness: 1.0,
|
||||
setVideoBrightness: value => set({ videoBrightness: value }),
|
||||
videoContrast: 1.0,
|
||||
setVideoContrast: value => set({ videoContrast: value }),
|
||||
}),
|
||||
{
|
||||
name: "settings",
|
||||
|
@ -344,17 +386,6 @@ export const useSettingsStore = create(
|
|||
),
|
||||
);
|
||||
|
||||
export interface DeviceSettingsState {
|
||||
trackpadSensitivity: number;
|
||||
mouseSensitivity: number;
|
||||
clampMin: number;
|
||||
clampMax: number;
|
||||
blockDelay: number;
|
||||
trackpadThreshold: number;
|
||||
scrollSensitivity: "low" | "default" | "high";
|
||||
setScrollSensitivity: (sensitivity: DeviceSettingsState["scrollSensitivity"]) => void;
|
||||
}
|
||||
|
||||
export interface RemoteVirtualMediaState {
|
||||
source: "WebRTC" | "HTTP" | "Storage" | null;
|
||||
mode: "CDROM" | "Disk" | null;
|
||||
|
@ -405,6 +436,21 @@ export const useMountMediaStore = create<MountMediaState>(set => ({
|
|||
setErrorMessage: message => set({ errorMessage: message }),
|
||||
}));
|
||||
|
||||
export interface KeyboardLedState {
|
||||
num_lock: boolean;
|
||||
caps_lock: boolean;
|
||||
scroll_lock: boolean;
|
||||
compose: boolean;
|
||||
kana: boolean;
|
||||
};
|
||||
const defaultKeyboardLedState: KeyboardLedState = {
|
||||
num_lock: false,
|
||||
caps_lock: false,
|
||||
scroll_lock: false,
|
||||
compose: false,
|
||||
kana: false,
|
||||
};
|
||||
|
||||
export interface HidState {
|
||||
activeKeys: number[];
|
||||
activeModifiers: number[];
|
||||
|
@ -423,18 +469,18 @@ export interface HidState {
|
|||
altGrCtrlTime: number; // _altGrCtrlTime
|
||||
setAltGrCtrlTime: (time: number) => void;
|
||||
|
||||
isNumLockActive: boolean;
|
||||
setIsNumLockActive: (enabled: boolean) => void;
|
||||
keyboardLedState?: KeyboardLedState;
|
||||
setKeyboardLedState: (state: KeyboardLedState) => void;
|
||||
setIsNumLockActive: (active: boolean) => void;
|
||||
setIsCapsLockActive: (active: boolean) => void;
|
||||
setIsScrollLockActive: (active: boolean) => void;
|
||||
|
||||
isScrollLockActive: boolean;
|
||||
setIsScrollLockActive: (enabled: boolean) => void;
|
||||
keyboardLedStateSyncAvailable: boolean;
|
||||
setKeyboardLedStateSyncAvailable: (available: boolean) => void;
|
||||
|
||||
isVirtualKeyboardEnabled: boolean;
|
||||
setVirtualKeyboardEnabled: (enabled: boolean) => void;
|
||||
|
||||
isCapsLockActive: boolean;
|
||||
setIsCapsLockActive: (enabled: boolean) => void;
|
||||
|
||||
isPasteModeEnabled: boolean;
|
||||
setPasteModeEnabled: (enabled: boolean) => void;
|
||||
|
||||
|
@ -442,7 +488,7 @@ export interface HidState {
|
|||
setUsbState: (state: HidState["usbState"]) => void;
|
||||
}
|
||||
|
||||
export const useHidStore = create<HidState>(set => ({
|
||||
export const useHidStore = create<HidState>((set, get) => ({
|
||||
activeKeys: [],
|
||||
activeModifiers: [],
|
||||
updateActiveKeysAndModifiers: ({ keys, modifiers }) => {
|
||||
|
@ -458,18 +504,29 @@ export const useHidStore = create<HidState>(set => ({
|
|||
altGrCtrlTime: 0,
|
||||
setAltGrCtrlTime: time => set({ altGrCtrlTime: time }),
|
||||
|
||||
isNumLockActive: false,
|
||||
setIsNumLockActive: enabled => set({ isNumLockActive: enabled }),
|
||||
setKeyboardLedState: ledState => set({ keyboardLedState: ledState }),
|
||||
setIsNumLockActive: active => {
|
||||
const keyboardLedState = { ...(get().keyboardLedState || defaultKeyboardLedState) };
|
||||
keyboardLedState.num_lock = active;
|
||||
set({ keyboardLedState });
|
||||
},
|
||||
setIsCapsLockActive: active => {
|
||||
const keyboardLedState = { ...(get().keyboardLedState || defaultKeyboardLedState) };
|
||||
keyboardLedState.caps_lock = active;
|
||||
set({ keyboardLedState });
|
||||
},
|
||||
setIsScrollLockActive: active => {
|
||||
const keyboardLedState = { ...(get().keyboardLedState || defaultKeyboardLedState) };
|
||||
keyboardLedState.scroll_lock = active;
|
||||
set({ keyboardLedState });
|
||||
},
|
||||
|
||||
isScrollLockActive: false,
|
||||
setIsScrollLockActive: enabled => set({ isScrollLockActive: enabled }),
|
||||
keyboardLedStateSyncAvailable: false,
|
||||
setKeyboardLedStateSyncAvailable: available => set({ keyboardLedStateSyncAvailable: available }),
|
||||
|
||||
isVirtualKeyboardEnabled: false,
|
||||
setVirtualKeyboardEnabled: enabled => set({ isVirtualKeyboardEnabled: enabled }),
|
||||
|
||||
isCapsLockActive: false,
|
||||
setIsCapsLockActive: enabled => set({ isCapsLockActive: enabled }),
|
||||
|
||||
isPasteModeEnabled: false,
|
||||
setPasteModeEnabled: enabled => set({ isPasteModeEnabled: enabled }),
|
||||
|
||||
|
|
|
@ -295,6 +295,10 @@ if (isOnDevice) {
|
|||
path: "hardware",
|
||||
element: <SettingsHardwareRoute />,
|
||||
},
|
||||
{
|
||||
path: "network",
|
||||
element: <SettingsNetworkRoute />,
|
||||
},
|
||||
{
|
||||
path: "access",
|
||||
children: [
|
||||
|
@ -350,10 +354,11 @@ if (isOnDevice) {
|
|||
loader: DeviceIdRename.loader,
|
||||
action: DeviceIdRename.action,
|
||||
},
|
||||
{
|
||||
path: "devices",
|
||||
{
|
||||
path: "devices",
|
||||
element: <DevicesRoute />,
|
||||
loader: DevicesRoute.loader },
|
||||
loader: DevicesRoute.loader
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
|
|
|
@ -1,17 +1,16 @@
|
|||
|
||||
import { useCallback, useState, useEffect } from "react";
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
|
||||
import { GridCard } from "@components/Card";
|
||||
|
||||
import { SettingsPageHeader } from "../components/SettingsPageheader";
|
||||
import Checkbox from "../components/Checkbox";
|
||||
import { useJsonRpc } from "../hooks/useJsonRpc";
|
||||
import notifications from "../notifications";
|
||||
import { TextAreaWithLabel } from "../components/TextArea";
|
||||
import { isOnDevice } from "../main";
|
||||
import { Button } from "../components/Button";
|
||||
import Checkbox from "../components/Checkbox";
|
||||
import { ConfirmDialog } from "../components/ConfirmDialog";
|
||||
import { SettingsPageHeader } from "../components/SettingsPageheader";
|
||||
import { TextAreaWithLabel } from "../components/TextArea";
|
||||
import { useSettingsStore } from "../hooks/stores";
|
||||
|
||||
import { useJsonRpc } from "../hooks/useJsonRpc";
|
||||
import { isOnDevice } from "../main";
|
||||
import notifications from "../notifications";
|
||||
|
||||
import { SettingsItem } from "./devices.$id.settings";
|
||||
|
||||
|
@ -22,6 +21,8 @@ export default function SettingsAdvancedRoute() {
|
|||
const setDeveloperMode = useSettingsStore(state => state.setDeveloperMode);
|
||||
const [devChannel, setDevChannel] = useState(false);
|
||||
const [usbEmulationEnabled, setUsbEmulationEnabled] = useState(false);
|
||||
const [showLoopbackWarning, setShowLoopbackWarning] = useState(false);
|
||||
const [localLoopbackOnly, setLocalLoopbackOnly] = useState(false);
|
||||
|
||||
const settings = useSettingsStore();
|
||||
|
||||
|
@ -46,6 +47,11 @@ export default function SettingsAdvancedRoute() {
|
|||
if ("error" in resp) return;
|
||||
setDevChannel(resp.result as boolean);
|
||||
});
|
||||
|
||||
send("getLocalLoopbackOnly", {}, resp => {
|
||||
if ("error" in resp) return;
|
||||
setLocalLoopbackOnly(resp.result as boolean);
|
||||
});
|
||||
}, [send, setDeveloperMode]);
|
||||
|
||||
const getUsbEmulationState = useCallback(() => {
|
||||
|
@ -110,17 +116,62 @@ export default function SettingsAdvancedRoute() {
|
|||
[send, setDeveloperMode],
|
||||
);
|
||||
|
||||
const handleDevChannelChange = (enabled: boolean) => {
|
||||
send("setDevChannelState", { enabled }, resp => {
|
||||
if ("error" in resp) {
|
||||
notifications.error(
|
||||
`Failed to set dev channel state: ${resp.error.data || "Unknown error"}`,
|
||||
);
|
||||
return;
|
||||
const handleDevChannelChange = useCallback(
|
||||
(enabled: boolean) => {
|
||||
send("setDevChannelState", { enabled }, resp => {
|
||||
if ("error" in resp) {
|
||||
notifications.error(
|
||||
`Failed to set dev channel state: ${resp.error.data || "Unknown error"}`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
setDevChannel(enabled);
|
||||
});
|
||||
},
|
||||
[send, setDevChannel],
|
||||
);
|
||||
|
||||
const applyLoopbackOnlyMode = useCallback(
|
||||
(enabled: boolean) => {
|
||||
send("setLocalLoopbackOnly", { enabled }, resp => {
|
||||
if ("error" in resp) {
|
||||
notifications.error(
|
||||
`Failed to ${enabled ? "enable" : "disable"} loopback-only mode: ${resp.error.data || "Unknown error"}`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
setLocalLoopbackOnly(enabled);
|
||||
if (enabled) {
|
||||
notifications.success(
|
||||
"Loopback-only mode enabled. Restart your device to apply.",
|
||||
);
|
||||
} else {
|
||||
notifications.success(
|
||||
"Loopback-only mode disabled. Restart your device to apply.",
|
||||
);
|
||||
}
|
||||
});
|
||||
},
|
||||
[send, setLocalLoopbackOnly],
|
||||
);
|
||||
|
||||
const handleLoopbackOnlyModeChange = useCallback(
|
||||
(enabled: boolean) => {
|
||||
// If trying to enable loopback-only mode, show warning first
|
||||
if (enabled) {
|
||||
setShowLoopbackWarning(true);
|
||||
} else {
|
||||
// If disabling, just proceed
|
||||
applyLoopbackOnlyMode(false);
|
||||
}
|
||||
setDevChannel(enabled);
|
||||
});
|
||||
};
|
||||
},
|
||||
[applyLoopbackOnlyMode, setShowLoopbackWarning],
|
||||
);
|
||||
|
||||
const confirmLoopbackModeEnable = useCallback(() => {
|
||||
applyLoopbackOnlyMode(true);
|
||||
setShowLoopbackWarning(false);
|
||||
}, [applyLoopbackOnlyMode, setShowLoopbackWarning]);
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
|
@ -153,7 +204,7 @@ export default function SettingsAdvancedRoute() {
|
|||
|
||||
{settings.developerMode && (
|
||||
<GridCard>
|
||||
<div className="flex select-none items-start gap-x-4 p-4">
|
||||
<div className="flex items-start gap-x-4 p-4 select-none">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 24 24"
|
||||
|
@ -187,6 +238,16 @@ export default function SettingsAdvancedRoute() {
|
|||
</GridCard>
|
||||
)}
|
||||
|
||||
<SettingsItem
|
||||
title="Loopback-Only Mode"
|
||||
description="Restrict web interface access to localhost only (127.0.0.1)"
|
||||
>
|
||||
<Checkbox
|
||||
checked={localLoopbackOnly}
|
||||
onChange={e => handleLoopbackOnlyModeChange(e.target.checked)}
|
||||
/>
|
||||
</SettingsItem>
|
||||
|
||||
{isOnDevice && settings.developerMode && (
|
||||
<div className="space-y-4">
|
||||
<SettingsItem
|
||||
|
@ -261,6 +322,30 @@ export default function SettingsAdvancedRoute() {
|
|||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<ConfirmDialog
|
||||
open={showLoopbackWarning}
|
||||
onClose={() => {
|
||||
setShowLoopbackWarning(false);
|
||||
}}
|
||||
title="Enable Loopback-Only Mode?"
|
||||
description={
|
||||
<>
|
||||
<p>
|
||||
WARNING: This will restrict web interface access to localhost (127.0.0.1)
|
||||
only.
|
||||
</p>
|
||||
<p>Before enabling this feature, make sure you have either:</p>
|
||||
<ul className="list-disc space-y-1 pl-5 text-xs text-slate-700 dark:text-slate-300">
|
||||
<li>SSH access configured and tested</li>
|
||||
<li>Cloud access enabled and working</li>
|
||||
</ul>
|
||||
</>
|
||||
}
|
||||
variant="warning"
|
||||
confirmText="I Understand, Enable Anyway"
|
||||
onConfirm={confirmLoopbackModeEnable}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
|
@ -0,0 +1,28 @@
|
|||
|
||||
import { Checkbox } from "@/components/Checkbox";
|
||||
import { SettingsPageHeader } from "@/components/SettingsPageheader";
|
||||
import { useSettingsStore } from "@/hooks/stores";
|
||||
|
||||
import { SettingsItem } from "./devices.$id.settings";
|
||||
|
||||
export default function SettingsCtrlAltDelRoute() {
|
||||
const enableCtrlAltDel = useSettingsStore(state => state.actionBarCtrlAltDel);
|
||||
const setEnableCtrlAltDel = useSettingsStore(state => state.setActionBarCtrlAltDel);
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<SettingsPageHeader
|
||||
title="Action Bar"
|
||||
description="Customize the action bar of your JetKVM interface"
|
||||
/>
|
||||
<div className="space-y-4">
|
||||
<SettingsItem title="Enable Ctrl-Alt-Del" description="Enable the Ctrl-Alt-Del key on the virtual keyboard">
|
||||
<Checkbox
|
||||
checked={enableCtrlAltDel}
|
||||
onChange={e => setEnableCtrlAltDel(e.target.checked)}
|
||||
/>
|
||||
</SettingsItem>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
|
@ -116,6 +116,15 @@ export default function SettingsHardwareRoute() {
|
|||
}}
|
||||
/>
|
||||
</SettingsItem>
|
||||
{/* <SettingsItem
|
||||
title="Enable Ctrl+Alt+Del Action Bar"
|
||||
description="Enable or disable the action bar action for sending a Ctrl+Alt+Del to the host"
|
||||
>
|
||||
<Checkbox
|
||||
checked={actionBarConfig.ctrlAltDel}
|
||||
onChange={onActionBarItemChange("ctrlAltDel")}
|
||||
/>
|
||||
</SettingsItem> */}
|
||||
{settings.backlightSettings.max_brightness != 0 && (
|
||||
<>
|
||||
<SettingsItem
|
||||
|
|
|
@ -1,10 +1,11 @@
|
|||
import { useCallback, useEffect, useMemo } from "react";
|
||||
|
||||
import { useSettingsStore } from "@/hooks/stores";
|
||||
import { KeyboardLedSync, useSettingsStore } from "@/hooks/stores";
|
||||
import { useJsonRpc } from "@/hooks/useJsonRpc";
|
||||
import notifications from "@/notifications";
|
||||
import { SettingsPageHeader } from "@components/SettingsPageheader";
|
||||
import { layouts } from "@/keyboardLayouts";
|
||||
import { Checkbox } from "@/components/Checkbox";
|
||||
|
||||
import { SelectMenuBasic } from "../components/SelectMenuBasic";
|
||||
|
||||
|
@ -12,18 +13,31 @@ import { SettingsItem } from "./devices.$id.settings";
|
|||
|
||||
export default function SettingsKeyboardRoute() {
|
||||
const keyboardLayout = useSettingsStore(state => state.keyboardLayout);
|
||||
const keyboardLedSync = useSettingsStore(state => state.keyboardLedSync);
|
||||
const showPressedKeys = useSettingsStore(state => state.showPressedKeys);
|
||||
const setKeyboardLayout = useSettingsStore(
|
||||
state => state.setKeyboardLayout,
|
||||
);
|
||||
const setKeyboardLedSync = useSettingsStore(
|
||||
state => state.setKeyboardLedSync,
|
||||
);
|
||||
const setShowPressedKeys = useSettingsStore(
|
||||
state => state.setShowPressedKeys,
|
||||
);
|
||||
|
||||
// this ensures we always get the original en-US if it hasn't been set yet
|
||||
// this ensures we always get the original en_US if it hasn't been set yet
|
||||
const safeKeyboardLayout = useMemo(() => {
|
||||
if (keyboardLayout && keyboardLayout.length > 0)
|
||||
return keyboardLayout;
|
||||
return "en-US";
|
||||
return "en_US";
|
||||
}, [keyboardLayout]);
|
||||
|
||||
const layoutOptions = Object.entries(layouts).map(([code, language]) => { return { value: code, label: language } })
|
||||
const ledSyncOptions = [
|
||||
{ value: "auto", label: "Automatic" },
|
||||
{ value: "browser", label: "Browser Only" },
|
||||
{ value: "host", label: "Host Only" },
|
||||
];
|
||||
|
||||
const [send] = useJsonRpc();
|
||||
|
||||
|
@ -54,7 +68,7 @@ export default function SettingsKeyboardRoute() {
|
|||
<div className="space-y-4">
|
||||
<SettingsPageHeader
|
||||
title="Keyboard"
|
||||
description="Configure keyboard layout settings for your device"
|
||||
description="Configure keyboard settings for your device"
|
||||
/>
|
||||
|
||||
<div className="space-y-4">
|
||||
|
@ -76,6 +90,35 @@ export default function SettingsKeyboardRoute() {
|
|||
Pasting text sends individual key strokes to the target device. The keyboard layout determines which key codes are being sent. Ensure that the keyboard layout in JetKVM matches the settings in the operating system.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-4">
|
||||
{ /* this menu item could be renamed to plain "Keyboard layout" in the future, when also the virtual keyboard layout mappings are being implemented */ }
|
||||
<SettingsItem
|
||||
title="LED state synchronization"
|
||||
description="Synchronize the LED state of the keyboard with the target device"
|
||||
>
|
||||
<SelectMenuBasic
|
||||
size="SM"
|
||||
label=""
|
||||
fullWidth
|
||||
value={keyboardLedSync}
|
||||
onChange={e => setKeyboardLedSync(e.target.value as KeyboardLedSync)}
|
||||
options={ledSyncOptions}
|
||||
/>
|
||||
</SettingsItem>
|
||||
</div>
|
||||
|
||||
<div className="space-y-4">
|
||||
<SettingsItem
|
||||
title="Show Pressed Keys"
|
||||
description="Display currently pressed keys in the status bar"
|
||||
>
|
||||
<Checkbox
|
||||
checked={showPressedKeys}
|
||||
onChange={e => setShowPressedKeys(e.target.checked)}
|
||||
/>
|
||||
</SettingsItem>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
|
@ -9,6 +9,7 @@ import { useSettingsStore } from "@/hooks/stores";
|
|||
import { useJsonRpc } from "@/hooks/useJsonRpc";
|
||||
import notifications from "@/notifications";
|
||||
import { SettingsPageHeader } from "@components/SettingsPageheader";
|
||||
import { SelectMenuBasic } from "@components/SelectMenuBasic";
|
||||
|
||||
import { useFeatureFlag } from "../hooks/useFeatureFlag";
|
||||
import { cx } from "../cva.config";
|
||||
|
@ -26,6 +27,19 @@ export default function SettingsMouseRoute() {
|
|||
|
||||
const [jiggler, setJiggler] = useState(false);
|
||||
|
||||
const scrollThrottling = useSettingsStore(state => state.scrollThrottling);
|
||||
const setScrollThrottling = useSettingsStore(
|
||||
state => state.setScrollThrottling,
|
||||
);
|
||||
|
||||
const scrollThrottlingOptions = [
|
||||
{ value: "0", label: "Off" },
|
||||
{ value: "10", label: "Low" },
|
||||
{ value: "25", label: "Medium" },
|
||||
{ value: "50", label: "High" },
|
||||
{ value: "100", label: "Very High" },
|
||||
];
|
||||
|
||||
const [send] = useJsonRpc();
|
||||
|
||||
useEffect(() => {
|
||||
|
@ -65,6 +79,21 @@ export default function SettingsMouseRoute() {
|
|||
/>
|
||||
</SettingsItem>
|
||||
|
||||
<SettingsItem
|
||||
title="Scroll Throttling"
|
||||
description="Reduce the frequency of scroll events"
|
||||
>
|
||||
<SelectMenuBasic
|
||||
size="SM"
|
||||
label=""
|
||||
className="max-w-[292px]"
|
||||
value={scrollThrottling}
|
||||
fullWidth
|
||||
onChange={e => setScrollThrottling(parseInt(e.target.value))}
|
||||
options={scrollThrottlingOptions}
|
||||
/>
|
||||
</SettingsItem>
|
||||
|
||||
<SettingsItem
|
||||
title="Jiggler"
|
||||
description="Simulate movement of a computer mouse. Prevents sleep mode, standby mode or the screensaver from activating"
|
||||
|
|
|
@ -228,7 +228,6 @@ export default function SettingsNetworkRoute() {
|
|||
size="SM"
|
||||
value={networkState?.mac_address}
|
||||
error={""}
|
||||
disabled={true}
|
||||
readOnly={true}
|
||||
className="dark:!text-opacity-60"
|
||||
/>
|
||||
|
|
|
@ -269,22 +269,17 @@ export default function SettingsRoute() {
|
|||
);
|
||||
}
|
||||
|
||||
export function SettingsItem({
|
||||
title,
|
||||
description,
|
||||
children,
|
||||
className,
|
||||
loading,
|
||||
badge,
|
||||
}: {
|
||||
title: string;
|
||||
description: string | React.ReactNode;
|
||||
children?: React.ReactNode;
|
||||
className?: string;
|
||||
name?: string;
|
||||
loading?: boolean;
|
||||
badge?: string;
|
||||
}) {
|
||||
interface SettingsItemProps {
|
||||
readonly title: string;
|
||||
readonly description: string | React.ReactNode;
|
||||
readonly badge?: string;
|
||||
readonly className?: string;
|
||||
readonly loading?: boolean;
|
||||
readonly children?: React.ReactNode;
|
||||
}
|
||||
export function SettingsItem(props: SettingsItemProps) {
|
||||
const { title, description, badge, children, className, loading } = props;
|
||||
|
||||
return (
|
||||
<label
|
||||
className={cx(
|
||||
|
|
|
@ -4,6 +4,7 @@ import { Button } from "@/components/Button";
|
|||
import { TextAreaWithLabel } from "@/components/TextArea";
|
||||
import { useJsonRpc } from "@/hooks/useJsonRpc";
|
||||
import { SettingsPageHeader } from "@components/SettingsPageheader";
|
||||
import { useSettingsStore } from "@/hooks/stores";
|
||||
|
||||
import notifications from "../notifications";
|
||||
import { SelectMenuBasic } from "../components/SelectMenuBasic";
|
||||
|
@ -45,6 +46,14 @@ export default function SettingsVideoRoute() {
|
|||
const [customEdidValue, setCustomEdidValue] = useState<string | null>(null);
|
||||
const [edid, setEdid] = useState<string | null>(null);
|
||||
|
||||
// Video enhancement settings from store
|
||||
const videoSaturation = useSettingsStore(state => state.videoSaturation);
|
||||
const setVideoSaturation = useSettingsStore(state => state.setVideoSaturation);
|
||||
const videoBrightness = useSettingsStore(state => state.videoBrightness);
|
||||
const setVideoBrightness = useSettingsStore(state => state.setVideoBrightness);
|
||||
const videoContrast = useSettingsStore(state => state.videoContrast);
|
||||
const setVideoContrast = useSettingsStore(state => state.setVideoContrast);
|
||||
|
||||
useEffect(() => {
|
||||
send("getStreamQualityFactor", {}, resp => {
|
||||
if ("error" in resp) return;
|
||||
|
@ -126,6 +135,73 @@ export default function SettingsVideoRoute() {
|
|||
onChange={e => handleStreamQualityChange(e.target.value)}
|
||||
/>
|
||||
</SettingsItem>
|
||||
|
||||
{/* Video Enhancement Settings */}
|
||||
<SettingsItem
|
||||
title="Video Enhancement"
|
||||
description="Adjust color settings to make the video output more vibrant and colorful"
|
||||
/>
|
||||
|
||||
<div className="space-y-4 pl-4">
|
||||
<SettingsItem
|
||||
title="Saturation"
|
||||
description={`Color saturation (${videoSaturation.toFixed(1)}x)`}
|
||||
>
|
||||
<input
|
||||
type="range"
|
||||
min="0.5"
|
||||
max="2.0"
|
||||
step="0.1"
|
||||
value={videoSaturation}
|
||||
onChange={e => setVideoSaturation(parseFloat(e.target.value))}
|
||||
className="w-32 h-2 bg-gray-200 rounded-lg appearance-none cursor-pointer dark:bg-gray-700"
|
||||
/>
|
||||
</SettingsItem>
|
||||
|
||||
<SettingsItem
|
||||
title="Brightness"
|
||||
description={`Brightness level (${videoBrightness.toFixed(1)}x)`}
|
||||
>
|
||||
<input
|
||||
type="range"
|
||||
min="0.5"
|
||||
max="1.5"
|
||||
step="0.1"
|
||||
value={videoBrightness}
|
||||
onChange={e => setVideoBrightness(parseFloat(e.target.value))}
|
||||
className="w-32 h-2 bg-gray-200 rounded-lg appearance-none cursor-pointer dark:bg-gray-700"
|
||||
/>
|
||||
</SettingsItem>
|
||||
|
||||
<SettingsItem
|
||||
title="Contrast"
|
||||
description={`Contrast level (${videoContrast.toFixed(1)}x)`}
|
||||
>
|
||||
<input
|
||||
type="range"
|
||||
min="0.5"
|
||||
max="2.0"
|
||||
step="0.1"
|
||||
value={videoContrast}
|
||||
onChange={e => setVideoContrast(parseFloat(e.target.value))}
|
||||
className="w-32 h-2 bg-gray-200 rounded-lg appearance-none cursor-pointer dark:bg-gray-700"
|
||||
/>
|
||||
</SettingsItem>
|
||||
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
size="SM"
|
||||
theme="light"
|
||||
text="Reset to Default"
|
||||
onClick={() => {
|
||||
setVideoSaturation(1.0);
|
||||
setVideoBrightness(1.0);
|
||||
setVideoContrast(1.0);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<SettingsItem
|
||||
title="EDID"
|
||||
description="Adjust the EDID settings for the display"
|
||||
|
|
|
@ -19,6 +19,7 @@ import useWebSocket from "react-use-websocket";
|
|||
import { cx } from "@/cva.config";
|
||||
import {
|
||||
HidState,
|
||||
KeyboardLedState,
|
||||
NetworkState,
|
||||
UpdateState,
|
||||
useDeviceStore,
|
||||
|
@ -586,6 +587,11 @@ export default function KvmIdRoute() {
|
|||
const setUsbState = useHidStore(state => state.setUsbState);
|
||||
const setHdmiState = useVideoStore(state => state.setHdmiState);
|
||||
|
||||
const keyboardLedState = useHidStore(state => state.keyboardLedState);
|
||||
const setKeyboardLedState = useHidStore(state => state.setKeyboardLedState);
|
||||
|
||||
const setKeyboardLedStateSyncAvailable = useHidStore(state => state.setKeyboardLedStateSyncAvailable);
|
||||
|
||||
const [hasUpdated, setHasUpdated] = useState(false);
|
||||
const { navigateTo } = useDeviceUiNavigation();
|
||||
|
||||
|
@ -607,6 +613,13 @@ export default function KvmIdRoute() {
|
|||
setNetworkState(resp.params as NetworkState);
|
||||
}
|
||||
|
||||
if (resp.method === "keyboardLedState") {
|
||||
const ledState = resp.params as KeyboardLedState;
|
||||
console.log("Setting keyboard led state", ledState);
|
||||
setKeyboardLedState(ledState);
|
||||
setKeyboardLedStateSyncAvailable(true);
|
||||
}
|
||||
|
||||
if (resp.method === "otaState") {
|
||||
const otaState = resp.params as UpdateState["otaState"];
|
||||
setOtaState(otaState);
|
||||
|
@ -643,6 +656,29 @@ export default function KvmIdRoute() {
|
|||
});
|
||||
}, [rpcDataChannel?.readyState, send, setHdmiState]);
|
||||
|
||||
// request keyboard led state from the device
|
||||
useEffect(() => {
|
||||
if (rpcDataChannel?.readyState !== "open") return;
|
||||
if (keyboardLedState !== undefined) return;
|
||||
console.log("Requesting keyboard led state");
|
||||
|
||||
send("getKeyboardLedState", {}, resp => {
|
||||
if ("error" in resp) {
|
||||
// -32601 means the method is not supported
|
||||
if (resp.error.code === -32601) {
|
||||
setKeyboardLedStateSyncAvailable(false);
|
||||
console.error("Failed to get keyboard led state, disabling sync", resp.error);
|
||||
} else {
|
||||
console.error("Failed to get keyboard led state", resp.error);
|
||||
}
|
||||
return;
|
||||
}
|
||||
console.log("Keyboard led state", resp.result);
|
||||
setKeyboardLedState(resp.result as KeyboardLedState);
|
||||
setKeyboardLedStateSyncAvailable(true);
|
||||
});
|
||||
}, [rpcDataChannel?.readyState, send, setKeyboardLedState, setKeyboardLedStateSyncAvailable, keyboardLedState]);
|
||||
|
||||
// When the update is successful, we need to refresh the client javascript and show a success modal
|
||||
useEffect(() => {
|
||||
if (queryParams.get("updateSuccess")) {
|
||||
|
@ -679,12 +715,10 @@ export default function KvmIdRoute() {
|
|||
useEffect(() => {
|
||||
if (!peerConnection) return;
|
||||
if (!kvmTerminal) {
|
||||
// console.log('Creating data channel "terminal"');
|
||||
setKvmTerminal(peerConnection.createDataChannel("terminal"));
|
||||
}
|
||||
|
||||
if (!serialConsole) {
|
||||
// console.log('Creating data channel "serial"');
|
||||
setSerialConsole(peerConnection.createDataChannel("serial"));
|
||||
}
|
||||
}, [kvmTerminal, peerConnection, serialConsole]);
|
||||
|
@ -719,10 +753,10 @@ export default function KvmIdRoute() {
|
|||
|
||||
const ConnectionStatusElement = useMemo(() => {
|
||||
const hasConnectionFailed =
|
||||
connectionFailed || ["failed", "closed"].includes(peerConnectionState || "");
|
||||
connectionFailed || ["failed", "closed"].includes(peerConnectionState ?? "");
|
||||
|
||||
const isPeerConnectionLoading =
|
||||
["connecting", "new"].includes(peerConnectionState || "") ||
|
||||
["connecting", "new"].includes(peerConnectionState ?? "") ||
|
||||
peerConnection === null;
|
||||
|
||||
const isDisconnected = peerConnectionState === "disconnected";
|
||||
|
@ -790,7 +824,7 @@ export default function KvmIdRoute() {
|
|||
isLoggedIn={authMode === "password" || !!user}
|
||||
userEmail={user?.email}
|
||||
picture={user?.picture}
|
||||
kvmName={deviceName || "JetKVM Device"}
|
||||
kvmName={deviceName ?? "JetKVM Device"}
|
||||
/>
|
||||
|
||||
<div className="relative flex h-full w-full overflow-hidden">
|
||||
|
@ -810,6 +844,9 @@ export default function KvmIdRoute() {
|
|||
|
||||
<div
|
||||
className="z-50"
|
||||
onClick={e => e.stopPropagation()}
|
||||
onMouseUp={e => e.stopPropagation()}
|
||||
onMouseDown={e => e.stopPropagation()}
|
||||
onKeyUp={e => e.stopPropagation()}
|
||||
onKeyDown={e => {
|
||||
e.stopPropagation();
|
||||
|
@ -833,7 +870,12 @@ export default function KvmIdRoute() {
|
|||
);
|
||||
}
|
||||
|
||||
function SidebarContainer({ sidebarView }: { sidebarView: string | null }) {
|
||||
interface SidebarContainerProps {
|
||||
readonly sidebarView: string | null;
|
||||
}
|
||||
|
||||
function SidebarContainer(props: SidebarContainerProps) {
|
||||
const { sidebarView }= props;
|
||||
return (
|
||||
<div
|
||||
className={cx(
|
||||
|
|
|
@ -2,6 +2,7 @@
|
|||
"compilerOptions": {
|
||||
"target": "ES2020",
|
||||
"useDefineForClassFields": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"lib": ["ES2021", "DOM", "DOM.Iterable"],
|
||||
"module": "ESNext",
|
||||
"skipLibCheck": true,
|
||||
|
|
15
usb.go
15
usb.go
|
@ -24,6 +24,17 @@ func initUsbGadget() {
|
|||
time.Sleep(500 * time.Millisecond)
|
||||
}
|
||||
}()
|
||||
|
||||
gadget.SetOnKeyboardStateChange(func(state usbgadget.KeyboardState) {
|
||||
if currentSession != nil {
|
||||
writeJSONRPCEvent("keyboardLedState", state, currentSession)
|
||||
}
|
||||
})
|
||||
|
||||
// open the keyboard hid file to listen for keyboard events
|
||||
if err := gadget.OpenKeyboardHidFile(); err != nil {
|
||||
usbLogger.Error().Err(err).Msg("failed to open keyboard hid file")
|
||||
}
|
||||
}
|
||||
|
||||
func rpcKeyboardReport(modifier uint8, keys []uint8) error {
|
||||
|
@ -42,6 +53,10 @@ func rpcWheelReport(wheelY int8) error {
|
|||
return gadget.AbsMouseWheelReport(wheelY)
|
||||
}
|
||||
|
||||
func rpcGetKeyboardLedState() (state usbgadget.KeyboardState) {
|
||||
return gadget.GetKeyboardState()
|
||||
}
|
||||
|
||||
var usbState = "unknown"
|
||||
|
||||
func rpcGetUSBState() (state string) {
|
||||
|
|
20
web.go
20
web.go
|
@ -52,8 +52,9 @@ type ChangePasswordRequest struct {
|
|||
}
|
||||
|
||||
type LocalDevice struct {
|
||||
AuthMode *string `json:"authMode"`
|
||||
DeviceID string `json:"deviceId"`
|
||||
AuthMode *string `json:"authMode"`
|
||||
DeviceID string `json:"deviceId"`
|
||||
LoopbackOnly bool `json:"loopbackOnly"`
|
||||
}
|
||||
|
||||
type DeviceStatus struct {
|
||||
|
@ -532,7 +533,15 @@ func basicAuthProtectedMiddleware(requireDeveloperMode bool) gin.HandlerFunc {
|
|||
|
||||
func RunWebServer() {
|
||||
r := setupRouter()
|
||||
err := r.Run(":80")
|
||||
|
||||
// Determine the binding address based on the config
|
||||
bindAddress := ":80" // Default to all interfaces
|
||||
if config.LocalLoopbackOnly {
|
||||
bindAddress = "localhost:80" // Loopback only (both IPv4 and IPv6)
|
||||
}
|
||||
|
||||
logger.Info().Str("bindAddress", bindAddress).Bool("loopbackOnly", config.LocalLoopbackOnly).Msg("Starting web server")
|
||||
err := r.Run(bindAddress)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
@ -540,8 +549,9 @@ func RunWebServer() {
|
|||
|
||||
func handleDevice(c *gin.Context) {
|
||||
response := LocalDevice{
|
||||
AuthMode: &config.LocalAuthMode,
|
||||
DeviceID: GetDeviceID(),
|
||||
AuthMode: &config.LocalAuthMode,
|
||||
DeviceID: GetDeviceID(),
|
||||
LoopbackOnly: config.LocalLoopbackOnly,
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, response)
|
||||
|
|
Loading…
Reference in New Issue