euv-cli 0.51.0

Cross-platform CLI tool for the euv native UI framework supporting run, build, check, fmt, doctor, new, and Hyperlane SSE dynamic updates across all supported platforms.
Documentation
import UIAbility from '@ohos.app.ability.UIAbility';
import AbilityConstant from '@ohos.app.ability.AbilityConstant';
import Want from '@ohos.app.ability.Want';
import Configuration from '@ohos.app.ability.Configuration';
import window from '@ohos.window';
import display from '@ohos.display';
import sensor from '@ohos.sensor';
import pasteboard from '@ohos.pasteboard';
import vibrator from '@ohos.vibrator';
import pointer from '@ohos.multimodalInput.pointer';
import deviceInfo from '@ohos.deviceInfo';
import euvNative from 'libeuv_harmony_host.so';

const DEFAULT_DEVICE_TYPE: string = '{{DEVICE_TYPE}}';

function resolveRuntimeDeviceType(): string {
  try {
    const dt: string = (deviceInfo.deviceType || '').toLowerCase();
    if (dt === '2in1' || dt === 'pc') return '2in1';
    if (dt === 'tablet') return 'tablet';
    if (dt === 'wearable' || dt === 'litewearable') return 'wearable';
    if (dt === 'tv') return 'tv';
    if (dt === 'car') return 'car';
    if (dt === 'phone' && display.isFoldable()) return 'foldable';
    if (dt.length > 0) return dt;
  } catch (_e) {}
  return DEFAULT_DEVICE_TYPE;
}

export default class EntryAbility extends UIAbility {
  private nativeHandle: number = 0;
  private runtimeDeviceType: string = DEFAULT_DEVICE_TYPE;
  private density: number = 3.0;
  private mainWindow: window.Window | null = null;
  private commandHandlerAttached: boolean = false;
  private motionActive: boolean = false;
  private gravDev: number[] = [0.0, 9.80665, 0.0];
  private linDev: number[] = [0.0, 0.0, 0.0];
  private gyroDev: number[] = [0.0, 0.0, 0.0];

  private isPcDesktop(): boolean {
    return this.runtimeDeviceType === '2in1' || this.runtimeDeviceType === 'pc';
  }

  onCreate(want: Want, _launchParam: AbilityConstant.LaunchParam): void {
    this.runtimeDeviceType = resolveRuntimeDeviceType();
    const defaultDisplay = display.getDefaultDisplaySync();
    this.density = Math.min(16.0, Math.max(0.25, defaultDisplay.densityPixels || (this.isPcDesktop() ? 2.0 : 3.0)));
    const initW: number = this.isPcDesktop()
      ? Math.min(defaultDisplay.width, Math.round(1440 * this.density))
      : defaultDisplay.width;
    const initH: number = this.isPcDesktop()
      ? Math.min(defaultDisplay.height, Math.round(900 * this.density))
      : defaultDisplay.height;
    this.nativeHandle = euvNative.euvHarmonyCreate(
      this.runtimeDeviceType,
      initW,
      initH,
      this.density
    );
    const wantUri: string = want.uri ?? '';
    euvNative.euvHarmonyOnLifecycle(this.nativeHandle, 'onCreate', wantUri);
  }

  onNewWant(want: Want, _launchParam: AbilityConstant.LaunchParam): void {
    if (this.nativeHandle !== 0 && want.uri) {
      euvNative.euvHarmonyOnLifecycle(this.nativeHandle, 'onNewWant', want.uri);
    }
  }

