Skip to content

Commit

Permalink
[data_detector] add data detector package for darwin
Browse files Browse the repository at this point in the history
  • Loading branch information
boyan01 committed Aug 14, 2024
1 parent b960a3b commit d3e8d2e
Show file tree
Hide file tree
Showing 12 changed files with 2,091 additions and 0 deletions.
29 changes: 29 additions & 0 deletions packages/data_detector/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# Miscellaneous
*.class
*.log
*.pyc
*.swp
.DS_Store
.atom/
.buildlog/
.history
.svn/
migrate_working_dir/

# IntelliJ related
*.iml
*.ipr
*.iws
.idea/

# The .vscode folder contains launch configuration and tasks you configure in
# VS Code which you may wish to be included in version control, so this line
# is commented out by default.
#.vscode/

# Flutter/Dart/Pub related
# Libraries should not include pubspec.lock, per https://dart.dev/guides/libraries/private-files#pubspeclock.
/pubspec.lock
**/doc/api/
.dart_tool/
build/
27 changes: 27 additions & 0 deletions packages/data_detector/.metadata
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# This file tracks properties of this Flutter project.
# Used by Flutter tool to assess capabilities and perform upgrades etc.
#
# This file should be version controlled and should not be manually edited.

version:
revision: "80c2e84975bbd28ecf5f8d4bd4ca5a2490bfc819"
channel: "stable"

project_type: plugin_ffi

# Tracks metadata for the flutter migrate command
migration:
platforms:
- platform: root
create_revision: 80c2e84975bbd28ecf5f8d4bd4ca5a2490bfc819
base_revision: 80c2e84975bbd28ecf5f8d4bd4ca5a2490bfc819

# User provided section

# List of Local paths (relative to this file) that should be
# ignored by the migrate tool.
#
# Files that are not part of the templates will be ignored by default.
unmanaged_files:
- 'lib/main.dart'
- 'ios/Runner.xcodeproj/project.pbxproj'
3 changes: 3 additions & 0 deletions packages/data_detector/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
## 0.0.1

* TODO: Describe initial release.
1 change: 1 addition & 0 deletions packages/data_detector/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
TODO: Add your license here.
95 changes: 95 additions & 0 deletions packages/data_detector/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
# data_detector

A new Flutter FFI plugin project.

## Getting Started

