Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions src/main/i18n.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,9 @@ export interface MainTexts {
overlayNoRenderer: string
overlayPressButton: string
overlayNote: string
noticeDisconnected: string // {n}
noticeReconnected: string // {n}
noticeLowBattery: string // {n}
}

const texts: Record<Locale, MainTexts> = {
Expand Down Expand Up @@ -114,6 +117,9 @@ const texts: Record<Locale, MainTexts> = {
overlayNoRenderer: 'Not available in this game',
overlayPressButton: 'Press a button',
overlayNote: 'PC only: controller, cable and TV delay not included',
noticeDisconnected: 'Controller {n} disconnected',
noticeReconnected: 'Controller {n} is back',
noticeLowBattery: 'Controller {n}: battery is low',
},
uk: {
trayIsolating: 'Ізоляція: {game}',
Expand Down Expand Up @@ -171,6 +177,9 @@ const texts: Record<Locale, MainTexts> = {
overlayNoRenderer: 'Недоступно в цій грі',
overlayPressButton: 'Натисніть кнопку',
overlayNote: 'Лише ПК: без затримки геймпада, кабелю й телевізора',
noticeDisconnected: 'Геймпад {n} відключився',
noticeReconnected: 'Геймпад {n} знову підключено',
noticeLowBattery: 'Геймпад {n}: батарея сідає',
},
ru: {
trayIsolating: 'Изоляция: {game}',
Expand Down Expand Up @@ -227,6 +236,9 @@ const texts: Record<Locale, MainTexts> = {
overlayNoRenderer: 'Недоступно в этой игре',
overlayPressButton: 'Нажмите кнопку',
overlayNote: 'Только ПК: без задержки геймпада, кабеля и телевизора',
noticeDisconnected: 'Геймпад {n} отключился',
noticeReconnected: 'Геймпад {n} снова подключён',
noticeLowBattery: 'Геймпад {n}: батарея садится',
},
es: {
trayIsolating: 'Aislando {game}',
Expand Down Expand Up @@ -283,6 +295,9 @@ const texts: Record<Locale, MainTexts> = {
overlayNoRenderer: 'No disponible en este juego',
overlayPressButton: 'Pulsa un botón',
overlayNote: 'Solo el PC: sin el retraso del mando, el cable y la TV',
noticeDisconnected: 'Mando {n} desconectado',
noticeReconnected: 'El mando {n} ha vuelto',
noticeLowBattery: 'Mando {n}: batería baja',
},
de: {
trayIsolating: '{game} wird isoliert',
Expand Down Expand Up @@ -340,6 +355,9 @@ const texts: Record<Locale, MainTexts> = {
overlayNoRenderer: 'In diesem Spiel nicht verfügbar',
overlayPressButton: 'Drück eine Taste',
overlayNote: 'Nur der PC: ohne Verzögerung von Controller, Kabel und TV',
noticeDisconnected: 'Controller {n} getrennt',
noticeReconnected: 'Controller {n} ist wieder da',
noticeLowBattery: 'Controller {n}: Akku fast leer',
},
fr: {
trayIsolating: 'Isolation de {game}',
Expand Down Expand Up @@ -397,6 +415,9 @@ const texts: Record<Locale, MainTexts> = {
overlayNoRenderer: 'Indisponible dans ce jeu',
overlayPressButton: 'Appuyez sur un bouton',
overlayNote: 'PC seul : sans le délai de la manette, du câble et de la TV',
noticeDisconnected: 'Manette {n} déconnectée',
noticeReconnected: 'La manette {n} est de retour',
noticeLowBattery: 'Manette {n} : batterie faible',
},
'pt-BR': {
trayIsolating: 'Isolando {game}',
Expand Down Expand Up @@ -452,6 +473,9 @@ const texts: Record<Locale, MainTexts> = {
overlayNoRenderer: 'Indisponível neste jogo',
overlayPressButton: 'Aperte um botão',
overlayNote: 'Só o PC: sem o atraso do controle, do cabo e da TV',
noticeDisconnected: 'Controle {n} desconectado',
noticeReconnected: 'O controle {n} voltou',
noticeLowBattery: 'Controle {n}: bateria fraca',
},
pl: {
trayIsolating: 'Izolowanie: {game}',
Expand Down Expand Up @@ -507,6 +531,9 @@ const texts: Record<Locale, MainTexts> = {
overlayNoRenderer: 'Niedostępne w tej grze',
overlayPressButton: 'Naciśnij przycisk',
overlayNote: 'Tylko PC: bez opóźnienia pada, kabla i telewizora',
noticeDisconnected: 'Kontroler {n} rozłączony',
noticeReconnected: 'Kontroler {n} znów połączony',
noticeLowBattery: 'Kontroler {n}: słaba bateria',
},
tr: {
trayIsolating: '{game} yalıtılıyor',
Expand Down Expand Up @@ -564,6 +591,9 @@ const texts: Record<Locale, MainTexts> = {
overlayNoRenderer: 'Bu oyunda kullanılamıyor',
overlayPressButton: 'Bir tuşa basın',
overlayNote: 'Yalnızca PC: kumanda, kablo ve TV gecikmesi dahil değil',
noticeDisconnected: 'Kumanda {n} bağlantısı kesildi',
noticeReconnected: 'Kumanda {n} yeniden bağlandı',
noticeLowBattery: 'Kumanda {n}: pil zayıf',
},
'zh-CN': {
trayIsolating: '正在隔离 {game}',
Expand Down Expand Up @@ -618,6 +648,9 @@ const texts: Record<Locale, MainTexts> = {
overlayNoRenderer: '此游戏不支持',
overlayPressButton: '请按一个按键',
overlayNote: '仅电脑部分:不含手柄、线缆和电视的延迟',
noticeDisconnected: '手柄 {n} 已断开',
noticeReconnected: '手柄 {n} 已重新连接',
noticeLowBattery: '手柄 {n}:电量低',
},
ja: {
trayIsolating: '{game} を分離中',
Expand Down Expand Up @@ -677,6 +710,9 @@ const texts: Record<Locale, MainTexts> = {
overlayNoRenderer: 'このゲームでは利用できません',
overlayPressButton: 'ボタンを押してください',
overlayNote: 'PC のみ: コントローラー、ケーブル、テレビの遅延は含みません',
noticeDisconnected: 'コントローラー {n} が切断されました',
noticeReconnected: 'コントローラー {n} が再接続されました',
noticeLowBattery: 'コントローラー {n}:バッテリー残量が少なくなっています',
},
}

Expand Down
44 changes: 43 additions & 1 deletion src/main/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@
import { spawn } from 'node:child_process'
import { join } from 'node:path'
import { app, dialog, nativeTheme, net, type BrowserWindow } from 'electron'
import type { IsolationView } from '@shared/domain'
import { controllerAlerts, type ControllerAlert } from '@shared/controller-alerts'
import type { Controller, IsolationView } from '@shared/domain'
import { resolveLocale } from '@shared/locales'
import { isDefaultTuning, toHelperTuning } from '@shared/tuning'
import { isSessionLive } from '@shared/support'
Expand All @@ -32,6 +33,7 @@ import { SettingsService } from './services/settings-service'
import { UpdateService } from './services/update-service'
import { mainTexts } from './i18n'
import { Notifier } from './notifier'
import { NoticeWindows } from './notice-window'
import { OverlayWindows } from './overlay-window'
import { OverlayService } from './services/overlay-service'
import { GameBarGuard, windowsGameBarSetting } from './services/game-bar-guard'
Expand Down Expand Up @@ -318,6 +320,45 @@ async function main(): Promise<void> {
ready ? notifier.updateReady(version) : notifier.updateAvailable(version),
)
devices.controllersChanged.on((list) => broadcast('controllers:changed', list))

// A controller of a running game disconnects, comes back or runs low: say so on the game's
// screen (the player there does not look at the PC) and in a Windows notification.
const notices = new NoticeWindows()
let lastControllers: Controller[] = []
const showControllerAlert = async (view: IsolationView, alert: ControllerAlert) => {
const t = texts()
const template = {
disconnected: t.noticeDisconnected,
reconnected: t.noticeReconnected,
lowBattery: t.noticeLowBattery,
}[alert.kind]
const text = template.replace('{n}', String(alert.slot + 1))
let monitor = null
if (view.target !== null) {
monitor = await backend
.request('windowMonitor', { hwnd: view.target.hwnd })
.then((r) => r.bounds)
.catch(() => null)
}
notices.show(monitor, text, alert.kind === 'reconnected' ? 'good' : 'warn')
notifier.controllerAlert(text, view)
}
devices.controllersChanged.on((list) => {
const previous = lastControllers
lastControllers = list
if (!settings.get().controllerAlerts) return
const running = seats.all().filter((view) => view.phase === 'running')
if (running.length === 0) return
const watched = new Set<number>()
for (const view of running) {
if (view.controllerSlot !== null) watched.add(view.controllerSlot)
else for (const c of previous) if (c.connected) watched.add(c.slot)
}
for (const alert of controllerAlerts(previous, list, watched)) {
const view = running.find((v) => v.controllerSlot === alert.slot) ?? running[0]!
void showControllerAlert(view, alert)
}
})
devices.displaysChanged.on((list) => broadcast('displays:changed', list))
devices.controllerState.on((state) => broadcast('controllers:state', state))
logger.onEntry((entry) => broadcast('log:entry', entry))
Expand Down Expand Up @@ -418,6 +459,7 @@ async function main(): Promise<void> {
automation.cancel()
updates.dispose()
overlay.closeAll()
notices.close()
await seats.stopAll()
await syncGameBar()
await backend.stop()
Expand Down
76 changes: 76 additions & 0 deletions src/main/notice-window.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
/**
* Short messages on the game's screen ("Controller disconnected"), for the player on the
* TV who does not look at the PC. A click-through, never-focused banner at the top of the
* monitor that closes itself after a few seconds; like the FPS overlay it is visible over
* windowed and borderless games.
*/
import { BrowserWindow, screen } from 'electron'
import type { Rect } from '@shared/domain'

const WIDTH = 560
const HEIGHT = 96
const SHOW_MS = 6000

const page = (text: string, tone: 'warn' | 'good') => `<!doctype html>
<html><head><meta charset="utf-8">
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'">
<style>
html, body { margin: 0; background: transparent; overflow: hidden; user-select: none; }
div { margin: 8px auto 0; width: fit-content; max-width: ${WIDTH - 32}px; padding: 12px 20px;
border-radius: 10px; background: rgba(8, 9, 12, 0.82); text-align: center;
border: 1px solid ${tone === 'warn' ? 'rgba(252, 211, 77, 0.55)' : 'rgba(110, 231, 160, 0.5)'};
font: 600 18px/1.35 "Segoe UI", system-ui, sans-serif; color: #f2f3f5;
text-shadow: 0 1px 2px rgba(0, 0, 0, 0.9); }
</style></head><body><div>${escapeHtml(text)}</div></body></html>`

function escapeHtml(text: string): string {
return text.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`)
}

export class NoticeWindows {
private current: BrowserWindow | null = null
private timer: NodeJS.Timeout | null = null

/** Shows `text` on the monitor at `monitor` (physical pixels; null: primary monitor). */
show(monitor: Rect | null, text: string, tone: 'warn' | 'good'): void {
this.close()
const display =
monitor === null
? screen.getPrimaryDisplay()
: screen.getDisplayMatching(
process.platform === 'win32' ? screen.screenToDipRect(null, monitor) : monitor,
)
const window = new BrowserWindow({
x: Math.round(display.bounds.x + (display.bounds.width - WIDTH) / 2),
y: display.bounds.y + 24,
width: WIDTH,
height: HEIGHT,
show: false,
frame: false,
transparent: true,
hasShadow: false,
resizable: false,
movable: false,
focusable: false,
skipTaskbar: true,
alwaysOnTop: true,
title: 'InputSplit',
webPreferences: { contextIsolation: true, sandbox: true, javascript: false, devTools: false },
})
window.setIgnoreMouseEvents(true)
window.setAlwaysOnTop(true, 'screen-saver')
window.webContents.once('did-finish-load', () => {
if (!window.isDestroyed()) window.showInactive()
})
void window.loadURL(`data:text/html;charset=utf-8,${encodeURIComponent(page(text, tone))}`)
this.current = window
this.timer = setTimeout(() => this.close(), SHOW_MS)
}

close(): void {
if (this.timer !== null) clearTimeout(this.timer)
this.timer = null
if (this.current !== null && !this.current.isDestroyed()) this.current.destroy()
this.current = null
}
}
5 changes: 5 additions & 0 deletions src/main/notifier.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,11 @@ export class Notifier {
}
}

/** Something about a player's controller (also shown on the game's screen). */
controllerAlert(title: string, view: IsolationView): void {
this.show(title, gameName(view))
}

nothingToStart(): void {
const text = this.options.texts()
this.show(text.notifyNothingTitle, text.notifyNothingBody, true)
Expand Down
3 changes: 3 additions & 0 deletions src/renderer/src/i18n/de.ts
Original file line number Diff line number Diff line change
Expand Up @@ -594,6 +594,9 @@ export const de: Messages = {
shortcut: 'Controller-Tastenkombination',
shortcutHint:
'Halte diese Tasten 2 Sekunden lang, um die Isolierung vom Sofa aus zu starten oder zu beenden. Läuft nichts, startet das zuletzt verwendete Profil, dessen Spiel geöffnet ist.',
alerts: 'Controller-Hinweise auf dem Spielbildschirm',
alertsHint:
'Wenn der Controller des Spielers getrennt wird, wieder da ist oder der Akku fast leer ist, erscheint eine kurze Meldung auf dem Spielbildschirm und als Windows-Benachrichtigung.',
rumble: 'Beim Starten und Beenden vibrieren',
rumbleHint:
'Ein langer Impuls: Isolierung aktiv. Zwei kurze: beendet. Drei: nichts zu starten.',
Expand Down
3 changes: 3 additions & 0 deletions src/renderer/src/i18n/en.ts
Original file line number Diff line number Diff line change
Expand Up @@ -586,6 +586,9 @@ export const en = {
shortcut: 'Controller shortcut',
shortcutHint:
'Hold these buttons for 2 seconds to start or stop isolation from the couch. With nothing running, it starts the most recently used profile whose game is open.',
alerts: "Controller warnings on the game's screen",
alertsHint:
"When the player's controller disconnects, comes back or its battery runs low, a short message appears on the game's screen and in a Windows notification.",
rumble: 'Vibrate on start and stop',
rumbleHint:
'One long pulse: isolation is on. Two short pulses: it is off. Three: nothing to start.',
Expand Down
3 changes: 3 additions & 0 deletions src/renderer/src/i18n/es.ts
Original file line number Diff line number Diff line change
Expand Up @@ -596,6 +596,9 @@ export const es: Messages = {
shortcut: 'Atajo del mando',
shortcutHint:
'Mantén estos botones 2 segundos para activar o detener el aislamiento desde el sofá. Si no hay nada en marcha, inicia el perfil usado más recientemente cuyo juego esté abierto.',
alerts: 'Avisos del mando en la pantalla del juego',
alertsHint:
'Si el mando del jugador se desconecta, vuelve o se queda sin batería, aparece un mensaje breve en la pantalla del juego y en una notificación de Windows.',
rumble: 'Vibrar al activar y detener',
rumbleHint:
'Un pulso largo: aislamiento activado. Dos cortos: desactivado. Tres: nada que iniciar.',
Expand Down
3 changes: 3 additions & 0 deletions src/renderer/src/i18n/fr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -597,6 +597,9 @@ export const fr: Messages = {
shortcut: 'Raccourci manette',
shortcutHint:
"Maintenez ces boutons 2 secondes pour démarrer ou arrêter l'isolation depuis le canapé. Si rien ne tourne, le profil utilisé le plus récemment dont le jeu est ouvert démarre.",
alerts: 'Alertes de manette sur l’écran du jeu',
alertsHint:
'Si la manette du joueur se déconnecte, revient ou a une batterie faible, un court message s’affiche sur l’écran du jeu et dans une notification Windows.',
rumble: "Vibrer au démarrage et à l'arrêt",
rumbleHint:
'Une longue impulsion : isolation activée. Deux courtes : désactivée. Trois : rien à démarrer.',
Expand Down
3 changes: 3 additions & 0 deletions src/renderer/src/i18n/ja.ts
Original file line number Diff line number Diff line change
Expand Up @@ -599,6 +599,9 @@ export const ja: Messages = {
shortcut: 'コントローラーのショートカット',
shortcutHint:
'これらのボタンを 2 秒間押し続けると、ソファーから分離を開始・停止できます。何も実行していない場合は、ゲームが開いている中で最近使ったプロファイルを開始します。',
alerts: 'ゲーム画面にコントローラーの通知を表示',
alertsHint:
'プレイヤーのコントローラーが切断・再接続されたときやバッテリーが少なくなったときに、ゲーム画面と Windows 通知に短いメッセージを表示します。',
rumble: '開始時と停止時に振動',
rumbleHint: '長い振動 1 回:分離オン。短い振動 2 回:オフ。3 回:開始できるものがありません。',
overlay: 'FPS と入力遅延',
Expand Down
3 changes: 3 additions & 0 deletions src/renderer/src/i18n/pl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -585,6 +585,9 @@ export const pl: Messages = {
shortcut: 'Skrót na kontrolerze',
shortcutHint:
'Przytrzymaj te przyciski przez 2 sekundy, aby włączyć lub wyłączyć izolację prosto z kanapy. Gdy nic nie działa, uruchamia ostatnio używany profil, którego gra jest otwarta.',
alerts: 'Ostrzeżenia o kontrolerze na ekranie gry',
alertsHint:
'Gdy kontroler gracza się rozłączy, wróci albo ma słabą baterię, na ekranie gry i w powiadomieniu Windows pojawi się krótki komunikat.',
rumble: 'Wibracja przy włączaniu i wyłączaniu',
rumbleHint:
'Jeden długi impuls: izolacja włączona. Dwa krótkie: wyłączona. Trzy: nie ma czego uruchomić.',
Expand Down
3 changes: 3 additions & 0 deletions src/renderer/src/i18n/pt-BR.ts
Original file line number Diff line number Diff line change
Expand Up @@ -588,6 +588,9 @@ export const ptBR: Messages = {
shortcut: 'Atalho do controle',
shortcutHint:
'Segure estes botões por 2 segundos para iniciar ou parar o isolamento do sofá. Se nada estiver rodando, inicia o perfil usado mais recentemente cujo jogo esteja aberto.',
alerts: 'Avisos do controle na tela do jogo',
alertsHint:
'Se o controle do jogador desconectar, voltar ou ficar com bateria fraca, uma mensagem curta aparece na tela do jogo e numa notificação do Windows.',
rumble: 'Vibrar ao iniciar e parar',
rumbleHint:
'Um pulso longo: isolamento ativado. Dois curtos: desativado. Três: nada para iniciar.',
Expand Down
3 changes: 3 additions & 0 deletions src/renderer/src/i18n/ru.ts
Original file line number Diff line number Diff line change
Expand Up @@ -582,6 +582,9 @@ export const ru: Messages = {
shortcut: 'Комбинация на геймпаде',
shortcutHint:
'Удерживайте эти кнопки 2 секунды, чтобы включить или выключить изоляцию прямо с дивана. Если ничего не запущено, включится последний использованный профиль, игра которого открыта.',
alerts: 'Предупреждения о геймпаде на экране игры',
alertsHint:
'Если геймпад игрока отключился, снова подключился или садится батарея, на экране игры и в уведомлении Windows появится короткое сообщение.',
rumble: 'Вибрация при включении и выключении',
rumbleHint:
'Один длинный импульс: изоляция включена. Два коротких: выключена. Три: нечего запускать.',
Expand Down
3 changes: 3 additions & 0 deletions src/renderer/src/i18n/tr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -585,6 +585,9 @@ export const tr: Messages = {
shortcut: 'Kumanda kısayolu',
shortcutHint:
'Yalıtımı koltuktan başlatmak veya durdurmak için bu düğmeleri 2 saniye basılı tutun. Hiçbir şey çalışmıyorsa, oyunu açık olan en son kullanılan profil başlar.',
alerts: 'Oyun ekranında kumanda uyarıları',
alertsHint:
'Oyuncunun kumandası koparsa, yeniden bağlanırsa ya da pili azalırsa oyun ekranında ve Windows bildiriminde kısa bir mesaj görünür.',
rumble: 'Başlatırken ve durdururken titreş',
rumbleHint: 'Bir uzun titreşim: yalıtım açık. İki kısa: kapalı. Üç: başlatılacak bir şey yok.',
overlay: 'FPS ve giriş gecikmesi',
Expand Down
Loading
Loading