diff --git a/entry/src/main/ets/common/BackgroundKeepAlive.ts b/entry/src/main/ets/common/BackgroundKeepAlive.ts new file mode 100644 index 0000000..17873b4 --- /dev/null +++ b/entry/src/main/ets/common/BackgroundKeepAlive.ts @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2026 Haven for HarmonyOS contributors. + * Port of Haven by GlassHaven (AGPL-3.0). See LICENSE. + * + * T12: continuous DATA_TRANSFER background task so live SSH sessions + * survive while the app is backgrounded (plan §6). The task starts with + * the first READY session and stops when none remain; deduped internally + * so callers can call start()/stop() on every state change. + */ + +import { backgroundTaskManager } from '@kit.BackgroundTasksKit'; +import { common, wantAgent } from '@kit.AbilityKit'; +import type { WantAgent } from '@kit.AbilityKit'; +import { Log } from './Log'; + +const BUNDLE_NAME: string = 'sh.haven.harmony'; + +export class BackgroundKeepAlive { + private static readonly TAG: string = 'BackgroundKeepAlive'; + private static active: boolean = false; + private static pending: boolean = false; + + /** True when the continuous task is held. */ + static isActive(): boolean { + return BackgroundKeepAlive.active; + } + + /** Request the DATA_TRANSFER continuous task (idempotent). */ + static start(context: common.Context): void { + if (BackgroundKeepAlive.active || BackgroundKeepAlive.pending) { + return; + } + BackgroundKeepAlive.pending = true; + const info: wantAgent.WantAgentInfo = { + wants: [{ bundleName: BUNDLE_NAME }], + requestCode: 0 + }; + wantAgent.getWantAgent(info) + .then((agent: WantAgent): Promise => { + return backgroundTaskManager.startBackgroundRunning( + context, backgroundTaskManager.BackgroundMode.DATA_TRANSFER, agent); + }) + .then((): void => { + BackgroundKeepAlive.active = true; + Log.info(BackgroundKeepAlive.TAG, 'dataTransfer task started'); + }) + .catch((e: Object): void => { + Log.warn(BackgroundKeepAlive.TAG, `start failed: ${(e as Error).message}`); + }) + .finally((): void => { + BackgroundKeepAlive.pending = false; + }); + } + + /** Release the continuous task (idempotent). */ + static stop(context: common.Context): void { + if (!BackgroundKeepAlive.active || BackgroundKeepAlive.pending) { + return; + } + backgroundTaskManager.stopBackgroundRunning(context) + .then((): void => { + BackgroundKeepAlive.active = false; + Log.info(BackgroundKeepAlive.TAG, 'dataTransfer task stopped'); + }) + .catch((e: Object): void => { + Log.warn(BackgroundKeepAlive.TAG, `stop failed: ${(e as Error).message}`); + }); + } +} diff --git a/entry/src/main/ets/entryability/EntryAbility.ets b/entry/src/main/ets/entryability/EntryAbility.ets index cb48473..a14e02a 100644 --- a/entry/src/main/ets/entryability/EntryAbility.ets +++ b/entry/src/main/ets/entryability/EntryAbility.ets @@ -1,63 +1,70 @@ /* - * Copyright (c) 2026 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * Copyright (c) 2026 Haven for HarmonyOS contributors. + * Port of Haven by GlassHaven (AGPL-3.0). See LICENSE. */ import { AbilityConstant, ConfigurationConstant, UIAbility, Want } from '@kit.AbilityKit'; import { hilog } from '@kit.PerformanceAnalysisKit'; import { window } from '@kit.ArkUI'; +import { SettingsRepository } from '../data/SettingsRepository'; const DOMAIN = 0x0000; +const TAG = 'Haven'; export default class EntryAbility extends UIAbility { onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void { try { this.context.getApplicationContext().setColorMode(ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET); } catch (err) { - hilog.error(DOMAIN, 'testTag', 'Failed to set colorMode. Cause: %{public}s', JSON.stringify(err)); + hilog.error(DOMAIN, 'Haven', 'Failed to set colorMode. Cause: %{public}s', JSON.stringify(err)); } - hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onCreate'); + hilog.info(DOMAIN, 'Haven', '%{public}s', 'Ability onCreate'); } onDestroy(): void { - hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onDestroy'); + hilog.info(DOMAIN, 'Haven', '%{public}s', 'Ability onDestroy'); } onWindowStageCreate(windowStage: window.WindowStage): void { // Main window is created, set main page for this ability - hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onWindowStageCreate'); + hilog.info(DOMAIN, 'Haven', 'Ability onWindowStageCreate'); + + // Keep-screen-on is a window-level flag: apply the persisted setting + // as soon as the main window exists (plan §5 SettingsPage / §6). + try { + if (SettingsRepository.getInstance(this.context).getKeepScreenOn()) { + windowStage.getMainWindow() + .then((win: window.Window): Promise => { + return win.setWindowKeepScreenOn(true); + }) + .catch((): void => { + }); + } + } catch (err) { + hilog.warn(DOMAIN, 'Haven', 'apply keep-screen-on failed: %{public}s', JSON.stringify(err)); + } windowStage.loadContent('pages/Index', (err) => { if (err.code) { - hilog.error(DOMAIN, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err)); + hilog.error(DOMAIN, 'Haven', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err)); return; } - hilog.info(DOMAIN, 'testTag', 'Succeeded in loading the content.'); + hilog.info(DOMAIN, 'Haven', 'Succeeded in loading the content.'); }); } onWindowStageDestroy(): void { // Main window is destroyed, release UI related resources - hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onWindowStageDestroy'); + hilog.info(DOMAIN, 'Haven', '%{public}s', 'Ability onWindowStageDestroy'); } onForeground(): void { // Ability has brought to foreground - hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onForeground'); + hilog.info(DOMAIN, 'Haven', '%{public}s', 'Ability onForeground'); } onBackground(): void { // Ability has back to background - hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onBackground'); + hilog.info(DOMAIN, 'Haven', '%{public}s', 'Ability onBackground'); } } \ No newline at end of file diff --git a/entry/src/main/ets/pages/Index.ets b/entry/src/main/ets/pages/Index.ets index 0592c83..8a08d9e 100644 --- a/entry/src/main/ets/pages/Index.ets +++ b/entry/src/main/ets/pages/Index.ets @@ -7,11 +7,14 @@ import { ConnectionsPage } from '../ui/ConnectionsPage'; import { TerminalPage } from '../ui/TerminalPage'; import { KeysPage } from '../ui/KeysPage'; import { SettingsPage } from '../ui/SettingsPage'; +import { SessionManager } from '../session/SessionManager'; +import { SettingsRepository } from '../data/SettingsRepository'; /** * App shell: bottom tab bar with 连接 / 终端 / 密钥 / 设置. * Cross-page navigation (e.g. "connect" jumping to the terminal tab) goes - * through AppStorage key 'activeTabIndex'. + * through AppStorage key 'activeTabIndex'; the last selected tab is + * persisted (plan §4 Settings.last_tab) and restored on launch. */ @Entry @Component @@ -19,12 +22,28 @@ struct Index { @StorageLink('activeTabIndex') @Watch('onTabRequested') activeTabIndex: number = 0; controller: TabsController = new TabsController(); + aboutToAppear(): void { + const context = this.getUIContext().getHostContext(); + if (context !== undefined) { + SessionManager.getInstance().setAppContext(context); + const settings: SettingsRepository = SettingsRepository.getInstance(context); + const lastTab: number = settings.getLastTab(); + if (lastTab >= 0 && lastTab <= 3) { + this.activeTabIndex = lastTab; + } + } + } + onTabRequested(): void { - this.controller.changeIndex(this.activeTabIndex); + try { + this.controller.changeIndex(this.activeTabIndex); + } catch (e) { + // Controller not attached yet; the Tabs index param covers it. + } } build() { - Tabs({ barPosition: BarPosition.End, controller: this.controller }) { + Tabs({ barPosition: BarPosition.End, controller: this.controller, index: this.activeTabIndex }) { TabContent() { ConnectionsPage() }.tabBar('连接') @@ -45,6 +64,11 @@ struct Index { .scrollable(true) .onChange((index: number): void => { this.activeTabIndex = index; + const context = this.getUIContext().getHostContext(); + if (context !== undefined) { + SettingsRepository.getInstance(context).setLastTab(index).catch((): void => { + }); + } }) .width('100%') .height('100%') diff --git a/entry/src/main/ets/session/SessionManager.ts b/entry/src/main/ets/session/SessionManager.ts index e25f6f6..54b1a03 100644 --- a/entry/src/main/ets/session/SessionManager.ts +++ b/entry/src/main/ets/session/SessionManager.ts @@ -6,8 +6,11 @@ * subscribe() and re-read all()/getActive() on every notification. */ +import { common } from '@kit.AbilityKit'; +import { BackgroundKeepAlive } from '../common/BackgroundKeepAlive'; import { TerminalSession } from './TerminalSession'; import type { ConnectSpec, SessionDeps } from './TerminalSession'; +import { SessionState } from './TerminalSession'; export class SessionManager { private static instance: SessionManager | null = null; @@ -23,6 +26,12 @@ export class SessionManager { private readonly listeners: Array<() => void> = []; private nextId: number = 1; private activeId: number | null = null; + private appContext: common.Context | null = null; + + /** Provide the ability context once (Index aboutToAppear) for keep-alive. */ + setAppContext(context: common.Context): void { + this.appContext = context; + } /** * Create a session, make it active and start dialing. The deps' @@ -109,5 +118,28 @@ export class SessionManager { for (let i: number = 0; i < snapshot.length; i++) { snapshot[i](); } + this.updateKeepAlive(); + } + + /** + * Hold the DATA_TRANSFER continuous task while any session is READY and + * release it once none remain (plan §6). + */ + private updateKeepAlive(): void { + const context: common.Context | null = this.appContext; + if (context === null) { + return; + } + let anyReady: boolean = false; + this.sessions.forEach((session: TerminalSession): void => { + if (!anyReady && session.getState() === SessionState.READY) { + anyReady = true; + } + }); + if (anyReady) { + BackgroundKeepAlive.start(context); + } else { + BackgroundKeepAlive.stop(context); + } } }