Skip to content

Commit

Permalink
Windows auto stop / auto start steam working
Browse files Browse the repository at this point in the history
  • Loading branch information
cbartondock committed Jun 7, 2024
1 parent 48e41ba commit f32a780
Show file tree
Hide file tree
Showing 5 changed files with 140 additions and 7 deletions.
1 change: 1 addition & 0 deletions src/lib/helpers/steam/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,4 @@ export * from './get-multiple-available-logins';
export * from './get-non-steam-shortcut-data';
export * from './steam-id-64-to-account-id';
export * from './image-extensions';
export * from './stop-start-steam';
107 changes: 107 additions & 0 deletions src/lib/helpers/steam/stop-start-steam.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
import { spawn, execSync } from "child_process";
import * as os from "os";

const checkDelay = 500;
const timeout = 5000;

interface ActAndCheck {
commands: {
action: string,
check: string,
},
messages: {
prefix: string,
success: string,
failure: string,
precheckPassed: string
},
checkOutput: string,
shell: string
}

async function actAndCheck(data: ActAndCheck) {
return await new Promise<{acted: boolean, messages: string[]}>((resolve, reject)=> {
let messages: string[] = [];
const precheck = execSync(data.commands.check, {shell: data.shell}).toString().trim();
if(precheck == data.checkOutput) {
resolve({acted: false, messages: [data.messages.precheckPassed]})
} else {
const proc = spawn(data.commands.action, {shell: data.shell});
proc.stdout.on('data', (procData) => {
messages.push(`${data.messages.prefix}: ${procData.toString('utf8')}`)
})
proc.stderr.on('data', (data) => {
reject(data.toString('utf8'))
})
proc.on('close', () => {
let elapsed = 0;
const interval: NodeJS.Timer = setInterval(() => {
const check = execSync(data.commands.check, {shell: data.shell}).toString().trim()
if(check == data.checkOutput){
messages.push(data.messages.success.interpolate({elapsed}))
clearTimeout(interval)
resolve({acted: true, messages: messages});
}
if(elapsed > timeout) {
reject(data.messages.failure.interpolate({timeout}))
clearTimeout(interval)
}
elapsed += checkDelay;
}, checkDelay)
})
}
})
}

// try to kill steam
export async function stopSteam() {

This comment has been minimized.

Copy link
@doZennn

doZennn Jun 7, 2024

Member

Any reason -shutdown or steam://exit isn't just used instead?

let data: ActAndCheck = {
commands: null,
messages: {
prefix: "Killing Steam",
success: "Killed Steam after ${elapsed}ms.",
failure: "Failed to kill Steam within ${timeout}ms.",
precheckPassed: "Steam is not running, no need to kill it."
},
checkOutput: 'True',
shell: 'powershell'
}
if (os.type() == 'Windows_NT') {
data.commands = {
action: `wmic process where "name='steam.exe'" delete`,
check: `(Get-Process steam -ErrorAction SilentlyContinue) -eq $null`
}
} else if (os.type() == 'Linux') {
data.commands = {
action: `killall steam`,
check: `echo "True"`
}
}
return await actAndCheck(data);
}