  onWindowStageCreate(windowStage: window.WindowStage): void {
    windowStage.on('windowStageEvent', (eventType: window.WindowStageEventType) => {
      if (this.nativeHandle === 0) return;
      if (eventType === window.WindowStageEventType.ACTIVE || eventType === window.WindowStageEventType.RESUMED) {
        euvNative.euvHarmonyOnLifecycle(this.nativeHandle, 'onWindowActive', '');
      } else if (eventType === window.WindowStageEventType.INACTIVE || eventType === window.WindowStageEventType.PAUSED) {
        euvNative.euvHarmonyOnLifecycle(this.nativeHandle, 'onWindowInactive', '');
      }
    });

    windowStage.getMainWindow((err, win) => {
      if (err.code || !win) return;
      this.mainWindow = win;
      if (this.isPcDesktop()) {
        try {
          win.setWindowDecorVisible(true);
          win.setWindowTitle('Euv Studio');
        } catch (_e) {}
        try {
          win.on('windowStatusChange', (status: window.WindowStatusType) => {
            if (this.nativeHandle === 0) return;
            let modeTag: number = 1;
            if (status === window.WindowStatusType.FULL_SCREEN) modeTag = 0;
            else if (status === window.WindowStatusType.FLOATING) modeTag = 1;
            else if (status === window.WindowStatusType.MAXIMIZE) modeTag = 2;
            else if (status === window.WindowStatusType.MINIMIZE) modeTag = 3;
            else if (status === window.WindowStatusType.SPLIT_SCREEN) modeTag = 4;
            euvNative.euvHarmonyOnWindowMode(this.nativeHandle, modeTag);
          });
        } catch (_e) {}
      } else {
        win.setWindowLayoutFullScreen(true);
      }
      this.pushAvoidArea(win);
      win.on('avoidAreaChange', () => this.pushAvoidArea(win));
      win.on('windowSizeChange', (size) => {
        if (this.nativeHandle !== 0) {
          euvNative.euvHarmonyResize(this.nativeHandle, size.width, size.height, this.density);
        }
      });
      win.on('keyboardHeightChange', (heightPx: number) => {
        if (this.nativeHandle !== 0) {
          euvNative.euvHarmonyOnKeyboardHeight(this.nativeHandle, heightPx / this.density);
        }
      });
    });

    AppStorage.setOrCreate('euvNativeHandle', this.nativeHandle);
    AppStorage.setOrCreate('euvDensity', this.density);
    AppStorage.setOrCreate('euvDeviceType', this.runtimeDeviceType);
    this.startHostCommandPump();
    windowStage.loadContent('pages/Index');
  }

  private startHostCommandPump(): void {
    if (this.commandHandlerAttached || this.nativeHandle === 0) return;
    this.commandHandlerAttached = true;
    euvNative.euvHarmonySetCommandHandler(() => {
      this.drainHostCommands();
    });
    this.drainHostCommands();
  }

  private stopHostCommandPump(): void {
    if (!this.commandHandlerAttached) return;
    this.commandHandlerAttached = false;
    euvNative.euvHarmonySetCommandHandler(null);
  }

  private drainHostCommands(): void {
    if (this.nativeHandle === 0) return;
    const raw: string = euvNative.euvHarmonyDrainHostCommands(this.nativeHandle);
    if (!raw || raw === '[]') return;
    try {
      const cmds: Array<Record<string, Object>> = JSON.parse(raw);
      for (let i = 0; i < cmds.length; i += 1) {
        this.executeHostCommand(cmds[i]);
      }
    } catch (_e) {}
  }

  private executeHostCommand(cmd: Record<string, Object>): void {
    const kind: string = String(cmd['kind'] || '');
    const arg1: string = String(cmd['arg1'] || '');
    const arg2: string = String(cmd['arg2'] || '');
    if (kind === 'harmony_window_title' && this.mainWindow) {
      try { this.mainWindow.setWindowTitle(arg1); } catch (_e) {}
    } else if (kind === 'harmony_decorations' && this.mainWindow) {
      try { this.mainWindow.setWindowDecorVisible(arg1 === 'on'); } catch (_e) {}
    } else if (kind === 'harmony_always_on_top' && this.mainWindow) {
      try { this.mainWindow.setWindowTopmost(arg1 === 'on'); } catch (_e) {}
    } else if ((kind === 'fullscreen' || kind === 'harmony_window_mode') && this.mainWindow) {
      try {
        if (arg1 === 'on' || arg1 === 'fullscreen') {
          this.mainWindow.setWindowLayoutFullScreen(true);
          if (!this.isPcDesktop()) {
            this.mainWindow.setWindowSystemBarEnable([]);
          }
        } else if (arg1 === 'maximize') {
          this.mainWindow.maximize();
        } else if (arg1 === 'minimize') {
          this.mainWindow.minimize();
        } else if (this.isPcDesktop()) {
          this.mainWindow.setWindowLayoutFullScreen(false);
        } else {
          this.mainWindow.setWindowLayoutFullScreen(true);
          this.mainWindow.setWindowSystemBarEnable(['status', 'navigation']);
        }
      } catch (_e) {}
    } else if (kind === 'harmony_cursor' && this.mainWindow) {
      try {
        const winId: number = this.mainWindow.getWindowProperties().id;
        const styleId: number = Number(arg1) || 0;
        pointer.setPointerStyleSync(winId, styleId);
      } catch (_e) {}
    } else if (kind === 'clipboard') {
      try {
        const text: string = arg2.length > 0 ? arg2 : arg1;
        const data = pasteboard.createData(pasteboard.MIMETYPE_TEXT_PLAIN, text);
        pasteboard.getSystemPasteboard().setData(data);
      } catch (_e) {}
    } else if (kind === 'haptic') {
      try {
        vibrator.startVibration({ type: 'time', duration: 15 }, { id: 0, usage: 'touch' });
      } catch (_e) {}
    } else if (kind === 'open_url' && arg1.length > 0) {
      try {
        this.context.startAbility({ action: 'ohos.want.action.viewData', uri: arg1 });
      } catch (_e) {}
    } else if (kind === 'webview') {
      if (arg1 === 'close') {
        AppStorage.setOrCreate('euvWebViewVisible', false);
        AppStorage.setOrCreate('euvWebViewUrl', '');
      } else if (arg1 === 'frame') {
        AppStorage.setOrCreate('euvWebViewFrame', arg2);
      } else if (arg1 === 'reload') {
        const seq: number = (AppStorage.get<number>('euvWebViewReloadSeq') ?? 0) + 1;
        AppStorage.setOrCreate('euvWebViewReloadSeq', seq);
      } else if (arg1.length > 0) {
        AppStorage.setOrCreate('euvWebViewUrl', arg1);
        AppStorage.setOrCreate('euvWebViewTitle', arg2);
        AppStorage.setOrCreate('euvWebViewVisible', true);
      }
    } else if (kind === 'ime') {
      AppStorage.setOrCreate('euvImeActive', arg1 === 'show');
    }
  }

