Skip to content

Commit 07a3d5a

Browse files
committed
fix
1 parent 361b3b6 commit 07a3d5a

4 files changed

Lines changed: 90 additions & 45 deletions

File tree

‎entry/src/main/ets/AbilityStage.ets‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,34 @@
44
* Extends WebAbilityStage from the web_engine module, which handles
55
* initializing the Electron 鸿蒙 native context (libadapter.so / libelectron.so)
66
* before any ability is created.
7+
*
8+
* On HarmonyOS, app.getPath('appData') does not work reliably in the
9+
* Electron runtime (SetContextPaths C++ binding has a race condition).
10+
* To work around this, we write the sandbox filesDir to a marker file
11+
* BEFORE the Electron runtime starts, so bootstrap.js can read it.
712
*/
813

914
import { WebAbilityStage } from 'web_engine';
15+
import fs from '@ohos.file.fs';
16+
17+
const TAG: string = 'ElectermAbilityStage';
1018

1119
export default class ElectermAbilityStage extends WebAbilityStage {
1220
onCreate(): void {
1321
super.onCreate();
22+
23+
// super.onCreate() schedules the Electron runtime start via setTimeout(0).
24+
// This synchronous code runs BEFORE that setTimeout fires, so the marker
25+
// file is guaranteed to exist when bootstrap.js loads.
26+
try {
27+
const filesDir: string = this.context.getApplicationContext().filesDir;
28+
const markerPath: string = `${filesDir}/.electerm-data-path`;
29+
const file = fs.openSync(markerPath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE | fs.OpenMode.TRUNC);
30+
fs.writeSync(file.fd, filesDir);
31+
fs.closeSync(file);
32+
console.info(`[${TAG}] wrote data path marker: ${markerPath} → ${filesDir}`);
33+
} catch (e) {
34+
console.error(`[${TAG}] failed to write data path marker: ${JSON.stringify(e)}`);
35+
}
1436
}
1537
}