export async function startSteam() {
let data: ActAndCheck = {
commands: null,
messages: {
prefix: "Starting Steam",
success: "Started Steam after ${elapsed}ms.",
failure: "Failed to start Steam within ${timeout}ms.",
precheckPassed: "Steam is already running, no need to start it."
},
checkOutput: 'True',
shell: 'powershell'
};
if (os.type() == 'Windows_NT') {
data.commands = {
action: "Start-Process -WindowStyle Minimized ${env:PROGRAMFILES(x86)}\\Steam\\steam.exe -ArgumentList \"-silent\"",
check: `(Get-Process steam -ErrorAction SilentlyContinue) -ne $null`
}
} else if (os.type() == 'Linux') {
data.commands = {
action: `start steam`,
check: `echo "True"`
}
}
return await actAndCheck(data)
}
5 changes: 4 additions & 1 deletion src/renderer/components/view.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ export class ViewComponent {
filterValue: string = '';
currentArtwork: {[artworkType: string]: string};
currentControllers:{[controllerType: string]: any} = {}
refreshingGames: boolean = false;
constructor(
private router: Router,
private activatedRoute: ActivatedRoute,
Expand Down Expand Up @@ -60,10 +61,12 @@ export class ViewComponent {
if(force) {
this.loggerService.info('Reading Shortcuts, Categories, and Controllers', {invokeAlert: true, alertTimeout: 3000})
}
if(!this.viewService.vdfData || force) {
if((!this.viewService.vdfData || force) && !this.refreshingGames) {
this.refreshingGames=true;
this.renderer.setStyle(this.elementRef.nativeElement, '--view-details-width', '0%', RendererStyleFlags2.DashCase);
this.currentShortcut = null;
await this.viewService.refreshGames();
this.refreshingGames=false;
}
this.changeDetectionRef.detectChanges();
}
Expand Down
18 changes: 15 additions & 3 deletions src/renderer/services/preview.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,13 @@ export class PreviewService {

async removeCategories(steamDir: string, userId: string) {
try {
const stop = await steam.stopSteam();
for(let message of stop.messages) { this.loggerService.info(message) }
await this.categoryManager.removeAllCategoriesAndWrite(steamDir, userId);
if(stop.acted) {
const start= await steam.startSteam();
for(let message of start.messages) { this.loggerService.info(message) }
}
} catch(error) {
this.loggerService.error(this.lang.errors.categorySaveError, { invokeAlert: true, alertTimeout: 3000 });
this.loggerService.error(this.lang.errors.categorySaveError__i.interpolate({error:error.message}));
Expand Down Expand Up @@ -216,10 +222,16 @@ export class PreviewService {
exAppIds = extraneousAppIds; //Non artwork-only extraneous app ids
addedCats = addedCategories; //Added categories for all app ids
})
.then(() => {
this.loggerService.info(this.lang.info.savingCategories)
.then(async () => {
if(!removeAll && !this.appSettings.previewSettings.disableCategories) {
return this.categoryManager.save(this.previewData, exAppIds, addedCats)
const stop = await steam.stopSteam();
for(let message of stop.messages) { this.loggerService.info(message) }
this.loggerService.info(this.lang.info.savingCategories)
await this.categoryManager.save(this.previewData, exAppIds, addedCats)
if(stop.acted) {
const start= await steam.startSteam();
for(let message of start.messages) { this.loggerService.info(message) }
}
}
}).catch((error: Acceptable_Error | Error) => {
if(error instanceof Acceptable_Error) {
Expand Down
16 changes: 13 additions & 3 deletions src/renderer/services/view.service.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Injectable } from '@angular/core';
import { ParsersService } from '../services';
import { LoggerService, ParsersService } from '../services';
import { VDF_ListData, ControllerTemplates, ControllerTemplate, SteamList, VDF_ListItem, SteamDirList } from '../../models';
import * as _ from "lodash";
import {
Expand All @@ -9,7 +9,7 @@ import {
} from "../../lib";
import { controllerTypes } from '../../lib/controller-manager';
import { BehaviorSubject } from 'rxjs';

import * as steam from '../../lib/helpers/steam';

@Injectable()
export class ViewService {
Expand All @@ -34,7 +34,9 @@ export class ViewService {
refreshingDetails: new BehaviorSubject(false)
}
constructor(
private parsersService: ParsersService) {
private parsersService: ParsersService,
private loggerService: LoggerService
) {
}

private clearData() {
Expand All @@ -56,6 +58,8 @@ export class ViewService {
await vdfManager.read({ addedItems: false });
this.vdfData = vdfManager.vdfData;
this.status.refreshingShortcuts.next(false);
const stop = await steam.stopSteam();
for(let message of stop.messages) { this.loggerService.info(message) }
for(const steamDirectory in this.vdfData) {
this.categoryData[steamDirectory] = {};
this.controllerData[steamDirectory] = {};
Expand All @@ -75,6 +79,12 @@ export class ViewService {
this.controllerTemplateData[steamDirectory][controllerType] = await ControllerManager.readTemplates(steamDirectory, controllerType)
}
}
if(stop.acted) {
const start= await steam.startSteam();
for(let message of start.messages) { this.loggerService.info(message) }
}

await steam.startSteam();
this.status.refreshingDetails.next(false);
}
}

0 comments on commit f32a780

Please sign in to comment.