  private pushAvoidArea(win: window.Window): void {
    if (this.nativeHandle === 0) return;
    if (this.isPcDesktop()) {
      euvNative.euvHarmonySetAvoidArea(this.nativeHandle, 0, 0, 0, 0, false);
      return;
    }
    const sys = win.getWindowAvoidArea(window.AvoidAreaType.TYPE_SYSTEM);
    const cutout = win.getWindowAvoidArea(window.AvoidAreaType.TYPE_CUTOUT);
    const nav = win.getWindowAvoidArea(window.AvoidAreaType.TYPE_NAVIGATION_INDICATOR);
    const topPx = Math.max(sys.topRect.height, cutout.topRect.height);
    const bottomPx = Math.max(sys.bottomRect.height, nav.bottomRect.height);
    const leftPx = Math.max(sys.leftRect.width, cutout.leftRect.width);
    const rightPx = Math.max(sys.rightRect.width, cutout.rightRect.width);
    euvNative.euvHarmonySetAvoidArea(
      this.nativeHandle,
      topPx / this.density,
      rightPx / this.density,
      bottomPx / this.density,
      leftPx / this.density,
      false
    );
  }

  private dispatchHarmonyMotion(timestampNs: number): void {
    if (this.nativeHandle === 0) return;
    let rot: number = 0;
    try {
      rot = display.getDefaultDisplaySync().rotation || 0;
    } catch (_e) {
      rot = 0;
    }
    const rGx = this.gravDev[0], rGy = this.gravDev[1], rGz = this.gravDev[2];
    const rLx = this.linDev[0], rLy = this.linDev[1], rLz = this.linDev[2];
    const rWx = this.gyroDev[0], rWy = this.gyroDev[1], rWz = this.gyroDev[2];
    let sGx = rGx, sGy = rGy;
    let sLx = rLx, sLy = rLy;
    let sWx = rWx, sWy = rWy;
    if (rot === 1) {
      sGx = -rGy; sGy = rGx;
      sLx = -rLy; sLy = rLx;
      sWx = -rWy; sWy = rWx;
    } else if (rot === 2) {
      sGx = -rGx; sGy = -rGy;
      sLx = -rLx; sLy = -rLy;
      sWx = -rWx; sWy = -rWy;
    } else if (rot === 3) {
      sGx = rGy; sGy = -rGx;
      sLx = rLy; sLy = -rLx;
      sWx = rWy; sWy = -rWx;
    }
    euvNative.euvHarmonyOnDeviceMotion(
      this.nativeHandle,
      -sGx,
      sGy,
      -rGz,
      sLx,
      -sLy,
      rLz,
      sWx,
      sWy,
      rWz,
      timestampNs
    );
  }

