Граф коммитов

12 Коммитов

Автор SHA1 Сообщение Дата
Paige Sun f9922a3f46 Fix AppState by removing guard for bridge, since it doesn't use bridge
Summary:
Changelog: [Internal][iOS] Fix AppState in Bridgeless mode by removing guard for bridge, since it doesn't use bridge

AppState doesn't use bridge because RCTAppState subclasses RCTEventEmitter, which calls `_callableJSModules invokeModule` in both Bridge and Bridgeless mode to send events to JS.

Reviewed By: fkgozali

Differential Revision: D35988515

fbshipit-source-id: fb19f0f2df5b270f0ef57637930f94686e39a9a1
2022-05-01 13:36:09 -07:00
Andres Suarez 8bd3edec88 Update copyright headers from Facebook to Meta
Reviewed By: aaronabramov

Differential Revision: D33367752

fbshipit-source-id: 4ce94d184485e5ee0a62cf67ad2d3ba16e285c8f
2021-12-30 15:11:21 -08:00
Lulu Wu ea93151f21 Make RCTEventDispatcher TurboModule-compatible
Summary:
This diff ended up being a bit more complicated than I anticipated, since the source files in `ReactInternal` were depending on `RCTEventDispatcher`. I made the following changes:
1. Make `RCTEventDispatcher` a `protocol`, keep it in `ReactInternal`.
2. Rename the `RCTEventDispatcher` NativeModule to `RCTEventDispatcherModule`, make it conform to the `RCTEventEmitter` `protocol`, and move it to `CoreModules`.
3. Where necessary, replace categories of `RCTEventDispatcher` with functions.

Changelog:
[iOS][Added] - Make RCTEventDispatcher TurboModule-comaptible

Reviewed By: fkgozali

Differential Revision: D18439488

fbshipit-source-id: b3da15c29459fddf884519f33b0c3b8c036b5539
2020-10-14 02:40:10 -07:00
Scott Kyle 23717e48af Call stopObserving on correct queue
Summary:
Since `dealloc` can be called from any thread, this would result `stopObserving` being called on a different thread/queue than the specified `methodQueue`. We specifically encountered this issue with a module needing the main queue having its `stopObserving` called on a background queue.

Changelog:
[iOS][Fixed] - Call [RCTEventEmitter stopObserving] on specified method queue

Reviewed By: RSNara

Differential Revision: D23821741

fbshipit-source-id: 693c3be6876f863da6dd214a829af2cc13a09c3f
2020-09-21 17:30:34 -07:00
Ramanpreet Nara 39d67737c0 Run getConstants method statements on main queue
Summary:
If a NativeModule requires main queue setup, its `getConstants()` method must be executed on the main thead. The legacy NativeModule infra takes care of this for us. With TurboModules, however, all synchronous methods, including `getConstants()`, execute on the JS thread. Therefore, if a TurboModule requires main queue setup, and exports constants, we must execute its `getConstants()` method body on the main queue explicitly.

**Notes:**
- The changes in this diff should be a noop when TurboModules is off, because `RCTUnsafeExecuteOnMainQueueSync` synchronously execute its block on the current thread if the current thread is the main thread.
- If a NativeModule doens't have the `requiresMainQueueSetup` method, but has the `constantsToExport` method, both NativeModules and TurboModules assume that it requires main queue setup.

## Script
```
const exec = require("../lib/exec");
const abspath = require("../lib/abspath");
const relpath = require("../lib/relpath");
const readFile = (filename) => require("fs").readFileSync(filename, "utf8");
const writeFile = (filename, content) =>
  require("fs").writeFileSync(filename, content);

function main() {
  const tmFiles = exec("cd ~/fbsource && xbgs -n 10000 -l constantsToExport")
    .split("\n")
    .filter(Boolean);

  const filesWithoutConstantsToExport = [];
  const filesWithConstantsToExportButNotGetConstants = [];
  const filesExplicitlyNotRequiringMainQueueSetup = [];

  tmFiles
    .filter((filename) => {
      if (filename.includes("microsoft-fork-of-react-native")) {
        return false;
      }

      return /\.mm?$/.test(filename);
    })
    .map(abspath)
    .forEach((filename) => {
      const code = readFile(filename);
      const relFilename = relpath(filename);

      if (!/constantsToExport\s*{/.test(code)) {
        filesWithoutConstantsToExport.push(relFilename);
        return;
      }

      if (!/getConstants\s*{/.test(code)) {
        filesWithConstantsToExportButNotGetConstants.push(relFilename);
        return;
      }

      if (/requiresMainQueueSetup\s*{/.test(code)) {
        const requiresMainQueueSetupRegex = /requiresMainQueueSetup\s*{\s*return\s+(?<requiresMainQueueSetup>YES|NO)/;
        const requiresMainQueueSetupRegexMatch = requiresMainQueueSetupRegex.exec(
          code
        );

        if (!requiresMainQueueSetupRegexMatch) {
          throw new Error(
            "Detected requiresMainQueueSetup method in file " +
              relFilename +
              " but was unable to parse the method return value"
          );
        }

        const {
          requiresMainQueueSetup,
        } = requiresMainQueueSetupRegexMatch.groups;

        if (requiresMainQueueSetup == "NO") {
          filesExplicitlyNotRequiringMainQueueSetup.push(relFilename);
          return;
        }
      }

      const getConstantsTypeRegex = () => /-\s*\((?<type>.*)\)getConstants\s*{/;
      const getConstantsTypeRegexMatch = getConstantsTypeRegex().exec(code);

      if (!getConstantsTypeRegexMatch) {
        throw new Error(
          `Failed to parse return type of getConstants method in file ${relFilename}`
        );
      }

      const getConstantsType = getConstantsTypeRegexMatch.groups.type;

      const getConstantsBody = code
        .split(getConstantsTypeRegex())[2]
        .split("\n}")[0];

      const newGetConstantsBody = `
  __block ${getConstantsType} constants;
  RCTUnsafeExecuteOnMainQueueSync(^{${getConstantsBody
    .replace(/\n/g, "\n  ")
    .replace(/_bridge/g, "self->_bridge")
    .replace(/return /g, "constants = ")}
  });

  return constants;
