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
27 changes: 27 additions & 0 deletions src/main/services/automation-service.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -238,6 +238,33 @@ describe('AutomationService', () => {
expect(await t.automation.toggle(3)).toBe('stopped')
})

it('starts a second copy of the same game for the other player', async () => {
const t = await setup([win(50, 'hollow_knight.exe')], true)
t.backend.handlers.listControllers = () => ({
controllers: [0, 1, 2].map((slot) => ({ slot, connected: slot !== 1 })),
})
t.backend.handlers.listDisplays = () => ({
displays: [
{ id: '\\\\.\\DISPLAY1', isPrimary: true },
{ id: '\\\\.\\DISPLAY3', isPrimary: false },
{ id: '\\\\.\\DISPLAY4', isPrimary: false },
],
})
const knight = await t.profiles.save({ ...profileInput, controllerSlot: 0 })
await t.automation.play(knight.id, false)
t.launch.mockImplementation(async () => {
t.state.windows = [...t.state.windows, win(70, 'hollow_knight.exe')]
})
await t.automation.play(knight.id, true)
expect(t.launch).toHaveBeenCalledTimes(1)
expect(t.seats.get(1)).toMatchObject({
phase: 'running',
target: { pid: 70 },
controllerSlot: 2,
displayId: '\\\\.\\DISPLAY4',
})
})