  private startMotionSensors(): void {
    if (this.motionActive || this.nativeHandle === 0 || this.isPcDesktop()) return;
    this.motionActive = true;
    try {
      sensor.on(sensor.SensorId.GRAVITY, (data: sensor.GravityResponse) => {
        this.gravDev = [data.x, data.y, data.z];
        this.dispatchHarmonyMotion(data.timestamp || 0);
      }, { interval: 16_000_000 });
    } catch (_e) {
      try {
        sensor.on(sensor.SensorId.ACCELEROMETER, (data: sensor.AccelerometerResponse) => {
          const a = 0.22;
          this.gravDev = [
            this.gravDev[0] * (1.0 - a) + data.x * a,
            this.gravDev[1] * (1.0 - a) + data.y * a,
            this.gravDev[2] * (1.0 - a) + data.z * a
          ];
          this.linDev = [data.x - this.gravDev[0], data.y - this.gravDev[1], data.z - this.gravDev[2]];
          this.dispatchHarmonyMotion(data.timestamp || 0);
        }, { interval: 16_000_000 });
      } catch (_e2) {}
    }
    try {
      sensor.on(sensor.SensorId.LINEAR_ACCELEROMETER, (data: sensor.LinearAccelerometerResponse) => {
        this.linDev = [data.x, data.y, data.z];
      }, { interval: 16_000_000 });
    } catch (_e) {}
    try {
      sensor.on(sensor.SensorId.GYROSCOPE, (data: sensor.GyroscopeResponse) => {
        this.gyroDev = [data.x, data.y, data.z];
      }, { interval: 16_000_000 });
    } catch (_e) {}
  }

  private stopMotionSensors(): void {
    if (!this.motionActive) return;
    this.motionActive = false;
    try { sensor.off(sensor.SensorId.GRAVITY); } catch (_e) {}
    try { sensor.off(sensor.SensorId.ACCELEROMETER); } catch (_e) {}
    try { sensor.off(sensor.SensorId.LINEAR_ACCELEROMETER); } catch (_e) {}
    try { sensor.off(sensor.SensorId.GYROSCOPE); } catch (_e) {}
  }

  onForeground(): void {
    if (this.nativeHandle !== 0) {
      euvNative.euvHarmonyOnLifecycle(this.nativeHandle, 'onForeground', '');
      if (this.mainWindow) {
        this.pushAvoidArea(this.mainWindow);
      }
      this.startMotionSensors();
      this.startHostCommandPump();
    }
  }

  onBackground(): void {
    this.stopMotionSensors();
    this.stopHostCommandPump();
    if (this.nativeHandle !== 0) {
      euvNative.euvHarmonyOnLifecycle(this.nativeHandle, 'onBackground', '');
    }
  }

  onWindowStageDestroy(): void {
    this.stopHostCommandPump();
    if (this.nativeHandle !== 0) {
      euvNative.euvHarmonyOnLifecycle(this.nativeHandle, 'onWindowStageDestroy', '');
    }
    this.mainWindow = null;
  }

  onDestroy(): void {
    this.stopMotionSensors();
    this.stopHostCommandPump();
    if (this.nativeHandle !== 0) {
      euvNative.euvHarmonyOnLifecycle(this.nativeHandle, 'onDestroy', '');
      euvNative.euvHarmonyDestroy(this.nativeHandle);
      this.nativeHandle = 0;
    }
  }

  onMemoryLevel(level: AbilityConstant.MemoryLevel): void {
    if (this.nativeHandle !== 0) {
      euvNative.euvHarmonyOnMemoryLevel(this.nativeHandle, level);
    }
  }

  onConfigurationUpdate(newConfig: Configuration): void {
    if (this.nativeHandle === 0) return;
    try {
      const curDisplay = display.getDefaultDisplaySync();
      this.density = Math.max(1.0, curDisplay.densityPixels || this.density);
      AppStorage.setOrCreate('euvDensity', this.density);
    } catch (_e) {}
    const isDark = newConfig.colorMode === 0;
    const locale = newConfig.language ?? 'en-US';
    const foldStatus = display.isFoldable() ? display.getFoldStatus() : 0;
    euvNative.euvHarmonyOnConfigUpdate(
      this.nativeHandle,
      isDark,
      locale,
      this.density,
      foldStatus
    );
    if (this.mainWindow) {
      this.pushAvoidArea(this.mainWindow);
    }
  }
}