`;

      writeFile(
        filename,
        code
          .replace(getConstantsBody, newGetConstantsBody)
          .replace("#import", "#import <React/RCTUtils.h>\n#import")
      );
    });

  console.log("Files without constantsToExport: ");
  filesWithoutConstantsToExport.forEach((file) => console.log(file));
  console.log();

  console.log("Files with constantsToExport but no getConstants: ");
  filesWithConstantsToExportButNotGetConstants.forEach((file) =>
    console.log(file)
  );
  console.log();

  console.log("Files with requiresMainQueueSetup = NO: ");
  filesExplicitlyNotRequiringMainQueueSetup.forEach((file) =>
    console.log(file)
  );
}

if (!module.parent) {
  main();
}

```

Changelog: [Internal]

Reviewed By: fkgozali

Differential Revision: D21797048

fbshipit-source-id: a822a858fecdbe976e6197f8339e509dc7cd917f
2020-06-02 23:01:35 -07:00
Ramanpreet Nara 03bd7d799e Part 2: Update ObjC++ codegen classes to use ObjCTurboModule::InitParams
Summary:
## Summary
Please check out D21035209.

## Changes
- Codemod all ObjC NativeModule `getTurboModuleWithJsInvoker:nativeInvoker:perfLogger` methods to `getTurboModule:(const ObjCTurboModule::Args)`

## Script
```
var withSpaces = (...args) => args.join('\s*')

var regexString = withSpaces(
  '-',
  '\(',
  'std::shared_ptr',
  '<',
  '(?<turboModuleClass>(facebook::react::|react::|::|)TurboModule)',
  '>',
  '\)',
  'getTurboModuleWithJsInvoker',
  ':',
  '\(',
  'std::shared_ptr',
  '<',
  '(?<fbNamespace>(facebook::react::|react::|::|))CallInvoker',
  '>',
  '\)',
  '(?<jsInvokerInstance>[A-Za-z0-9]+)',
  'nativeInvoker',
  ':',
  '\(',
  'std::shared_ptr',
  '<',
  '(facebook::react::|react::|::|)CallInvoker',
  '>',
  '\)',
  '(?<nativeInvokerInstance>[A-Za-z0-9]+)',
  'perfLogger',
  ':',
  '\(',
  'id',
  '<',
  'RCTTurboModulePerformanceLogger',
  '>',
  '\)',
  '(?<perfLoggerInstance>[A-Za-z0-9]+)',
  '{',
  'return',
  'std::make_shared',
  '<',
  '(?<specName>(facebook::react::|react::|::|)Native[%A-Za-z0-9]+SpecJSI)',
  '>',
  '\(',
  'self',
  ',',
  '\k<jsInvokerInstance>',
  ',',
  '\k<nativeInvokerInstance>',
  ',',
  '\k<perfLoggerInstance>',
  '\)',
  ';',
  '}',
)

var replaceString = `- (std::shared_ptr<$<turboModuleClass>>) getTurboModule:(const $<fbNamespace>ObjCTurboModule::InitParams &)params
{
  return std::make_shared<$<specName>>(params);
}`

const exec = require('../lib/exec');
const abspath = require('../lib/abspath');
const relpath = require('../lib/relpath');
const readFile = (filename) => require('fs').readFileSync(filename, 'utf8');
const writeFile = (filename, content) => require('fs').writeFileSync(filename, content);

function main() {
  const tmFiles = exec('cd ~/fbsource && xbgs -n 10000 -l getTurboModuleWithJsInvoker:').split('\n').filter(Boolean);

  tmFiles
    .filter((filename) => !filename.includes('microsoft-fork-of-react-native'))
    .map(abspath)
    .forEach((filename) => {
      const source = readFile(filename);
      const newSource = source.replace(new RegExp(regexString, 'g'), replaceString);

      if (source == newSource) {
        console.log(relpath(filename));
      }

      writeFile(filename, newSource);
    });
}

if (!module.parent) {
  main();
}
```