‎scripts/build-app.sh‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -273,9 +273,10 @@ new_setpaths = ''' this.nativeThemeAdapter = Inject.get(NativeThemeAdapte
273273
content = content.replace(old_setpaths, new_setpaths)
274274
275275
if content == original:
276-
print(' ERROR: WebAbilityStage.ets pattern not found — file may already be patched or structure changed')
277-
print(' The SetContextPaths timing fix was NOT applied. app.getPath("appData") will fail at runtime.')
278-
sys.exit(1)
276+
print(' WARNING: WebAbilityStage.ets pattern not found — file may already be patched or structure changed')
277+
print(' The SetContextPaths timing fix was NOT applied, but this is non-fatal.')
278+
print(' bootstrap.js + AbilityStage.ets marker file handles the path issue.')
279+
sys.exit(0)
279280
280281
with open('${WEB_ABILITY_STAGE}', 'w') as f:
281282
f.write(content)

‎src/app/bootstrap.js‎

Lines changed: 61 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -1,52 +1,73 @@
11
/**
22
* bootstrap.js — HarmonyOS entry point.
33
*
4-
* On HarmonyOS, the Electron 鸿蒙 runtime starts the Node.js process before
5-
* the ArkTS layer has finished calling JsBindingUtils.SetContextPaths().
6-
* If app.js (which transitively loads app-props.js) is loaded too early,
7-
* app.getPath('appData') throws "Failed to get 'appData' path" and crashes
8-
* the main process.
4+
* On HarmonyOS, app.getPath('appData') does not work in the Electron runtime
5+
* due to a C++ binding issue (SetContextPaths is not effective). Instead,
6+
* AbilityStage.ets writes the sandbox filesDir to a marker file before the
7+
* Electron runtime starts. This file reads that marker and sets
8+
* process.env.DATA_PATH so all downstream modules (app-props.js, db.js, etc.)
9+
* use the correct sandbox path.
910
*
10-
* This bootstrap polls app.getPath('appData') until it succeeds, then loads
11-
* app.js. This guarantees that all downstream modules (db.js, ipc.js, etc.)
12-
* can safely call app.getPath() at module load time.
13-
*
14-
* On non-HarmonyOS platforms, app.getPath('appData') works immediately and
15-
* app.js is loaded without delay.
11+
* Path derivation:
12+
* __dirname = /data/storage/el1/bundle/entry/resources/resfile/resources/app
13+
* filesDir = /data/storage/el2/base/haps/entry/files
14+
* Transform: replace "/el1/bundle/" with "/el2/base/haps/", strip the
15+
* resources/resfile/... suffix, append "/files".
1616
*/
17-
const { app } = require('electron')
18-
19-
const POLL_INTERVAL = 50 // ms
20-
const MAX_WAIT = 10000 // 10 seconds
17+
const fs = require('fs')
18+
const path = require('path')
19+
const os = require('os')
2120

22-
function isPathReady () {
23-
try {
24-
app.getPath('appData')
25-
return true
26-
} catch {
27-
return false
21+
function deriveSandboxFilesDir () {
22+
// __dirname is like: /data/storage/el1/bundle/entry/resources/resfile/resources/app
23+
// sandbox filesDir is like: /data/storage/el2/base/haps/entry/files
24+
const m = __dirname.match(/^(.+?)\/el1\/bundle\/([^/]+)/)
25+
if (m) {
26+
return `${m[1]}/el2/base/haps/${m[2]}/files`
2827
}
28+
return null
2929
}
3030

31-
function startApp () {
32-
require('./app.js')
33-
}
31+
function getDataPath () {
32+
const derivedDir = deriveSandboxFilesDir()
33+
34+
if (derivedDir) {
35+
// 1. Try reading the marker file written by AbilityStage.ets
36+
const markerPath = path.join(derivedDir, '.electerm-data-path')
37+
try {
38+
const data = fs.readFileSync(markerPath, 'utf8').trim()
39+
if (data) {
40+
console.log('[bootstrap] got data path from marker file:', data)
41+
return data
42+
}
43+
} catch (e) {
44+
console.log('[bootstrap] marker file not found at', markerPath)
45+
}
3446

35-
if (isPathReady()) {
36-
startApp()
37-
} else {
38-
console.log('[bootstrap] waiting for app.getPath("appData") to become available...')
39-
const startTime = Date.now()
40-
const timer = setInterval(() => {
41-
if (isPathReady()) {
42-
clearInterval(timer)
43-
console.log(`[bootstrap] app.getPath("appData") ready after ${Date.now() - startTime}ms`)
44-
startApp()
45-
} else if (Date.now() - startTime > MAX_WAIT) {
46-
clearInterval(timer)
47-
console.error(`[bootstrap] timed out after ${MAX_WAIT}ms waiting for app.getPath("appData")`)
48-
// Start anyway — app-props.js has a try/catch fallback
49-
startApp()
47+
// 2. Marker not found — try the derived path directly
48+
try {
49+
fs.mkdirSync(derivedDir, { recursive: true })
50+
console.log('[bootstrap] using derived sandbox path:', derivedDir)
51+
return derivedDir
52+
} catch (e) {
53+
console.warn('[bootstrap] derived path not writable:', derivedDir, e.message)
5054
}
51-
}, POLL_INTERVAL)
55+
}
56+
57+
// 3. Last resort: try app.getPath('appData')
58+
try {
59+
const { app } = require('electron')
60+
const p = app.getPath('appData')
61+
console.log('[bootstrap] using app.getPath("appData"):', p)
62+
return p
63+
} catch (e) {
64+
console.warn('[bootstrap] app.getPath("appData") failed:', e.message)
65+
}
66+
67+
// 4. Final fallback
68+
console.warn('[bootstrap] falling back to os.tmpdir():', os.tmpdir())
69+
return os.tmpdir()
5270
}
71+
72+
process.env.DATA_PATH = getDataPath()
73+
require('./app.js')

‎src/app/common/app-props.js‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,13 @@
33
*
44
* On HarmonyOS, appData (filesDir) serves as both the app data directory
55
* and the home directory. There is no separate home concept or portable mode.
6+
*
7+
* bootstrap.js sets process.env.DATA_PATH before loading app.js.
68
*/
7-
const { app } = require('electron')
89
const { resolve } = require('path')
910
const constants = require('./runtime-constants')
1011

11-
const appDataPath = app.getPath('appData')
12+
const appDataPath = process.env.DATA_PATH
1213

1314
module.exports = {
1415
appPath: appDataPath,

0 commit comments

Comments
 (0)