This project is a starting point for a Flutter
[FFI plugin](https://flutter.dev/to/ffi-package),
a specialized package that includes native code directly invoked with Dart FFI.

## Project structure

This template uses the following structure:

* `src`: Contains the native source code, and a CmakeFile.txt file for building
that source code into a dynamic library.

* `lib`: Contains the Dart code that defines the API of the plugin, and which
calls into the native code using `dart:ffi`.

* platform folders (`android`, `ios`, `windows`, etc.): Contains the build files
for building and bundling the native code library with the platform application.

## Building and bundling native code

The `pubspec.yaml` specifies FFI plugins as follows:

```yaml
plugin:
platforms:
some_platform:
ffiPlugin: true
```
This configuration invokes the native build for the various target platforms
and bundles the binaries in Flutter applications using these FFI plugins.
This can be combined with dartPluginClass, such as when FFI is used for the
implementation of one platform in a federated plugin:
```yaml
plugin:
implements: some_other_plugin
platforms:
some_platform:
dartPluginClass: SomeClass
ffiPlugin: true
```
A plugin can have both FFI and method channels:
```yaml
plugin:
platforms:
some_platform:
pluginClass: SomeName
ffiPlugin: true
```
The native build systems that are invoked by FFI (and method channel) plugins are:
* For Android: Gradle, which invokes the Android NDK for native builds.
* See the documentation in android/build.gradle.
* For iOS and MacOS: Xcode, via CocoaPods.
* See the documentation in ios/data_detector.podspec.
* See the documentation in macos/data_detector.podspec.
* For Linux and Windows: CMake.
* See the documentation in linux/CMakeLists.txt.
* See the documentation in windows/CMakeLists.txt.
## Binding to native code
To use the native code, bindings in Dart are needed.
To avoid writing these by hand, they are generated from the header file
(`src/data_detector.h`) by `package:ffigen`.
Regenerate the bindings by running `dart run ffigen --config ffigen.yaml`.

## Invoking native code

Very short-running native functions can be directly invoked from any isolate.
For example, see `sum` in `lib/data_detector.dart`.

Longer-running functions should be invoked on a helper isolate to avoid
dropping frames in Flutter applications.
For example, see `sumAsync` in `lib/data_detector.dart`.

## Flutter help

For help getting started with Flutter, view our
[online documentation](https://docs.flutter.dev), which offers tutorials,
samples, guidance on mobile development, and a full API reference.

The plugin project was generated without specifying the `--platforms` flag, so no platforms are currently supported.
To add platforms, run `flutter create -t plugin_ffi --platforms <platforms> .` in this directory.
You can also find a detailed instruction on how to add platforms in the `pubspec.yaml` at https://flutter.dev/to/pubspec-plugin-platforms.
4 changes: 4 additions & 0 deletions packages/data_detector/analysis_options.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
include: package:flutter_lints/flutter.yaml

# Additional information about this file can be found at
# https://dart.dev/guides/language/analysis-options
28 changes: 28 additions & 0 deletions packages/data_detector/ffigen.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# Run with `dart run ffigen --config ffigen.yaml`.
name: DataDetectorBindings
description: |
Bindings for NSDataDetector.
Regenerate bindings with `dart run ffigen --config ffigen.yaml`.
output: 'lib/src/data_detector_bindings_generated.dart'
language: objc
exclude-all-by-default: true
objc-interfaces:
include:
- 'NSRegularExpression'
- 'NSDataDetector'
structs:
include:
- _NSRange
rename:
_NSRange: NSRange
headers:
entry-points:
- '/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/System/Library/Frameworks/Foundation.framework/Headers/NSRegularExpression.h'
preamble: |
// ignore_for_file: always_specify_types
// ignore_for_file: camel_case_types
// ignore_for_file: non_constant_identifier_names
comments:
style: any
length: full
94 changes: 94 additions & 0 deletions packages/data_detector/lib/data_detector.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
import 'dart:ffi';
import 'dart:ui';

import 'package:ffi/ffi.dart';
import 'package:objective_c/objective_c.dart' as objc;

import 'src/data_detector_bindings_generated.dart' as binding;

export 'src/data_detector_bindings_generated.dart'
show NSTextCheckingType, NSMatchingOptions;

extension on TextRange {
Pointer<binding.NSRange> toNSRange() {
final range = malloc.allocate<binding.NSRange>(sizeOf<binding.NSRange>());
range.ref.location = start;
range.ref.length = end - start;
return range;
}
}

class TextCheckingResult {
TextCheckingResult._(this._inner);

final binding.NSTextCheckingResult _inner;

binding.NSTextCheckingType get type => _inner.resultType;

TextRange get range {
final p = malloc.allocate<binding.NSRange>(sizeOf<binding.NSRange>());
_inner.getRange(p);
final textRange =
TextRange(start: p.ref.location, end: p.ref.location + p.ref.length);
malloc.free(p);
return textRange;
}

DateTime? get date {
final timestamp = _inner.date?.timeIntervalSince1970;
if (timestamp == null) {
return null;
}
return DateTime.fromMicrosecondsSinceEpoch((timestamp * 1e6) as int);
}

Duration get duration =>
Duration(microseconds: (_inner.duration * 1e6) as int);

Uri? get url {
final url = _inner.URL?.absoluteString;
if (url == null) {
return null;
}
return Uri.parse(url.toString());
}
}

class DataDetector {
factory DataDetector(binding.NSTextCheckingType type) {
final error = malloc
.allocate<Pointer<objc.ObjCObject>>(sizeOf<Pointer<objc.ObjCObject>>());
final detector =
binding.NSDataDetector.alloc().initWithTypes_error_(type.value, error);
if (error.value != nullptr) {
final err = objc.NSError.castFromPointer(error.value);
throw err;
}
return DataDetector._(detector!);
}

DataDetector._(this._detector);

final binding.NSDataDetector _detector;

List<TextCheckingResult> matchesInString(
String str, {
binding.NSMatchingOptions? options,
TextRange? range,
}) {
final nsRange = (range ?? TextRange(start: 0, end: str.length)).toNSRange();
final array = _detector.matchesInString_options_range_(
str.toNSString(),
options ?? binding.NSMatchingOptions.NSMatchingReportCompletion,
nsRange.ref);
malloc.free(nsRange);

final results = <TextCheckingResult>[];
for (var i = 0; i < array.count; i++) {
final result =
binding.NSTextCheckingResult.castFrom(array.objectAtIndex_(i));
results.add(TextCheckingResult._(result));
}
return results;
}
}
Loading

0 comments on commit d3e8d2e

Please sign in to comment.