## Re-generating diff
```
> hg revert -r .^ --all
> node index.js # run script
```

Changelog: [iOS][Changed] - Make all ObjC NativeModules create TurboModules using ObjCTurboModule::Args

Reviewed By: PeteTheHeat

Differential Revision: D21036265

fbshipit-source-id: 404bcc548d1775ef23d793527606d02fe384a0a2
2020-04-16 17:29:55 -07:00
Ramanpreet Nara 69698b25fc Codemod all getTurboModuleWithJsInvoker methods to accept a native CallInvoker
Summary:
To make iOS TurboModules integrate with the bridge's onBatchComplete event, they need to use a native CallInvoker. This call invoker is created by the `NativeToJsBridge`, and ObjCTurboModule will use this native CallInvoker to dispatch TurboModule method calls. This diff makes sure that ObjCTurboModules are created with that native CallInvoker.

## Script
```
var withSpaces = (...args) => args.join('\s*')

var regexString = withSpaces(
  '-',
  '\(',
  'std::shared_ptr',
  '<',
  '(?<turboModuleClass>(facebook::react::|react::|::|)TurboModule)',
  '>',
  '\)',
  'getTurboModuleWithJsInvoker',
  ':',
  '\(',
  'std::shared_ptr',
  '<',
  '(?<callInvokerClass>(facebook::react::|react::|::|)CallInvoker)',
  '>',
  '\)',
  '(?<jsInvokerInstance>[A-Za-z0-9]+)',
  'perfLogger',
  ':',
  '\(',
  'id',
  '<',
  'RCTTurboModulePerformanceLogger',
  '>',
  '\)',
  '(?<perfLoggerInstance>[A-Za-z0-9]+)',
  '{',
  'return',
  'std::make_shared',
  '<',
  '(?<specName>(facebook::react::|react::|::|)Native[%A-Za-z0-9]+SpecJSI)',
  '>',
  '\(',
  'self',
  ',',
  '\k<jsInvokerInstance>',
  ',',
  '\k<perfLoggerInstance>',
  '\)',
  ';',
  '}',
)

var replaceString = `- (std::shared_ptr<$<turboModuleClass>>)
    getTurboModuleWithJsInvoker:(std::shared_ptr<$<callInvokerClass>>)$<jsInvokerInstance>
                  nativeInvoker:(std::shared_ptr<$<callInvokerClass>>)nativeInvoker
                     perfLogger:(id<RCTTurboModulePerformanceLogger>)$<perfLoggerInstance>
{
  return std::make_shared<$<specName>>(self, $<jsInvokerInstance>, nativeInvoker, $<perfLoggerInstance>);
}`

const exec = require('../lib/exec');
const abspath = require('../lib/abspath');
const relpath = require('../lib/relpath');
const readFile = (filename) => require('fs').readFileSync(filename, 'utf8');
const writeFile = (filename, content) => require('fs').writeFileSync(filename, content);

function main() {
  const tmFiles = exec('cd ~/fbsource && xbgs -n 10000 -l getTurboModuleWithJsInvoker:').split('\n').filter(Boolean);

  tmFiles
    .filter((filename) => !filename.includes('microsoft-fork-of-react-native'))
    .map(abspath)
    .forEach((filename) => {
      const source = readFile(filename);
      const newSource = source.replace(new RegExp(regexString, 'g'), replaceString);

      if (source == newSource) {
        console.log(relpath(filename));
      }

      writeFile(filename, newSource);
    });
}

if (!module.parent) {
  main();
}
```

Changelog: [Internal]

Reviewed By: fkgozali

Differential Revision: D20809202

fbshipit-source-id: 5d39b3cacdaa5681b70ce1803351d0432dd74550
2020-04-03 02:27:10 -07:00
Ramanpreet Nara 652fa1b8d4 Add a perfLogger argument to getTurboModuleWithJSInvoker:
Summary:
## Purpose
We must modify the `getTurboModuleWithJsInvoker:` method of all our NativeModules to also accept a `id<RCTTurboModulePerformanceLogger>` object. This performance logger object should then be forwarded to the `Native*SpecJSI` constructor.