it('refuses two games on the same controller', async () => {
const t = await setup([win(50, 'hollow_knight.exe'), win(60, 'celeste.exe')], true)
const knight = await t.profiles.save({ ...profileInput, controllerSlot: 0 })
Expand Down
49 changes: 46 additions & 3 deletions src/main/services/automation-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@
* - the controller shortcut: stop the pressing player's isolation, or start the most recent
* profile whose game is open.
*
* With "Two players" on, each of these takes the first free seat.
* With "Two players" on, each of these takes the first free seat. "Play" on a profile whose
* game the other player already plays starts a second copy, with a free controller and screen.
*
* Each game process is started automatically at most once: after the user stops it, the
* same process is left alone until it exits.
Expand All @@ -16,6 +17,7 @@ import { spawn } from 'node:child_process'
import { dirname } from 'node:path'
import type {
AutomationState,
IsolationView,
Profile,
Seat,
StartIsolationInput,
Expand Down Expand Up @@ -187,6 +189,10 @@ export class AutomationService {
}

const run = ++this.run
const others = seats.all().filter(isSeatTaken)
const exe = profile.exeName.toLowerCase()
const secondCopy = others.some((v) => v.target?.exeName.toLowerCase() === exe)
const placed = secondCopy ? await this.placeSecondCopy(profile, others) : profile
let window = await this.findWindow(profile.exeName)
if (window === null) {
if (!launch) {
Expand Down Expand Up @@ -214,10 +220,37 @@ export class AutomationService {
if (run !== this.run) return // cancelled
if (window === null) {
this.setIdle()
if (secondCopy) {
throw new AppException('secondCopyTimeout', 'The game did not open a second copy.')
}
throw new AppException('launchTimeout', 'The game window did not appear in time.')
}
}
await this.startFor(profile, window)
await this.startFor(placed, window)
}

/**
* The second copy of a game gets the profile's controller and screen unless the other
* player already has them; then a free connected controller and a free secondary screen.
*/
private async placeSecondCopy(profile: Profile, others: IsolationView[]): Promise<Profile> {
const { backend } = this.options
const usedSlots = new Set(others.map((v) => v.controllerSlot))
const usedDisplays = new Set(others.map((v) => v.displayId))
let controllerSlot = profile.controllerSlot
if (controllerSlot === null || usedSlots.has(controllerSlot)) {
const { controllers } = await backend.request('listControllers', {})
controllerSlot = controllers.find((c) => c.connected && !usedSlots.has(c.slot))?.slot ?? null
if (controllerSlot === null) {
throw new AppException('noFreeController', 'Connect a controller for the second player.')
}
}
let displayId = profile.displayId
if (displayId !== null && usedDisplays.has(displayId)) {
const { displays } = await backend.request('listDisplays', {})
displayId = displays.find((d) => !d.isPrimary && !usedDisplays.has(d.id))?.id ?? null
}
return { ...profile, controllerSlot, displayId }
}

/** Stops waiting for a launched game (the game itself keeps running); clears an error. */
Expand Down Expand Up @@ -372,8 +405,18 @@ export class AutomationService {
return null
}

/** The game's window, skipping copies another player already plays. */
private async findWindow(exeName: string): Promise<WindowInfo | null> {
return bestWindow(await this.listWindows(), exeName)
const taken = new Set(
this.options.seats
.all()
.filter(isSeatTaken)
.map((v) => v.target?.pid),
)
return bestWindow(
(await this.listWindows()).filter((w) => !taken.has(w.pid)),
exeName,
)
}

private async listWindows(): Promise<WindowInfo[]> {
Expand Down
5 changes: 5 additions & 0 deletions src/renderer/src/i18n/de.ts
Original file line number Diff line number Diff line change
Expand Up @@ -276,6 +276,9 @@ export const de: Messages = {
noExePath: 'Dieses Profil weiß nicht, wo das Spiel liegt. Wähle die Spieldatei im Profil aus.',
launchFailed: 'Das Spiel konnte nicht gestartet werden. Prüfe die Spieldatei im Profil.',
launchTimeout: 'Das Spielfenster ist nicht rechtzeitig erschienen.',
secondCopyTimeout:
'Das Spiel hat keine zweite Kopie geöffnet. Manche Spiele erlauben nur eine Kopie gleichzeitig.',
noFreeController: 'Kein freier Controller für den zweiten Spieler. Schließe einen weiteren an.',
updateUnavailable: 'Es ist kein Update zur Installation bereit.',
updateDevBuild: 'Updates werden nur in der installierten App installiert.',
updateFailed: 'Das Update konnte nicht heruntergeladen werden. Versuche es später erneut.',
Expand Down Expand Up @@ -711,6 +714,8 @@ export const de: Messages = {
player: 'Spieler {n}',
noGame: 'Kein Spiel gewählt',
twoPlayers: 'Zwei Spieler',
sameGameHint:
'Dasselbe Spiel für beide: Drücke im Profil erneut auf Spielen. InputSplit startet eine zweite Kopie für den anderen Spieler, mit freiem Controller und Bildschirm (wenn das Spiel zwei Kopien erlaubt).',
twoPlayersHint:
'Zwei Spiele gleichzeitig, jedes mit eigenem Controller. Die Übersicht zeigt einen Tab pro Spieler.',
},
Expand Down
5 changes: 5 additions & 0 deletions src/renderer/src/i18n/en.ts
Original file line number Diff line number Diff line change
Expand Up @@ -271,6 +271,9 @@ export const en = {
noExePath: 'This profile does not know where the game is. Choose the game file in the profile.',
launchFailed: 'The game could not be started. Check the game file in the profile.',
launchTimeout: 'The game window did not appear in time.',
secondCopyTimeout:
'The game did not open a second copy. Some games allow only one copy at a time.',
noFreeController: 'No free controller for the second player. Connect another controller.',
updateUnavailable: 'No update is ready to install.',
updateDevBuild: 'Updates install only in the installed app.',
updateFailed: 'The update could not be downloaded. Try again later.',
Expand Down Expand Up @@ -695,6 +698,8 @@ export const en = {
player: 'Player {n}',
noGame: 'No game chosen',
twoPlayers: 'Two players',
sameGameHint:
'Same game for both: press Play on its profile again. InputSplit starts a second copy for the other player, with a free controller and screen (if the game allows two copies).',
twoPlayersHint:
'Two games at once, each with its own controller. The dashboard shows a tab for each player.',
},
Expand Down
5 changes: 5 additions & 0 deletions src/renderer/src/i18n/es.ts
Original file line number Diff line number Diff line change
Expand Up @@ -275,6 +275,9 @@ export const es: Messages = {
noExePath: 'Este perfil no sabe dónde está el juego. Elige el archivo del juego en el perfil.',
launchFailed: 'No se pudo iniciar el juego. Revisa el archivo del juego en el perfil.',
launchTimeout: 'La ventana del juego no apareció a tiempo.',
secondCopyTimeout:
'El juego no abrió una segunda copia. Algunos juegos solo permiten una copia a la vez.',
noFreeController: 'No hay un mando libre para el segundo jugador. Conecta otro.',
updateUnavailable: 'No hay ninguna actualización lista para instalar.',
updateDevBuild: 'Las actualizaciones solo se instalan en la aplicación instalada.',
updateFailed: 'No se pudo descargar la actualización. Inténtalo más tarde.',
Expand Down Expand Up @@ -710,6 +713,8 @@ export const es: Messages = {
player: 'Jugador {n}',
noGame: 'Ningún juego elegido',
twoPlayers: 'Dos jugadores',
sameGameHint:
'El mismo juego para los dos: pulsa Jugar en su perfil otra vez. InputSplit abre una segunda copia para el otro jugador, con un mando y una pantalla libres (si el juego permite dos copias).',
twoPlayersHint:
'Dos juegos a la vez, cada uno con su propio mando. El panel muestra una pestaña por jugador.',
},
Expand Down
5 changes: 5 additions & 0 deletions src/renderer/src/i18n/fr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -275,6 +275,9 @@ export const fr: Messages = {
'Ce profil ne sait pas où se trouve le jeu. Choisissez le fichier du jeu dans le profil.',
launchFailed: 'Impossible de lancer le jeu. Vérifiez le fichier du jeu dans le profil.',
launchTimeout: "La fenêtre du jeu n'est pas apparue à temps.",
secondCopyTimeout:
'Le jeu n’a pas ouvert de deuxième copie. Certains jeux n’autorisent qu’une copie à la fois.',
noFreeController: 'Aucune manette libre pour le deuxième joueur. Branchez-en une autre.',
updateUnavailable: "Aucune mise à jour n'est prête à être installée.",
updateDevBuild: "Les mises à jour ne s'installent que dans l'application installée.",
updateFailed: 'Impossible de télécharger la mise à jour. Réessayez plus tard.',
Expand Down Expand Up @@ -712,6 +715,8 @@ export const fr: Messages = {
player: 'Joueur {n}',
noGame: 'Aucun jeu choisi',
twoPlayers: 'Deux joueurs',
sameGameHint:
'Le même jeu pour les deux : appuyez encore sur Jouer dans son profil. InputSplit lance une deuxième copie pour l’autre joueur, avec une manette et un écran libres (si le jeu autorise deux copies).',
twoPlayersHint:
'Deux jeux en même temps, chacun avec sa manette. Le tableau de bord affiche un onglet par joueur.',
},
Expand Down
6 changes: 6 additions & 0 deletions src/renderer/src/i18n/ja.ts
Original file line number Diff line number Diff line change
Expand Up @@ -277,6 +277,10 @@ export const ja: Messages = {
'このプロファイルにはゲームの場所が設定されていません。プロファイルでゲームのファイルを選択してください。',
launchFailed: 'ゲームを起動できませんでした。プロファイルのゲームファイルを確認してください。',
launchTimeout: 'ゲームのウィンドウが時間内に表示されませんでした。',
secondCopyTimeout:
'ゲームの2つ目のコピーが開きませんでした。同時に1つしか起動できないゲームもあります。',
noFreeController:
'2人目のプレイヤー用の空いているコントローラーがありません。もう1台接続してください。',
updateUnavailable: 'インストールできるアップデートはありません。',
updateDevBuild: 'アップデートはインストール版のアプリでのみインストールできます。',
updateFailed: 'アップデートをダウンロードできませんでした。後でもう一度お試しください。',
Expand Down Expand Up @@ -708,6 +712,8 @@ export const ja: Messages = {
player: 'プレイヤー {n}',
noGame: 'ゲーム未選択',
twoPlayers: '2人プレイ',
sameGameHint:
'2人で同じゲーム:そのプロファイルの「プレイ」をもう一度押してください。InputSplit がもう1人のプレイヤー用に、空いているコントローラーと画面で2つ目のコピーを起動します(ゲームが2つの起動を許す場合)。',
twoPlayersHint:
'2つのゲームを同時に、それぞれ専用のコントローラーで。ダッシュボードにプレイヤーごとのタブが表示されます。',
},
Expand Down
5 changes: 5 additions & 0 deletions src/renderer/src/i18n/pl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -269,6 +269,9 @@ export const pl: Messages = {
noExePath: 'Ten profil nie wie, gdzie jest gra. Wybierz plik gry w profilu.',
launchFailed: 'Nie udało się uruchomić gry. Sprawdź plik gry w profilu.',
launchTimeout: 'Okno gry nie pojawiło się na czas.',
secondCopyTimeout:
'Gra nie otworzyła drugiej kopii. Niektóre gry pozwalają tylko na jedną kopię naraz.',
noFreeController: 'Brak wolnego pada dla drugiego gracza. Podłącz kolejny.',
updateUnavailable: 'Żadna aktualizacja nie jest gotowa do instalacji.',
updateDevBuild: 'Aktualizacje instalują się tylko w zainstalowanej aplikacji.',
updateFailed: 'Nie udało się pobrać aktualizacji. Spróbuj później.',
Expand Down Expand Up @@ -697,6 +700,8 @@ export const pl: Messages = {
player: 'Gracz {n}',
noGame: 'Nie wybrano gry',
twoPlayers: 'Dwóch graczy',
sameGameHint:
'Ta sama gra dla obu: naciśnij ponownie Graj w jej profilu. InputSplit uruchomi drugą kopię dla drugiego gracza, z wolnym padem i ekranem (jeśli gra pozwala na dwie kopie).',
twoPlayersHint:
'Dwie gry naraz, każda z własnym kontrolerem. Panel pokazuje kartę dla każdego gracza.',
},
Expand Down
5 changes: 5 additions & 0 deletions src/renderer/src/i18n/pt-BR.ts
Original file line number Diff line number Diff line change
Expand Up @@ -271,6 +271,9 @@ export const ptBR: Messages = {
noExePath: 'Este perfil não sabe onde está o jogo. Escolha o arquivo do jogo no perfil.',
launchFailed: 'Não foi possível iniciar o jogo. Verifique o arquivo do jogo no perfil.',
launchTimeout: 'A janela do jogo não apareceu a tempo.',
secondCopyTimeout:
'O jogo não abriu uma segunda cópia. Alguns jogos permitem só uma cópia por vez.',
noFreeController: 'Não há controle livre para o segundo jogador. Conecte outro.',
updateUnavailable: 'Nenhuma atualização está pronta para instalar.',
updateDevBuild: 'As atualizações só são instaladas no aplicativo instalado.',
updateFailed: 'Não foi possível baixar a atualização. Tente novamente mais tarde.',
Expand Down Expand Up @@ -701,6 +704,8 @@ export const ptBR: Messages = {
player: 'Jogador {n}',
noGame: 'Nenhum jogo escolhido',
twoPlayers: 'Dois jogadores',
sameGameHint:
'O mesmo jogo para os dois: aperte Jogar no perfil dele de novo. O InputSplit abre uma segunda cópia para o outro jogador, com controle e tela livres (se o jogo permitir duas cópias).',
twoPlayersHint:
'Dois jogos ao mesmo tempo, cada um com seu próprio controle. O painel mostra uma aba por jogador.',
},
Expand Down
5 changes: 5 additions & 0 deletions src/renderer/src/i18n/ru.ts
Original file line number Diff line number Diff line change
Expand Up @@ -266,6 +266,9 @@ export const ru: Messages = {
noExePath: 'Профиль не знает, где находится игра. Выберите файл игры в профиле.',
launchFailed: 'Не удалось запустить игру. Проверьте файл игры в профиле.',
launchTimeout: 'Окно игры не появилось вовремя.',
secondCopyTimeout:
'Вторая копия игры не открылась. Некоторые игры разрешают только одну копию.',
noFreeController: 'Нет свободного геймпада для второго игрока. Подключите ещё один.',
updateUnavailable: 'Нет обновления, готового к установке.',
updateDevBuild: 'Обновления устанавливаются только в установленном приложении.',
updateFailed: 'Не удалось скачать обновление. Попробуйте позже.',
Expand Down Expand Up @@ -693,6 +696,8 @@ export const ru: Messages = {
player: 'Игрок {n}',
noGame: 'Игра не выбрана',
twoPlayers: 'Два игрока',
sameGameHint:
'Одна игра на двоих: нажмите «Играть» в её профиле ещё раз. InputSplit запустит вторую копию для другого игрока со свободным геймпадом и экраном (если игра разрешает две копии).',
twoPlayersHint:
'Две игры одновременно, у каждой свой контроллер. На главной появится вкладка для каждого игрока.',
},
Expand Down
5 changes: 5 additions & 0 deletions src/renderer/src/i18n/tr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -267,6 +267,9 @@ export const tr: Messages = {
noExePath: 'Bu profil oyunun nerede olduğunu bilmiyor. Profilde oyun dosyasını seçin.',
launchFailed: 'Oyun başlatılamadı. Profildeki oyun dosyasını kontrol edin.',
launchTimeout: 'Oyun penceresi zamanında açılmadı.',
secondCopyTimeout:
'Oyun ikinci bir kopya açmadı. Bazı oyunlar aynı anda yalnızca bir kopyaya izin verir.',
noFreeController: 'İkinci oyuncu için boş kumanda yok. Bir kumanda daha bağlayın.',
updateUnavailable: 'Yüklenmeye hazır bir güncelleme yok.',
updateDevBuild: 'Güncellemeler yalnızca yüklü uygulamada kurulur.',
updateFailed: 'Güncelleme indirilemedi. Daha sonra tekrar deneyin.',
Expand Down Expand Up @@ -695,6 +698,8 @@ export const tr: Messages = {
player: 'Oyuncu {n}',
noGame: 'Oyun seçilmedi',
twoPlayers: 'İki oyuncu',
sameGameHint:
"İkisi için aynı oyun: profilinde Oyna'ya tekrar basın. InputSplit diğer oyuncu için boş bir kumanda ve ekranla ikinci bir kopya başlatır (oyun iki kopyaya izin veriyorsa).",
twoPlayersHint:
'Aynı anda iki oyun, her biri kendi kontrolcüsüyle. Panelde her oyuncu için bir sekme görünür.',
},
Expand Down
4 changes: 4 additions & 0 deletions src/renderer/src/i18n/uk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -266,6 +266,8 @@ export const uk: Messages = {
noExePath: 'Профіль не знає, де розташована гра. Виберіть файл гри в профілі.',
launchFailed: 'Не вдалося запустити гру. Перевірте файл гри в профілі.',
launchTimeout: 'Вікно гри не з’явилося вчасно.',
secondCopyTimeout: 'Друга копія гри не відкрилася. Деякі ігри дозволяють лише одну копію.',
noFreeController: 'Немає вільного геймпада для другого гравця. Підключіть ще один.',
updateUnavailable: 'Немає оновлення, готового до встановлення.',
updateDevBuild: 'Оновлення встановлюються лише у встановленому застосунку.',
updateFailed: 'Не вдалося завантажити оновлення. Спробуйте пізніше.',
Expand Down Expand Up @@ -691,6 +693,8 @@ export const uk: Messages = {
player: 'Гравець {n}',
noGame: 'Гру не вибрано',
twoPlayers: 'Два гравці',
sameGameHint:
'Одна гра на двох: натисніть «Грати» в її профілі ще раз. InputSplit запустить другу копію для іншого гравця з вільним геймпадом та екраном (якщо гра дозволяє дві копії).',
twoPlayersHint:
'Дві гри одночасно, у кожної свій контролер. На головній зʼявиться вкладка для кожного гравця.',
},
Expand Down
4 changes: 4 additions & 0 deletions src/renderer/src/i18n/zh-CN.ts
Original file line number Diff line number Diff line change
Expand Up @@ -253,6 +253,8 @@ export const zhCN: Messages = {
noExePath: '此配置不知道游戏的位置。请在配置中选择游戏文件。',
launchFailed: '无法启动游戏。请检查配置中的游戏文件。',
launchTimeout: '游戏窗口未能及时出现。',
secondCopyTimeout: '游戏没有打开第二个副本。有些游戏同一时间只允许运行一个。',
noFreeController: '没有空闲的手柄给第二位玩家。请再连接一个。',
updateUnavailable: '没有可安装的更新。',
updateDevBuild: '更新只能在已安装的应用中安装。',
updateFailed: '无法下载更新,请稍后重试。',
Expand Down Expand Up @@ -663,6 +665,8 @@ export const zhCN: Messages = {
player: '玩家 {n}',
noGame: '未选择游戏',
twoPlayers: '双人模式',
sameGameHint:
'两人玩同一个游戏:在它的配置中再次点击“开始游戏”。InputSplit 会为另一位玩家启动第二个副本,并使用空闲的手柄和屏幕(前提是游戏允许运行两个)。',
twoPlayersHint: '同时运行两个游戏,各用自己的手柄。主页会为每位玩家显示一个标签页。',
},
library: {
Expand Down
Loading
Loading