ensureInitialized method

  1. @override
void ensureInitialized()
override

Implementation

@override
void ensureInitialized() {
  if (isInitialized) {
    return;
  }

  final Map<String, String> effectiveEnv = <String, String>{};
  effectiveEnv['TERM'] = 'xterm-256color';
  // Without this, tools like "vi" produce sequences that are not UTF-8 friendly
  effectiveEnv['LANG'] = 'en_US.UTF-8';

  const Set<String> envValuesToCopy = {
    'LOGNAME',
    'USER',
    'DISPLAY',
    'LC_TYPE',
    'HOME',
    'PATH',
  };

  for (var entry in Platform.environment.entries) {
    if (envValuesToCopy.contains(entry.key)) {
      effectiveEnv[entry.key] = entry.value;
    }
  }
  if (environment != null) {
    for (var entry in (environment ?? {}).entries) {
      effectiveEnv[entry.key] = entry.value;
    }
  }
  // build argv
  final argv = calloc<Pointer<Utf8>>(arguments.length + 2);

  argv.elementAt(0).value = executable.toNativeUtf8();
  for (var i = 0; i < arguments.length; i++) {
    argv.elementAt(i + 1).value = arguments[i].toNativeUtf8();
  }
  argv.elementAt(arguments.length + 1).value = nullptr;

  //build env
  final envp = calloc<Pointer<Utf8>>(effectiveEnv.length + 1);
  for (var i = 0; i < effectiveEnv.length; i++) {
    final entry = effectiveEnv.entries.elementAt(i);
    envp.elementAt(i).value = '${entry.key}=${entry.value}'.toNativeUtf8();
  }
  envp.elementAt(effectiveEnv.length).value = nullptr;

  final options = calloc<PtyOptions>();
  options.ref.rows = rows;
  options.ref.cols = columns;
  options.ref.executable = executable.toNativeUtf8().cast();
  options.ref.arguments = argv.cast();
  options.ref.environment = envp.cast();
  options.ref.stdout_port = stdout_receive_port.sendPort.nativePort;
  options.ref.exit_port = exit_receive_port.sendPort.nativePort;
  options.ref.ackRead = isAckRead;

  if ((workingDirectory ?? "").isNotEmpty) {
    options.ref.working_directory =
        (workingDirectory ?? "").toNativeUtf8().cast();
  } else {
    options.ref.working_directory = nullptr;
  }

  _handle = pty_library.pty_create(options);

  calloc.free(options);

  if (_handle == nullptr) {
    throw StateError('Failed to create PTY: ${_getPtyLibraryError()}');
  }
  exit_receive_port.first.then(_onExitCode);
  stdout_receive_port.listen(
    (data) {
      event_emitter.emit(eventName: event_output, value: data);
    },
    onDone: () {},
  );
  isInitialized = true;
}