## Script
Run the following script via Node:
```
var withSpaces = (...args) => args.join('\s*')

var regexString = withSpaces(
  '-',
  '\(',
  'std::shared_ptr',
  '<',
  '(?<turboModuleClass>(facebook::react::|react::|::|)TurboModule)',
  '>',
  '\)',
  'getTurboModuleWithJsInvoker',
  ':',
  '\(',
  'std::shared_ptr',
  '<',
  '(?<callInvokerClass>(facebook::react::|react::|::|)CallInvoker)',
  '>',
  '\)',
  'jsInvoker',
  '{',
  'return',
  'std::make_shared',
  '<',
  '(?<specName>(facebook::react::|react::|::|)Native[A-Za-z0-9]+SpecJSI)',
  '>',
  '\(',
  '(?<arg1>[A-Za-z0-9]+)',
  ',',
  '(?<arg2>[A-Za-z0-9]+)',
  '\)',
  ';',
  '}',
)

var replaceString = `- (std::shared_ptr<$<turboModuleClass>>)
    getTurboModuleWithJsInvoker:(std::shared_ptr<$<callInvokerClass>>)jsInvoker
                     perfLogger:(id<RCTTurboModulePerformanceLogger>)perfLogger
{
  return std::make_shared<$<specName>>($<arg1>, $<arg2>, perfLogger);
}`

const exec = (cmd) => require('child_process').execSync(cmd, { encoding: 'utf8' });
const abspath = (filename) => `${process.env.HOME}/${filename}`;
const relpath = (filename) => filename.replace(process.env.HOME + '/', '');
const readFile = (filename) => require('fs').readFileSync(filename, 'utf8');
const writeFile = (filename, content) => require('fs').writeFileSync(filename, content);

function main() {
  const tmFiles = exec('cd ~/fbsource && xbgs -n 10000 -l getTurboModuleWithJsInvoker:').split('\n').filter(Boolean);

  tmFiles
    .filter((filename) => !filename.includes('microsoft-fork-of-react-native'))
    .map(abspath)
    .forEach((filename) => {
      const source = readFile(filename);
      const newSource = source.replace(new RegExp(regexString, 'g'), replaceString);

      if (source == newSource) {
        console.log(relpath(filename));
      }

      writeFile(filename, newSource);
    });
}

if (!module.parent) {
  main();
}
```

Also, run: `pushd ~/fbsource && js1 build oss-native-modules-specs -p ios && js1 build oss-native-modules-specs -p android && popd;`

Changelog: [Internal]

Reviewed By: fkgozali

Differential Revision: D20478718

fbshipit-source-id: 89ee27ed8a0338a66a9b2dbb716168a4c4582c44
2020-03-18 11:01:15 -07:00
Valentin Shergin d0871d0a9a Clang format for all React Native files
Summary:
Buckle up, this enables clang-format prettifier for all files in React Native opensource repo.

Changelog: [Internal] Clang-format codemod.

Reviewed By: mdvacca

Differential Revision: D20331210

fbshipit-source-id: 8da0f94700be0c35bfd399e0c48f1706de04f5b1
2020-03-08 23:01:17 -07:00
Peter Argany 58d226f0b5 Guard against nil bridge during RCTAppState change
Summary: Somehow, `RCTAppState` is still trying to send events without the bridge. This diff effectively silences the warning, since I still believe there is no point sending events to JS if the bridge is nil.

Reviewed By: fkgozali

Differential Revision: D19560149

fbshipit-source-id: 5077335f6a47fe7d1896e078668c1eb4da1339de
2020-01-24 14:20:43 -08:00
Peter Argany b4d5ffb804 Guard against nil bridge during teardown
Summary:
A UBN surfaced in v252 because [this assert](https://our.intern.facebook.com/intern/diffusion/FBS/browse/master/xplat/js/react-native-github/React/Modules/RCTEventEmitter.m?commit=e5d1e6375a640d0387bb7016d3becd262c22c327&lines=40) started firing, originating from `RCTAppState`.

This appears to be a race condition during RN teardown. RN receives a memory warning and attempts to forward to JS, but the bridge is already destroyed.

IMO, if the bridge is already destroyed, then there shouldn't be a need to send a memory warning to JS? This is just a hunch though, if anyone feels otherwise, please let me know :)

See the UBN task for further details.

Changelog: [iOS][Internal] Guard against nil bridge during teardown

Reviewed By: shergin

Differential Revision: D19293063

fbshipit-source-id: 566f21af30d3d9bcd25a673ce664f8caddc701ca
2020-01-06 17:03:06 -08:00
Ramanpreet Nara 7233ae4f11 Make RCTAppState TurboModule-compatible
Summary:
See title.

Changelog:
[iOS][Added] - Make RCTAppState TurboModule-compatible

Reviewed By: PeteTheHeat

Differential Revision: D18142253

fbshipit-source-id: 5bd8afa6e3ee98f92aac3b2ebdfe63b9f7afc775
2019-11-01 12:06:21 -07:00