Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[WIP]ウィンドウ情報の取得をポーリング方式からイベント駆動方式にする #44

Draft
wants to merge 8 commits into
base: master
Choose a base branch
from
1 change: 1 addition & 0 deletions electron-builder.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ directories:
files:
- '!**/.vscode/*'
- '!src/*'
- '!nativeSrc/*'
- '!electron.vite.config.{js,ts,mjs,cjs}'
- '!{.eslintignore,.eslintrc.cjs,.prettierignore,.prettierrc.yaml,dev-app-update.yml,CHANGELOG.md,README.md}'
- '!{.env,.env.*,.npmrc,pnpm-lock.yaml}'
Expand Down
107 changes: 0 additions & 107 deletions nativeSrc/helper.swift

This file was deleted.

50 changes: 45 additions & 5 deletions nativeSrc/taskbar.helper/main.swift
Original file line number Diff line number Diff line change
Expand Up @@ -86,8 +86,50 @@ func getWindowInfoListData() -> Data? {
}


class WindowObserver {
static let shared = WindowObserver()

private init() {}

// ウィンドウの変更を監視
func observeWindowChanges() {
let notificationCenter = NSWorkspace.shared.notificationCenter

// アクティブになるイベントの監視
notificationCenter.addObserver(
self,
selector: #selector(windowDidChange(notification:)),
name: NSWorkspace.didActivateApplicationNotification,
object: nil
)

// アプリケーションが起動されたイベントを監視
notificationCenter.addObserver(
self,
selector: #selector(windowDidChange(notification:)),
name: NSWorkspace.didLaunchApplicationNotification,
object: nil
)
}

@objc func windowDidChange(notification: NSNotification) {
// 非同期処理を開始
DispatchQueue.global(qos: .background).async {
// わずかに遅延させて非同期処理を実行
// これがないと開いたウィンドウの変更が反映されない
let delayTime = DispatchTime.now() + .milliseconds(500)

DispatchQueue.global(qos: .background).asyncAfter(deadline: delayTime) {
DispatchQueue.main.async {
if let data = getWindowInfoListData() {
let stdOut = FileHandle.standardOutput
stdOut.write(data)
}
}
}
}
}
}


let arguments = CommandLine.arguments
Expand All @@ -103,11 +145,9 @@ case "grant":
CGRequestScreenCaptureAccess()
case "list":

if let data = getWindowInfoListData() {
let stdOut = FileHandle.standardOutput
stdOut.write(data)
}
// ウィンドウの変更を監視
WindowObserver.shared.observeWindowChanges()
RunLoop.main.run()
default:
print("default")
}

Binary file modified resources/TaskbarHelper
Binary file not shown.
41 changes: 27 additions & 14 deletions src/main/funcs/helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,25 +14,38 @@ if (app.isPackaged) {

export const macWindowProcesses: MacWindow[] = []

export function getAndSubmitProcesses(): void {
export async function getAndSubmitProcesses(): Promise<void> {
let rawData = ''
try {
const taskbarHelper = spawn(binaryPath, ['list'])
taskbarHelper.stdout.on('data', (raw) => {
rawData += raw
})
taskbarHelper.stderr.on('data', (raw) => {
console.error(raw)
})
taskbarHelper.on('close', async (code) => {
if ((await code) === 0) {
const jsoned = JSON.parse(Buffer.from(rawData).toString('utf-8'))
applyProcessChange(jsoned)
rawData = ''

for await (const chunk of taskbarHelper.stdout) {
rawData += chunk.toString()
if (rawData.endsWith(']')) {
try {
const jsoned = JSON.parse(rawData)
await applyProcessChange(jsoned)
rawData = ''
} catch (parseError) {
console.error('Failed to parse JSON:', parseError)
rawData = '' // Reset rawData to avoid accumulating invalid data
}
}
}

taskbarHelper.stderr.on('data', (data) => {
console.error(`TaskbarHelper error: ${data.toString()}`)
})

await new Promise<void>((resolve) => {
taskbarHelper.on('close', (code) => {
console.log(`TaskbarHelper process exited with code ${code}`)
resolve()
})
})
} catch (e) {
console.log(e)
} catch (error) {
console.error('Error in getAndSubmitProcesses:', error);
throw error // Re-throw the error for upper-level error handling
}
}

Expand Down
6 changes: 2 additions & 4 deletions src/main/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,8 @@ app.whenReady().then(() => {
setEventHandlers()
})

// 1秒ごとにプロセスを取得する
setInterval(() => {
getAndSubmitProcesses()
}, 1000)
// プロセスを取得するプロセスを起動
getAndSubmitProcesses()

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
Expand Down