commit 6843d5ab5c774fde8df67f79ff24ba7fc35b72ac Author: Max Date: Tue Jan 27 15:25:56 2026 +0800 完成 Phase1-Phase3:策略/拦截器/指标上报/最近事件与 Demo/测试 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..dd5eb98 --- /dev/null +++ b/.gitignore @@ -0,0 +1,31 @@ +# 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/ +.flutter-plugins-dependencies +/build/ +/coverage/ diff --git a/.metadata b/.metadata new file mode 100644 index 0000000..9e2f122 --- /dev/null +++ b/.metadata @@ -0,0 +1,10 @@ +# 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: "ac4e799d237041cf905519190471f657b657155a" + channel: "stable" + +project_type: package diff --git a/0.总体目标与边界.md b/0.总体目标与边界.md new file mode 100644 index 0000000..dc73155 --- /dev/null +++ b/0.总体目标与边界.md @@ -0,0 +1,457 @@ +# 一、总体目标与边界 + +## 1.1 目标 + +基于现有后端接口,建设一套统一的埋点 SDK,覆盖: + +- 技术栈: + - Flutter:**独立纯 Dart SDK** + - Android:原生 Kotlin SDK + - iOS:原生 Swift SDK +- 对齐后端接口: + - `GET /api/ExternalEventlogs/GetSystemAllDimInfo` + - `POST /api/ExternalEventlogs/AddEventListLog` + - `POST /api/ExternalEventlogs/AddEventLog` +- 三阶段演进: + - Phase 1:可用性 + 安全稳定性 + - Phase 2:可维护性 + 配置化 + 调试 + - Phase 3:可观测性 + 动态策略 + 插件化 + +不绑定具体业务逻辑,但要能支持 OA、教育等各类场景。 + +## 1.2 统一事件数据模型 + +### 请求结构(与后端对齐) + +jsonc + +``` +{ + "system_code": "string", + "eventType": "string", + "userInfo": { + "userId": 0, + "userName": "string", + "account": "string" + }, + "clientType": 1, + "clientTimestamp": 0, + "timestamp": "2026-01-26T08:29:44.734Z", + "deviceInfo": { + "os": "string", + "model": "string", + "screenResolution": "string" + }, + "eventParams": { + // 事件上下文,例如 page、buttonId、url… + }, + "customTags": { + // 扩展维度,业务可自定义 + } +} +``` + +### 统一对外 API 设计(跨三端) + +(伪接口,三端风格尽量保持一致) + +ts + +``` +class Analytics { + static init(config: SDKConfig): void | Future + + static track( + eventType: string, + options?: { + eventParams?: Map + customTags?: Map + timestamp?: number // 毫秒级 client 时间,可不传 + } + ): void | Future + + static setUser(userInfo: UserInfo | null): void | Future + + static setDeviceInfo(deviceInfo: DeviceInfo): void | Future + + static flush(): void | Future + + static setDebug(enabled: boolean): void +} +``` + +`SDKConfig` 关键字段(统一): + +- `systemCode: string` +- `endpointBaseUrl: string`(如 `https://host/api/ExternalEventlogs`) +- `clientType: int`(统一约定:1=Android,2=iOS,3=Flutter) +- `enableDebug: boolean` +- `batchSize: int`(默认 20) +- `flushInterval: int`(秒,默认 15) +- `maxCacheSize: int`(默认 5000) +- `maxRetryCount: int`(默认 3) +- `connectTimeout`, `readTimeout` + +------ + +# 二、整体架构设计(通用视角) + +SDK 内部统一分层: + +1. **API 层(Facade)** + - 暴露 `init / track / flush / setUser / setDebug` + - 做参数校验、线程切换(原生)。 +2. **EventManager(事件管理层)** + - 构造标准事件对象(填充 system_code、userInfo、deviceInfo、时间)。 + - 写入本地队列;触发上传调度。 +3. **Storage(存储层)** + - 事件持久化(SQLite / 本地 KV)。 + - 控制队列长度、过期清理。 +4. **NetworkClient(网络层)** + - 封装调用:`AddEventListLog`(优先)、`AddEventLog`(可选降级)。 + - 统一超时、重试、错误处理。 +5. **Config / DimensionManager(配置 & 维度)** + - 管理 SDKConfig。 + - Phase 2+:拉取 `GetSystemAllDimInfo`,存本地。 +6. **Validator / Debug(校验 & 调试)** + - Phase 2+:基于配置做事件参数校验。 + - 统一 debug 日志输出。 +7. **Interceptors / Plugins(插件层)** + - Phase 3:对事件发送前后提供 Hook。 + +------ + +# 三、三端实现策略 + +## 3.1 Flutter 独立 SDK(纯 Dart) + +- 语言:Dart +- 存储:推荐 `sqflite`(SQLite)或 `hive`(KV): + - `events(id, payload_json, retry_count, create_time)` +- 网络:`dio` 或 `http` 包 +- 调度: + - `Timer.periodic` 实现定时 flush + - 控制并发:用一个「上传中」标志避免并发多次 flush +- 生命周期: + - SDK 暴露 `flush()`; + - 应用可在自身生命周期(如 `WidgetsBindingObserver` 或 Router)中调用。 + +## 3.2 Android SDK + +- 语言:Kotlin(对 Java 兼容) +- 存储:Room 或 SQLite 封装 +- 网络:OkHttp + Retrofit +- 线程:Kotlin Coroutines + 单一上传协程 +- 生命周期:`ProcessLifecycleOwner` 监听前后台 → 后台前触发 `flush` + +## 3.3 iOS SDK + +- 语言:Swift(暴露 ObjC 兼容 API) +- 存储:SQLite 或 Core Data 轻量封装 +- 网络:URLSession +- 生命周期:监听 `willResignActive` / `didEnterBackground` 调用 `flush` + +------ + +# 四、三阶段规划(含架构与验收) + +------ + +## Phase 1:可用性 + 安全稳定性 + +### 4.1 目标 + +- 提供稳定、可用的基础事件采集 & 批量上报能力。 +- 不影响业务性能和体验。 +- 基本安全(HTTPS,预留签名扩展)。 + +### 4.2 能力范围 + +1. 初始化 + - 校验并保存 `SDKConfig`; + - 自动采集 `DeviceInfo`; + - 初始化本地存储; + - 启动定时 flush 调度(根据 flushInterval)。 +2. 事件写入(track) + - 检查 SDK 是否已 init; + - 构造 Event: + - `system_code` from config + - `eventType` from 调用 + - `userInfo` from `setUser` + - `clientType` from config + - `clientTimestamp` = 当前毫秒时间戳 + - `timestamp` = ISO8601 字符串 + - `deviceInfo` from 初始化采集 + - `eventParams`、`customTags` from 调用 + - 事件入内存队列 + 异步持久化保存。 +3. 缓存与发送策略 + - 存储: + - SQLite / KV + 索引; + - 最大缓存条数:`maxCacheSize`,超限则删除最旧事件。 + - 发送: + - 定时器触发 flush; + - 队列长度 >= `batchSize` 可立即 flush; + - 调用 `AddEventListLog` 批量上传; + - 如后端明确不支持,可选降级 `AddEventLog`。 + - 重试: + - 网络错误或 5xx 重试,最多 `maxRetryCount`,指数退避; + - 4xx 视为业务失败,不重试,直接丢弃该批,并记录错误(日志)。 +4. 安全与稳定 + - endpoint 必须为 HTTPS; + - 预留请求 header 扩展(签名 / 时间戳 / nonce)。 + - 所有 IO 和网络在后台线程 / async,不阻塞 UI; + - 所有异常在 SDK 内部捕获,不向上抛出导致崩溃。 + +### 4.3 开发要求 + +通用: + +- 核心逻辑单元测试覆盖率 ≥ 80%(事件构造、缓存、上传、重试)。 +- 使用统一的日志前缀(例如 `[AnalyticsSDK]`)。 +- API 文档齐全,含参数说明和示例代码。 + +Flutter: + +- 不引入过重依赖,确保兼容常见 Flutter stable 版本; +- 高频 track 时(例如 10 次/秒)主 Isolate 无明显卡顿。 + +Android: + +- 支持主流 Android 版本(按照公司基线,例如 API 21+); +- 在 debug 版开启详细日志,release 版关闭。 + +iOS: + +- 支持主流 iOS 版本(例如 iOS 12+); +- 保证在 App 退后台 / 杀进程前能尽可能 flush。 + +### 4.4 Phase 1 验收标准 + +功能: + +- 三端均可: + `init → setUser → track → flush` 全流程成功; +- 离线: + - 断网时事件成功写入本地; + - 恢复网络后自动/手动 flush,可在后端查看到补发数据; +- 批量: + - 实际调用 `AddEventListLog`; + - 后端数据结构与约定一致(字段正确)。 + +稳定: + +- 连续调用 track 1 万次以内无崩溃; +- 事件缓存满时按预期丢弃最旧数据,不影响业务。 + +安全: + +- 所有请求通过 HTTPS; +- 默认不输出包含 userInfo 的敏感日志(除非显式 enableDebug)。 + +文档: + +- 各端接入指南(集成、初始化、上报示例); +- 一份基础 FAQ(常见错误、排查方式)。 + +------ + +## Phase 2:可维护性 + 配置化 + 调试能力 + +### 5.1 目标 + +- 降低埋点维护成本; +- 支持通过后端配置管理事件和维度; +- 提供调试和校验工具,提高埋点正确率。 + +### 5.2 能力范围 + +1. 利用 `GetSystemAllDimInfo` 下发配置 + +- SDK 在 init 后或定期调用: + - 获取 `systemInfo`、`systemEventTypes`、`systemCustonTas`; +- 转换成本地配置对象,缓存到本地(带 version / lastModified): + +ts + +``` +type EventDefinition = { + eventCode: string + eventName: string + description?: string +} + +type TagDefinition = { + tagName: string + tagType: string // string/int/bool/enum + isRequired: boolean + description?: string +} +``` + +- 失败不影响事件发送(降级为无配置模式)。 + +1. 事件校验 + +- 在 `track` 时(主要在 debug 模式启用): + - 校验 `eventType` 是否存在于 `systemEventTypes`; + - 使用 `systemCustonTas` 检查: + - 必填 tag 是否存在; + - 类型是否匹配(尝试容错转换)。 +- 错误处理: + - Debug 模式: + - 在日志中详细打印:未注册事件、缺失字段、类型错误; + - 可配置:是否禁止发送这类事件。 + - Release 模式: + - 仍发送,但在 `customTags` 中附加: + - `_sdk_invalid_event` + - `_sdk_missing_tags` + - `_sdk_type_error_fields` + +1. 调试工具 + +- 日志级: + - `setDebug(true)` 时: + - 打印每条事件的 JSON; + - 打印发送结果(状态码、错误内容)。 +- Demo 内调试页面(建议): + - 支持: + - 查看缓存事件数量 / 最近 N 条事件摘要; + - 按钮触发 flush。 + +1. 队列与策略优化(基本) + +- 事件过期时间(例如默认 7 天); +- 网络状态感知(原生): + - Wi-Fi 下更高频 / 大批次; + - 蜂窝网络下减少频率 / 批量。 + +### 5.3 开发要求 + +- 新增模块: + - `ConfigManager`:拉取与缓存后端维度配置; + - `Validator`:统一事件校验逻辑。 +- 兼容 Phase 1: + - 未取到配置时,一切行为回退到 Phase 1 模式; +- 增加测试: + - 事件存在 / 不存在; + - 必填字段缺失; + - 类型错误时的行为。 + +### 5.4 Phase 2 验收标准 + +功能: + +- 初始化后,可以成功调用 `GetSystemAllDimInfo` 并本地缓存; +- 在 debug 模式下: + - 未配置的 `eventType` 调用时有明确日志提示; + - 缺失必填 tag / 类型错误能被检测并打印提示。 + +调试体验: + +- 开发可以在本地: + - 看到完整事件 JSON; + - 根据提示迅速发现埋点错漏。 + +可维护性: + +- 后端新增事件配置(systemEventTypes 中新增)后,不发版即可在客户端调用新事件; +- 对关键事件,可以通过配置 + SDK 校验,显著减少埋点错误。 + +------ + +## Phase 3:可观测性 + 动态策略 + 插件化 + +### 6.1 目标 + +- 让 SDK 自身「可被监控、可被远程控制」; +- 支持高级使用场景:采样、动态开关、插件扩展。 + +### 6.2 能力范围 + +1. SDK 自身监控埋点 + +- 内部采集 SDK 运行指标(作为特殊事件上报): + - 发送成功计数 / 失败计数 / 重试次数; + - 平均延迟; + - 队列当前长度 / 溢出丢弃数; +- 周期性上报(如每 N 分钟一次)。 + +1. 动态策略控制 + +- 通过配置(可在 `GetSystemAllDimInfo` 扩展,或单独接口)下发策略,如: + +jsonc + +``` +{ + "enabled": true, + "eventSettings": { + "EVENT_A": { "enabled": true, "sampleRate": 1.0 }, + "EVENT_B": { "enabled": false, "sampleRate": 0.0 }, + "EVENT_C": { "enabled": true, "sampleRate": 0.1 } + } +} +``` + +- SDK 在 `track` 时: + - 若事件被标记 `enabled=false` → 直接丢弃; + - 若 `sampleRate < 1` → 按采样率丢弃部分事件(哈希或随机)。 + +1. 插件 / 拦截器机制 + +- 接口示例(通用设计): + +ts + +``` +interface EventInterceptor { + beforeSend(event: Event): Event | null | Promise + afterSend(event: Event, result: SendResult): void | Promise +} +``` + +- SDK 提供: + - `registerInterceptor(interceptor)` / `addInterceptor` 方法; + - 内置拦截器:debug 打印、公共字段填充等。 + +典型用途: + +- 业务统一追加自定义 `customTags`(如租户 ID、业务线 ID); +- 将部分发送失败事件写入本地日志,便于问题排查。 + +1. 版本管理 + +- 事件级 schemaVersion 预留: + - 在 `customTags` 或 `eventParams` 中加入 `_schema_version`。 +- SDK 版本上报: + - 每条事件默认携带 `_sdk_version` 和 `_platform`,便于后端统计版本分布。 + +### 6.3 开发要求 + +- 性能: + - 插件链路运行开销可控(单条事件处理在毫秒级以内); +- 隔离: + - 单个插件抛出的异常不会影响主流程和其他插件; +- 文档: + - 清晰说明策略配置字段及含义; + - 插件开发 & 使用指南。 + +### 6.4 Phase 3 验收标准 + +- 自监控: + - 后端可以查看 SDK 的发送成功率、失败率、队列长度等; +- 动态控制: + - 通过配置关闭某个 eventType 后,客户端不再上报该事件; + - 调整 sampleRate 后,事件量按预期变化; +- 插件: + - 样例插件能实现: + - 自动附加业务 tag; + - 记录失败事件到本地日志。 + +------ + +这版方案已经: + +- 明确:Flutter 为独立纯 Dart SDK,与 Android/iOS 平行; +- 统一:三端对外 API、数据结构、阶段目标和验收标准; +- 预留:维度配置、校验、动态策略、插件机制的扩展空间。 \ No newline at end of file diff --git a/1.统一模型 & 规范(细化).md b/1.统一模型 & 规范(细化).md new file mode 100644 index 0000000..92e2c9a --- /dev/null +++ b/1.统一模型 & 规范(细化).md @@ -0,0 +1,530 @@ +## 一、统一模型 & 规范(细化) + +### 1.1 SDKConfig 统一规范 + +所有端保持字段一致,命名按各端风格适配: + +jsonc + +``` +{ + "systemCode": "OA_APP", + "endpointBaseUrl": "https://host/api/ExternalEventlogs", + "clientType": 1, // 1 Android, 2 iOS, 3 Flutter + "enableDebug": false, + + "batchSize": 20, // 单次最多上传条数 + "flushInterval": 15, // 秒,定时 flush 间隔 + "maxCacheSize": 5000, // 本地缓存最大事件条数 + "maxRetryCount": 3, // 最大重试次数 + + "connectTimeout": 5000, // ms + "readTimeout": 5000 // ms + + // 预留,将来可扩: + // "globalTags": { "appVersion": "1.0.0", "channel": "official" } +} +``` + +### 1.2 Event 内部字段规范 + +统一内部 Event 类字段(各端自行建模): + +ts + +``` +class Event { + String id; // 本地ID/主键 + String systemCode; + String eventType; + + UserInfo? userInfo; + int clientType; + int clientTimestamp; // ms + String timestamp; // ISO8601 + + DeviceInfo deviceInfo; + + Map? eventParams; + Map? customTags; + + int retryCount; // 已重试次数 + DateTime createTime; +} +``` + +------ + +## 二、Phase 1:可用 + 稳定(细化到类 & 表) + +### 2.1 通用逻辑(跨端统一) + +#### 2.1.1 发送流程(时序) + +1. App 调用 `Analytics.init(config)` +2. SDK: + - 保存 config + - 采集 DeviceInfo + - 初始化 Storage + - 启动定时任务(每 flushInterval 秒执行 flush) +3. App 调用 `Analytics.setUser(...)`(可多次) +4. App 调用 `Analytics.track(eventType, {...})`: + - 构造 Event + - 持久化入库 + - 如果缓存条数 ≥ batchSize:启动一次 flush +5. flush 流程: + - 从存储取前 `batchSize` 条事件; + - 调用 `AddEventListLog`: + - 成功:删除这些事件; + - 网络错/5xx:更新 retryCount,重排队,按指数退避调度; + - 4xx:记录日志,删除这些事件(视为「业务不可重试」)。 + +#### 2.1.2 本地表结构(推荐统一) + +SQLite 表 `events`: + +sql + +``` +CREATE TABLE events ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + payload TEXT NOT NULL, -- 事件完整 JSON + retry_count INTEGER NOT NULL DEFAULT 0, + create_time INTEGER NOT NULL -- ms since epoch +); +``` + +索引: + +sql + +``` +CREATE INDEX idx_events_create_time ON events(create_time); +``` + +> Flutter 可用 sqflite 按此结构实现。 + +------ + +### 2.2 Flutter SDK(Dart 独立实现) + +#### 2.2.1 目录结构建议 + +text + +``` +lib/ + analytics.dart // 对外 Facade + src/ + config/ + analytics_config.dart + model/ + event.dart + user_info.dart + device_info.dart + storage/ + event_storage.dart // 接口 + sqflite_event_storage.dart + network/ + api_client.dart + core/ + analytics_core.dart // EventManager + Scheduler + scheduler.dart + util/ + logger.dart + time_util.dart +``` + +#### 2.2.2 关键类职责 + +- `Analytics`(facade) + - 静态方法:`init / track / setUser / setDeviceInfo / flush / setDebug` + - 内部持有单例 `AnalyticsCore` +- `AnalyticsCore` + - 字段: + - `AnalyticsConfig _config` + - `UserInfo? _user` + - `DeviceInfo _device` + - `EventStorage _storage` + - `ApiClient _apiClient` + - `Timer? _timer` + - `bool _isFlushing` + - 方法: + - `init(config)` + - `setUser` + - `setDeviceInfo` + - `track(...)` + - `flush({bool force = false})` +- `EventStorage` 接口 + `SqfliteEventStorage` 实现 + - `Future insert(Event event)` + - `Future> fetchBatch(int limit)` + - `Future deleteByIds(List ids)` + - `Future count()` + - `Future trimToMaxSize(int maxSize)` +- `ApiClient` + - `Future sendBatch(List events)` + - POST `/AddEventListLog`,Body 为数组; + - 成功返回 true,失败 false 或抛异常。 + - (可选)单条 `sendSingle(Event)` 作降级方案。 +- `Scheduler` + - 内含 `Timer.periodic`; + - 每次 tick 调用 `core.flush()`; + - 通过 `_isFlushing` 防并发。 + +#### 2.2.3 技术要求(Flutter) + +- 使用 `async/await`,所有 IO 非阻塞; +- `Analytics` 所有对外 API 均返回 `Future`(init / track / flush)便于业务 await; +- 避免 `Timer` 仍在运行却对象已销毁:在必要时提供 `dispose`(可选)。 + +------ + +### 2.3 Android SDK(Kotlin) + +#### 2.3.1 目录结构建议 + +text + +``` +com.company.analytics/ + Analytics.kt // Facade + config/ + AnalyticsConfig.kt + model/ + Event.kt + UserInfo.kt + DeviceInfo.kt + storage/ + EventDao.kt + EventDatabase.kt + network/ + ApiService.kt + NetworkClient.kt + core/ + AnalyticsCore.kt + FlushScheduler.kt + util/ + Logger.kt + TimeUtil.kt +``` + +#### 2.3.2 关键实现要点 + +- Room 表结构: + +kotlin + +``` +@Entity(tableName = "events") +data class EventEntity( + @PrimaryKey(autoGenerate = true) val id: Long = 0, + @ColumnInfo(name = "payload") val payload: String, + @ColumnInfo(name = "retry_count") val retryCount: Int = 0, + @ColumnInfo(name = "create_time") val createTime: Long = System.currentTimeMillis() +) +``` + +- DAO: + +kotlin + +``` +@Dao +interface EventDao { + @Insert + suspend fun insert(entity: EventEntity) + + @Query("SELECT * FROM events ORDER BY create_time ASC LIMIT :limit") + suspend fun fetchBatch(limit: Int): List + + @Query("DELETE FROM events WHERE id IN (:ids)") + suspend fun deleteByIds(ids: List) + + @Query("SELECT COUNT(*) FROM events") + suspend fun count(): Int + + @Query(""" + DELETE FROM events WHERE id IN ( + SELECT id FROM events ORDER BY create_time ASC LIMIT + (SELECT MAX(0, COUNT(*) - :maxSize) FROM events) + ) + """) + suspend fun trimToMaxSize(maxSize: Int) +} +``` + +- 调度: + - 使用 `CoroutineScope(SupervisorJob() + Dispatchers.IO)`; + - `FlushScheduler` 用 `delay` 或 `TickerChannel` 实现周期任务; + - 使用 `Mutex` 或 flag 控制“单一 flush”。 + +------ + +### 2.4 iOS SDK(Swift) + +#### 2.4.1 目录结构建议 + +text + +``` +AnalyticsSDK/ + Analytics.swift // Facade + Config/ + AnalyticsConfig.swift + Model/ + Event.swift + UserInfo.swift + DeviceInfo.swift + Storage/ + EventStorage.swift + SQLiteEventStorage.swift + Network/ + ApiClient.swift + Core/ + AnalyticsCore.swift + FlushScheduler.swift + Util/ + Logger.swift + TimeUtil.swift +``` + +#### 2.4.2 关键实现要点 + +- 存储: + - 使用 SQLite(用 FMDB/GRDB 等封装,或自己写简单 wrapper); +- 网络: + - URLSession + Codable 序列化; +- 定时: + - `Timer.scheduledTimer` 或 `DispatchSourceTimer`; +- 生命周期: + - 订阅 `UIApplication` 通知,在进入后台前调用 `flush()`。 + +------ + +### 2.5 Phase 1 验收 checklist(落地用) + +- 三端提供初始化、用户设置、事件上报、flush API; +- 本地缓存可持久化,多次启动数据不丢; +- 断网 → 上报 → 恢复,事件能补发到后端; +- 压测 10K 条事件,上报成功率可接受(> 99%,无 crash); +- 业务方集成 Demo App 并通过功能测试。 + +------ + +## 三、Phase 2:配置化 + 校验 + 调试(细化) + +### 3.1 新增数据结构 + +#### 3.1.1 维度配置缓存(本地) + +以通用视角描述,三端类似: + +ts + +``` +class SystemDimInfo { + SystemInfo systemInfo; + List eventDefinitions; + List tagDefinitions; + DateTime lastFetchedAt; + String? version; // 从后端 header 或 body 获得 +} +``` + +- `EventDefinition` 来自 `systemEventTypes`: + - `eventCode`, `eventName`, `description` +- `TagDefinition` 来自 `systemCustonTas`: + - `tag_name`, `tag_type`, `is_required`, `description` + +本地可存储在: + +- Flutter:sqflite/hive 单独表/box; +- Android:Room 新表 `config`; +- iOS:UserDefaults / SQLite。 + +### 3.2 ConfigManager / DimensionManager + +职责: + +- 拉取 `GetSystemAllDimInfo(system_code)`; +- 解析为 `SystemDimInfo`; +- 序列化到本地; +- 提供只读访问 API 给 Validator。 + +调用时机: + +- init 成功后异步拉取; +- 间隔 N 小时(如 12 / 24h)自动刷新; +- 提供 `forceRefresh()` 接口(仅 debug 使用)。 + +### 3.3 Validator 详细逻辑 + +以伪代码描述: + +ts + +``` +validateEvent(event: Event): ValidationResult { + let result = new ValidationResult() + + // 1. eventType 是否在配置中 + if (!config.hasEvent(event.eventType)) { + result.addError("UNKNOWN_EVENT_TYPE") + } + + // 2. 校验必填 tag(customTags) + let requiredTags = config.getRequiredTags() + for (tag in requiredTags) { + if (!event.customTags?.containsKey(tag.name)) { + result.addWarning("MISSING_REQUIRED_TAG", tag.name) + } + else { + // 3. 简单类型校验 + if (!typeMatch(event.customTags[tag.name], tag.type)) { + result.addWarning("TYPE_MISMATCH", tag.name) + } + } + } + + return result +} +``` + +- Debug 模式: + - 所有 `errors` + `warnings` 打到日志; + - 可选策略:有 error 的事件不发送。 +- Release 模式: + - 仍发送,但将错误信息 encode 到 `customTags._sdk_validation` 中。 + +### 3.4 调试支持细化 + +#### 3.4.1 日志规范 + +统一日志前缀与级别: + +- `[AnalyticsSDK][DEBUG] ...` +- `[AnalyticsSDK][ERROR] ...` + +在 debug 打开时: + +- 打印: + - 初始化配置; + - 事件构造后的 JSON; + - 每次发送的批次大小、结果状态码; + - 校验结果(仅 debug)。 + +#### 3.4.2 Demo 调试面板(可选但推荐) + +Flutter / 原生各自 Demo App 中: + +- 提供一个 Debug 页面: + - 显示当前缓存条数; + - 最近 20 条事件简要信息(id、eventType、createTime、是否校验通过); + - 按钮:`Flush Now`,调用 `Analytics.flush()`。 + +------ + +## 四、Phase 3:监控 + 动态策略 + 插件(细化) + +### 4.1 SDK 自监控事件设计 + +定义一批内部保留事件(只你们自己分析用): + +- `SDK_METRICS_SEND`: + - 字段: + - `sentCount` + - `failedCount` + - `retryCount` + - `avgLatencyMs` +- `SDK_METRICS_QUEUE`: + - 字段: + - `queueSize` + - `droppedEvents` + +实现: + +- 在 SDK 内部维护计数器; +- 每隔 M 分钟(如 10 分钟)封装成 Event,正常通过日志接口上报。 + +### 4.2 策略配置结构 + +可通过扩展 `GetSystemAllDimInfo` 或另建接口下发 JSON,例如: + +jsonc + +``` +{ + "sdkStrategy": { + "enabled": true, + "defaultSampleRate": 1.0, + "eventSettings": { + "PAGE_VIEW": { "enabled": true, "sampleRate": 0.2 }, + "DEBUG_EVENT": { "enabled": false, "sampleRate": 0.0 } + } + } +} +``` + +SDK 行为: + +- 加载策略后: + - `if !strategy.enabled`:`track` 直接返回,不做任何事情(紧急开关)。 + - 查找具体 eventType 的策略: + - `enabled=false` → 直接丢; + - `sampleRate<1` → 按 sampleRate 随机采样(或使用 eventId hash)。 + +### 4.3 插件机制设计 + +通用接口(以伪代码): + +ts + +``` +interface EventInterceptor { + beforeSend(event: Event): Event | null | Promise + afterSend(event: Event, result: SendResult): void | Promise +} +``` + +- SDK 内部维护 `List`; +- 在真正上传前,按顺序调用 `beforeSend`: + - 任一返回 null → 事件被拦截,标记为丢弃; +- 上传结束后,按顺序调用 `afterSend`。 + +错误隔离: + +ts + +``` +for interceptor in interceptors: + try { + event = interceptor.beforeSend(event) + } catch (e) { + log.warn("interceptor error: ", e) + } +``` + +示例内置插件: + +- DebugInterceptor: + - beforeSend 打印事件 JSON(受 debug 开关控制); +- CommonTagsInterceptor: + - 自动在 customTags 注入 `_sdk_version`、`_platform` 等。 + +------ + +## 五、落地实施建议(简短) + +### 5.1 Phase 1 任务拆分(多端并行) + +- 架构公共约定 & 协议定义(1~2 天) +- Flutter SDK Phase 1 实现(约 5~10 个工作日) +- Android SDK Phase 1 实现(约 5~10 天) +- iOS SDK Phase 1 实现(约 5~10 天) +- 后端联调 & Demo App 验证(3~5 天) + +### 5.2 后续 Phase 2/3 可以按版本迭代 + +- v1.x:只做 Phase 1,快速在一个业务 App 落地; +- v2.x:引入配置拉取 + 校验 + Debug 面板; +- v3.x:按需要逐步加上策略控制 & 插件。 \ No newline at end of file diff --git a/2.Flutter 埋点 SDK 设计方案(独立 Dart 实现).md b/2.Flutter 埋点 SDK 设计方案(独立 Dart 实现).md new file mode 100644 index 0000000..a7eb7a9 --- /dev/null +++ b/2.Flutter 埋点 SDK 设计方案(独立 Dart 实现).md @@ -0,0 +1,446 @@ + + +# Flutter 埋点 SDK 设计方案(独立 Dart 实现) + +## 1. 概述 + +### 1.1 背景 + +为企业内部 OA / 教育等应用统一建设埋点能力,当前后端已提供日志上报接口: + +- `GET /api/ExternalEventlogs/GetSystemAllDimInfo` +- `POST /api/ExternalEventlogs/AddEventListLog` +- `POST /api/ExternalEventlogs/AddEventLog` + +需要基于上述接口,开发一个独立的 Flutter 埋点 SDK(纯 Dart 实现),并规划三阶段能力演进。 + +### 1.2 目标 + +- 开发 Flutter 独立埋点 SDK 包(例如:`company_analytics_sdk`)。 +- 提供统一的初始化、事件上报、缓存与批量上报能力。 +- 三阶段演进目标: + - Phase 1:可用性 + 安全稳定性。 + - Phase 2:可维护性 + 配置化 + 调试。 + - Phase 3:可观测性 + 动态策略 + 插件化。 + +--- + +## 2. 统一模型与对外 API + +### 2.1 统一事件数据结构(对齐后端) + +```jsonc +{ + "system_code": "string", + "eventType": "string", + "userInfo": { + "userId": 0, + "userName": "string", + "account": "string" + }, + "clientType": 1, + "clientTimestamp": 0, + "timestamp": "2026-01-26T08:29:44.734Z", + "deviceInfo": { + "os": "string", + "model": "string", + "screenResolution": "string" + }, + "eventParams": { + // 事件上下文 + }, + "customTags": { + // 业务维度 + } +} +``` + +### 2.2 Flutter SDK 对外 Facade API + +```dart +class Analytics { + static Future init(AnalyticsConfig config); + + static Future track( + String eventType, { + Map? eventParams, + Map? customTags, + int? timestamp, // ms + }); + + static Future setUser(UserInfo? userInfo); + + static Future setDeviceInfo(DeviceInfo deviceInfo); + + static Future flush(); + + static void setDebug(bool enabled); + + // Phase 3 + static void addInterceptor(AnalyticsInterceptor interceptor); +} +``` + +### 2.3 SDKConfig 统一规范 + +```dart +class AnalyticsConfig { + final String systemCode; + final String endpointBaseUrl; // https://host/api/ExternalEventlogs + final int clientType; // 1=Android, 2=iOS, 3=Flutter + final bool enableDebug; + + final int batchSize; // 默认 20 + final int flushInterval; // 秒,默认 15 + final int maxCacheSize; // 默认 5000 + final int maxRetryCount; // 默认 3 + + final Duration connectTimeout; // 默认 5s + final Duration readTimeout; // 默认 5s + + const AnalyticsConfig({ + required this.systemCode, + required this.endpointBaseUrl, + required this.clientType, + this.enableDebug = false, + this.batchSize = 20, + this.flushInterval = 15, + this.maxCacheSize = 5000, + this.maxRetryCount = 3, + this.connectTimeout = const Duration(seconds: 5), + this.readTimeout = const Duration(seconds: 5), + }); +} +``` + +--- + +## 3. 包结构与模块划分 + +### 3.1 目录结构(建议) + +```text +lib/ + company_analytics.dart // 对外 Facade(唯一入口) + + src/ + config/ + analytics_config.dart // SDKConfig + config_manager.dart // (Phase 2+) 维度 & 策略配置 + + model/ + event.dart // Event, StoredEvent + user_info.dart + device_info.dart + system_dim_info.dart // (Phase 2+) SystemInfo, EventDefinition, TagDefinition + + storage/ + event_storage.dart // 抽象接口 + sqflite_event_storage.dart // SQLite 实现 + + network/ + api_client.dart // 与后端 API 通信 + http_client.dart // 封装 Dio / http + + core/ + analytics_core.dart // 主逻辑:init/track/flush + scheduler.dart // 定时任务 & 并发控制 + validator.dart // (Phase 2+) 事件校验 + interceptors.dart // (Phase 3) 插件接口 & 管理 + + util/ + logger.dart // 日志 & debug 控制 + time_util.dart // 时间格式化 + device_util.dart // 获取 os/model/screenResolution + id_generator.dart // 本地 eventId 生成 +``` + +### 3.2 核心模型 + +UserInfo: + +```dart +class UserInfo { + final int? userId; + final String? userName; + final String? account; + + const UserInfo({this.userId, this.userName, this.account}); + + Map toJson() => { + 'userId': userId, + 'userName': userName, + 'account': account, + }..removeWhere((k, v) => v == null); +} +``` + +DeviceInfo: + +```dart +class DeviceInfo { + final String os; + final String model; + final String screenResolution; + + const DeviceInfo({ + required this.os, + required this.model, + required this.screenResolution, + }); + + Map toJson() => { + 'os': os, + 'model': model, + 'screenResolution': screenResolution, + }; +} +``` + +Event: + +```dart +class Event { + final String systemCode; + final String eventType; + final UserInfo? userInfo; + final int clientType; + final int clientTimestamp; + final String timestamp; + final DeviceInfo deviceInfo; + final Map? eventParams; + final Map? customTags; + final DateTime createTime; + final int retryCount; + + Event({ + required this.systemCode, + required this.eventType, + required this.userInfo, + required this.clientType, + required this.clientTimestamp, + required this.timestamp, + required this.deviceInfo, + required this.eventParams, + required this.customTags, + required this.createTime, + this.retryCount = 0, + }); + + Map toJson() => { + 'system_code': systemCode, + 'eventType': eventType, + 'userInfo': userInfo?.toJson(), + 'clientType': clientType, + 'clientTimestamp': clientTimestamp, + 'timestamp': timestamp, + 'deviceInfo': deviceInfo.toJson(), + 'eventParams': eventParams, + 'customTags': customTags, + }; +} +``` + +StoredEvent: + +```dart +class StoredEvent { + final int id; + final Event event; + final int retryCount; + final DateTime createTime; + + StoredEvent({ + required this.id, + required this.event, + required this.retryCount, + required this.createTime, + }); +} +``` + +--- + +## 4. Phase 1:可用性 + 安全稳定性 + +### 4.1 功能范围 + +- SDK 初始化: + - 校验 `AnalyticsConfig`; + - 自动采集 `DeviceInfo`; + - 初始化本地 SQLite 存储; + - 启动定时 flush 任务。 +- 事件上报: + - 构造 Event(system_code、userInfo、deviceInfo、时间戳等); + - 异步写入本地队列(SQLite)。 +- 批量上传: + - 定时 & 条数触发 flush; + - 调用 `POST /AddEventListLog`; + - 处理重试 / 失败 / 删除等逻辑。 +- 安全: + - endpoint 强制 HTTPS; + - 预留 header 扩展(签名等)。 + +### 4.2 本地存储设计(Sqflite) + +表结构: + +```sql +CREATE TABLE events ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + payload TEXT NOT NULL, + retry_count INTEGER NOT NULL DEFAULT 0, + create_time INTEGER NOT NULL +); + +CREATE INDEX idx_events_create_time ON events(create_time); +``` + +接口:`EventStorage` + +```dart +abstract class EventStorage { + Future init(); + Future insert(Event event); + Future> fetchBatch(int limit); + Future deleteByIds(List ids); + Future count(); + Future trimToMaxSize(int maxSize); + Future updateRetryCount(int id, int retryCount); +} +``` + +使用 `SqfliteEventStorage` 具体实现。 + +### 4.3 网络层 ApiClient + +- 基于 `dio` 或 `http` 实现: + - `sendBatch(List events)` 调用 `/AddEventListLog`。 +- 超时控制:使用 `config.connectTimeout` / `readTimeout`。 + +### 4.4 核心逻辑 AnalyticsCore + +职责: + +- 保存配置、用户状态、设备信息。 +- `track`:构造 Event、写入存储、触发 flush。 +- `flush`:从本地取批量事件,调用 ApiClient,上报异常处理和重试。 + +关键点: + +- 使用 `_isFlushing` 标志防止并发 flush; +- 使用 `Scheduler`(Timer.periodic)实现周期 flush; +- 所有 IO 调用 async/await,避免阻塞 UI。 + +### 4.5 Phase 1 验收标准(Flutter) + +- 功能: + - Demo 中完成初始化、用户设置、事件上报、flush; + - 断网时事件写入本地,恢复网络后自动/手动 flush 成功。 +- 稳定性: + - 高频 `track`(10 次/秒,5 分钟)无 crash、无明显卡顿。 +- 安全: + - 所有请求走 HTTPS; + - 默认不打印 userInfo 等敏感数据(除非 debug=true)。 +- 文档: + - 接入文档 + 示例代码。 + +--- + +## 5. Phase 2:配置化 + 校验 + 调试 + +### 5.1 配置下发(GetSystemAllDimInfo) + +- Flutter SDK 调用: + - `GET /GetSystemAllDimInfo?system_code=xxx` +- 解析为: + - `SystemInfo` + - `EventDefinition` 列表(来自 `systemEventTypes`) + - `TagDefinition` 列表(来自 `systemCustonTas`) + +本地缓存为 `SystemDimInfo`(可存 SQLite / hive / SharedPreferences)。 + +### 5.2 ConfigManager + +- 负责: + - 首次 init 后拉取配置; + - 定期刷新; + - 提供当前配置给 Validator 使用。 + +### 5.3 Validator 事件校验 + +- 校验点: + - `eventType` 是否在配置中存在; + - 必填 tag(来自 `TagDefinition.isRequired`)是否存在于 `customTags`; + - 简单类型检查(int/bool/string)。 + +策略: + +- Debug 模式: + - 日志详细提示未知事件、缺失字段、类型错误; + - 可配置是否阻断发送。 +- Release 模式: + - 不阻断,错误信息写入 `customTags._sdk_validation`。 + +### 5.4 调试能力 + +- 日志: + - `Logger` 控制 debug 开关; + - 打印事件 JSON、发送结果、校验结果。 +- Demo 调试界面(推荐): + - 展示缓存事件数量 / 最近 N 条; + - 提供“立即 flush”按钮。 + +--- + +## 6. Phase 3:可观测性 + 策略 + 插件 + +### 6.1 SDK 自监控 + +- 内部统计: + - 发送成功次数 / 失败次数; + - 重试次数; + - 队列长度 / 溢出丢弃个数。 +- 周期上报为特殊事件(如 `SDK_METRICS_SEND`/`SDK_METRICS_QUEUE`)。 + +### 6.2 动态策略控制 + +- 从配置中下发策略字段,例如: + +```jsonc +{ + "sdkStrategy": { + "enabled": true, + "defaultSampleRate": 1.0, + "eventSettings": { + "PAGE_VIEW": { "enabled": true, "sampleRate": 0.2 }, + "DEBUG_EVENT": { "enabled": false, "sampleRate": 0.0 } + } + } +} +``` + +- `track` 时根据策略: + - 全局关停:直接丢弃全部事件; + - 单事件关闭:丢弃该 eventType; + - 按 sampleRate 采样丢弃部分事件。 + +### 6.3 插件(拦截器)机制 + +接口示例: + +```dart +abstract class AnalyticsInterceptor { + Future beforeSend(Event event) async => event; + Future afterSend(Event event, bool success) async {} +} +``` + +- 在 `AnalyticsCore` 中注册多个拦截器; +- flush 时在实际发送前后调用; +- 捕获拦截器内部异常,不影响主流程。 + +内置拦截器示例: + +- `DebugInterceptor`:打印事件详细信息; +- `CommonTagsInterceptor`:为所有事件追加 `_sdk_version`、`_platform` 等 tag。 diff --git a/3.Flutter todo list.md b/3.Flutter todo list.md new file mode 100644 index 0000000..b0219ae --- /dev/null +++ b/3.Flutter todo list.md @@ -0,0 +1,138 @@ +## 一、准备阶段 + +### A. 项目初始化 + +- [x] 创建 Flutter package 工程(当前包名:`yx_tracking_flutter`) +- [x] 配置 `pubspec.yaml`(已添加 `sqflite`、`path_provider`、`dio`、`path`) +- [x] 配置 SDK 最低支持 Flutter / Dart 版本(Flutter `>=3.22.0`,Dart `>=3.3.0 <4.0.0`) +- [x] 建立基础目录结构(入口为 `lib/yx_tracking_flutter.dart`,`lib/src/*` 已建立) +- [x] 约定统一代码风格(使用 `flutter_lints`) + +------ + +## 二、Phase 1 开发任务(可用性 + 稳定性) + +### 1. 基础模型与配置 + +- [x] 实现 `AnalyticsConfig`(含 HTTPS 与参数校验) +- [x] 实现 `UserInfo` +- [x] 实现 `DeviceInfo` +- [x] 实现 `Event` & `StoredEvent`(含 payload 序列化/反序列化) +- [x] 实现 `TimeUtil`(时间戳 & ISO8601 格式化) +- [x] 实现 `Logger`(debug/info/warn/error,debug 开关控制) +- [x] 实现 `DeviceUtil`(采集 os/model/screenResolution 的最小实现) + +### 2. 存储层(EventStorage + Sqflite) + +- [x] 抽象接口 `EventStorage`(含 init/insert/fetchBatch/delete/count/trim/updateRetryCount/dispose) +- [x] 实现 `SqfliteEventStorage`(建表、索引、CRUD、trim、retryCount 更新) +- [x] 封装事件反序列化(`Event.fromPayload` / `Event.fromJson`) +- [x] 稳定性修补:`fetchBatch` 会删除解析失败的坏数据,避免队列被卡死 + +### 3. 网络层(ApiClient) + +- [x] 封装 `HttpClient`(基于 Dio,支持超时与自定义 headers) +- [x] 实现 `ApiClient.sendBatch`(调用 `/AddEventListLog`) +- [x] 状态码与异常模型(`ApiException` 区分可重试/不可重试) + +### 4. 核心逻辑(AnalyticsCore + Scheduler) + +- [x] 实现 `Scheduler`(`Timer.periodic` + start/stop) +- [x] 实现 `AnalyticsCore.init`(校验配置、采集设备、初始化存储/网络、启动调度) +- [x] 实现 `track` 主流程(构造事件、入库、trim、达到 batchSize 触发 flush) +- [x] 实现 `flush`(互斥、防并发、批量发送、重试与退避) +- [x] 稳定性增强(重试退避、异常兜底、坏数据清理) +- [x] Phase 2 已接入(ConfigManager、Validator、配置周期刷新、release 校验标记) + +### 5. Facade 对外接口(company_analytics.dart) + +- [x] 暴露 `Analytics` Facade(入口文件:`lib/yx_tracking_flutter.dart`) +- [x] 已提供 `init/track/setUser/setDeviceInfo/flush/setDebug/dispose` +- [x] 调试 API:`cachedEventCount/cachedRecentEvents/refreshConfig/reportMetricsNow` +- [x] `addInterceptor(...)` 已实现(Phase 3) + +### 6. Phase 1 测试任务 + +- [x] 基础单测已存在(配置校验、事件序列化/反序列化) +- [x] `EventStorage` 行为测试已覆盖(trim、fetchRecent、retryCount 更新等契约测试) +- [x] `AnalyticsCore.track/flush` 成功与失败重试路径测试已覆盖 +- [x] 已完成 mock 集成测试与压力测试(断网恢复补发、track 1 万次稳定性) + +------ + +## 三、Phase 2 开发任务(配置化 + 校验 + 调试) + +### 1. 配置模型 & 持久化 + +- [x] 定义 `SystemInfo / EventDefinition / TagDefinition / SystemDimInfo` +- [x] 使用 sqflite 同库缓存配置(表:`config_cache`) +- [x] 已实现 `saveSystemDimInfo / loadSystemDimInfo` + +### 2. ConfigManager + +- [x] 已实现 `ConfigManager`(持有 `currentConfig`、支持缓存加载与拉取) +- [x] 已接入 `GET /GetSystemAllDimInfo?system_code=...` +- [x] 已在 `AnalyticsCore.init` 中异步拉取(失败不影响埋点) +- [x] 周期刷新已补齐(定时器按 refreshInterval 拉取) + +### 3. Validator(事件校验) + +- [x] 已实现 `Validator`(依赖 `ConfigManager`,输出 `ValidationResult`) +- [x] 已在 `AnalyticsCore.track` 中接入校验并打印 errors/warnings +- [x] Release 模式已补充校验标记(写入 `_sdk_invalid_event/_sdk_missing_tags/_sdk_type_error_fields`) +- [x] “严重 error 阻断发送”的策略开关已实现(`blockOnValidationError`) + +### 4. 调试增强 + +- [x] `Logger` 已具备 debug/info/warn/error 级别与 debug 开关 +- [x] 关键路径日志已接入(init/track/flush/validator/config) +- [x] 已提供 Demo 调试界面(`example/`) +- [x] Demo 已支持:缓存条数、最近事件摘要、Track Demo Event、Flush Now、Refresh Config + +### 5. Phase 2 测试任务 + +- [x] 配置拉取测试已覆盖(正确/错误 JSON、刷新跳过、缓存保持) +- [x] 校验行为测试已覆盖(未知事件、缺失必填、类型不匹配) +- [x] “配置失败不影响发送”的降级路径已覆盖(无配置仍可 track/flush) + +------ + +## 四、Phase 3 开发任务(监控 + 策略 + 插件) + +### 1. 自监控埋点 + +- [x] 已在 `AnalyticsCore` 中增加统计字段(sent/failed/retry/dropped、平均延迟、窗口时间) +- [x] 已在 flush 成功 / 失败 / 删除 / 丢弃等位置更新计数 +- [x] 已实现指标上报(定时器 + 内部事件 `SDK_METRICS_SEND / SDK_METRICS_QUEUE`) +- [x] 已提供调试入口:`Analytics.reportMetricsNow()` + +### 2. 策略控制(采样与开关) + +- [x] 已在 `SystemDimInfo` 中增加策略字段(`SdkStrategy / EventStrategy`) +- [x] 已在 `ConfigManager` 中解析并缓存策略 +- [x] 已在 `AnalyticsCore.track` 入口接入策略(全局开关 / 事件开关 / 采样率) + +### 3. 插件(拦截器)机制 + +- [x] 已定义接口 `AnalyticsInterceptor`(`beforeSend / afterSend`) +- [x] 已在 `AnalyticsCore` 中维护拦截器列表并实现 `addInterceptor(...)` +- [x] 已在 flush 前调用 `beforeSend`(支持返回 null 拦截事件) +- [x] 已在 flush 后调用 `afterSend`(成功/失败均回调) +- [x] 已做异常隔离(拦截器异常不会影响主流程) +- [x] 已内置 `CommonTagsInterceptor`(自动追加 `_sdk_version/_platform`) + +### 4. Phase 3 测试任务 + +- [x] 自监控事件测试已覆盖(`reportMetricsNow` 生成 `SDK_METRICS_*` 事件) +- [x] 策略测试已覆盖(全局关闭、事件关闭、采样率) +- [x] 拦截器测试已覆盖(追加 tag、拦截事件、异常隔离、afterSend 回调) + +------ + +## 五、交付物与文档清单 + +- [x] SDK 源码(Flutter package) +- [x] 单元测试代码(关键路径已覆盖;覆盖率统计报告需单独产出) +- [x] 集成 Demo App(示例项目,含 Debug 页面) +- [x] 文档:README(使用说明 + 调试/拦截器/指标能力) +- [x] 文档:设计说明(`2.Flutter 埋点 SDK 设计方案(独立 Dart 实现).md`) diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..41cc7d8 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,3 @@ +## 0.0.1 + +* TODO: Describe initial release. diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..ba75c69 --- /dev/null +++ b/LICENSE @@ -0,0 +1 @@ +TODO: Add your license here. diff --git a/README.md b/README.md new file mode 100644 index 0000000..465f1e9 --- /dev/null +++ b/README.md @@ -0,0 +1,121 @@ +# yx_tracking_flutter + +企业级 Flutter 埋点 SDK(纯 Dart 实现),对齐后端接口: + +- `GET /api/ExternalEventlogs/GetSystemAllDimInfo` +- `POST /api/ExternalEventlogs/AddEventListLog` +- `POST /api/ExternalEventlogs/AddEventLog`(可选降级) + +当前已覆盖 Phase 1 / Phase 2 / Phase 3 的核心能力:初始化、持久化队列、批量上报、配置下发、校验、策略控制、拦截器与 SDK 自监控指标。 + +## 功能特性 + +- 统一事件模型,自动补齐公共字段(systemCode、deviceInfo、时间戳等) +- 本地持久化队列(sqflite),断网可缓存,恢复后补发 +- 批量上报 + 重试退避 + 队列上限裁剪 +- 配置下发(`GetSystemAllDimInfo`)与本地缓存 +- 事件校验(Debug 详细日志,Release 自动标记 `_sdk_*`) +- 动态策略(全局开关、事件级开关、采样率) +- 拦截器机制(beforeSend / afterSend,异常隔离) +- SDK 自监控指标(发送成功/失败/重试/丢弃、队列长度、平均延迟) + +## 快速开始 + +在你的 App 初始化阶段调用: + +```dart +import 'package:yx_tracking_flutter/yx_tracking_flutter.dart'; + +Future bootstrapAnalytics() async { + await Analytics.init( + const AnalyticsConfig( + systemCode: 'OA_APP', + endpointBaseUrl: 'https://your-host/api/ExternalEventlogs', + clientType: 3, + enableDebug: true, + ), + ); +} +``` + +上报事件: + +```dart +await Analytics.track( + 'PAGE_VIEW', + eventParams: const {'page': 'home'}, + customTags: const {'tenantId': 't1'}, +); +``` + +手动触发发送: + +```dart +await Analytics.flush(force: true); +``` + +## 关键配置项(AnalyticsConfig) + +除了文档中的 Phase 1 配置项,还新增了以下能力配置: + +- `enableMetrics`:是否启用 SDK 自监控指标(默认 `true`) +- `metricsReportInterval`:指标上报周期(默认 10 分钟) +- `blockOnValidationError`:Debug 下遇到校验 error 是否阻断发送(默认 `false`) + +所有配置项详见:`lib/src/config/analytics_config.dart` + +## 调试与运维能力 + +调试 API: + +```dart +final count = await Analytics.cachedEventCount(); +final recent = await Analytics.cachedRecentEvents(limit: 20); +await Analytics.refreshConfig(force: true); +await Analytics.reportMetricsNow(); +``` + +## 拦截器(Phase 3) + +```dart +class TenantInterceptor extends AnalyticsInterceptor { + @override + Future beforeSend(Event event) async { + final tags = Map.from(event.customTags ?? const {}); + tags['tenantId'] = 't1'; + return event.copyWith(customTags: tags); + } +} + +void setupInterceptors() { + Analytics.addInterceptor(TenantInterceptor()); +} +``` + +SDK 内置 `CommonTagsInterceptor`,会自动追加: + +- `_sdk_version` +- `_platform` + +## 运行示例 Demo + +仓库已包含最小调试 Demo: + +```bash +cd example +flutter run +``` + +Demo 提供:缓存条数、最近事件摘要、Track Demo Event、Flush Now、Refresh Config。 + +## 测试与校验 + +已通过以下本地校验: + +- 根目录:`flutter analyze` / `flutter test` +- example:`flutter analyze` / `flutter test` + +## 参考文档 + +- 设计方案:`2.Flutter 埋点 SDK 设计方案(独立 Dart 实现).md` +- 实施清单:`3.Flutter todo list.md` diff --git a/analysis_options.yaml b/analysis_options.yaml new file mode 100644 index 0000000..a5744c1 --- /dev/null +++ b/analysis_options.yaml @@ -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 diff --git a/example/.gitignore b/example/.gitignore new file mode 100644 index 0000000..3820a95 --- /dev/null +++ b/example/.gitignore @@ -0,0 +1,45 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.build/ +.buildlog/ +.history +.svn/ +.swiftpm/ +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 +**/doc/api/ +**/ios/Flutter/.last_build_id +.dart_tool/ +.flutter-plugins-dependencies +.pub-cache/ +.pub/ +/build/ +/coverage/ + +# Symbolication related +app.*.symbols + +# Obfuscation related +app.*.map.json + +# Android Studio will place build artifacts here +/android/app/debug +/android/app/profile +/android/app/release diff --git a/example/.metadata b/example/.metadata new file mode 100644 index 0000000..b11d65d --- /dev/null +++ b/example/.metadata @@ -0,0 +1,45 @@ +# 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: "ac4e799d237041cf905519190471f657b657155a" + channel: "stable" + +project_type: app + +# Tracks metadata for the flutter migrate command +migration: + platforms: + - platform: root + create_revision: ac4e799d237041cf905519190471f657b657155a + base_revision: ac4e799d237041cf905519190471f657b657155a + - platform: android + create_revision: ac4e799d237041cf905519190471f657b657155a + base_revision: ac4e799d237041cf905519190471f657b657155a + - platform: ios + create_revision: ac4e799d237041cf905519190471f657b657155a + base_revision: ac4e799d237041cf905519190471f657b657155a + - platform: linux + create_revision: ac4e799d237041cf905519190471f657b657155a + base_revision: ac4e799d237041cf905519190471f657b657155a + - platform: macos + create_revision: ac4e799d237041cf905519190471f657b657155a + base_revision: ac4e799d237041cf905519190471f657b657155a + - platform: web + create_revision: ac4e799d237041cf905519190471f657b657155a + base_revision: ac4e799d237041cf905519190471f657b657155a + - platform: windows + create_revision: ac4e799d237041cf905519190471f657b657155a + base_revision: ac4e799d237041cf905519190471f657b657155a + + # 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' diff --git a/example/README.md b/example/README.md new file mode 100644 index 0000000..2b3fce4 --- /dev/null +++ b/example/README.md @@ -0,0 +1,16 @@ +# example + +A new Flutter project. + +## Getting Started + +This project is a starting point for a Flutter application. + +A few resources to get you started if this is your first Flutter project: + +- [Lab: Write your first Flutter app](https://docs.flutter.dev/get-started/codelab) +- [Cookbook: Useful Flutter samples](https://docs.flutter.dev/cookbook) + +For help getting started with Flutter development, view the +[online documentation](https://docs.flutter.dev/), which offers tutorials, +samples, guidance on mobile development, and a full API reference. diff --git a/example/analysis_options.yaml b/example/analysis_options.yaml new file mode 100644 index 0000000..0d29021 --- /dev/null +++ b/example/analysis_options.yaml @@ -0,0 +1,28 @@ +# This file configures the analyzer, which statically analyzes Dart code to +# check for errors, warnings, and lints. +# +# The issues identified by the analyzer are surfaced in the UI of Dart-enabled +# IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be +# invoked from the command line by running `flutter analyze`. + +# The following line activates a set of recommended lints for Flutter apps, +# packages, and plugins designed to encourage good coding practices. +include: package:flutter_lints/flutter.yaml + +linter: + # The lint rules applied to this project can be customized in the + # section below to disable rules from the `package:flutter_lints/flutter.yaml` + # included above or to enable additional rules. A list of all available lints + # and their documentation is published at https://dart.dev/lints. + # + # Instead of disabling a lint rule for the entire project in the + # section below, it can also be suppressed for a single line of code + # or a specific dart file by using the `// ignore: name_of_lint` and + # `// ignore_for_file: name_of_lint` syntax on the line or in the file + # producing the lint. + rules: + # avoid_print: false # Uncomment to disable the `avoid_print` rule + # prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule + +# Additional information about this file can be found at +# https://dart.dev/guides/language/analysis-options diff --git a/example/android/.gitignore b/example/android/.gitignore new file mode 100644 index 0000000..be3943c --- /dev/null +++ b/example/android/.gitignore @@ -0,0 +1,14 @@ +gradle-wrapper.jar +/.gradle +/captures/ +/gradlew +/gradlew.bat +/local.properties +GeneratedPluginRegistrant.java +.cxx/ + +# Remember to never publicly share your keystore. +# See https://flutter.dev/to/reference-keystore +key.properties +**/*.keystore +**/*.jks diff --git a/example/android/app/build.gradle.kts b/example/android/app/build.gradle.kts new file mode 100644 index 0000000..21ecea9 --- /dev/null +++ b/example/android/app/build.gradle.kts @@ -0,0 +1,44 @@ +plugins { + id("com.android.application") + id("kotlin-android") + // The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins. + id("dev.flutter.flutter-gradle-plugin") +} + +android { + namespace = "com.example.example" + compileSdk = flutter.compileSdkVersion + ndkVersion = flutter.ndkVersion + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_11 + targetCompatibility = JavaVersion.VERSION_11 + } + + kotlinOptions { + jvmTarget = JavaVersion.VERSION_11.toString() + } + + defaultConfig { + // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). + applicationId = "com.example.example" + // You can update the following values to match your application needs. + // For more information, see: https://flutter.dev/to/review-gradle-config. + minSdk = flutter.minSdkVersion + targetSdk = flutter.targetSdkVersion + versionCode = flutter.versionCode + versionName = flutter.versionName + } + + buildTypes { + release { + // TODO: Add your own signing config for the release build. + // Signing with the debug keys for now, so `flutter run --release` works. + signingConfig = signingConfigs.getByName("debug") + } + } +} + +flutter { + source = "../.." +} diff --git a/example/android/app/src/debug/AndroidManifest.xml b/example/android/app/src/debug/AndroidManifest.xml new file mode 100644 index 0000000..399f698 --- /dev/null +++ b/example/android/app/src/debug/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + diff --git a/example/android/app/src/main/AndroidManifest.xml b/example/android/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..74a78b9 --- /dev/null +++ b/example/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,45 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/example/android/app/src/main/kotlin/com/example/example/MainActivity.kt b/example/android/app/src/main/kotlin/com/example/example/MainActivity.kt new file mode 100644 index 0000000..ac81bae --- /dev/null +++ b/example/android/app/src/main/kotlin/com/example/example/MainActivity.kt @@ -0,0 +1,5 @@ +package com.example.example + +import io.flutter.embedding.android.FlutterActivity + +class MainActivity : FlutterActivity() diff --git a/example/android/app/src/main/res/drawable-v21/launch_background.xml b/example/android/app/src/main/res/drawable-v21/launch_background.xml new file mode 100644 index 0000000..f74085f --- /dev/null +++ b/example/android/app/src/main/res/drawable-v21/launch_background.xml @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/example/android/app/src/main/res/drawable/launch_background.xml b/example/android/app/src/main/res/drawable/launch_background.xml new file mode 100644 index 0000000..304732f --- /dev/null +++ b/example/android/app/src/main/res/drawable/launch_background.xml @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/example/android/app/src/main/res/mipmap-hdpi/ic_launcher.png b/example/android/app/src/main/res/mipmap-hdpi/ic_launcher.png new file mode 100644 index 0000000..db77bb4 Binary files /dev/null and b/example/android/app/src/main/res/mipmap-hdpi/ic_launcher.png differ diff --git a/example/android/app/src/main/res/mipmap-mdpi/ic_launcher.png b/example/android/app/src/main/res/mipmap-mdpi/ic_launcher.png new file mode 100644 index 0000000..17987b7 Binary files /dev/null and b/example/android/app/src/main/res/mipmap-mdpi/ic_launcher.png differ diff --git a/example/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/example/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png new file mode 100644 index 0000000..09d4391 Binary files /dev/null and b/example/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png differ diff --git a/example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png new file mode 100644 index 0000000..d5f1c8d Binary files /dev/null and b/example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png differ diff --git a/example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 0000000..4d6372e Binary files /dev/null and b/example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png differ diff --git a/example/android/app/src/main/res/values-night/styles.xml b/example/android/app/src/main/res/values-night/styles.xml new file mode 100644 index 0000000..06952be --- /dev/null +++ b/example/android/app/src/main/res/values-night/styles.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/example/android/app/src/main/res/values/styles.xml b/example/android/app/src/main/res/values/styles.xml new file mode 100644 index 0000000..cb1ef88 --- /dev/null +++ b/example/android/app/src/main/res/values/styles.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/example/android/app/src/profile/AndroidManifest.xml b/example/android/app/src/profile/AndroidManifest.xml new file mode 100644 index 0000000..399f698 --- /dev/null +++ b/example/android/app/src/profile/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + diff --git a/example/android/build.gradle.kts b/example/android/build.gradle.kts new file mode 100644 index 0000000..dbee657 --- /dev/null +++ b/example/android/build.gradle.kts @@ -0,0 +1,24 @@ +allprojects { + repositories { + google() + mavenCentral() + } +} + +val newBuildDir: Directory = + rootProject.layout.buildDirectory + .dir("../../build") + .get() +rootProject.layout.buildDirectory.value(newBuildDir) + +subprojects { + val newSubprojectBuildDir: Directory = newBuildDir.dir(project.name) + project.layout.buildDirectory.value(newSubprojectBuildDir) +} +subprojects { + project.evaluationDependsOn(":app") +} + +tasks.register("clean") { + delete(rootProject.layout.buildDirectory) +} diff --git a/example/android/gradle.properties b/example/android/gradle.properties new file mode 100644 index 0000000..f018a61 --- /dev/null +++ b/example/android/gradle.properties @@ -0,0 +1,3 @@ +org.gradle.jvmargs=-Xmx8G -XX:MaxMetaspaceSize=4G -XX:ReservedCodeCacheSize=512m -XX:+HeapDumpOnOutOfMemoryError +android.useAndroidX=true +android.enableJetifier=true diff --git a/example/android/gradle/wrapper/gradle-wrapper.properties b/example/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..ac3b479 --- /dev/null +++ b/example/android/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.12-all.zip diff --git a/example/android/settings.gradle.kts b/example/android/settings.gradle.kts new file mode 100644 index 0000000..fb605bc --- /dev/null +++ b/example/android/settings.gradle.kts @@ -0,0 +1,26 @@ +pluginManagement { + val flutterSdkPath = + run { + val properties = java.util.Properties() + file("local.properties").inputStream().use { properties.load(it) } + val flutterSdkPath = properties.getProperty("flutter.sdk") + require(flutterSdkPath != null) { "flutter.sdk not set in local.properties" } + flutterSdkPath + } + + includeBuild("$flutterSdkPath/packages/flutter_tools/gradle") + + repositories { + google() + mavenCentral() + gradlePluginPortal() + } +} + +plugins { + id("dev.flutter.flutter-plugin-loader") version "1.0.0" + id("com.android.application") version "8.9.1" apply false + id("org.jetbrains.kotlin.android") version "2.1.0" apply false +} + +include(":app") diff --git a/example/ios/.gitignore b/example/ios/.gitignore new file mode 100644 index 0000000..7a7f987 --- /dev/null +++ b/example/ios/.gitignore @@ -0,0 +1,34 @@ +**/dgph +*.mode1v3 +*.mode2v3 +*.moved-aside +*.pbxuser +*.perspectivev3 +**/*sync/ +.sconsign.dblite +.tags* +**/.vagrant/ +**/DerivedData/ +Icon? +**/Pods/ +**/.symlinks/ +profile +xcuserdata +**/.generated/ +Flutter/App.framework +Flutter/Flutter.framework +Flutter/Flutter.podspec +Flutter/Generated.xcconfig +Flutter/ephemeral/ +Flutter/app.flx +Flutter/app.zip +Flutter/flutter_assets/ +Flutter/flutter_export_environment.sh +ServiceDefinitions.json +Runner/GeneratedPluginRegistrant.* + +# Exceptions to above rules. +!default.mode1v3 +!default.mode2v3 +!default.pbxuser +!default.perspectivev3 diff --git a/example/ios/Flutter/AppFrameworkInfo.plist b/example/ios/Flutter/AppFrameworkInfo.plist new file mode 100644 index 0000000..1dc6cf7 --- /dev/null +++ b/example/ios/Flutter/AppFrameworkInfo.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + App + CFBundleIdentifier + io.flutter.flutter.app + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + App + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.0 + CFBundleSignature + ???? + CFBundleVersion + 1.0 + MinimumOSVersion + 13.0 + + diff --git a/example/ios/Flutter/Debug.xcconfig b/example/ios/Flutter/Debug.xcconfig new file mode 100644 index 0000000..ec97fc6 --- /dev/null +++ b/example/ios/Flutter/Debug.xcconfig @@ -0,0 +1,2 @@ +#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig" +#include "Generated.xcconfig" diff --git a/example/ios/Flutter/Release.xcconfig b/example/ios/Flutter/Release.xcconfig new file mode 100644 index 0000000..c4855bf --- /dev/null +++ b/example/ios/Flutter/Release.xcconfig @@ -0,0 +1,2 @@ +#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig" +#include "Generated.xcconfig" diff --git a/example/ios/Podfile b/example/ios/Podfile new file mode 100644 index 0000000..620e46e --- /dev/null +++ b/example/ios/Podfile @@ -0,0 +1,43 @@ +# Uncomment this line to define a global platform for your project +# platform :ios, '13.0' + +# CocoaPods analytics sends network stats synchronously affecting flutter build latency. +ENV['COCOAPODS_DISABLE_STATS'] = 'true' + +project 'Runner', { + 'Debug' => :debug, + 'Profile' => :release, + 'Release' => :release, +} + +def flutter_root + generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'Generated.xcconfig'), __FILE__) + unless File.exist?(generated_xcode_build_settings_path) + raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure flutter pub get is executed first" + end + + File.foreach(generated_xcode_build_settings_path) do |line| + matches = line.match(/FLUTTER_ROOT\=(.*)/) + return matches[1].strip if matches + end + raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Generated.xcconfig, then run flutter pub get" +end + +require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root) + +flutter_ios_podfile_setup + +target 'Runner' do + use_frameworks! + + flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__)) + target 'RunnerTests' do + inherit! :search_paths + end +end + +post_install do |installer| + installer.pods_project.targets.each do |target| + flutter_additional_ios_build_settings(target) + end +end diff --git a/example/ios/Runner.xcodeproj/project.pbxproj b/example/ios/Runner.xcodeproj/project.pbxproj new file mode 100644 index 0000000..c8a4ad8 --- /dev/null +++ b/example/ios/Runner.xcodeproj/project.pbxproj @@ -0,0 +1,619 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 54; + objects = { + +/* Begin PBXBuildFile section */ + 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */ = {isa = PBXBuildFile; fileRef = 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */; }; + 331C808B294A63AB00263BE5 /* RunnerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 331C807B294A618700263BE5 /* RunnerTests.swift */; }; + 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; }; + 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74858FAE1ED2DC5600515810 /* AppDelegate.swift */; }; + 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; }; + 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FD1CF9000F007C117D /* Assets.xcassets */; }; + 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 331C8085294A63A400263BE5 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 97C146E61CF9000F007C117D /* Project object */; + proxyType = 1; + remoteGlobalIDString = 97C146ED1CF9000F007C117D; + remoteInfo = Runner; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXCopyFilesBuildPhase section */ + 9705A1C41CF9048500538489 /* Embed Frameworks */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = ""; + dstSubfolderSpec = 10; + files = ( + ); + name = "Embed Frameworks"; + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXCopyFilesBuildPhase section */ + +/* Begin PBXFileReference section */ + 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GeneratedPluginRegistrant.h; sourceTree = ""; }; + 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GeneratedPluginRegistrant.m; sourceTree = ""; }; + 331C807B294A618700263BE5 /* RunnerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RunnerTests.swift; sourceTree = ""; }; + 331C8081294A63A400263BE5 /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = AppFrameworkInfo.plist; path = Flutter/AppFrameworkInfo.plist; sourceTree = ""; }; + 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Runner-Bridging-Header.h"; sourceTree = ""; }; + 74858FAE1ED2DC5600515810 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Release.xcconfig; path = Flutter/Release.xcconfig; sourceTree = ""; }; + 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Debug.xcconfig; path = Flutter/Debug.xcconfig; sourceTree = ""; }; + 9740EEB31CF90195004384FC /* Generated.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Generated.xcconfig; path = Flutter/Generated.xcconfig; sourceTree = ""; }; + 97C146EE1CF9000F007C117D /* Runner.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Runner.app; sourceTree = BUILT_PRODUCTS_DIR; }; + 97C146FB1CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; + 97C146FD1CF9000F007C117D /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; + 97C147001CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; + 97C147021CF9000F007C117D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 97C146EB1CF9000F007C117D /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 331C8082294A63A400263BE5 /* RunnerTests */ = { + isa = PBXGroup; + children = ( + 331C807B294A618700263BE5 /* RunnerTests.swift */, + ); + path = RunnerTests; + sourceTree = ""; + }; + 9740EEB11CF90186004384FC /* Flutter */ = { + isa = PBXGroup; + children = ( + 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */, + 9740EEB21CF90195004384FC /* Debug.xcconfig */, + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */, + 9740EEB31CF90195004384FC /* Generated.xcconfig */, + ); + name = Flutter; + sourceTree = ""; + }; + 97C146E51CF9000F007C117D = { + isa = PBXGroup; + children = ( + 9740EEB11CF90186004384FC /* Flutter */, + 97C146F01CF9000F007C117D /* Runner */, + 97C146EF1CF9000F007C117D /* Products */, + 331C8082294A63A400263BE5 /* RunnerTests */, + ); + sourceTree = ""; + }; + 97C146EF1CF9000F007C117D /* Products */ = { + isa = PBXGroup; + children = ( + 97C146EE1CF9000F007C117D /* Runner.app */, + 331C8081294A63A400263BE5 /* RunnerTests.xctest */, + ); + name = Products; + sourceTree = ""; + }; + 97C146F01CF9000F007C117D /* Runner */ = { + isa = PBXGroup; + children = ( + 97C146FA1CF9000F007C117D /* Main.storyboard */, + 97C146FD1CF9000F007C117D /* Assets.xcassets */, + 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */, + 97C147021CF9000F007C117D /* Info.plist */, + 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */, + 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */, + 74858FAE1ED2DC5600515810 /* AppDelegate.swift */, + 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */, + ); + path = Runner; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 331C8080294A63A400263BE5 /* RunnerTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 331C8087294A63A400263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */; + buildPhases = ( + 331C807D294A63A400263BE5 /* Sources */, + 331C807F294A63A400263BE5 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 331C8086294A63A400263BE5 /* PBXTargetDependency */, + ); + name = RunnerTests; + productName = RunnerTests; + productReference = 331C8081294A63A400263BE5 /* RunnerTests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; + 97C146ED1CF9000F007C117D /* Runner */ = { + isa = PBXNativeTarget; + buildConfigurationList = 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */; + buildPhases = ( + 9740EEB61CF901F6004384FC /* Run Script */, + 97C146EA1CF9000F007C117D /* Sources */, + 97C146EB1CF9000F007C117D /* Frameworks */, + 97C146EC1CF9000F007C117D /* Resources */, + 9705A1C41CF9048500538489 /* Embed Frameworks */, + 3B06AD1E1E4923F5004D2608 /* Thin Binary */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = Runner; + productName = Runner; + productReference = 97C146EE1CF9000F007C117D /* Runner.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 97C146E61CF9000F007C117D /* Project object */ = { + isa = PBXProject; + attributes = { + BuildIndependentTargetsInParallel = YES; + LastUpgradeCheck = 1510; + ORGANIZATIONNAME = ""; + TargetAttributes = { + 331C8080294A63A400263BE5 = { + CreatedOnToolsVersion = 14.0; + TestTargetID = 97C146ED1CF9000F007C117D; + }; + 97C146ED1CF9000F007C117D = { + CreatedOnToolsVersion = 7.3.1; + LastSwiftMigration = 1100; + }; + }; + }; + buildConfigurationList = 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */; + compatibilityVersion = "Xcode 9.3"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 97C146E51CF9000F007C117D; + productRefGroup = 97C146EF1CF9000F007C117D /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 97C146ED1CF9000F007C117D /* Runner */, + 331C8080294A63A400263BE5 /* RunnerTests */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 331C807F294A63A400263BE5 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 97C146EC1CF9000F007C117D /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */, + 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */, + 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */, + 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXShellScriptBuildPhase section */ + 3B06AD1E1E4923F5004D2608 /* Thin Binary */ = { + isa = PBXShellScriptBuildPhase; + alwaysOutOfDate = 1; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + "${TARGET_BUILD_DIR}/${INFOPLIST_PATH}", + ); + name = "Thin Binary"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" embed_and_thin"; + }; + 9740EEB61CF901F6004384FC /* Run Script */ = { + isa = PBXShellScriptBuildPhase; + alwaysOutOfDate = 1; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "Run Script"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" build"; + }; +/* End PBXShellScriptBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 331C807D294A63A400263BE5 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 331C808B294A63AB00263BE5 /* RunnerTests.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 97C146EA1CF9000F007C117D /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */, + 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 331C8086294A63A400263BE5 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 97C146ED1CF9000F007C117D /* Runner */; + targetProxy = 331C8085294A63A400263BE5 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin PBXVariantGroup section */ + 97C146FA1CF9000F007C117D /* Main.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 97C146FB1CF9000F007C117D /* Base */, + ); + name = Main.storyboard; + sourceTree = ""; + }; + 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 97C147001CF9000F007C117D /* Base */, + ); + name = LaunchScreen.storyboard; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + 249021D3217E4FDB00AE95B9 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + SUPPORTED_PLATFORMS = iphoneos; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + }; + name = Profile; + }; + 249021D4217E4FDB00AE95B9 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + DEVELOPMENT_TEAM = Z778GC45N8; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = com.example.example; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Profile; + }; + 331C8088294A63A400263BE5 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.example.example.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + }; + name = Debug; + }; + 331C8089294A63A400263BE5 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.example.example.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + }; + name = Release; + }; + 331C808A294A63A400263BE5 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.example.example.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + }; + name = Profile; + }; + 97C147031CF9000F007C117D /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = iphoneos; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Debug; + }; + 97C147041CF9000F007C117D /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + SUPPORTED_PLATFORMS = iphoneos; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + 97C147061CF9000F007C117D /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + DEVELOPMENT_TEAM = Z778GC45N8; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = com.example.example; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Debug; + }; + 97C147071CF9000F007C117D /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + DEVELOPMENT_TEAM = Z778GC45N8; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = com.example.example; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 331C8087294A63A400263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 331C8088294A63A400263BE5 /* Debug */, + 331C8089294A63A400263BE5 /* Release */, + 331C808A294A63A400263BE5 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 97C147031CF9000F007C117D /* Debug */, + 97C147041CF9000F007C117D /* Release */, + 249021D3217E4FDB00AE95B9 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 97C147061CF9000F007C117D /* Debug */, + 97C147071CF9000F007C117D /* Release */, + 249021D4217E4FDB00AE95B9 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 97C146E61CF9000F007C117D /* Project object */; +} diff --git a/example/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/example/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..919434a --- /dev/null +++ b/example/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/example/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/example/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/example/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/example/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/example/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings new file mode 100644 index 0000000..f9b0d7c --- /dev/null +++ b/example/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings @@ -0,0 +1,8 @@ + + + + + PreviewsEnabled + + + diff --git a/example/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/example/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme new file mode 100644 index 0000000..e3773d4 --- /dev/null +++ b/example/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -0,0 +1,101 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/example/ios/Runner.xcworkspace/contents.xcworkspacedata b/example/ios/Runner.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..1d526a1 --- /dev/null +++ b/example/ios/Runner.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/example/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/example/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/example/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/example/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/example/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings new file mode 100644 index 0000000..f9b0d7c --- /dev/null +++ b/example/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings @@ -0,0 +1,8 @@ + + + + + PreviewsEnabled + + + diff --git a/example/ios/Runner/AppDelegate.swift b/example/ios/Runner/AppDelegate.swift new file mode 100644 index 0000000..6266644 --- /dev/null +++ b/example/ios/Runner/AppDelegate.swift @@ -0,0 +1,13 @@ +import Flutter +import UIKit + +@main +@objc class AppDelegate: FlutterAppDelegate { + override func application( + _ application: UIApplication, + didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? + ) -> Bool { + GeneratedPluginRegistrant.register(with: self) + return super.application(application, didFinishLaunchingWithOptions: launchOptions) + } +} diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 0000000..d36b1fa --- /dev/null +++ b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,122 @@ +{ + "images" : [ + { + "size" : "20x20", + "idiom" : "iphone", + "filename" : "Icon-App-20x20@2x.png", + "scale" : "2x" + }, + { + "size" : "20x20", + "idiom" : "iphone", + "filename" : "Icon-App-20x20@3x.png", + "scale" : "3x" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "filename" : "Icon-App-29x29@1x.png", + "scale" : "1x" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "filename" : "Icon-App-29x29@2x.png", + "scale" : "2x" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "filename" : "Icon-App-29x29@3x.png", + "scale" : "3x" + }, + { + "size" : "40x40", + "idiom" : "iphone", + "filename" : "Icon-App-40x40@2x.png", + "scale" : "2x" + }, + { + "size" : "40x40", + "idiom" : "iphone", + "filename" : "Icon-App-40x40@3x.png", + "scale" : "3x" + }, + { + "size" : "60x60", + "idiom" : "iphone", + "filename" : "Icon-App-60x60@2x.png", + "scale" : "2x" + }, + { + "size" : "60x60", + "idiom" : "iphone", + "filename" : "Icon-App-60x60@3x.png", + "scale" : "3x" + }, + { + "size" : "20x20", + "idiom" : "ipad", + "filename" : "Icon-App-20x20@1x.png", + "scale" : "1x" + }, + { + "size" : "20x20", + "idiom" : "ipad", + "filename" : "Icon-App-20x20@2x.png", + "scale" : "2x" + }, + { + "size" : "29x29", + "idiom" : "ipad", + "filename" : "Icon-App-29x29@1x.png", + "scale" : "1x" + }, + { + "size" : "29x29", + "idiom" : "ipad", + "filename" : "Icon-App-29x29@2x.png", + "scale" : "2x" + }, + { + "size" : "40x40", + "idiom" : "ipad", + "filename" : "Icon-App-40x40@1x.png", + "scale" : "1x" + }, + { + "size" : "40x40", + "idiom" : "ipad", + "filename" : "Icon-App-40x40@2x.png", + "scale" : "2x" + }, + { + "size" : "76x76", + "idiom" : "ipad", + "filename" : "Icon-App-76x76@1x.png", + "scale" : "1x" + }, + { + "size" : "76x76", + "idiom" : "ipad", + "filename" : "Icon-App-76x76@2x.png", + "scale" : "2x" + }, + { + "size" : "83.5x83.5", + "idiom" : "ipad", + "filename" : "Icon-App-83.5x83.5@2x.png", + "scale" : "2x" + }, + { + "size" : "1024x1024", + "idiom" : "ios-marketing", + "filename" : "Icon-App-1024x1024@1x.png", + "scale" : "1x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png new file mode 100644 index 0000000..dc9ada4 Binary files /dev/null and b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png differ diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png new file mode 100644 index 0000000..7353c41 Binary files /dev/null and b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png differ diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png new file mode 100644 index 0000000..797d452 Binary files /dev/null and b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png differ diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png new file mode 100644 index 0000000..6ed2d93 Binary files /dev/null and b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png differ diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png new file mode 100644 index 0000000..4cd7b00 Binary files /dev/null and b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png differ diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png new file mode 100644 index 0000000..fe73094 Binary files /dev/null and b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png differ diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png new file mode 100644 index 0000000..321773c Binary files /dev/null and b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png differ diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png new file mode 100644 index 0000000..797d452 Binary files /dev/null and b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png differ diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png new file mode 100644 index 0000000..502f463 Binary files /dev/null and b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png differ diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png new file mode 100644 index 0000000..0ec3034 Binary files /dev/null and b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png differ diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png new file mode 100644 index 0000000..0ec3034 Binary files /dev/null and b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png differ diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png new file mode 100644 index 0000000..e9f5fea Binary files /dev/null and b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png differ diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png new file mode 100644 index 0000000..84ac32a Binary files /dev/null and b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png differ diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png new file mode 100644 index 0000000..8953cba Binary files /dev/null and b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png differ diff --git a/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png new file mode 100644 index 0000000..0467bf1 Binary files /dev/null and b/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png differ diff --git a/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json b/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json new file mode 100644 index 0000000..0bedcf2 --- /dev/null +++ b/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json @@ -0,0 +1,23 @@ +{ + "images" : [ + { + "idiom" : "universal", + "filename" : "LaunchImage.png", + "scale" : "1x" + }, + { + "idiom" : "universal", + "filename" : "LaunchImage@2x.png", + "scale" : "2x" + }, + { + "idiom" : "universal", + "filename" : "LaunchImage@3x.png", + "scale" : "3x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} diff --git a/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png b/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png new file mode 100644 index 0000000..9da19ea Binary files /dev/null and b/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png differ diff --git a/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png b/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png new file mode 100644 index 0000000..9da19ea Binary files /dev/null and b/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png differ diff --git a/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png b/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png new file mode 100644 index 0000000..9da19ea Binary files /dev/null and b/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png differ diff --git a/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md b/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md new file mode 100644 index 0000000..89c2725 --- /dev/null +++ b/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md @@ -0,0 +1,5 @@ +# Launch Screen Assets + +You can customize the launch screen with your own desired assets by replacing the image files in this directory. + +You can also do it by opening your Flutter project's Xcode project with `open ios/Runner.xcworkspace`, selecting `Runner/Assets.xcassets` in the Project Navigator and dropping in the desired images. \ No newline at end of file diff --git a/example/ios/Runner/Base.lproj/LaunchScreen.storyboard b/example/ios/Runner/Base.lproj/LaunchScreen.storyboard new file mode 100644 index 0000000..f2e259c --- /dev/null +++ b/example/ios/Runner/Base.lproj/LaunchScreen.storyboard @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/example/ios/Runner/Base.lproj/Main.storyboard b/example/ios/Runner/Base.lproj/Main.storyboard new file mode 100644 index 0000000..f3c2851 --- /dev/null +++ b/example/ios/Runner/Base.lproj/Main.storyboard @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/example/ios/Runner/Info.plist b/example/ios/Runner/Info.plist new file mode 100644 index 0000000..5458fc4 --- /dev/null +++ b/example/ios/Runner/Info.plist @@ -0,0 +1,49 @@ + + + + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleDisplayName + Example + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + example + CFBundlePackageType + APPL + CFBundleShortVersionString + $(FLUTTER_BUILD_NAME) + CFBundleSignature + ???? + CFBundleVersion + $(FLUTTER_BUILD_NUMBER) + LSRequiresIPhoneOS + + UILaunchStoryboardName + LaunchScreen + UIMainStoryboardFile + Main + UISupportedInterfaceOrientations + + UIInterfaceOrientationPortrait + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + UISupportedInterfaceOrientations~ipad + + UIInterfaceOrientationPortrait + UIInterfaceOrientationPortraitUpsideDown + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + CADisableMinimumFrameDurationOnPhone + + UIApplicationSupportsIndirectInputEvents + + + diff --git a/example/ios/Runner/Runner-Bridging-Header.h b/example/ios/Runner/Runner-Bridging-Header.h new file mode 100644 index 0000000..308a2a5 --- /dev/null +++ b/example/ios/Runner/Runner-Bridging-Header.h @@ -0,0 +1 @@ +#import "GeneratedPluginRegistrant.h" diff --git a/example/ios/RunnerTests/RunnerTests.swift b/example/ios/RunnerTests/RunnerTests.swift new file mode 100644 index 0000000..86a7c3b --- /dev/null +++ b/example/ios/RunnerTests/RunnerTests.swift @@ -0,0 +1,12 @@ +import Flutter +import UIKit +import XCTest + +class RunnerTests: XCTestCase { + + func testExample() { + // If you add code to the Runner application, consider adding tests here. + // See https://developer.apple.com/documentation/xctest for more information about using XCTest. + } + +} diff --git a/example/lib/main.dart b/example/lib/main.dart new file mode 100644 index 0000000..a9a52b8 --- /dev/null +++ b/example/lib/main.dart @@ -0,0 +1,191 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:yx_tracking_flutter/yx_tracking_flutter.dart'; + +Future main() async { + WidgetsFlutterBinding.ensureInitialized(); + + await Analytics.init( + const AnalyticsConfig( + systemCode: 'DEMO_APP', + endpointBaseUrl: 'https://example.com/api/ExternalEventlogs', + clientType: 3, + enableDebug: true, + batchSize: 5, + flushInterval: 30, + ), + ); + + runApp(const DemoApp()); +} + +class DemoApp extends StatelessWidget { + const DemoApp({super.key}); + + @override + Widget build(BuildContext context) { + return const MaterialApp( + home: DemoPage(), + ); + } +} + +class DemoPage extends StatefulWidget { + const DemoPage({super.key}); + + @override + State createState() => _DemoPageState(); +} + +class _DemoPageState extends State { + int _cacheCount = 0; + List _recent = const []; + bool _flushing = false; + bool _refreshingConfig = false; + Timer? _pollTimer; + + @override + void initState() { + super.initState(); + _refreshCount(); + _pollTimer = Timer.periodic(const Duration(seconds: 2), (_) { + _refreshCount(); + }); + } + + @override + void dispose() { + _pollTimer?.cancel(); + super.dispose(); + } + + Future _refreshCount() async { + final results = await Future.wait(>[ + Analytics.cachedEventCount(), + Analytics.cachedRecentEvents(limit: 20), + ]); + final count = results[0] as int; + final recent = results[1] as List; + if (!mounted) { + return; + } + setState(() { + _cacheCount = count; + _recent = recent; + }); + } + + Future _trackDemoEvent() async { + await Analytics.track( + 'DEMO_BUTTON_CLICK', + eventParams: const {'page': 'demo'}, + customTags: const { + 'tenantId': 't1', + 'feature': 'demo', + }, + ); + await _refreshCount(); + } + + Future _flushNow() async { + if (_flushing) { + return; + } + setState(() { + _flushing = true; + }); + try { + await Analytics.flush(force: true); + } finally { + if (mounted) { + setState(() { + _flushing = false; + }); + } + await _refreshCount(); + } + } + + Future _refreshConfig() async { + if (_refreshingConfig) { + return; + } + setState(() { + _refreshingConfig = true; + }); + try { + await Analytics.refreshConfig(force: true); + } finally { + if (mounted) { + setState(() { + _refreshingConfig = false; + }); + } + } + } + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar(title: const Text('YX Tracking Demo')), + body: Padding( + padding: const EdgeInsets.all(16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + '本地缓存事件数:$_cacheCount', + style: Theme.of(context).textTheme.titleMedium, + ), + const SizedBox(height: 16), + Wrap( + spacing: 12, + runSpacing: 12, + children: [ + ElevatedButton( + onPressed: _trackDemoEvent, + child: const Text('Track Demo Event'), + ), + ElevatedButton( + onPressed: _flushing ? null : _flushNow, + child: Text(_flushing ? 'Flushing...' : 'Flush Now'), + ), + OutlinedButton( + onPressed: _refreshingConfig ? null : _refreshConfig, + child: Text(_refreshingConfig ? 'Refreshing...' : 'Refresh Config'), + ), + ], + ), + const SizedBox(height: 12), + const Text( + '说明:Demo 使用 example.com 作为占位地址,' + '实际联调时请替换为真实 HTTPS 域名。', + ), + const SizedBox(height: 12), + Text('最近事件(最多 20 条)', style: Theme.of(context).textTheme.titleSmall), + const SizedBox(height: 8), + Expanded( + child: _recent.isEmpty + ? const Text('暂无事件') + : ListView.separated( + itemCount: _recent.length, + separatorBuilder: (_, __) => const Divider(height: 1), + itemBuilder: (context, index) { + final item = _recent[index]; + return ListTile( + dense: true, + title: Text(item.eventType), + subtitle: Text( + '${item.createTime.toIso8601String()} · retry=${item.retryCount}', + ), + ); + }, + ), + ), + ], + ), + ), + ); + } +} diff --git a/example/linux/.gitignore b/example/linux/.gitignore new file mode 100644 index 0000000..d3896c9 --- /dev/null +++ b/example/linux/.gitignore @@ -0,0 +1 @@ +flutter/ephemeral diff --git a/example/linux/CMakeLists.txt b/example/linux/CMakeLists.txt new file mode 100644 index 0000000..7a9a314 --- /dev/null +++ b/example/linux/CMakeLists.txt @@ -0,0 +1,128 @@ +# Project-level configuration. +cmake_minimum_required(VERSION 3.13) +project(runner LANGUAGES CXX) + +# The name of the executable created for the application. Change this to change +# the on-disk name of your application. +set(BINARY_NAME "example") +# The unique GTK application identifier for this application. See: +# https://wiki.gnome.org/HowDoI/ChooseApplicationID +set(APPLICATION_ID "com.example.example") + +# Explicitly opt in to modern CMake behaviors to avoid warnings with recent +# versions of CMake. +cmake_policy(SET CMP0063 NEW) + +# Load bundled libraries from the lib/ directory relative to the binary. +set(CMAKE_INSTALL_RPATH "$ORIGIN/lib") + +# Root filesystem for cross-building. +if(FLUTTER_TARGET_PLATFORM_SYSROOT) + set(CMAKE_SYSROOT ${FLUTTER_TARGET_PLATFORM_SYSROOT}) + set(CMAKE_FIND_ROOT_PATH ${CMAKE_SYSROOT}) + set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) + set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY) + set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) + set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) +endif() + +# Define build configuration options. +if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) + set(CMAKE_BUILD_TYPE "Debug" CACHE + STRING "Flutter build mode" FORCE) + set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS + "Debug" "Profile" "Release") +endif() + +# Compilation settings that should be applied to most targets. +# +# Be cautious about adding new options here, as plugins use this function by +# default. In most cases, you should add new options to specific targets instead +# of modifying this function. +function(APPLY_STANDARD_SETTINGS TARGET) + target_compile_features(${TARGET} PUBLIC cxx_std_14) + target_compile_options(${TARGET} PRIVATE -Wall -Werror) + target_compile_options(${TARGET} PRIVATE "$<$>:-O3>") + target_compile_definitions(${TARGET} PRIVATE "$<$>:NDEBUG>") +endfunction() + +# Flutter library and tool build rules. +set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") +add_subdirectory(${FLUTTER_MANAGED_DIR}) + +# System-level dependencies. +find_package(PkgConfig REQUIRED) +pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) + +# Application build; see runner/CMakeLists.txt. +add_subdirectory("runner") + +# Run the Flutter tool portions of the build. This must not be removed. +add_dependencies(${BINARY_NAME} flutter_assemble) + +# Only the install-generated bundle's copy of the executable will launch +# correctly, since the resources must in the right relative locations. To avoid +# people trying to run the unbundled copy, put it in a subdirectory instead of +# the default top-level location. +set_target_properties(${BINARY_NAME} + PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/intermediates_do_not_run" +) + + +# Generated plugin build rules, which manage building the plugins and adding +# them to the application. +include(flutter/generated_plugins.cmake) + + +# === Installation === +# By default, "installing" just makes a relocatable bundle in the build +# directory. +set(BUILD_BUNDLE_DIR "${PROJECT_BINARY_DIR}/bundle") +if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) + set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) +endif() + +# Start with a clean build bundle directory every time. +install(CODE " + file(REMOVE_RECURSE \"${BUILD_BUNDLE_DIR}/\") + " COMPONENT Runtime) + +set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") +set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}/lib") + +install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +foreach(bundled_library ${PLUGIN_BUNDLED_LIBRARIES}) + install(FILES "${bundled_library}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endforeach(bundled_library) + +# Copy the native assets provided by the build.dart from all packages. +set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/linux/") +install(DIRECTORY "${NATIVE_ASSETS_DIR}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +# Fully re-copy the assets directory on each build to avoid having stale files +# from a previous install. +set(FLUTTER_ASSET_DIR_NAME "flutter_assets") +install(CODE " + file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") + " COMPONENT Runtime) +install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" + DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) + +# Install the AOT library on non-Debug builds only. +if(NOT CMAKE_BUILD_TYPE MATCHES "Debug") + install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endif() diff --git a/example/linux/flutter/CMakeLists.txt b/example/linux/flutter/CMakeLists.txt new file mode 100644 index 0000000..d5bd016 --- /dev/null +++ b/example/linux/flutter/CMakeLists.txt @@ -0,0 +1,88 @@ +# This file controls Flutter-level build steps. It should not be edited. +cmake_minimum_required(VERSION 3.10) + +set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") + +# Configuration provided via flutter tool. +include(${EPHEMERAL_DIR}/generated_config.cmake) + +# TODO: Move the rest of this into files in ephemeral. See +# https://github.com/flutter/flutter/issues/57146. + +# Serves the same purpose as list(TRANSFORM ... PREPEND ...), +# which isn't available in 3.10. +function(list_prepend LIST_NAME PREFIX) + set(NEW_LIST "") + foreach(element ${${LIST_NAME}}) + list(APPEND NEW_LIST "${PREFIX}${element}") + endforeach(element) + set(${LIST_NAME} "${NEW_LIST}" PARENT_SCOPE) +endfunction() + +# === Flutter Library === +# System-level dependencies. +find_package(PkgConfig REQUIRED) +pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) +pkg_check_modules(GLIB REQUIRED IMPORTED_TARGET glib-2.0) +pkg_check_modules(GIO REQUIRED IMPORTED_TARGET gio-2.0) + +set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/libflutter_linux_gtk.so") + +# Published to parent scope for install step. +set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) +set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) +set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) +set(AOT_LIBRARY "${PROJECT_DIR}/build/lib/libapp.so" PARENT_SCOPE) + +list(APPEND FLUTTER_LIBRARY_HEADERS + "fl_basic_message_channel.h" + "fl_binary_codec.h" + "fl_binary_messenger.h" + "fl_dart_project.h" + "fl_engine.h" + "fl_json_message_codec.h" + "fl_json_method_codec.h" + "fl_message_codec.h" + "fl_method_call.h" + "fl_method_channel.h" + "fl_method_codec.h" + "fl_method_response.h" + "fl_plugin_registrar.h" + "fl_plugin_registry.h" + "fl_standard_message_codec.h" + "fl_standard_method_codec.h" + "fl_string_codec.h" + "fl_value.h" + "fl_view.h" + "flutter_linux.h" +) +list_prepend(FLUTTER_LIBRARY_HEADERS "${EPHEMERAL_DIR}/flutter_linux/") +add_library(flutter INTERFACE) +target_include_directories(flutter INTERFACE + "${EPHEMERAL_DIR}" +) +target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}") +target_link_libraries(flutter INTERFACE + PkgConfig::GTK + PkgConfig::GLIB + PkgConfig::GIO +) +add_dependencies(flutter flutter_assemble) + +# === Flutter tool backend === +# _phony_ is a non-existent file to force this command to run every time, +# since currently there's no way to get a full input/output list from the +# flutter tool. +add_custom_command( + OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} + ${CMAKE_CURRENT_BINARY_DIR}/_phony_ + COMMAND ${CMAKE_COMMAND} -E env + ${FLUTTER_TOOL_ENVIRONMENT} + "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.sh" + ${FLUTTER_TARGET_PLATFORM} ${CMAKE_BUILD_TYPE} + VERBATIM +) +add_custom_target(flutter_assemble DEPENDS + "${FLUTTER_LIBRARY}" + ${FLUTTER_LIBRARY_HEADERS} +) diff --git a/example/linux/flutter/generated_plugin_registrant.cc b/example/linux/flutter/generated_plugin_registrant.cc new file mode 100644 index 0000000..e71a16d --- /dev/null +++ b/example/linux/flutter/generated_plugin_registrant.cc @@ -0,0 +1,11 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + + +void fl_register_plugins(FlPluginRegistry* registry) { +} diff --git a/example/linux/flutter/generated_plugin_registrant.h b/example/linux/flutter/generated_plugin_registrant.h new file mode 100644 index 0000000..e0f0a47 --- /dev/null +++ b/example/linux/flutter/generated_plugin_registrant.h @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#ifndef GENERATED_PLUGIN_REGISTRANT_ +#define GENERATED_PLUGIN_REGISTRANT_ + +#include + +// Registers Flutter plugins. +void fl_register_plugins(FlPluginRegistry* registry); + +#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/example/linux/flutter/generated_plugins.cmake b/example/linux/flutter/generated_plugins.cmake new file mode 100644 index 0000000..2e1de87 --- /dev/null +++ b/example/linux/flutter/generated_plugins.cmake @@ -0,0 +1,23 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST +) + +list(APPEND FLUTTER_FFI_PLUGIN_LIST +) + +set(PLUGIN_BUNDLED_LIBRARIES) + +foreach(plugin ${FLUTTER_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/linux plugins/${plugin}) + target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) + list(APPEND PLUGIN_BUNDLED_LIBRARIES $) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) +endforeach(plugin) + +foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/linux plugins/${ffi_plugin}) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) +endforeach(ffi_plugin) diff --git a/example/linux/runner/CMakeLists.txt b/example/linux/runner/CMakeLists.txt new file mode 100644 index 0000000..e97dabc --- /dev/null +++ b/example/linux/runner/CMakeLists.txt @@ -0,0 +1,26 @@ +cmake_minimum_required(VERSION 3.13) +project(runner LANGUAGES CXX) + +# Define the application target. To change its name, change BINARY_NAME in the +# top-level CMakeLists.txt, not the value here, or `flutter run` will no longer +# work. +# +# Any new source files that you add to the application should be added here. +add_executable(${BINARY_NAME} + "main.cc" + "my_application.cc" + "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" +) + +# Apply the standard set of build settings. This can be removed for applications +# that need different build settings. +apply_standard_settings(${BINARY_NAME}) + +# Add preprocessor definitions for the application ID. +add_definitions(-DAPPLICATION_ID="${APPLICATION_ID}") + +# Add dependency libraries. Add any application-specific dependencies here. +target_link_libraries(${BINARY_NAME} PRIVATE flutter) +target_link_libraries(${BINARY_NAME} PRIVATE PkgConfig::GTK) + +target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") diff --git a/example/linux/runner/main.cc b/example/linux/runner/main.cc new file mode 100644 index 0000000..e7c5c54 --- /dev/null +++ b/example/linux/runner/main.cc @@ -0,0 +1,6 @@ +#include "my_application.h" + +int main(int argc, char** argv) { + g_autoptr(MyApplication) app = my_application_new(); + return g_application_run(G_APPLICATION(app), argc, argv); +} diff --git a/example/linux/runner/my_application.cc b/example/linux/runner/my_application.cc new file mode 100644 index 0000000..f6904ba --- /dev/null +++ b/example/linux/runner/my_application.cc @@ -0,0 +1,144 @@ +#include "my_application.h" + +#include +#ifdef GDK_WINDOWING_X11 +#include +#endif + +#include "flutter/generated_plugin_registrant.h" + +struct _MyApplication { + GtkApplication parent_instance; + char** dart_entrypoint_arguments; +}; + +G_DEFINE_TYPE(MyApplication, my_application, GTK_TYPE_APPLICATION) + +// Called when first Flutter frame received. +static void first_frame_cb(MyApplication* self, FlView *view) +{ + gtk_widget_show(gtk_widget_get_toplevel(GTK_WIDGET(view))); +} + +// Implements GApplication::activate. +static void my_application_activate(GApplication* application) { + MyApplication* self = MY_APPLICATION(application); + GtkWindow* window = + GTK_WINDOW(gtk_application_window_new(GTK_APPLICATION(application))); + + // Use a header bar when running in GNOME as this is the common style used + // by applications and is the setup most users will be using (e.g. Ubuntu + // desktop). + // If running on X and not using GNOME then just use a traditional title bar + // in case the window manager does more exotic layout, e.g. tiling. + // If running on Wayland assume the header bar will work (may need changing + // if future cases occur). + gboolean use_header_bar = TRUE; +#ifdef GDK_WINDOWING_X11 + GdkScreen* screen = gtk_window_get_screen(window); + if (GDK_IS_X11_SCREEN(screen)) { + const gchar* wm_name = gdk_x11_screen_get_window_manager_name(screen); + if (g_strcmp0(wm_name, "GNOME Shell") != 0) { + use_header_bar = FALSE; + } + } +#endif + if (use_header_bar) { + GtkHeaderBar* header_bar = GTK_HEADER_BAR(gtk_header_bar_new()); + gtk_widget_show(GTK_WIDGET(header_bar)); + gtk_header_bar_set_title(header_bar, "example"); + gtk_header_bar_set_show_close_button(header_bar, TRUE); + gtk_window_set_titlebar(window, GTK_WIDGET(header_bar)); + } else { + gtk_window_set_title(window, "example"); + } + + gtk_window_set_default_size(window, 1280, 720); + + g_autoptr(FlDartProject) project = fl_dart_project_new(); + fl_dart_project_set_dart_entrypoint_arguments(project, self->dart_entrypoint_arguments); + + FlView* view = fl_view_new(project); + GdkRGBA background_color; + // Background defaults to black, override it here if necessary, e.g. #00000000 for transparent. + gdk_rgba_parse(&background_color, "#000000"); + fl_view_set_background_color(view, &background_color); + gtk_widget_show(GTK_WIDGET(view)); + gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(view)); + + // Show the window when Flutter renders. + // Requires the view to be realized so we can start rendering. + g_signal_connect_swapped(view, "first-frame", G_CALLBACK(first_frame_cb), self); + gtk_widget_realize(GTK_WIDGET(view)); + + fl_register_plugins(FL_PLUGIN_REGISTRY(view)); + + gtk_widget_grab_focus(GTK_WIDGET(view)); +} + +// Implements GApplication::local_command_line. +static gboolean my_application_local_command_line(GApplication* application, gchar*** arguments, int* exit_status) { + MyApplication* self = MY_APPLICATION(application); + // Strip out the first argument as it is the binary name. + self->dart_entrypoint_arguments = g_strdupv(*arguments + 1); + + g_autoptr(GError) error = nullptr; + if (!g_application_register(application, nullptr, &error)) { + g_warning("Failed to register: %s", error->message); + *exit_status = 1; + return TRUE; + } + + g_application_activate(application); + *exit_status = 0; + + return TRUE; +} + +// Implements GApplication::startup. +static void my_application_startup(GApplication* application) { + //MyApplication* self = MY_APPLICATION(object); + + // Perform any actions required at application startup. + + G_APPLICATION_CLASS(my_application_parent_class)->startup(application); +} + +// Implements GApplication::shutdown. +static void my_application_shutdown(GApplication* application) { + //MyApplication* self = MY_APPLICATION(object); + + // Perform any actions required at application shutdown. + + G_APPLICATION_CLASS(my_application_parent_class)->shutdown(application); +} + +// Implements GObject::dispose. +static void my_application_dispose(GObject* object) { + MyApplication* self = MY_APPLICATION(object); + g_clear_pointer(&self->dart_entrypoint_arguments, g_strfreev); + G_OBJECT_CLASS(my_application_parent_class)->dispose(object); +} + +static void my_application_class_init(MyApplicationClass* klass) { + G_APPLICATION_CLASS(klass)->activate = my_application_activate; + G_APPLICATION_CLASS(klass)->local_command_line = my_application_local_command_line; + G_APPLICATION_CLASS(klass)->startup = my_application_startup; + G_APPLICATION_CLASS(klass)->shutdown = my_application_shutdown; + G_OBJECT_CLASS(klass)->dispose = my_application_dispose; +} + +static void my_application_init(MyApplication* self) {} + +MyApplication* my_application_new() { + // Set the program name to the application ID, which helps various systems + // like GTK and desktop environments map this running application to its + // corresponding .desktop file. This ensures better integration by allowing + // the application to be recognized beyond its binary name. + g_set_prgname(APPLICATION_ID); + + return MY_APPLICATION(g_object_new(my_application_get_type(), + "application-id", APPLICATION_ID, + "flags", G_APPLICATION_NON_UNIQUE, + nullptr)); +} diff --git a/example/linux/runner/my_application.h b/example/linux/runner/my_application.h new file mode 100644 index 0000000..72271d5 --- /dev/null +++ b/example/linux/runner/my_application.h @@ -0,0 +1,18 @@ +#ifndef FLUTTER_MY_APPLICATION_H_ +#define FLUTTER_MY_APPLICATION_H_ + +#include + +G_DECLARE_FINAL_TYPE(MyApplication, my_application, MY, APPLICATION, + GtkApplication) + +/** + * my_application_new: + * + * Creates a new Flutter-based application. + * + * Returns: a new #MyApplication. + */ +MyApplication* my_application_new(); + +#endif // FLUTTER_MY_APPLICATION_H_ diff --git a/example/macos/.gitignore b/example/macos/.gitignore new file mode 100644 index 0000000..746adbb --- /dev/null +++ b/example/macos/.gitignore @@ -0,0 +1,7 @@ +# Flutter-related +**/Flutter/ephemeral/ +**/Pods/ + +# Xcode-related +**/dgph +**/xcuserdata/ diff --git a/example/macos/Flutter/Flutter-Debug.xcconfig b/example/macos/Flutter/Flutter-Debug.xcconfig new file mode 100644 index 0000000..4b81f9b --- /dev/null +++ b/example/macos/Flutter/Flutter-Debug.xcconfig @@ -0,0 +1,2 @@ +#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig" +#include "ephemeral/Flutter-Generated.xcconfig" diff --git a/example/macos/Flutter/Flutter-Release.xcconfig b/example/macos/Flutter/Flutter-Release.xcconfig new file mode 100644 index 0000000..5caa9d1 --- /dev/null +++ b/example/macos/Flutter/Flutter-Release.xcconfig @@ -0,0 +1,2 @@ +#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig" +#include "ephemeral/Flutter-Generated.xcconfig" diff --git a/example/macos/Flutter/GeneratedPluginRegistrant.swift b/example/macos/Flutter/GeneratedPluginRegistrant.swift new file mode 100644 index 0000000..252c004 --- /dev/null +++ b/example/macos/Flutter/GeneratedPluginRegistrant.swift @@ -0,0 +1,14 @@ +// +// Generated file. Do not edit. +// + +import FlutterMacOS +import Foundation + +import path_provider_foundation +import sqflite_darwin + +func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { + PathProviderPlugin.register(with: registry.registrar(forPlugin: "PathProviderPlugin")) + SqflitePlugin.register(with: registry.registrar(forPlugin: "SqflitePlugin")) +} diff --git a/example/macos/Podfile b/example/macos/Podfile new file mode 100644 index 0000000..ff5ddb3 --- /dev/null +++ b/example/macos/Podfile @@ -0,0 +1,42 @@ +platform :osx, '10.15' + +# CocoaPods analytics sends network stats synchronously affecting flutter build latency. +ENV['COCOAPODS_DISABLE_STATS'] = 'true' + +project 'Runner', { + 'Debug' => :debug, + 'Profile' => :release, + 'Release' => :release, +} + +def flutter_root + generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'ephemeral', 'Flutter-Generated.xcconfig'), __FILE__) + unless File.exist?(generated_xcode_build_settings_path) + raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure \"flutter pub get\" is executed first" + end + + File.foreach(generated_xcode_build_settings_path) do |line| + matches = line.match(/FLUTTER_ROOT\=(.*)/) + return matches[1].strip if matches + end + raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Flutter-Generated.xcconfig, then run \"flutter pub get\"" +end + +require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root) + +flutter_macos_podfile_setup + +target 'Runner' do + use_frameworks! + + flutter_install_all_macos_pods File.dirname(File.realpath(__FILE__)) + target 'RunnerTests' do + inherit! :search_paths + end +end + +post_install do |installer| + installer.pods_project.targets.each do |target| + flutter_additional_macos_build_settings(target) + end +end diff --git a/example/macos/Runner.xcodeproj/project.pbxproj b/example/macos/Runner.xcodeproj/project.pbxproj new file mode 100644 index 0000000..a548a46 --- /dev/null +++ b/example/macos/Runner.xcodeproj/project.pbxproj @@ -0,0 +1,705 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 54; + objects = { + +/* Begin PBXAggregateTarget section */ + 33CC111A2044C6BA0003C045 /* Flutter Assemble */ = { + isa = PBXAggregateTarget; + buildConfigurationList = 33CC111B2044C6BA0003C045 /* Build configuration list for PBXAggregateTarget "Flutter Assemble" */; + buildPhases = ( + 33CC111E2044C6BF0003C045 /* ShellScript */, + ); + dependencies = ( + ); + name = "Flutter Assemble"; + productName = FLX; + }; +/* End PBXAggregateTarget section */ + +/* Begin PBXBuildFile section */ + 331C80D8294CF71000263BE5 /* RunnerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 331C80D7294CF71000263BE5 /* RunnerTests.swift */; }; + 335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */; }; + 33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC10F02044A3C60003C045 /* AppDelegate.swift */; }; + 33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F22044A3C60003C045 /* Assets.xcassets */; }; + 33CC10F62044A3C60003C045 /* MainMenu.xib in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F42044A3C60003C045 /* MainMenu.xib */; }; + 33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 331C80D9294CF71000263BE5 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 33CC10E52044A3C60003C045 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 33CC10EC2044A3C60003C045; + remoteInfo = Runner; + }; + 33CC111F2044C79F0003C045 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 33CC10E52044A3C60003C045 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 33CC111A2044C6BA0003C045; + remoteInfo = FLX; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXCopyFilesBuildPhase section */ + 33CC110E2044A8840003C045 /* Bundle Framework */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = ""; + dstSubfolderSpec = 10; + files = ( + ); + name = "Bundle Framework"; + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXCopyFilesBuildPhase section */ + +/* Begin PBXFileReference section */ + 331C80D5294CF71000263BE5 /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + 331C80D7294CF71000263BE5 /* RunnerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RunnerTests.swift; sourceTree = ""; }; + 333000ED22D3DE5D00554162 /* Warnings.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Warnings.xcconfig; sourceTree = ""; }; + 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GeneratedPluginRegistrant.swift; sourceTree = ""; }; + 33CC10ED2044A3C60003C045 /* example.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "example.app"; sourceTree = BUILT_PRODUCTS_DIR; }; + 33CC10F02044A3C60003C045 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 33CC10F22044A3C60003C045 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; name = Assets.xcassets; path = Runner/Assets.xcassets; sourceTree = ""; }; + 33CC10F52044A3C60003C045 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = Base; path = Base.lproj/MainMenu.xib; sourceTree = ""; }; + 33CC10F72044A3C60003C045 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; name = Info.plist; path = Runner/Info.plist; sourceTree = ""; }; + 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MainFlutterWindow.swift; sourceTree = ""; }; + 33CEB47222A05771004F2AC0 /* Flutter-Debug.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Flutter-Debug.xcconfig"; sourceTree = ""; }; + 33CEB47422A05771004F2AC0 /* Flutter-Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Flutter-Release.xcconfig"; sourceTree = ""; }; + 33CEB47722A0578A004F2AC0 /* Flutter-Generated.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = "Flutter-Generated.xcconfig"; path = "ephemeral/Flutter-Generated.xcconfig"; sourceTree = ""; }; + 33E51913231747F40026EE4D /* DebugProfile.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = DebugProfile.entitlements; sourceTree = ""; }; + 33E51914231749380026EE4D /* Release.entitlements */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.entitlements; path = Release.entitlements; sourceTree = ""; }; + 33E5194F232828860026EE4D /* AppInfo.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = AppInfo.xcconfig; sourceTree = ""; }; + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Release.xcconfig; sourceTree = ""; }; + 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = Debug.xcconfig; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 331C80D2294CF70F00263BE5 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 33CC10EA2044A3C60003C045 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 331C80D6294CF71000263BE5 /* RunnerTests */ = { + isa = PBXGroup; + children = ( + 331C80D7294CF71000263BE5 /* RunnerTests.swift */, + ); + path = RunnerTests; + sourceTree = ""; + }; + 33BA886A226E78AF003329D5 /* Configs */ = { + isa = PBXGroup; + children = ( + 33E5194F232828860026EE4D /* AppInfo.xcconfig */, + 9740EEB21CF90195004384FC /* Debug.xcconfig */, + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */, + 333000ED22D3DE5D00554162 /* Warnings.xcconfig */, + ); + path = Configs; + sourceTree = ""; + }; + 33CC10E42044A3C60003C045 = { + isa = PBXGroup; + children = ( + 33FAB671232836740065AC1E /* Runner */, + 33CEB47122A05771004F2AC0 /* Flutter */, + 331C80D6294CF71000263BE5 /* RunnerTests */, + 33CC10EE2044A3C60003C045 /* Products */, + D73912EC22F37F3D000D13A0 /* Frameworks */, + ); + sourceTree = ""; + }; + 33CC10EE2044A3C60003C045 /* Products */ = { + isa = PBXGroup; + children = ( + 33CC10ED2044A3C60003C045 /* example.app */, + 331C80D5294CF71000263BE5 /* RunnerTests.xctest */, + ); + name = Products; + sourceTree = ""; + }; + 33CC11242044D66E0003C045 /* Resources */ = { + isa = PBXGroup; + children = ( + 33CC10F22044A3C60003C045 /* Assets.xcassets */, + 33CC10F42044A3C60003C045 /* MainMenu.xib */, + 33CC10F72044A3C60003C045 /* Info.plist */, + ); + name = Resources; + path = ..; + sourceTree = ""; + }; + 33CEB47122A05771004F2AC0 /* Flutter */ = { + isa = PBXGroup; + children = ( + 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */, + 33CEB47222A05771004F2AC0 /* Flutter-Debug.xcconfig */, + 33CEB47422A05771004F2AC0 /* Flutter-Release.xcconfig */, + 33CEB47722A0578A004F2AC0 /* Flutter-Generated.xcconfig */, + ); + path = Flutter; + sourceTree = ""; + }; + 33FAB671232836740065AC1E /* Runner */ = { + isa = PBXGroup; + children = ( + 33CC10F02044A3C60003C045 /* AppDelegate.swift */, + 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */, + 33E51913231747F40026EE4D /* DebugProfile.entitlements */, + 33E51914231749380026EE4D /* Release.entitlements */, + 33CC11242044D66E0003C045 /* Resources */, + 33BA886A226E78AF003329D5 /* Configs */, + ); + path = Runner; + sourceTree = ""; + }; + D73912EC22F37F3D000D13A0 /* Frameworks */ = { + isa = PBXGroup; + children = ( + ); + name = Frameworks; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 331C80D4294CF70F00263BE5 /* RunnerTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 331C80DE294CF71000263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */; + buildPhases = ( + 331C80D1294CF70F00263BE5 /* Sources */, + 331C80D2294CF70F00263BE5 /* Frameworks */, + 331C80D3294CF70F00263BE5 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 331C80DA294CF71000263BE5 /* PBXTargetDependency */, + ); + name = RunnerTests; + productName = RunnerTests; + productReference = 331C80D5294CF71000263BE5 /* RunnerTests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; + 33CC10EC2044A3C60003C045 /* Runner */ = { + isa = PBXNativeTarget; + buildConfigurationList = 33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */; + buildPhases = ( + 33CC10E92044A3C60003C045 /* Sources */, + 33CC10EA2044A3C60003C045 /* Frameworks */, + 33CC10EB2044A3C60003C045 /* Resources */, + 33CC110E2044A8840003C045 /* Bundle Framework */, + 3399D490228B24CF009A79C7 /* ShellScript */, + ); + buildRules = ( + ); + dependencies = ( + 33CC11202044C79F0003C045 /* PBXTargetDependency */, + ); + name = Runner; + productName = Runner; + productReference = 33CC10ED2044A3C60003C045 /* example.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 33CC10E52044A3C60003C045 /* Project object */ = { + isa = PBXProject; + attributes = { + BuildIndependentTargetsInParallel = YES; + LastSwiftUpdateCheck = 0920; + LastUpgradeCheck = 1510; + ORGANIZATIONNAME = ""; + TargetAttributes = { + 331C80D4294CF70F00263BE5 = { + CreatedOnToolsVersion = 14.0; + TestTargetID = 33CC10EC2044A3C60003C045; + }; + 33CC10EC2044A3C60003C045 = { + CreatedOnToolsVersion = 9.2; + LastSwiftMigration = 1100; + ProvisioningStyle = Automatic; + SystemCapabilities = { + com.apple.Sandbox = { + enabled = 1; + }; + }; + }; + 33CC111A2044C6BA0003C045 = { + CreatedOnToolsVersion = 9.2; + ProvisioningStyle = Manual; + }; + }; + }; + buildConfigurationList = 33CC10E82044A3C60003C045 /* Build configuration list for PBXProject "Runner" */; + compatibilityVersion = "Xcode 9.3"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 33CC10E42044A3C60003C045; + productRefGroup = 33CC10EE2044A3C60003C045 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 33CC10EC2044A3C60003C045 /* Runner */, + 331C80D4294CF70F00263BE5 /* RunnerTests */, + 33CC111A2044C6BA0003C045 /* Flutter Assemble */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 331C80D3294CF70F00263BE5 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 33CC10EB2044A3C60003C045 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */, + 33CC10F62044A3C60003C045 /* MainMenu.xib in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXShellScriptBuildPhase section */ + 3399D490228B24CF009A79C7 /* ShellScript */ = { + isa = PBXShellScriptBuildPhase; + alwaysOutOfDate = 1; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + ); + outputFileListPaths = ( + ); + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "echo \"$PRODUCT_NAME.app\" > \"$PROJECT_DIR\"/Flutter/ephemeral/.app_filename && \"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh embed\n"; + }; + 33CC111E2044C6BF0003C045 /* ShellScript */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + Flutter/ephemeral/FlutterInputs.xcfilelist, + ); + inputPaths = ( + Flutter/ephemeral/tripwire, + ); + outputFileListPaths = ( + Flutter/ephemeral/FlutterOutputs.xcfilelist, + ); + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh && touch Flutter/ephemeral/tripwire"; + }; +/* End PBXShellScriptBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 331C80D1294CF70F00263BE5 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 331C80D8294CF71000263BE5 /* RunnerTests.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 33CC10E92044A3C60003C045 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */, + 33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */, + 335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 331C80DA294CF71000263BE5 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 33CC10EC2044A3C60003C045 /* Runner */; + targetProxy = 331C80D9294CF71000263BE5 /* PBXContainerItemProxy */; + }; + 33CC11202044C79F0003C045 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 33CC111A2044C6BA0003C045 /* Flutter Assemble */; + targetProxy = 33CC111F2044C79F0003C045 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin PBXVariantGroup section */ + 33CC10F42044A3C60003C045 /* MainMenu.xib */ = { + isa = PBXVariantGroup; + children = ( + 33CC10F52044A3C60003C045 /* Base */, + ); + name = MainMenu.xib; + path = Runner; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + 331C80DB294CF71000263BE5 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.example.example.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/example.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/example"; + }; + name = Debug; + }; + 331C80DC294CF71000263BE5 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.example.example.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/example.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/example"; + }; + name = Release; + }; + 331C80DD294CF71000263BE5 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.example.example.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/example.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/example"; + }; + name = Profile; + }; + 338D0CE9231458BD00FA5F75 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CODE_SIGN_IDENTITY = "-"; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 10.15; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = macosx; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + }; + name = Profile; + }; + 338D0CEA231458BD00FA5F75 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/DebugProfile.entitlements; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_VERSION = 5.0; + }; + name = Profile; + }; + 338D0CEB231458BD00FA5F75 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Manual; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Profile; + }; + 33CC10F92044A3C60003C045 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CODE_SIGN_IDENTITY = "-"; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 10.15; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = macosx; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + }; + name = Debug; + }; + 33CC10FA2044A3C60003C045 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CODE_SIGN_IDENTITY = "-"; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 10.15; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = macosx; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + }; + name = Release; + }; + 33CC10FC2044A3C60003C045 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/DebugProfile.entitlements; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + }; + name = Debug; + }; + 33CC10FD2044A3C60003C045 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/Release.entitlements; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_VERSION = 5.0; + }; + name = Release; + }; + 33CC111C2044C6BA0003C045 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Manual; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Debug; + }; + 33CC111D2044C6BA0003C045 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Automatic; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 331C80DE294CF71000263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 331C80DB294CF71000263BE5 /* Debug */, + 331C80DC294CF71000263BE5 /* Release */, + 331C80DD294CF71000263BE5 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 33CC10E82044A3C60003C045 /* Build configuration list for PBXProject "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 33CC10F92044A3C60003C045 /* Debug */, + 33CC10FA2044A3C60003C045 /* Release */, + 338D0CE9231458BD00FA5F75 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 33CC10FC2044A3C60003C045 /* Debug */, + 33CC10FD2044A3C60003C045 /* Release */, + 338D0CEA231458BD00FA5F75 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 33CC111B2044C6BA0003C045 /* Build configuration list for PBXAggregateTarget "Flutter Assemble" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 33CC111C2044C6BA0003C045 /* Debug */, + 33CC111D2044C6BA0003C045 /* Release */, + 338D0CEB231458BD00FA5F75 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 33CC10E52044A3C60003C045 /* Project object */; +} diff --git a/example/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/example/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/example/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/example/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/example/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme new file mode 100644 index 0000000..ac78810 --- /dev/null +++ b/example/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -0,0 +1,99 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/example/macos/Runner.xcworkspace/contents.xcworkspacedata b/example/macos/Runner.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..1d526a1 --- /dev/null +++ b/example/macos/Runner.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/example/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/example/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/example/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/example/macos/Runner/AppDelegate.swift b/example/macos/Runner/AppDelegate.swift new file mode 100644 index 0000000..b3c1761 --- /dev/null +++ b/example/macos/Runner/AppDelegate.swift @@ -0,0 +1,13 @@ +import Cocoa +import FlutterMacOS + +@main +class AppDelegate: FlutterAppDelegate { + override func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { + return true + } + + override func applicationSupportsSecureRestorableState(_ app: NSApplication) -> Bool { + return true + } +} diff --git a/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json b/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 0000000..a2ec33f --- /dev/null +++ b/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,68 @@ +{ + "images" : [ + { + "size" : "16x16", + "idiom" : "mac", + "filename" : "app_icon_16.png", + "scale" : "1x" + }, + { + "size" : "16x16", + "idiom" : "mac", + "filename" : "app_icon_32.png", + "scale" : "2x" + }, + { + "size" : "32x32", + "idiom" : "mac", + "filename" : "app_icon_32.png", + "scale" : "1x" + }, + { + "size" : "32x32", + "idiom" : "mac", + "filename" : "app_icon_64.png", + "scale" : "2x" + }, + { + "size" : "128x128", + "idiom" : "mac", + "filename" : "app_icon_128.png", + "scale" : "1x" + }, + { + "size" : "128x128", + "idiom" : "mac", + "filename" : "app_icon_256.png", + "scale" : "2x" + }, + { + "size" : "256x256", + "idiom" : "mac", + "filename" : "app_icon_256.png", + "scale" : "1x" + }, + { + "size" : "256x256", + "idiom" : "mac", + "filename" : "app_icon_512.png", + "scale" : "2x" + }, + { + "size" : "512x512", + "idiom" : "mac", + "filename" : "app_icon_512.png", + "scale" : "1x" + }, + { + "size" : "512x512", + "idiom" : "mac", + "filename" : "app_icon_1024.png", + "scale" : "2x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} diff --git a/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png b/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png new file mode 100644 index 0000000..82b6f9d Binary files /dev/null and b/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png differ diff --git a/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png b/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png new file mode 100644 index 0000000..13b35eb Binary files /dev/null and b/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png differ diff --git a/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png b/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png new file mode 100644 index 0000000..0a3f5fa Binary files /dev/null and b/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png differ diff --git a/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png b/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png new file mode 100644 index 0000000..bdb5722 Binary files /dev/null and b/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png differ diff --git a/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png b/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png new file mode 100644 index 0000000..f083318 Binary files /dev/null and b/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png differ diff --git a/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png b/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png new file mode 100644 index 0000000..326c0e7 Binary files /dev/null and b/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png differ diff --git a/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png b/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png new file mode 100644 index 0000000..2f1632c Binary files /dev/null and b/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png differ diff --git a/example/macos/Runner/Base.lproj/MainMenu.xib b/example/macos/Runner/Base.lproj/MainMenu.xib new file mode 100644 index 0000000..80e867a --- /dev/null +++ b/example/macos/Runner/Base.lproj/MainMenu.xib @@ -0,0 +1,343 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/example/macos/Runner/Configs/AppInfo.xcconfig b/example/macos/Runner/Configs/AppInfo.xcconfig new file mode 100644 index 0000000..f67a84b --- /dev/null +++ b/example/macos/Runner/Configs/AppInfo.xcconfig @@ -0,0 +1,14 @@ +// Application-level settings for the Runner target. +// +// This may be replaced with something auto-generated from metadata (e.g., pubspec.yaml) in the +// future. If not, the values below would default to using the project name when this becomes a +// 'flutter create' template. + +// The application's name. By default this is also the title of the Flutter window. +PRODUCT_NAME = example + +// The application's bundle identifier +PRODUCT_BUNDLE_IDENTIFIER = com.example.example + +// The copyright displayed in application information +PRODUCT_COPYRIGHT = Copyright © 2026 com.example. All rights reserved. diff --git a/example/macos/Runner/Configs/Debug.xcconfig b/example/macos/Runner/Configs/Debug.xcconfig new file mode 100644 index 0000000..36b0fd9 --- /dev/null +++ b/example/macos/Runner/Configs/Debug.xcconfig @@ -0,0 +1,2 @@ +#include "../../Flutter/Flutter-Debug.xcconfig" +#include "Warnings.xcconfig" diff --git a/example/macos/Runner/Configs/Release.xcconfig b/example/macos/Runner/Configs/Release.xcconfig new file mode 100644 index 0000000..dff4f49 --- /dev/null +++ b/example/macos/Runner/Configs/Release.xcconfig @@ -0,0 +1,2 @@ +#include "../../Flutter/Flutter-Release.xcconfig" +#include "Warnings.xcconfig" diff --git a/example/macos/Runner/Configs/Warnings.xcconfig b/example/macos/Runner/Configs/Warnings.xcconfig new file mode 100644 index 0000000..42bcbf4 --- /dev/null +++ b/example/macos/Runner/Configs/Warnings.xcconfig @@ -0,0 +1,13 @@ +WARNING_CFLAGS = -Wall -Wconditional-uninitialized -Wnullable-to-nonnull-conversion -Wmissing-method-return-type -Woverlength-strings +GCC_WARN_UNDECLARED_SELECTOR = YES +CLANG_UNDEFINED_BEHAVIOR_SANITIZER_NULLABILITY = YES +CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE +CLANG_WARN__DUPLICATE_METHOD_MATCH = YES +CLANG_WARN_PRAGMA_PACK = YES +CLANG_WARN_STRICT_PROTOTYPES = YES +CLANG_WARN_COMMA = YES +GCC_WARN_STRICT_SELECTOR_MATCH = YES +CLANG_WARN_OBJC_REPEATED_USE_OF_WEAK = YES +CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES +GCC_WARN_SHADOW = YES +CLANG_WARN_UNREACHABLE_CODE = YES diff --git a/example/macos/Runner/DebugProfile.entitlements b/example/macos/Runner/DebugProfile.entitlements new file mode 100644 index 0000000..dddb8a3 --- /dev/null +++ b/example/macos/Runner/DebugProfile.entitlements @@ -0,0 +1,12 @@ + + + + + com.apple.security.app-sandbox + + com.apple.security.cs.allow-jit + + com.apple.security.network.server + + + diff --git a/example/macos/Runner/Info.plist b/example/macos/Runner/Info.plist new file mode 100644 index 0000000..4789daa --- /dev/null +++ b/example/macos/Runner/Info.plist @@ -0,0 +1,32 @@ + + + + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIconFile + + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + APPL + CFBundleShortVersionString + $(FLUTTER_BUILD_NAME) + CFBundleVersion + $(FLUTTER_BUILD_NUMBER) + LSMinimumSystemVersion + $(MACOSX_DEPLOYMENT_TARGET) + NSHumanReadableCopyright + $(PRODUCT_COPYRIGHT) + NSMainNibFile + MainMenu + NSPrincipalClass + NSApplication + + diff --git a/example/macos/Runner/MainFlutterWindow.swift b/example/macos/Runner/MainFlutterWindow.swift new file mode 100644 index 0000000..3cc05eb --- /dev/null +++ b/example/macos/Runner/MainFlutterWindow.swift @@ -0,0 +1,15 @@ +import Cocoa +import FlutterMacOS + +class MainFlutterWindow: NSWindow { + override func awakeFromNib() { + let flutterViewController = FlutterViewController() + let windowFrame = self.frame + self.contentViewController = flutterViewController + self.setFrame(windowFrame, display: true) + + RegisterGeneratedPlugins(registry: flutterViewController) + + super.awakeFromNib() + } +} diff --git a/example/macos/Runner/Release.entitlements b/example/macos/Runner/Release.entitlements new file mode 100644 index 0000000..852fa1a --- /dev/null +++ b/example/macos/Runner/Release.entitlements @@ -0,0 +1,8 @@ + + + + + com.apple.security.app-sandbox + + + diff --git a/example/macos/RunnerTests/RunnerTests.swift b/example/macos/RunnerTests/RunnerTests.swift new file mode 100644 index 0000000..61f3bd1 --- /dev/null +++ b/example/macos/RunnerTests/RunnerTests.swift @@ -0,0 +1,12 @@ +import Cocoa +import FlutterMacOS +import XCTest + +class RunnerTests: XCTestCase { + + func testExample() { + // If you add code to the Runner application, consider adding tests here. + // See https://developer.apple.com/documentation/xctest for more information about using XCTest. + } + +} diff --git a/example/pubspec.lock b/example/pubspec.lock new file mode 100644 index 0000000..1f10ae0 --- /dev/null +++ b/example/pubspec.lock @@ -0,0 +1,396 @@ +# Generated by pub +# See https://dart.dev/tools/pub/glossary#lockfile +packages: + async: + dependency: transitive + description: + name: async + sha256: "758e6d74e971c3e5aceb4110bfd6698efc7f501675bcfe0c775459a8140750eb" + url: "https://pub.flutter-io.cn" + source: hosted + version: "2.13.0" + boolean_selector: + dependency: transitive + description: + name: boolean_selector + sha256: "8aab1771e1243a5063b8b0ff68042d67334e3feab9e95b9490f9a6ebf73b42ea" + url: "https://pub.flutter-io.cn" + source: hosted + version: "2.1.2" + characters: + dependency: transitive + description: + name: characters + sha256: f71061c654a3380576a52b451dd5532377954cf9dbd272a78fc8479606670803 + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.4.0" + clock: + dependency: transitive + description: + name: clock + sha256: fddb70d9b5277016c77a80201021d40a2247104d9f4aa7bab7157b7e3f05b84b + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.1.2" + collection: + dependency: transitive + description: + name: collection + sha256: "2f5709ae4d3d59dd8f7cd309b4e023046b57d8a6c82130785d2b0e5868084e76" + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.19.1" + cupertino_icons: + dependency: "direct main" + description: + name: cupertino_icons + sha256: ba631d1c7f7bef6b729a622b7b752645a2d076dba9976925b8f25725a30e1ee6 + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.0.8" + dio: + dependency: transitive + description: + name: dio + sha256: d90ee57923d1828ac14e492ca49440f65477f4bb1263575900be731a3dac66a9 + url: "https://pub.flutter-io.cn" + source: hosted + version: "5.9.0" + dio_web_adapter: + dependency: transitive + description: + name: dio_web_adapter + sha256: "7586e476d70caecaf1686d21eee7247ea43ef5c345eab9e0cc3583ff13378d78" + url: "https://pub.flutter-io.cn" + source: hosted + version: "2.1.1" + fake_async: + dependency: transitive + description: + name: fake_async + sha256: "5368f224a74523e8d2e7399ea1638b37aecfca824a3cc4dfdf77bf1fa905ac44" + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.3.3" + ffi: + dependency: transitive + description: + name: ffi + sha256: d07d37192dbf97461359c1518788f203b0c9102cfd2c35a716b823741219542c + url: "https://pub.flutter-io.cn" + source: hosted + version: "2.1.5" + flutter: + dependency: "direct main" + description: flutter + source: sdk + version: "0.0.0" + flutter_lints: + dependency: "direct dev" + description: + name: flutter_lints + sha256: "5398f14efa795ffb7a33e9b6a08798b26a180edac4ad7db3f231e40f82ce11e1" + url: "https://pub.flutter-io.cn" + source: hosted + version: "5.0.0" + flutter_test: + dependency: "direct dev" + description: flutter + source: sdk + version: "0.0.0" + http_parser: + dependency: transitive + description: + name: http_parser + sha256: "178d74305e7866013777bab2c3d8726205dc5a4dd935297175b19a23a2e66571" + url: "https://pub.flutter-io.cn" + source: hosted + version: "4.1.2" + leak_tracker: + dependency: transitive + description: + name: leak_tracker + sha256: "33e2e26bdd85a0112ec15400c8cbffea70d0f9c3407491f672a2fad47915e2de" + url: "https://pub.flutter-io.cn" + source: hosted + version: "11.0.2" + leak_tracker_flutter_testing: + dependency: transitive + description: + name: leak_tracker_flutter_testing + sha256: "1dbc140bb5a23c75ea9c4811222756104fbcd1a27173f0c34ca01e16bea473c1" + url: "https://pub.flutter-io.cn" + source: hosted + version: "3.0.10" + leak_tracker_testing: + dependency: transitive + description: + name: leak_tracker_testing + sha256: "8d5a2d49f4a66b49744b23b018848400d23e54caf9463f4eb20df3eb8acb2eb1" + url: "https://pub.flutter-io.cn" + source: hosted + version: "3.0.2" + lints: + dependency: transitive + description: + name: lints + sha256: c35bb79562d980e9a453fc715854e1ed39e24e7d0297a880ef54e17f9874a9d7 + url: "https://pub.flutter-io.cn" + source: hosted + version: "5.1.1" + matcher: + dependency: transitive + description: + name: matcher + sha256: dc58c723c3c24bf8d3e2d3ad3f2f9d7bd9cf43ec6feaa64181775e60190153f2 + url: "https://pub.flutter-io.cn" + source: hosted + version: "0.12.17" + material_color_utilities: + dependency: transitive + description: + name: material_color_utilities + sha256: f7142bb1154231d7ea5f96bc7bde4bda2a0945d2806bb11670e30b850d56bdec + url: "https://pub.flutter-io.cn" + source: hosted + version: "0.11.1" + meta: + dependency: transitive + description: + name: meta + sha256: e3641ec5d63ebf0d9b41bd43201a66e3fc79a65db5f61fc181f04cd27aab950c + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.16.0" + mime: + dependency: transitive + description: + name: mime + sha256: "41a20518f0cb1256669420fdba0cd90d21561e560ac240f26ef8322e45bb7ed6" + url: "https://pub.flutter-io.cn" + source: hosted + version: "2.0.0" + path: + dependency: transitive + description: + name: path + sha256: "75cca69d1490965be98c73ceaea117e8a04dd21217b37b292c9ddbec0d955bc5" + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.9.1" + path_provider: + dependency: transitive + description: + name: path_provider + sha256: "50c5dd5b6e1aaf6fb3a78b33f6aa3afca52bf903a8a5298f53101fdaee55bbcd" + url: "https://pub.flutter-io.cn" + source: hosted + version: "2.1.5" + path_provider_android: + dependency: transitive + description: + name: path_provider_android + sha256: f2c65e21139ce2c3dad46922be8272bb5963516045659e71bb16e151c93b580e + url: "https://pub.flutter-io.cn" + source: hosted + version: "2.2.22" + path_provider_foundation: + dependency: transitive + description: + name: path_provider_foundation + sha256: "6d13aece7b3f5c5a9731eaf553ff9dcbc2eff41087fd2df587fd0fed9a3eb0c4" + url: "https://pub.flutter-io.cn" + source: hosted + version: "2.5.1" + path_provider_linux: + dependency: transitive + description: + name: path_provider_linux + sha256: f7a1fe3a634fe7734c8d3f2766ad746ae2a2884abe22e241a8b301bf5cac3279 + url: "https://pub.flutter-io.cn" + source: hosted + version: "2.2.1" + path_provider_platform_interface: + dependency: transitive + description: + name: path_provider_platform_interface + sha256: "88f5779f72ba699763fa3a3b06aa4bf6de76c8e5de842cf6f29e2e06476c2334" + url: "https://pub.flutter-io.cn" + source: hosted + version: "2.1.2" + path_provider_windows: + dependency: transitive + description: + name: path_provider_windows + sha256: bd6f00dbd873bfb70d0761682da2b3a2c2fccc2b9e84c495821639601d81afe7 + url: "https://pub.flutter-io.cn" + source: hosted + version: "2.3.0" + platform: + dependency: transitive + description: + name: platform + sha256: "5d6b1b0036a5f331ebc77c850ebc8506cbc1e9416c27e59b439f917a902a4984" + url: "https://pub.flutter-io.cn" + source: hosted + version: "3.1.6" + plugin_platform_interface: + dependency: transitive + description: + name: plugin_platform_interface + sha256: "4820fbfdb9478b1ebae27888254d445073732dae3d6ea81f0b7e06d5dedc3f02" + url: "https://pub.flutter-io.cn" + source: hosted + version: "2.1.8" + sky_engine: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" + source_span: + dependency: transitive + description: + name: source_span + sha256: "254ee5351d6cb365c859e20ee823c3bb479bf4a293c22d17a9f1bf144ce86f7c" + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.10.1" + sqflite: + dependency: transitive + description: + name: sqflite + sha256: e2297b1da52f127bc7a3da11439985d9b536f75070f3325e62ada69a5c585d03 + url: "https://pub.flutter-io.cn" + source: hosted + version: "2.4.2" + sqflite_android: + dependency: transitive + description: + name: sqflite_android + sha256: ecd684501ebc2ae9a83536e8b15731642b9570dc8623e0073d227d0ee2bfea88 + url: "https://pub.flutter-io.cn" + source: hosted + version: "2.4.2+2" + sqflite_common: + dependency: transitive + description: + name: sqflite_common + sha256: "6ef422a4525ecc601db6c0a2233ff448c731307906e92cabc9ba292afaae16a6" + url: "https://pub.flutter-io.cn" + source: hosted + version: "2.5.6" + sqflite_darwin: + dependency: transitive + description: + name: sqflite_darwin + sha256: "279832e5cde3fe99e8571879498c9211f3ca6391b0d818df4e17d9fff5c6ccb3" + url: "https://pub.flutter-io.cn" + source: hosted + version: "2.4.2" + sqflite_platform_interface: + dependency: transitive + description: + name: sqflite_platform_interface + sha256: "8dd4515c7bdcae0a785b0062859336de775e8c65db81ae33dd5445f35be61920" + url: "https://pub.flutter-io.cn" + source: hosted + version: "2.4.0" + stack_trace: + dependency: transitive + description: + name: stack_trace + sha256: "8b27215b45d22309b5cddda1aa2b19bdfec9df0e765f2de506401c071d38d1b1" + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.12.1" + stream_channel: + dependency: transitive + description: + name: stream_channel + sha256: "969e04c80b8bcdf826f8f16579c7b14d780458bd97f56d107d3950fdbeef059d" + url: "https://pub.flutter-io.cn" + source: hosted + version: "2.1.4" + string_scanner: + dependency: transitive + description: + name: string_scanner + sha256: "921cd31725b72fe181906c6a94d987c78e3b98c2e205b397ea399d4054872b43" + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.4.1" + synchronized: + dependency: transitive + description: + name: synchronized + sha256: c254ade258ec8282947a0acbbc90b9575b4f19673533ee46f2f6e9b3aeefd7c0 + url: "https://pub.flutter-io.cn" + source: hosted + version: "3.4.0" + term_glyph: + dependency: transitive + description: + name: term_glyph + sha256: "7f554798625ea768a7518313e58f83891c7f5024f88e46e7182a4558850a4b8e" + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.2.2" + test_api: + dependency: transitive + description: + name: test_api + sha256: "522f00f556e73044315fa4585ec3270f1808a4b186c936e612cab0b565ff1e00" + url: "https://pub.flutter-io.cn" + source: hosted + version: "0.7.6" + typed_data: + dependency: transitive + description: + name: typed_data + sha256: f9049c039ebfeb4cf7a7104a675823cd72dba8297f264b6637062516699fa006 + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.4.0" + vector_math: + dependency: transitive + description: + name: vector_math + sha256: d530bd74fea330e6e364cda7a85019c434070188383e1cd8d9777ee586914c5b + url: "https://pub.flutter-io.cn" + source: hosted + version: "2.2.0" + vm_service: + dependency: transitive + description: + name: vm_service + sha256: "45caa6c5917fa127b5dbcfbd1fa60b14e583afdc08bfc96dda38886ca252eb60" + url: "https://pub.flutter-io.cn" + source: hosted + version: "15.0.2" + web: + dependency: transitive + description: + name: web + sha256: "868d88a33d8a87b18ffc05f9f030ba328ffefba92d6c127917a2ba740f9cfe4a" + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.1.1" + xdg_directories: + dependency: transitive + description: + name: xdg_directories + sha256: "7a3f37b05d989967cdddcbb571f1ea834867ae2faa29725fd085180e0883aa15" + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.1.0" + yx_tracking_flutter: + dependency: "direct main" + description: + path: ".." + relative: true + source: path + version: "0.1.0" +sdks: + dart: ">=3.9.2 <4.0.0" + flutter: ">=3.35.0" diff --git a/example/pubspec.yaml b/example/pubspec.yaml new file mode 100644 index 0000000..d24e8d1 --- /dev/null +++ b/example/pubspec.yaml @@ -0,0 +1,91 @@ +name: example +description: "A new Flutter project." +# The following line prevents the package from being accidentally published to +# pub.dev using `flutter pub publish`. This is preferred for private packages. +publish_to: 'none' # Remove this line if you wish to publish to pub.dev + +# The following defines the version and build number for your application. +# A version number is three numbers separated by dots, like 1.2.43 +# followed by an optional build number separated by a +. +# Both the version and the builder number may be overridden in flutter +# build by specifying --build-name and --build-number, respectively. +# In Android, build-name is used as versionName while build-number used as versionCode. +# Read more about Android versioning at https://developer.android.com/studio/publish/versioning +# In iOS, build-name is used as CFBundleShortVersionString while build-number is used as CFBundleVersion. +# Read more about iOS versioning at +# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html +# In Windows, build-name is used as the major, minor, and patch parts +# of the product and file versions while build-number is used as the build suffix. +version: 1.0.0+1 + +environment: + sdk: ^3.9.2 + +# Dependencies specify other packages that your package needs in order to work. +# To automatically upgrade your package dependencies to the latest versions +# consider running `flutter pub upgrade --major-versions`. Alternatively, +# dependencies can be manually updated by changing the version numbers below to +# the latest version available on pub.dev. To see which dependencies have newer +# versions available, run `flutter pub outdated`. +dependencies: + flutter: + sdk: flutter + yx_tracking_flutter: + path: ../ + + # The following adds the Cupertino Icons font to your application. + # Use with the CupertinoIcons class for iOS style icons. + cupertino_icons: ^1.0.8 + +dev_dependencies: + flutter_test: + sdk: flutter + + # The "flutter_lints" package below contains a set of recommended lints to + # encourage good coding practices. The lint set provided by the package is + # activated in the `analysis_options.yaml` file located at the root of your + # package. See that file for information about deactivating specific lint + # rules and activating additional ones. + flutter_lints: ^5.0.0 + +# For information on the generic Dart part of this file, see the +# following page: https://dart.dev/tools/pub/pubspec + +# The following section is specific to Flutter packages. +flutter: + + # The following line ensures that the Material Icons font is + # included with your application, so that you can use the icons in + # the material Icons class. + uses-material-design: true + + # To add assets to your application, add an assets section, like this: + # assets: + # - images/a_dot_burr.jpeg + # - images/a_dot_ham.jpeg + + # An image asset can refer to one or more resolution-specific "variants", see + # https://flutter.dev/to/resolution-aware-images + + # For details regarding adding assets from package dependencies, see + # https://flutter.dev/to/asset-from-package + + # To add custom fonts to your application, add a fonts section here, + # in this "flutter" section. Each entry in this list should have a + # "family" key with the font family name, and a "fonts" key with a + # list giving the asset and other descriptors for the font. For + # example: + # fonts: + # - family: Schyler + # fonts: + # - asset: fonts/Schyler-Regular.ttf + # - asset: fonts/Schyler-Italic.ttf + # style: italic + # - family: Trajan Pro + # fonts: + # - asset: fonts/TrajanPro.ttf + # - asset: fonts/TrajanPro_Bold.ttf + # weight: 700 + # + # For details regarding fonts from package dependencies, + # see https://flutter.dev/to/font-from-package diff --git a/example/test/widget_test.dart b/example/test/widget_test.dart new file mode 100644 index 0000000..df8115b --- /dev/null +++ b/example/test/widget_test.dart @@ -0,0 +1,15 @@ +import 'package:flutter_test/flutter_test.dart'; + +import 'package:example/main.dart'; + +void main() { + testWidgets('Demo 页面基础元素可渲染', (WidgetTester tester) async { + await tester.pumpWidget(const DemoApp()); + await tester.pump(); + + expect(find.text('YX Tracking Demo'), findsOneWidget); + expect(find.textContaining('本地缓存事件数'), findsOneWidget); + expect(find.text('Track Demo Event'), findsOneWidget); + expect(find.text('Flush Now'), findsOneWidget); + }); +} diff --git a/example/web/favicon.png b/example/web/favicon.png new file mode 100644 index 0000000..8aaa46a Binary files /dev/null and b/example/web/favicon.png differ diff --git a/example/web/icons/Icon-192.png b/example/web/icons/Icon-192.png new file mode 100644 index 0000000..b749bfe Binary files /dev/null and b/example/web/icons/Icon-192.png differ diff --git a/example/web/icons/Icon-512.png b/example/web/icons/Icon-512.png new file mode 100644 index 0000000..88cfd48 Binary files /dev/null and b/example/web/icons/Icon-512.png differ diff --git a/example/web/icons/Icon-maskable-192.png b/example/web/icons/Icon-maskable-192.png new file mode 100644 index 0000000..eb9b4d7 Binary files /dev/null and b/example/web/icons/Icon-maskable-192.png differ diff --git a/example/web/icons/Icon-maskable-512.png b/example/web/icons/Icon-maskable-512.png new file mode 100644 index 0000000..d69c566 Binary files /dev/null and b/example/web/icons/Icon-maskable-512.png differ diff --git a/example/web/index.html b/example/web/index.html new file mode 100644 index 0000000..29b5808 --- /dev/null +++ b/example/web/index.html @@ -0,0 +1,38 @@ + + + + + + + + + + + + + + + + + + + + example + + + + + + diff --git a/example/web/manifest.json b/example/web/manifest.json new file mode 100644 index 0000000..096edf8 --- /dev/null +++ b/example/web/manifest.json @@ -0,0 +1,35 @@ +{ + "name": "example", + "short_name": "example", + "start_url": ".", + "display": "standalone", + "background_color": "#0175C2", + "theme_color": "#0175C2", + "description": "A new Flutter project.", + "orientation": "portrait-primary", + "prefer_related_applications": false, + "icons": [ + { + "src": "icons/Icon-192.png", + "sizes": "192x192", + "type": "image/png" + }, + { + "src": "icons/Icon-512.png", + "sizes": "512x512", + "type": "image/png" + }, + { + "src": "icons/Icon-maskable-192.png", + "sizes": "192x192", + "type": "image/png", + "purpose": "maskable" + }, + { + "src": "icons/Icon-maskable-512.png", + "sizes": "512x512", + "type": "image/png", + "purpose": "maskable" + } + ] +} diff --git a/example/windows/.gitignore b/example/windows/.gitignore new file mode 100644 index 0000000..d492d0d --- /dev/null +++ b/example/windows/.gitignore @@ -0,0 +1,17 @@ +flutter/ephemeral/ + +# Visual Studio user-specific files. +*.suo +*.user +*.userosscache +*.sln.docstates + +# Visual Studio build-related files. +x64/ +x86/ + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ diff --git a/example/windows/CMakeLists.txt b/example/windows/CMakeLists.txt new file mode 100644 index 0000000..d960948 --- /dev/null +++ b/example/windows/CMakeLists.txt @@ -0,0 +1,108 @@ +# Project-level configuration. +cmake_minimum_required(VERSION 3.14) +project(example LANGUAGES CXX) + +# The name of the executable created for the application. Change this to change +# the on-disk name of your application. +set(BINARY_NAME "example") + +# Explicitly opt in to modern CMake behaviors to avoid warnings with recent +# versions of CMake. +cmake_policy(VERSION 3.14...3.25) + +# Define build configuration option. +get_property(IS_MULTICONFIG GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) +if(IS_MULTICONFIG) + set(CMAKE_CONFIGURATION_TYPES "Debug;Profile;Release" + CACHE STRING "" FORCE) +else() + if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) + set(CMAKE_BUILD_TYPE "Debug" CACHE + STRING "Flutter build mode" FORCE) + set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS + "Debug" "Profile" "Release") + endif() +endif() +# Define settings for the Profile build mode. +set(CMAKE_EXE_LINKER_FLAGS_PROFILE "${CMAKE_EXE_LINKER_FLAGS_RELEASE}") +set(CMAKE_SHARED_LINKER_FLAGS_PROFILE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE}") +set(CMAKE_C_FLAGS_PROFILE "${CMAKE_C_FLAGS_RELEASE}") +set(CMAKE_CXX_FLAGS_PROFILE "${CMAKE_CXX_FLAGS_RELEASE}") + +# Use Unicode for all projects. +add_definitions(-DUNICODE -D_UNICODE) + +# Compilation settings that should be applied to most targets. +# +# Be cautious about adding new options here, as plugins use this function by +# default. In most cases, you should add new options to specific targets instead +# of modifying this function. +function(APPLY_STANDARD_SETTINGS TARGET) + target_compile_features(${TARGET} PUBLIC cxx_std_17) + target_compile_options(${TARGET} PRIVATE /W4 /WX /wd"4100") + target_compile_options(${TARGET} PRIVATE /EHsc) + target_compile_definitions(${TARGET} PRIVATE "_HAS_EXCEPTIONS=0") + target_compile_definitions(${TARGET} PRIVATE "$<$:_DEBUG>") +endfunction() + +# Flutter library and tool build rules. +set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") +add_subdirectory(${FLUTTER_MANAGED_DIR}) + +# Application build; see runner/CMakeLists.txt. +add_subdirectory("runner") + + +# Generated plugin build rules, which manage building the plugins and adding +# them to the application. +include(flutter/generated_plugins.cmake) + + +# === Installation === +# Support files are copied into place next to the executable, so that it can +# run in place. This is done instead of making a separate bundle (as on Linux) +# so that building and running from within Visual Studio will work. +set(BUILD_BUNDLE_DIR "$") +# Make the "install" step default, as it's required to run. +set(CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD 1) +if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) + set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) +endif() + +set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") +set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}") + +install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +if(PLUGIN_BUNDLED_LIBRARIES) + install(FILES "${PLUGIN_BUNDLED_LIBRARIES}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endif() + +# Copy the native assets provided by the build.dart from all packages. +set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/windows/") +install(DIRECTORY "${NATIVE_ASSETS_DIR}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +# Fully re-copy the assets directory on each build to avoid having stale files +# from a previous install. +set(FLUTTER_ASSET_DIR_NAME "flutter_assets") +install(CODE " + file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") + " COMPONENT Runtime) +install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" + DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) + +# Install the AOT library on non-Debug builds only. +install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + CONFIGURATIONS Profile;Release + COMPONENT Runtime) diff --git a/example/windows/flutter/CMakeLists.txt b/example/windows/flutter/CMakeLists.txt new file mode 100644 index 0000000..903f489 --- /dev/null +++ b/example/windows/flutter/CMakeLists.txt @@ -0,0 +1,109 @@ +# This file controls Flutter-level build steps. It should not be edited. +cmake_minimum_required(VERSION 3.14) + +set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") + +# Configuration provided via flutter tool. +include(${EPHEMERAL_DIR}/generated_config.cmake) + +# TODO: Move the rest of this into files in ephemeral. See +# https://github.com/flutter/flutter/issues/57146. +set(WRAPPER_ROOT "${EPHEMERAL_DIR}/cpp_client_wrapper") + +# Set fallback configurations for older versions of the flutter tool. +if (NOT DEFINED FLUTTER_TARGET_PLATFORM) + set(FLUTTER_TARGET_PLATFORM "windows-x64") +endif() + +# === Flutter Library === +set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/flutter_windows.dll") + +# Published to parent scope for install step. +set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) +set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) +set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) +set(AOT_LIBRARY "${PROJECT_DIR}/build/windows/app.so" PARENT_SCOPE) + +list(APPEND FLUTTER_LIBRARY_HEADERS + "flutter_export.h" + "flutter_windows.h" + "flutter_messenger.h" + "flutter_plugin_registrar.h" + "flutter_texture_registrar.h" +) +list(TRANSFORM FLUTTER_LIBRARY_HEADERS PREPEND "${EPHEMERAL_DIR}/") +add_library(flutter INTERFACE) +target_include_directories(flutter INTERFACE + "${EPHEMERAL_DIR}" +) +target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}.lib") +add_dependencies(flutter flutter_assemble) + +# === Wrapper === +list(APPEND CPP_WRAPPER_SOURCES_CORE + "core_implementations.cc" + "standard_codec.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_CORE PREPEND "${WRAPPER_ROOT}/") +list(APPEND CPP_WRAPPER_SOURCES_PLUGIN + "plugin_registrar.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_PLUGIN PREPEND "${WRAPPER_ROOT}/") +list(APPEND CPP_WRAPPER_SOURCES_APP + "flutter_engine.cc" + "flutter_view_controller.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_APP PREPEND "${WRAPPER_ROOT}/") + +# Wrapper sources needed for a plugin. +add_library(flutter_wrapper_plugin STATIC + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_PLUGIN} +) +apply_standard_settings(flutter_wrapper_plugin) +set_target_properties(flutter_wrapper_plugin PROPERTIES + POSITION_INDEPENDENT_CODE ON) +set_target_properties(flutter_wrapper_plugin PROPERTIES + CXX_VISIBILITY_PRESET hidden) +target_link_libraries(flutter_wrapper_plugin PUBLIC flutter) +target_include_directories(flutter_wrapper_plugin PUBLIC + "${WRAPPER_ROOT}/include" +) +add_dependencies(flutter_wrapper_plugin flutter_assemble) + +# Wrapper sources needed for the runner. +add_library(flutter_wrapper_app STATIC + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_APP} +) +apply_standard_settings(flutter_wrapper_app) +target_link_libraries(flutter_wrapper_app PUBLIC flutter) +target_include_directories(flutter_wrapper_app PUBLIC + "${WRAPPER_ROOT}/include" +) +add_dependencies(flutter_wrapper_app flutter_assemble) + +# === Flutter tool backend === +# _phony_ is a non-existent file to force this command to run every time, +# since currently there's no way to get a full input/output list from the +# flutter tool. +set(PHONY_OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/_phony_") +set_source_files_properties("${PHONY_OUTPUT}" PROPERTIES SYMBOLIC TRUE) +add_custom_command( + OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} + ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN} + ${CPP_WRAPPER_SOURCES_APP} + ${PHONY_OUTPUT} + COMMAND ${CMAKE_COMMAND} -E env + ${FLUTTER_TOOL_ENVIRONMENT} + "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.bat" + ${FLUTTER_TARGET_PLATFORM} $ + VERBATIM +) +add_custom_target(flutter_assemble DEPENDS + "${FLUTTER_LIBRARY}" + ${FLUTTER_LIBRARY_HEADERS} + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_PLUGIN} + ${CPP_WRAPPER_SOURCES_APP} +) diff --git a/example/windows/flutter/generated_plugin_registrant.cc b/example/windows/flutter/generated_plugin_registrant.cc new file mode 100644 index 0000000..8b6d468 --- /dev/null +++ b/example/windows/flutter/generated_plugin_registrant.cc @@ -0,0 +1,11 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + + +void RegisterPlugins(flutter::PluginRegistry* registry) { +} diff --git a/example/windows/flutter/generated_plugin_registrant.h b/example/windows/flutter/generated_plugin_registrant.h new file mode 100644 index 0000000..dc139d8 --- /dev/null +++ b/example/windows/flutter/generated_plugin_registrant.h @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#ifndef GENERATED_PLUGIN_REGISTRANT_ +#define GENERATED_PLUGIN_REGISTRANT_ + +#include + +// Registers Flutter plugins. +void RegisterPlugins(flutter::PluginRegistry* registry); + +#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/example/windows/flutter/generated_plugins.cmake b/example/windows/flutter/generated_plugins.cmake new file mode 100644 index 0000000..b93c4c3 --- /dev/null +++ b/example/windows/flutter/generated_plugins.cmake @@ -0,0 +1,23 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST +) + +list(APPEND FLUTTER_FFI_PLUGIN_LIST +) + +set(PLUGIN_BUNDLED_LIBRARIES) + +foreach(plugin ${FLUTTER_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/windows plugins/${plugin}) + target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) + list(APPEND PLUGIN_BUNDLED_LIBRARIES $) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) +endforeach(plugin) + +foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/windows plugins/${ffi_plugin}) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) +endforeach(ffi_plugin) diff --git a/example/windows/runner/CMakeLists.txt b/example/windows/runner/CMakeLists.txt new file mode 100644 index 0000000..394917c --- /dev/null +++ b/example/windows/runner/CMakeLists.txt @@ -0,0 +1,40 @@ +cmake_minimum_required(VERSION 3.14) +project(runner LANGUAGES CXX) + +# Define the application target. To change its name, change BINARY_NAME in the +# top-level CMakeLists.txt, not the value here, or `flutter run` will no longer +# work. +# +# Any new source files that you add to the application should be added here. +add_executable(${BINARY_NAME} WIN32 + "flutter_window.cpp" + "main.cpp" + "utils.cpp" + "win32_window.cpp" + "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" + "Runner.rc" + "runner.exe.manifest" +) + +# Apply the standard set of build settings. This can be removed for applications +# that need different build settings. +apply_standard_settings(${BINARY_NAME}) + +# Add preprocessor definitions for the build version. +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION=\"${FLUTTER_VERSION}\"") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MAJOR=${FLUTTER_VERSION_MAJOR}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MINOR=${FLUTTER_VERSION_MINOR}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_PATCH=${FLUTTER_VERSION_PATCH}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_BUILD=${FLUTTER_VERSION_BUILD}") + +# Disable Windows macros that collide with C++ standard library functions. +target_compile_definitions(${BINARY_NAME} PRIVATE "NOMINMAX") + +# Add dependency libraries and include directories. Add any application-specific +# dependencies here. +target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app) +target_link_libraries(${BINARY_NAME} PRIVATE "dwmapi.lib") +target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") + +# Run the Flutter tool portions of the build. This must not be removed. +add_dependencies(${BINARY_NAME} flutter_assemble) diff --git a/example/windows/runner/Runner.rc b/example/windows/runner/Runner.rc new file mode 100644 index 0000000..0e3e27b --- /dev/null +++ b/example/windows/runner/Runner.rc @@ -0,0 +1,121 @@ +// Microsoft Visual C++ generated resource script. +// +#pragma code_page(65001) +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#include "winres.h" + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// English (United States) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) +LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE +BEGIN + "#include ""winres.h""\r\n" + "\0" +END + +3 TEXTINCLUDE +BEGIN + "\r\n" + "\0" +END + +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// Icon +// + +// Icon with lowest ID value placed first to ensure application icon +// remains consistent on all systems. +IDI_APP_ICON ICON "resources\\app_icon.ico" + + +///////////////////////////////////////////////////////////////////////////// +// +// Version +// + +#if defined(FLUTTER_VERSION_MAJOR) && defined(FLUTTER_VERSION_MINOR) && defined(FLUTTER_VERSION_PATCH) && defined(FLUTTER_VERSION_BUILD) +#define VERSION_AS_NUMBER FLUTTER_VERSION_MAJOR,FLUTTER_VERSION_MINOR,FLUTTER_VERSION_PATCH,FLUTTER_VERSION_BUILD +#else +#define VERSION_AS_NUMBER 1,0,0,0 +#endif + +#if defined(FLUTTER_VERSION) +#define VERSION_AS_STRING FLUTTER_VERSION +#else +#define VERSION_AS_STRING "1.0.0" +#endif + +VS_VERSION_INFO VERSIONINFO + FILEVERSION VERSION_AS_NUMBER + PRODUCTVERSION VERSION_AS_NUMBER + FILEFLAGSMASK VS_FFI_FILEFLAGSMASK +#ifdef _DEBUG + FILEFLAGS VS_FF_DEBUG +#else + FILEFLAGS 0x0L +#endif + FILEOS VOS__WINDOWS32 + FILETYPE VFT_APP + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904e4" + BEGIN + VALUE "CompanyName", "com.example" "\0" + VALUE "FileDescription", "example" "\0" + VALUE "FileVersion", VERSION_AS_STRING "\0" + VALUE "InternalName", "example" "\0" + VALUE "LegalCopyright", "Copyright (C) 2026 com.example. All rights reserved." "\0" + VALUE "OriginalFilename", "example.exe" "\0" + VALUE "ProductName", "example" "\0" + VALUE "ProductVersion", VERSION_AS_STRING "\0" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 1252 + END +END + +#endif // English (United States) resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// + + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED diff --git a/example/windows/runner/flutter_window.cpp b/example/windows/runner/flutter_window.cpp new file mode 100644 index 0000000..955ee30 --- /dev/null +++ b/example/windows/runner/flutter_window.cpp @@ -0,0 +1,71 @@ +#include "flutter_window.h" + +#include + +#include "flutter/generated_plugin_registrant.h" + +FlutterWindow::FlutterWindow(const flutter::DartProject& project) + : project_(project) {} + +FlutterWindow::~FlutterWindow() {} + +bool FlutterWindow::OnCreate() { + if (!Win32Window::OnCreate()) { + return false; + } + + RECT frame = GetClientArea(); + + // The size here must match the window dimensions to avoid unnecessary surface + // creation / destruction in the startup path. + flutter_controller_ = std::make_unique( + frame.right - frame.left, frame.bottom - frame.top, project_); + // Ensure that basic setup of the controller was successful. + if (!flutter_controller_->engine() || !flutter_controller_->view()) { + return false; + } + RegisterPlugins(flutter_controller_->engine()); + SetChildContent(flutter_controller_->view()->GetNativeWindow()); + + flutter_controller_->engine()->SetNextFrameCallback([&]() { + this->Show(); + }); + + // Flutter can complete the first frame before the "show window" callback is + // registered. The following call ensures a frame is pending to ensure the + // window is shown. It is a no-op if the first frame hasn't completed yet. + flutter_controller_->ForceRedraw(); + + return true; +} + +void FlutterWindow::OnDestroy() { + if (flutter_controller_) { + flutter_controller_ = nullptr; + } + + Win32Window::OnDestroy(); +} + +LRESULT +FlutterWindow::MessageHandler(HWND hwnd, UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + // Give Flutter, including plugins, an opportunity to handle window messages. + if (flutter_controller_) { + std::optional result = + flutter_controller_->HandleTopLevelWindowProc(hwnd, message, wparam, + lparam); + if (result) { + return *result; + } + } + + switch (message) { + case WM_FONTCHANGE: + flutter_controller_->engine()->ReloadSystemFonts(); + break; + } + + return Win32Window::MessageHandler(hwnd, message, wparam, lparam); +} diff --git a/example/windows/runner/flutter_window.h b/example/windows/runner/flutter_window.h new file mode 100644 index 0000000..6da0652 --- /dev/null +++ b/example/windows/runner/flutter_window.h @@ -0,0 +1,33 @@ +#ifndef RUNNER_FLUTTER_WINDOW_H_ +#define RUNNER_FLUTTER_WINDOW_H_ + +#include +#include + +#include + +#include "win32_window.h" + +// A window that does nothing but host a Flutter view. +class FlutterWindow : public Win32Window { + public: + // Creates a new FlutterWindow hosting a Flutter view running |project|. + explicit FlutterWindow(const flutter::DartProject& project); + virtual ~FlutterWindow(); + + protected: + // Win32Window: + bool OnCreate() override; + void OnDestroy() override; + LRESULT MessageHandler(HWND window, UINT const message, WPARAM const wparam, + LPARAM const lparam) noexcept override; + + private: + // The project to run. + flutter::DartProject project_; + + // The Flutter instance hosted by this window. + std::unique_ptr flutter_controller_; +}; + +#endif // RUNNER_FLUTTER_WINDOW_H_ diff --git a/example/windows/runner/main.cpp b/example/windows/runner/main.cpp new file mode 100644 index 0000000..a61bf80 --- /dev/null +++ b/example/windows/runner/main.cpp @@ -0,0 +1,43 @@ +#include +#include +#include + +#include "flutter_window.h" +#include "utils.h" + +int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev, + _In_ wchar_t *command_line, _In_ int show_command) { + // Attach to console when present (e.g., 'flutter run') or create a + // new console when running with a debugger. + if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) { + CreateAndAttachConsole(); + } + + // Initialize COM, so that it is available for use in the library and/or + // plugins. + ::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED); + + flutter::DartProject project(L"data"); + + std::vector command_line_arguments = + GetCommandLineArguments(); + + project.set_dart_entrypoint_arguments(std::move(command_line_arguments)); + + FlutterWindow window(project); + Win32Window::Point origin(10, 10); + Win32Window::Size size(1280, 720); + if (!window.Create(L"example", origin, size)) { + return EXIT_FAILURE; + } + window.SetQuitOnClose(true); + + ::MSG msg; + while (::GetMessage(&msg, nullptr, 0, 0)) { + ::TranslateMessage(&msg); + ::DispatchMessage(&msg); + } + + ::CoUninitialize(); + return EXIT_SUCCESS; +} diff --git a/example/windows/runner/resource.h b/example/windows/runner/resource.h new file mode 100644 index 0000000..66a65d1 --- /dev/null +++ b/example/windows/runner/resource.h @@ -0,0 +1,16 @@ +//{{NO_DEPENDENCIES}} +// Microsoft Visual C++ generated include file. +// Used by Runner.rc +// +#define IDI_APP_ICON 101 + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 102 +#define _APS_NEXT_COMMAND_VALUE 40001 +#define _APS_NEXT_CONTROL_VALUE 1001 +#define _APS_NEXT_SYMED_VALUE 101 +#endif +#endif diff --git a/example/windows/runner/resources/app_icon.ico b/example/windows/runner/resources/app_icon.ico new file mode 100644 index 0000000..c04e20c Binary files /dev/null and b/example/windows/runner/resources/app_icon.ico differ diff --git a/example/windows/runner/runner.exe.manifest b/example/windows/runner/runner.exe.manifest new file mode 100644 index 0000000..153653e --- /dev/null +++ b/example/windows/runner/runner.exe.manifest @@ -0,0 +1,14 @@ + + + + + PerMonitorV2 + + + + + + + + + diff --git a/example/windows/runner/utils.cpp b/example/windows/runner/utils.cpp new file mode 100644 index 0000000..3a0b465 --- /dev/null +++ b/example/windows/runner/utils.cpp @@ -0,0 +1,65 @@ +#include "utils.h" + +#include +#include +#include +#include + +#include + +void CreateAndAttachConsole() { + if (::AllocConsole()) { + FILE *unused; + if (freopen_s(&unused, "CONOUT$", "w", stdout)) { + _dup2(_fileno(stdout), 1); + } + if (freopen_s(&unused, "CONOUT$", "w", stderr)) { + _dup2(_fileno(stdout), 2); + } + std::ios::sync_with_stdio(); + FlutterDesktopResyncOutputStreams(); + } +} + +std::vector GetCommandLineArguments() { + // Convert the UTF-16 command line arguments to UTF-8 for the Engine to use. + int argc; + wchar_t** argv = ::CommandLineToArgvW(::GetCommandLineW(), &argc); + if (argv == nullptr) { + return std::vector(); + } + + std::vector command_line_arguments; + + // Skip the first argument as it's the binary name. + for (int i = 1; i < argc; i++) { + command_line_arguments.push_back(Utf8FromUtf16(argv[i])); + } + + ::LocalFree(argv); + + return command_line_arguments; +} + +std::string Utf8FromUtf16(const wchar_t* utf16_string) { + if (utf16_string == nullptr) { + return std::string(); + } + unsigned int target_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + -1, nullptr, 0, nullptr, nullptr) + -1; // remove the trailing null character + int input_length = (int)wcslen(utf16_string); + std::string utf8_string; + if (target_length == 0 || target_length > utf8_string.max_size()) { + return utf8_string; + } + utf8_string.resize(target_length); + int converted_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + input_length, utf8_string.data(), target_length, nullptr, nullptr); + if (converted_length == 0) { + return std::string(); + } + return utf8_string; +} diff --git a/example/windows/runner/utils.h b/example/windows/runner/utils.h new file mode 100644 index 0000000..3879d54 --- /dev/null +++ b/example/windows/runner/utils.h @@ -0,0 +1,19 @@ +#ifndef RUNNER_UTILS_H_ +#define RUNNER_UTILS_H_ + +#include +#include + +// Creates a console for the process, and redirects stdout and stderr to +// it for both the runner and the Flutter library. +void CreateAndAttachConsole(); + +// Takes a null-terminated wchar_t* encoded in UTF-16 and returns a std::string +// encoded in UTF-8. Returns an empty std::string on failure. +std::string Utf8FromUtf16(const wchar_t* utf16_string); + +// Gets the command line arguments passed in as a std::vector, +// encoded in UTF-8. Returns an empty std::vector on failure. +std::vector GetCommandLineArguments(); + +#endif // RUNNER_UTILS_H_ diff --git a/example/windows/runner/win32_window.cpp b/example/windows/runner/win32_window.cpp new file mode 100644 index 0000000..60608d0 --- /dev/null +++ b/example/windows/runner/win32_window.cpp @@ -0,0 +1,288 @@ +#include "win32_window.h" + +#include +#include + +#include "resource.h" + +namespace { + +/// Window attribute that enables dark mode window decorations. +/// +/// Redefined in case the developer's machine has a Windows SDK older than +/// version 10.0.22000.0. +/// See: https://docs.microsoft.com/windows/win32/api/dwmapi/ne-dwmapi-dwmwindowattribute +#ifndef DWMWA_USE_IMMERSIVE_DARK_MODE +#define DWMWA_USE_IMMERSIVE_DARK_MODE 20 +#endif + +constexpr const wchar_t kWindowClassName[] = L"FLUTTER_RUNNER_WIN32_WINDOW"; + +/// Registry key for app theme preference. +/// +/// A value of 0 indicates apps should use dark mode. A non-zero or missing +/// value indicates apps should use light mode. +constexpr const wchar_t kGetPreferredBrightnessRegKey[] = + L"Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize"; +constexpr const wchar_t kGetPreferredBrightnessRegValue[] = L"AppsUseLightTheme"; + +// The number of Win32Window objects that currently exist. +static int g_active_window_count = 0; + +using EnableNonClientDpiScaling = BOOL __stdcall(HWND hwnd); + +// Scale helper to convert logical scaler values to physical using passed in +// scale factor +int Scale(int source, double scale_factor) { + return static_cast(source * scale_factor); +} + +// Dynamically loads the |EnableNonClientDpiScaling| from the User32 module. +// This API is only needed for PerMonitor V1 awareness mode. +void EnableFullDpiSupportIfAvailable(HWND hwnd) { + HMODULE user32_module = LoadLibraryA("User32.dll"); + if (!user32_module) { + return; + } + auto enable_non_client_dpi_scaling = + reinterpret_cast( + GetProcAddress(user32_module, "EnableNonClientDpiScaling")); + if (enable_non_client_dpi_scaling != nullptr) { + enable_non_client_dpi_scaling(hwnd); + } + FreeLibrary(user32_module); +} + +} // namespace + +// Manages the Win32Window's window class registration. +class WindowClassRegistrar { + public: + ~WindowClassRegistrar() = default; + + // Returns the singleton registrar instance. + static WindowClassRegistrar* GetInstance() { + if (!instance_) { + instance_ = new WindowClassRegistrar(); + } + return instance_; + } + + // Returns the name of the window class, registering the class if it hasn't + // previously been registered. + const wchar_t* GetWindowClass(); + + // Unregisters the window class. Should only be called if there are no + // instances of the window. + void UnregisterWindowClass(); + + private: + WindowClassRegistrar() = default; + + static WindowClassRegistrar* instance_; + + bool class_registered_ = false; +}; + +WindowClassRegistrar* WindowClassRegistrar::instance_ = nullptr; + +const wchar_t* WindowClassRegistrar::GetWindowClass() { + if (!class_registered_) { + WNDCLASS window_class{}; + window_class.hCursor = LoadCursor(nullptr, IDC_ARROW); + window_class.lpszClassName = kWindowClassName; + window_class.style = CS_HREDRAW | CS_VREDRAW; + window_class.cbClsExtra = 0; + window_class.cbWndExtra = 0; + window_class.hInstance = GetModuleHandle(nullptr); + window_class.hIcon = + LoadIcon(window_class.hInstance, MAKEINTRESOURCE(IDI_APP_ICON)); + window_class.hbrBackground = 0; + window_class.lpszMenuName = nullptr; + window_class.lpfnWndProc = Win32Window::WndProc; + RegisterClass(&window_class); + class_registered_ = true; + } + return kWindowClassName; +} + +void WindowClassRegistrar::UnregisterWindowClass() { + UnregisterClass(kWindowClassName, nullptr); + class_registered_ = false; +} + +Win32Window::Win32Window() { + ++g_active_window_count; +} + +Win32Window::~Win32Window() { + --g_active_window_count; + Destroy(); +} + +bool Win32Window::Create(const std::wstring& title, + const Point& origin, + const Size& size) { + Destroy(); + + const wchar_t* window_class = + WindowClassRegistrar::GetInstance()->GetWindowClass(); + + const POINT target_point = {static_cast(origin.x), + static_cast(origin.y)}; + HMONITOR monitor = MonitorFromPoint(target_point, MONITOR_DEFAULTTONEAREST); + UINT dpi = FlutterDesktopGetDpiForMonitor(monitor); + double scale_factor = dpi / 96.0; + + HWND window = CreateWindow( + window_class, title.c_str(), WS_OVERLAPPEDWINDOW, + Scale(origin.x, scale_factor), Scale(origin.y, scale_factor), + Scale(size.width, scale_factor), Scale(size.height, scale_factor), + nullptr, nullptr, GetModuleHandle(nullptr), this); + + if (!window) { + return false; + } + + UpdateTheme(window); + + return OnCreate(); +} + +bool Win32Window::Show() { + return ShowWindow(window_handle_, SW_SHOWNORMAL); +} + +// static +LRESULT CALLBACK Win32Window::WndProc(HWND const window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + if (message == WM_NCCREATE) { + auto window_struct = reinterpret_cast(lparam); + SetWindowLongPtr(window, GWLP_USERDATA, + reinterpret_cast(window_struct->lpCreateParams)); + + auto that = static_cast(window_struct->lpCreateParams); + EnableFullDpiSupportIfAvailable(window); + that->window_handle_ = window; + } else if (Win32Window* that = GetThisFromHandle(window)) { + return that->MessageHandler(window, message, wparam, lparam); + } + + return DefWindowProc(window, message, wparam, lparam); +} + +LRESULT +Win32Window::MessageHandler(HWND hwnd, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + switch (message) { + case WM_DESTROY: + window_handle_ = nullptr; + Destroy(); + if (quit_on_close_) { + PostQuitMessage(0); + } + return 0; + + case WM_DPICHANGED: { + auto newRectSize = reinterpret_cast(lparam); + LONG newWidth = newRectSize->right - newRectSize->left; + LONG newHeight = newRectSize->bottom - newRectSize->top; + + SetWindowPos(hwnd, nullptr, newRectSize->left, newRectSize->top, newWidth, + newHeight, SWP_NOZORDER | SWP_NOACTIVATE); + + return 0; + } + case WM_SIZE: { + RECT rect = GetClientArea(); + if (child_content_ != nullptr) { + // Size and position the child window. + MoveWindow(child_content_, rect.left, rect.top, rect.right - rect.left, + rect.bottom - rect.top, TRUE); + } + return 0; + } + + case WM_ACTIVATE: + if (child_content_ != nullptr) { + SetFocus(child_content_); + } + return 0; + + case WM_DWMCOLORIZATIONCOLORCHANGED: + UpdateTheme(hwnd); + return 0; + } + + return DefWindowProc(window_handle_, message, wparam, lparam); +} + +void Win32Window::Destroy() { + OnDestroy(); + + if (window_handle_) { + DestroyWindow(window_handle_); + window_handle_ = nullptr; + } + if (g_active_window_count == 0) { + WindowClassRegistrar::GetInstance()->UnregisterWindowClass(); + } +} + +Win32Window* Win32Window::GetThisFromHandle(HWND const window) noexcept { + return reinterpret_cast( + GetWindowLongPtr(window, GWLP_USERDATA)); +} + +void Win32Window::SetChildContent(HWND content) { + child_content_ = content; + SetParent(content, window_handle_); + RECT frame = GetClientArea(); + + MoveWindow(content, frame.left, frame.top, frame.right - frame.left, + frame.bottom - frame.top, true); + + SetFocus(child_content_); +} + +RECT Win32Window::GetClientArea() { + RECT frame; + GetClientRect(window_handle_, &frame); + return frame; +} + +HWND Win32Window::GetHandle() { + return window_handle_; +} + +void Win32Window::SetQuitOnClose(bool quit_on_close) { + quit_on_close_ = quit_on_close; +} + +bool Win32Window::OnCreate() { + // No-op; provided for subclasses. + return true; +} + +void Win32Window::OnDestroy() { + // No-op; provided for subclasses. +} + +void Win32Window::UpdateTheme(HWND const window) { + DWORD light_mode; + DWORD light_mode_size = sizeof(light_mode); + LSTATUS result = RegGetValue(HKEY_CURRENT_USER, kGetPreferredBrightnessRegKey, + kGetPreferredBrightnessRegValue, + RRF_RT_REG_DWORD, nullptr, &light_mode, + &light_mode_size); + + if (result == ERROR_SUCCESS) { + BOOL enable_dark_mode = light_mode == 0; + DwmSetWindowAttribute(window, DWMWA_USE_IMMERSIVE_DARK_MODE, + &enable_dark_mode, sizeof(enable_dark_mode)); + } +} diff --git a/example/windows/runner/win32_window.h b/example/windows/runner/win32_window.h new file mode 100644 index 0000000..e901dde --- /dev/null +++ b/example/windows/runner/win32_window.h @@ -0,0 +1,102 @@ +#ifndef RUNNER_WIN32_WINDOW_H_ +#define RUNNER_WIN32_WINDOW_H_ + +#include + +#include +#include +#include + +// A class abstraction for a high DPI-aware Win32 Window. Intended to be +// inherited from by classes that wish to specialize with custom +// rendering and input handling +class Win32Window { + public: + struct Point { + unsigned int x; + unsigned int y; + Point(unsigned int x, unsigned int y) : x(x), y(y) {} + }; + + struct Size { + unsigned int width; + unsigned int height; + Size(unsigned int width, unsigned int height) + : width(width), height(height) {} + }; + + Win32Window(); + virtual ~Win32Window(); + + // Creates a win32 window with |title| that is positioned and sized using + // |origin| and |size|. New windows are created on the default monitor. Window + // sizes are specified to the OS in physical pixels, hence to ensure a + // consistent size this function will scale the inputted width and height as + // as appropriate for the default monitor. The window is invisible until + // |Show| is called. Returns true if the window was created successfully. + bool Create(const std::wstring& title, const Point& origin, const Size& size); + + // Show the current window. Returns true if the window was successfully shown. + bool Show(); + + // Release OS resources associated with window. + void Destroy(); + + // Inserts |content| into the window tree. + void SetChildContent(HWND content); + + // Returns the backing Window handle to enable clients to set icon and other + // window properties. Returns nullptr if the window has been destroyed. + HWND GetHandle(); + + // If true, closing this window will quit the application. + void SetQuitOnClose(bool quit_on_close); + + // Return a RECT representing the bounds of the current client area. + RECT GetClientArea(); + + protected: + // Processes and route salient window messages for mouse handling, + // size change and DPI. Delegates handling of these to member overloads that + // inheriting classes can handle. + virtual LRESULT MessageHandler(HWND window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept; + + // Called when CreateAndShow is called, allowing subclass window-related + // setup. Subclasses should return false if setup fails. + virtual bool OnCreate(); + + // Called when Destroy is called. + virtual void OnDestroy(); + + private: + friend class WindowClassRegistrar; + + // OS callback called by message pump. Handles the WM_NCCREATE message which + // is passed when the non-client area is being created and enables automatic + // non-client DPI scaling so that the non-client area automatically + // responds to changes in DPI. All other messages are handled by + // MessageHandler. + static LRESULT CALLBACK WndProc(HWND const window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept; + + // Retrieves a class instance pointer for |window| + static Win32Window* GetThisFromHandle(HWND const window) noexcept; + + // Update the window frame's theme to match the system theme. + static void UpdateTheme(HWND const window); + + bool quit_on_close_ = false; + + // window handle for top level window. + HWND window_handle_ = nullptr; + + // window handle for hosted content. + HWND child_content_ = nullptr; +}; + +#endif // RUNNER_WIN32_WINDOW_H_ diff --git a/lib/src/config/analytics_config.dart b/lib/src/config/analytics_config.dart new file mode 100644 index 0000000..0c15cf6 --- /dev/null +++ b/lib/src/config/analytics_config.dart @@ -0,0 +1,113 @@ +import 'dart:core'; + +/// SDK 初始化配置。 +class AnalyticsConfig { + final String systemCode; + final String endpointBaseUrl; + final int clientType; + final bool enableDebug; + + final int batchSize; + final int flushInterval; + final int maxCacheSize; + final int maxRetryCount; + + final Duration connectTimeout; + final Duration readTimeout; + final bool enableMetrics; + final Duration metricsReportInterval; + + /// Debug 下是否在校验错误时阻断发送。 + final bool blockOnValidationError; + + const AnalyticsConfig({ + required this.systemCode, + required this.endpointBaseUrl, + required this.clientType, + this.enableDebug = false, + this.batchSize = 20, + this.flushInterval = 15, + this.maxCacheSize = 5000, + this.maxRetryCount = 3, + this.connectTimeout = const Duration(seconds: 5), + this.readTimeout = const Duration(seconds: 5), + this.enableMetrics = true, + this.metricsReportInterval = const Duration(minutes: 10), + this.blockOnValidationError = false, + }); + + /// 对配置做基础校验。 + /// + /// Phase 1 要求 endpoint 使用 HTTPS,并且关键数值为正数。 + void validate() { + if (systemCode.trim().isEmpty) { + throw ArgumentError.value(systemCode, 'systemCode', 'systemCode 不能为空'); + } + + final uri = Uri.tryParse(endpointBaseUrl); + if (uri == null || uri.scheme.isEmpty || uri.host.isEmpty) { + throw ArgumentError.value( + endpointBaseUrl, + 'endpointBaseUrl', + 'endpointBaseUrl 不是合法的 URL', + ); + } + if (uri.scheme.toLowerCase() != 'https') { + throw ArgumentError.value( + endpointBaseUrl, + 'endpointBaseUrl', + 'endpointBaseUrl 必须使用 HTTPS', + ); + } + + if (clientType <= 0) { + throw ArgumentError.value(clientType, 'clientType', 'clientType 必须为正整数'); + } + if (batchSize <= 0) { + throw ArgumentError.value(batchSize, 'batchSize', 'batchSize 必须为正整数'); + } + if (flushInterval <= 0) { + throw ArgumentError.value(flushInterval, 'flushInterval', 'flushInterval 必须为正整数(秒)'); + } + if (maxCacheSize <= 0) { + throw ArgumentError.value(maxCacheSize, 'maxCacheSize', 'maxCacheSize 必须为正整数'); + } + if (maxRetryCount < 0) { + throw ArgumentError.value(maxRetryCount, 'maxRetryCount', 'maxRetryCount 不能为负数'); + } + if (connectTimeout <= Duration.zero) { + throw ArgumentError.value(connectTimeout, 'connectTimeout', 'connectTimeout 必须大于 0'); + } + if (readTimeout <= Duration.zero) { + throw ArgumentError.value(readTimeout, 'readTimeout', 'readTimeout 必须大于 0'); + } + if (enableMetrics && metricsReportInterval <= Duration.zero) { + throw ArgumentError.value( + metricsReportInterval, + 'metricsReportInterval', + 'metricsReportInterval 必须大于 0', + ); + } + } + + /// `/AddEventListLog` 的完整地址。 + Uri get addEventListLogUri => _appendPath('AddEventListLog'); + + /// `/AddEventLog` 的完整地址(可选降级)。 + Uri get addEventLogUri => _appendPath('AddEventLog'); + + /// `/GetSystemAllDimInfo` 的完整地址(Phase 2+)。 + Uri get getSystemAllDimInfoUri => _appendPath('GetSystemAllDimInfo'); + + Uri _appendPath(String leaf) { + final base = Uri.parse(endpointBaseUrl); + final normalizedBasePath = base.path.endsWith('/') + ? base.path.substring(0, base.path.length - 1) + : base.path; + final nextPath = normalizedBasePath.isEmpty + ? '/$leaf' + : '$normalizedBasePath/$leaf'; + + return base.replace(path: nextPath); + } +} diff --git a/lib/src/config/config_manager.dart b/lib/src/config/config_manager.dart new file mode 100644 index 0000000..743360d --- /dev/null +++ b/lib/src/config/config_manager.dart @@ -0,0 +1,124 @@ +import 'package:dio/dio.dart'; + +import '../model/system_dim_info.dart'; +import '../network/http_client.dart'; +import '../storage/config_storage.dart'; +import '../storage/sqflite_config_storage.dart'; +import '../util/logger.dart'; +import 'analytics_config.dart'; + +/// Phase 2:配置拉取与缓存管理。 +class ConfigManager { + final AnalyticsConfig config; + final Duration refreshInterval; + + final HttpClient _httpClient; + final ConfigStorage _storage; + + SystemDimInfo? _current; + + ConfigManager({ + required this.config, + this.refreshInterval = const Duration(hours: 12), + ConfigStorage? storage, + HttpClient? httpClient, + }) : _httpClient = httpClient ?? HttpClient(config), + _storage = storage ?? SqfliteConfigStorage(); + + SystemDimInfo? get currentConfig => _current; + + Future init() async { + await _storage.init(); + _current = await _storage.loadSystemDimInfo(); + if (_current != null) { + Logger.info( + '已加载本地配置缓存: events=${_current!.eventDefinitions.length}, tags=${_current!.tagDefinitions.length}', + ); + } + } + + Future fetchAndCacheConfig({bool force = false}) async { + if (!force && _shouldSkipFetch()) { + final last = _current?.lastFetchedAt; + Logger.info('配置未过期,跳过拉取: lastFetchedAt=$last'); + return; + } + + try { + final response = await _httpClient.get( + 'GetSystemAllDimInfo', + queryParameters: {'system_code': config.systemCode}, + ); + + final payload = _extractPayloadMap(response.data); + if (payload == null) { + Logger.warn('配置拉取成功但响应结构无法解析,已忽略'); + return; + } + + final version = response.headers.value('etag') ?? + response.headers.value('x-config-version'); + final info = SystemDimInfo.fromResponse(payload, version: version); + + await _storage.saveSystemDimInfo(info); + _current = info; + + Logger.info( + '配置拉取并缓存成功: events=${info.eventDefinitions.length}, tags=${info.tagDefinitions.length}', + ); + } on DioException catch (e, st) { + Logger.error('配置拉取失败(DioException)', e, st); + } catch (e, st) { + Logger.error('配置拉取失败(未知异常)', e, st); + } + } + + Future forceRefresh() => fetchAndCacheConfig(force: true); + + Future dispose() => _storage.dispose(); + + bool _shouldSkipFetch() { + final current = _current; + if (current == null) { + return false; + } + final age = DateTime.now().difference(current.lastFetchedAt); + return age < refreshInterval; + } + + Map? _extractPayloadMap(dynamic data) { + final root = _asStringKeyMap(data); + if (root == null) { + return null; + } + + if (_looksLikeDimInfo(root)) { + return root; + } + + for (final key in const ['data', 'result', 'payload']) { + final nested = _asStringKeyMap(root[key]); + if (nested != null && _looksLikeDimInfo(nested)) { + return nested; + } + } + + return root; + } + + bool _looksLikeDimInfo(Map map) { + return map.containsKey('systemEventTypes') || + map.containsKey('systemCustonTas') || + map.containsKey('systemCustomTags'); + } + + Map? _asStringKeyMap(dynamic value) { + if (value is Map) { + return value; + } + if (value is Map) { + return value.map((k, v) => MapEntry(k.toString(), v)); + } + return null; + } +} diff --git a/lib/src/core/analytics_core.dart b/lib/src/core/analytics_core.dart new file mode 100644 index 0000000..c0a7f9f --- /dev/null +++ b/lib/src/core/analytics_core.dart @@ -0,0 +1,712 @@ +import 'dart:async'; +import 'dart:math'; + +import '../config/analytics_config.dart'; +import '../config/config_manager.dart'; +import '../model/device_info.dart'; +import '../model/event.dart'; +import '../model/recent_event_summary.dart'; +import '../model/user_info.dart'; +import '../network/api_client.dart'; +import '../storage/event_storage.dart'; +import '../storage/sqflite_event_storage.dart'; +import '../util/device_util.dart'; +import '../util/logger.dart'; +import '../util/time_util.dart'; +import 'interceptors.dart'; +import 'scheduler.dart'; +import 'validator.dart'; + +/// SDK 核心逻辑:事件构造、存储、调度与发送。 +class AnalyticsCore { + final EventStorage Function() _storageFactory; + final ApiClient Function(AnalyticsConfig config) _apiClientFactory; + final ConfigManager Function(AnalyticsConfig config) _configManagerFactory; + final Future Function() _deviceInfoCollector; + final Scheduler Function(Duration interval, Future Function() onTick) + _schedulerFactory; + final double Function() _randomDouble; + final DateTime Function() _now; + final bool _includeCommonTagsInterceptor; + final List _initialInterceptors; + + AnalyticsCore({ + EventStorage Function()? storageFactory, + ApiClient Function(AnalyticsConfig config)? apiClientFactory, + ConfigManager Function(AnalyticsConfig config)? configManagerFactory, + Future Function()? deviceInfoCollector, + Scheduler Function(Duration interval, Future Function() onTick)? + schedulerFactory, + double Function()? randomDouble, + DateTime Function()? now, + bool includeCommonTagsInterceptor = true, + List interceptors = const [], + }) : _storageFactory = storageFactory ?? (() => SqfliteEventStorage()), + _apiClientFactory = apiClientFactory ?? ((c) => ApiClient(c)), + _configManagerFactory = + configManagerFactory ?? ((c) => ConfigManager(config: c)), + _deviceInfoCollector = deviceInfoCollector ?? DeviceUtil.collectDeviceInfo, + _schedulerFactory = + schedulerFactory ?? + ((interval, onTick) => Scheduler(interval: interval, onTick: onTick)), + _randomDouble = randomDouble ?? Random().nextDouble, + _now = now ?? DateTime.now, + _includeCommonTagsInterceptor = includeCommonTagsInterceptor, + _initialInterceptors = interceptors; + + AnalyticsConfig? _config; + UserInfo? _user; + DeviceInfo? _deviceInfo; + + EventStorage? _storage; + ApiClient? _apiClient; + Scheduler? _scheduler; + ConfigManager? _configManager; + Validator? _validator; + Timer? _configRefreshTimer; + Timer? _metricsTimer; + final List _interceptors = []; + + bool _initialized = false; + bool _isFlushing = false; + DateTime? _nextAllowedFlushTime; + + // Phase 3:SDK 自监控指标。 + int _sentCount = 0; + int _failedCount = 0; + int _retryCount = 0; + int _droppedCount = 0; + int _totalLatencyMs = 0; + int _latencySamples = 0; + DateTime? _lastMetricsReportTime; + + static const String _metricsSendEventType = 'SDK_METRICS_SEND'; + static const String _metricsQueueEventType = 'SDK_METRICS_QUEUE'; + static const Set _internalEventTypes = { + _metricsSendEventType, + _metricsQueueEventType, + }; + + bool get isInitialized => _initialized; + + Future init(AnalyticsConfig config) async { + // 支持重复 init:先优雅释放旧资源再重新初始化。 + if (_initialized) { + await dispose(); + } + + config.validate(); + Logger.setDebug(config.enableDebug); + Logger.info('AnalyticsCore 初始化开始'); + + final deviceInfo = await _deviceInfoCollector(); + final storage = _storageFactory(); + await storage.init(); + final configManager = _configManagerFactory(config); + await configManager.init(); + + _config = config; + _deviceInfo = deviceInfo; + _storage = storage; + _apiClient = _apiClientFactory(config); + _configManager = configManager; + _validator = Validator(configManager); + _resetInterceptors(); + + final scheduler = _schedulerFactory( + Duration(seconds: config.flushInterval), + () => flush(), + ); + scheduler.start(); + _scheduler = scheduler; + + _initialized = true; + Logger.info('AnalyticsCore 初始化完成'); + + // Phase 2:初始化后异步拉取配置,失败不影响埋点主流程。 + unawaited(configManager.fetchAndCacheConfig()); + _startConfigRefreshTimer(configManager); + _startMetricsTimer(config); + } + + void addInterceptor(AnalyticsInterceptor interceptor) { + _interceptors.add(interceptor); + } + + Future setUser(UserInfo? userInfo) async { + _user = userInfo; + Logger.info('用户信息已更新'); + } + + Future setDeviceInfo(DeviceInfo deviceInfo) async { + _deviceInfo = deviceInfo; + Logger.info('设备信息已覆盖'); + } + + Future track( + String eventType, { + Map? eventParams, + Map? customTags, + int? timestamp, + }) async { + await _track( + eventType, + eventParams: eventParams, + customTags: customTags, + timestamp: timestamp, + internal: false, + ); + } + + Future _track( + String eventType, { + Map? eventParams, + Map? customTags, + int? timestamp, + required bool internal, + }) async { + final config = _config; + final storage = _storage; + final deviceInfo = _deviceInfo; + + if (!_initialized || config == null || storage == null || deviceInfo == null) { + Logger.warn('track 被调用但 SDK 尚未初始化,已忽略: $eventType'); + return; + } + if (eventType.trim().isEmpty) { + Logger.warn('eventType 为空,已忽略'); + return; + } + + if (!internal && _shouldDropByStrategy(eventType)) { + _droppedCount += 1; + Logger.info('事件被策略丢弃: $eventType'); + return; + } + + final now = _now(); + final clientTimestamp = timestamp ?? now.millisecondsSinceEpoch; + final event = Event( + systemCode: config.systemCode, + eventType: eventType, + userInfo: _user, + clientType: config.clientType, + clientTimestamp: clientTimestamp, + timestamp: TimeUtil.iso8601FromMs(clientTimestamp), + deviceInfo: deviceInfo, + eventParams: eventParams, + customTags: customTags, + createTime: now, + ); + + final validatedEvent = internal ? event : _validateAndDecorate(event, config); + if (validatedEvent == null) { + _droppedCount += 1; + return; + } + + if (Logger.isDebugEnabled) { + Logger.debug('track: $eventType payload=${validatedEvent.toJson()}'); + } + + await storage.insert(validatedEvent); + final trimmed = await storage.trimToMaxSize(config.maxCacheSize); + if (trimmed > 0) { + _droppedCount += trimmed; + } + + final currentCount = await storage.count(); + if (currentCount >= config.batchSize) { + // 不阻塞调用方,尽快触发一次上报。 + unawaited(flush()); + } + } + + Future cachedEventCount() async { + final storage = _storage; + if (!_initialized || storage == null) { + return 0; + } + return storage.count(); + } + + Future> cachedRecentEvents({int limit = 20}) async { + final storage = _storage; + if (!_initialized || storage == null || limit <= 0) { + return const []; + } + final recent = await storage.fetchRecent(limit); + return recent + .map( + (stored) => RecentEventSummary( + id: stored.id, + eventType: stored.event.eventType, + createTime: stored.createTime, + retryCount: stored.retryCount, + ), + ) + .toList(growable: false); + } + + Future refreshConfig({bool force = true}) async { + final manager = _configManager; + if (!_initialized || manager == null) { + return; + } + if (force) { + await manager.forceRefresh(); + return; + } + await manager.fetchAndCacheConfig(); + } + + Future reportMetricsNow() => _reportMetrics(); + + Future flush({bool force = false}) async { + final config = _config; + final storage = _storage; + final apiClient = _apiClient; + + if (!_initialized || config == null || storage == null || apiClient == null) { + Logger.warn('flush 被调用但 SDK 尚未初始化,已忽略'); + return; + } + + final now = _now(); + final nextAllowed = _nextAllowedFlushTime; + if (!force && nextAllowed != null && now.isBefore(nextAllowed)) { + Logger.info('flush 被退避策略延后: nextAllowed=$nextAllowed'); + return; + } + + if (_isFlushing) { + Logger.info('已有 flush 在进行中,本次跳过'); + return; + } + + _isFlushing = true; + try { + final flushStart = _now(); + final batch = await storage.fetchBatch(config.batchSize); + if (batch.isEmpty) { + return; + } + + final prepared = await _prepareBatch(storage, batch); + if (prepared.sendable.isEmpty) { + return; + } + final events = + prepared.sendable.map((item) => item.event).toList(growable: false); + final ids = + prepared.sendable.map((item) => item.stored.id).toList(growable: false); + + try { + await apiClient.sendBatch(events); + await storage.deleteByIds(ids); + _nextAllowedFlushTime = null; + _recordSuccessMetrics(events, flushStart); + await _runAfterSend( + prepared.sendable, + const SendResult(success: true, retryable: false), + ); + } on ApiException catch (e) { + _recordFailureMetrics(events); + await _runAfterSend( + prepared.sendable, + SendResult( + success: false, + retryable: e.retryable, + statusCode: e.statusCode, + error: e, + ), + ); + if (e.retryable) { + await _handleRetryableFailure(prepared.sendable, config); + } else { + Logger.warn('不可重试错误,直接丢弃该批次: status=${e.statusCode}'); + await storage.deleteByIds(ids); + _droppedCount += _countNonInternalEvents(events); + } + } catch (e, st) { + Logger.error('flush 发生未知异常,按可重试处理', e, st); + _recordFailureMetrics(events); + await _runAfterSend( + prepared.sendable, + SendResult(success: false, retryable: true, error: e), + ); + await _handleRetryableFailure(prepared.sendable, config); + } + } finally { + _isFlushing = false; + } + } + + Future<_PreparedBatch> _prepareBatch( + EventStorage storage, + List batch, + ) async { + final sendable = <_SendableStoredEvent>[]; + final dropped = <_SendableStoredEvent>[]; + + for (final stored in batch) { + final transformed = await _runBeforeSend(stored.event); + if (transformed == null) { + dropped.add(_SendableStoredEvent(stored: stored, event: stored.event)); + continue; + } + sendable.add(_SendableStoredEvent(stored: stored, event: transformed)); + } + + if (dropped.isNotEmpty) { + final droppedIds = dropped.map((item) => item.stored.id).toList(); + await storage.deleteByIds(droppedIds); + final droppedEvents = + dropped.map((item) => item.event).toList(growable: false); + _droppedCount += _countNonInternalEvents(droppedEvents); + } + + return _PreparedBatch(sendable: sendable); + } + + Future _runBeforeSend(Event event) async { + var current = event; + for (final interceptor in _interceptors) { + try { + final next = await interceptor.beforeSend(current); + if (next == null) { + return null; + } + current = next; + } catch (e, st) { + Logger.error('beforeSend 拦截器异常,已忽略并继续', e, st); + } + } + return current; + } + + Future _runAfterSend( + List<_SendableStoredEvent> events, + SendResult result, + ) async { + if (events.isEmpty) { + return; + } + for (final interceptor in _interceptors) { + for (final item in events) { + try { + await interceptor.afterSend(item.event, result); + } catch (e, st) { + Logger.error('afterSend 拦截器异常,已忽略并继续', e, st); + } + } + } + } + + bool _shouldDropByStrategy(String eventType) { + if (_isInternalEvent(eventType)) { + return false; + } + final config = _configManager?.currentConfig; + if (config == null) { + return false; + } + if (!config.isStrategyEnabled) { + return true; + } + if (!config.isEventEnabledByStrategy(eventType)) { + return true; + } + final sampleRate = config.sampleRateFor(eventType); + if (sampleRate <= 0) { + return true; + } + if (sampleRate >= 1) { + return false; + } + final sampledIn = _randomDouble() < sampleRate; + return !sampledIn; + } + + bool _isInternalEvent(String eventType) => _internalEventTypes.contains(eventType); + + int _countNonInternalEvents(List events) { + var count = 0; + for (final event in events) { + if (_isInternalEvent(event.eventType)) { + continue; + } + count += 1; + } + return count; + } + + void _recordSuccessMetrics(List events, DateTime flushStart) { + final count = _countNonInternalEvents(events); + if (count <= 0) { + return; + } + _sentCount += count; + final elapsedMs = _now().difference(flushStart).inMilliseconds; + final safeElapsedMs = elapsedMs < 0 ? 0 : elapsedMs; + _totalLatencyMs += safeElapsedMs * count; + _latencySamples += count; + } + + void _recordFailureMetrics(List events) { + final count = _countNonInternalEvents(events); + if (count <= 0) { + return; + } + _failedCount += count; + } + + void _startMetricsTimer(AnalyticsConfig config) { + _metricsTimer?.cancel(); + _metricsTimer = null; + if (!config.enableMetrics) { + _resetMetricsWindow(); + return; + } + _resetMetricsWindow(); + _metricsTimer = Timer.periodic(config.metricsReportInterval, (_) { + unawaited(_reportMetrics()); + }); + Logger.info( + '指标上报定时器已启动: interval=${config.metricsReportInterval.inMinutes}m', + ); + } + + Future _reportMetrics() async { + final config = _config; + final storage = _storage; + if (!_initialized || config == null || storage == null || !config.enableMetrics) { + return; + } + + final now = _now(); + final windowStart = _lastMetricsReportTime ?? now; + final windowMs = now.difference(windowStart).inMilliseconds; + final queueSize = await storage.count(); + final avgLatencyMs = _latencySamples == 0 ? 0 : _totalLatencyMs ~/ _latencySamples; + + final sendParams = { + 'sentCount': _sentCount, + 'failedCount': _failedCount, + 'retryCount': _retryCount, + 'droppedCount': _droppedCount, + 'avgLatencyMs': avgLatencyMs, + 'windowMs': windowMs, + }; + final queueParams = { + 'queueSize': queueSize, + 'droppedCount': _droppedCount, + 'windowMs': windowMs, + }; + + await _track(_metricsSendEventType, eventParams: sendParams, internal: true); + await _track(_metricsQueueEventType, eventParams: queueParams, internal: true); + _resetMetricsWindow(startAt: now); + } + + void _resetMetricsWindow({DateTime? startAt}) { + _sentCount = 0; + _failedCount = 0; + _retryCount = 0; + _droppedCount = 0; + _totalLatencyMs = 0; + _latencySamples = 0; + _lastMetricsReportTime = startAt ?? _now(); + } + + Future _handleRetryableFailure( + List<_SendableStoredEvent> batch, + AnalyticsConfig config, + ) async { + final storage = _storage; + if (storage == null) { + return; + } + + final toDelete = []; + var maxRetryForBackoff = 0; + var retryUpdatedNonInternal = 0; + + for (final sendable in batch) { + final stored = sendable.stored; + final nextRetry = stored.retryCount + 1; + final cappedRetry = min(nextRetry, config.maxRetryCount); + maxRetryForBackoff = max(maxRetryForBackoff, cappedRetry); + + if (nextRetry > config.maxRetryCount) { + toDelete.add(stored.id); + continue; + } + await storage.updateRetryCount(stored.id, nextRetry); + if (!_isInternalEvent(sendable.event.eventType)) { + retryUpdatedNonInternal += 1; + } + } + + if (retryUpdatedNonInternal > 0) { + _retryCount += retryUpdatedNonInternal; + } + + if (toDelete.isNotEmpty) { + Logger.warn('超过最大重试次数,丢弃事件数: ${toDelete.length}'); + await storage.deleteByIds(toDelete); + final toDeleteSet = toDelete.toSet(); + final droppedCount = batch + .where((item) => toDeleteSet.contains(item.stored.id)) + .map((item) => item.event) + .toList(growable: false); + _droppedCount += _countNonInternalEvents(droppedCount); + } + + final backoff = _computeBackoff(maxRetryForBackoff); + _nextAllowedFlushTime = _now().add(backoff); + Logger.info('flush 失败,进入退避: backoff=${backoff.inSeconds}s'); + } + + Duration _computeBackoff(int retryCount) { + if (retryCount <= 0) { + return const Duration(seconds: 1); + } + final seconds = min(60, pow(2, retryCount).toInt()); + return Duration(seconds: seconds); + } + + Future setDebug(bool enabled) async { + Logger.setDebug(enabled); + } + + Future dispose() async { + _scheduler?.dispose(); + _scheduler = null; + + _configRefreshTimer?.cancel(); + _configRefreshTimer = null; + + _metricsTimer?.cancel(); + _metricsTimer = null; + + await _configManager?.dispose(); + _configManager = null; + _validator = null; + + await _storage?.dispose(); + _storage = null; + + _apiClient = null; + _config = null; + _deviceInfo = null; + _initialized = false; + _isFlushing = false; + _nextAllowedFlushTime = null; + _interceptors.clear(); + _resetMetricsWindow(); + + Logger.info('AnalyticsCore 已释放资源'); + } + + Event? _validateAndDecorate(Event event, AnalyticsConfig config) { + final validator = _validator; + if (validator == null) { + return event; + } + final result = validator.validate(event); + if (result.isEmpty) { + return event; + } + if (result.hasErrors) { + Logger.warn('事件校验 errors: ${result.errors.join(' | ')}'); + } + if (result.hasWarnings) { + Logger.warn('事件校验 warnings: ${result.warnings.join(' | ')}'); + } + + // Debug 模式可选阻断;Release 模式追加校验结果标记但不阻断发送。 + if (Logger.isDebugEnabled) { + if (config.blockOnValidationError && result.hasErrors) { + Logger.warn('配置为阻断发送:校验 errors 存在,事件已丢弃'); + return null; + } + return event; + } + return _decorateEventWithValidation(event, result); + } + + Event _decorateEventWithValidation(Event event, ValidationResult result) { + final tags = Map.from( + event.customTags ?? const {}, + ); + + final hasUnknownEvent = result.errors.any( + (e) => e.code == Validator.unknownEventType, + ); + final missingTags = result.warnings + .where( + (w) => + w.code == Validator.missingRequiredTag && + (w.field?.isNotEmpty ?? false), + ) + .map((w) => w.field!) + .toList(growable: false); + final typeMismatchFields = result.warnings + .where( + (w) => + w.code == Validator.typeMismatch && (w.field?.isNotEmpty ?? false), + ) + .map((w) => w.field!) + .toList(growable: false); + + if (hasUnknownEvent) { + tags['_sdk_invalid_event'] = true; + } + if (missingTags.isNotEmpty) { + tags['_sdk_missing_tags'] = missingTags; + } + if (typeMismatchFields.isNotEmpty) { + tags['_sdk_type_error_fields'] = typeMismatchFields; + } + + return event.copyWith(customTags: tags); + } + + void _startConfigRefreshTimer(ConfigManager configManager) { + _configRefreshTimer?.cancel(); + final interval = configManager.refreshInterval; + if (interval <= Duration.zero) { + return; + } + _configRefreshTimer = Timer.periodic(interval, (_) { + unawaited(configManager.fetchAndCacheConfig()); + }); + Logger.info('配置刷新定时器已启动: interval=${interval.inHours}h'); + } + + void _resetInterceptors() { + _interceptors + ..clear() + ..addAll(_initialInterceptors); + if (_includeCommonTagsInterceptor) { + _interceptors.insert(0, CommonTagsInterceptor()); + } + } +} + +class _PreparedBatch { + final List<_SendableStoredEvent> sendable; + + const _PreparedBatch({required this.sendable}); +} + +class _SendableStoredEvent { + final StoredEvent stored; + final Event event; + + const _SendableStoredEvent({ + required this.stored, + required this.event, + }); +} diff --git a/lib/src/core/interceptors.dart b/lib/src/core/interceptors.dart new file mode 100644 index 0000000..0bb0304 --- /dev/null +++ b/lib/src/core/interceptors.dart @@ -0,0 +1,39 @@ +import 'dart:async'; + +import '../model/event.dart'; +import '../util/sdk_info.dart'; + +/// 发送结果。 +class SendResult { + final bool success; + final int? statusCode; + final bool retryable; + final Object? error; + + const SendResult({ + required this.success, + required this.retryable, + this.statusCode, + this.error, + }); +} + +/// 埋点事件拦截器。 +abstract class AnalyticsInterceptor { + FutureOr beforeSend(Event event) => event; + + FutureOr afterSend(Event event, SendResult result) {} +} + +/// 内置拦截器:为所有事件追加通用 tag。 +class CommonTagsInterceptor extends AnalyticsInterceptor { + @override + Event beforeSend(Event event) { + final tags = Map.from( + event.customTags ?? const {}, + ); + tags.putIfAbsent('_sdk_version', () => SdkInfo.sdkVersion); + tags.putIfAbsent('_platform', () => SdkInfo.platform); + return event.copyWith(customTags: tags); + } +} diff --git a/lib/src/core/scheduler.dart b/lib/src/core/scheduler.dart new file mode 100644 index 0000000..27a99d8 --- /dev/null +++ b/lib/src/core/scheduler.dart @@ -0,0 +1,40 @@ +import 'dart:async'; + +import '../util/logger.dart'; + +/// 简单定时调度器。 +class Scheduler { + final Duration interval; + final Future Function() onTick; + + Timer? _timer; + + Scheduler({ + required this.interval, + required this.onTick, + }); + + bool get isRunning => _timer?.isActive ?? false; + + void start() { + if (isRunning) { + return; + } + _timer = Timer.periodic(interval, (_) async { + try { + await onTick(); + } catch (e, st) { + Logger.error('Scheduler tick 执行失败', e, st); + } + }); + Logger.info('Scheduler 已启动: interval=${interval.inSeconds}s'); + } + + void stop() { + _timer?.cancel(); + _timer = null; + Logger.info('Scheduler 已停止'); + } + + void dispose() => stop(); +} diff --git a/lib/src/core/validator.dart b/lib/src/core/validator.dart new file mode 100644 index 0000000..a6e8ecd --- /dev/null +++ b/lib/src/core/validator.dart @@ -0,0 +1,160 @@ +import '../config/config_manager.dart'; +import '../model/event.dart'; + +/// 校验结果。 +class ValidationResult { + final List errors; + final List warnings; + + const ValidationResult({ + this.errors = const [], + this.warnings = const [], + }); + + bool get hasErrors => errors.isNotEmpty; + bool get hasWarnings => warnings.isNotEmpty; + bool get isEmpty => !hasErrors && !hasWarnings; +} + +/// 校验问题项。 +class ValidationIssue { + final String code; + final String message; + final String? field; + + const ValidationIssue({ + required this.code, + required this.message, + this.field, + }); + + @override + String toString() { + if (field == null || field!.isEmpty) { + return '$code: $message'; + } + return '$code($field): $message'; + } +} + +/// Phase 2:事件校验器。 +class Validator { + static const String unknownEventType = 'UNKNOWN_EVENT_TYPE'; + static const String missingRequiredTag = 'MISSING_REQUIRED_TAG'; + static const String typeMismatch = 'TYPE_MISMATCH'; + + final ConfigManager _configManager; + + const Validator(this._configManager); + + ValidationResult validate(Event event) { + final config = _configManager.currentConfig; + if (config == null) { + return const ValidationResult(); + } + + final errors = []; + final warnings = []; + + if (!config.hasEvent(event.eventType)) { + errors.add( + ValidationIssue( + code: unknownEventType, + message: 'eventType 未在后端配置中注册: ${event.eventType}', + ), + ); + } + + final tags = event.customTags ?? const {}; + for (final tag in config.tagDefinitions) { + if (!tags.containsKey(tag.tagName)) { + if (tag.isRequired) { + warnings.add( + ValidationIssue( + code: missingRequiredTag, + field: tag.tagName, + message: '缺少必填 customTags 字段', + ), + ); + } + continue; + } + final value = tags[tag.tagName]; + if (!_typeMatches(value, tag.tagType)) { + warnings.add( + ValidationIssue( + code: typeMismatch, + field: tag.tagName, + message: '类型不匹配,期望 ${tag.tagType},实际 ${value.runtimeType}', + ), + ); + } + } + + return ValidationResult(errors: errors, warnings: warnings); + } + + bool _typeMatches(dynamic value, String tagType) { + final normalized = tagType.trim().toLowerCase(); + switch (normalized) { + case 'string': + return value is String; + case 'int': + case 'integer': + return _matchesInt(value); + case 'bool': + case 'boolean': + return _matchesBool(value); + case 'double': + case 'float': + case 'number': + case 'num': + return _matchesNum(value); + default: + // 未知类型先不阻断。 + return true; + } + } + + bool _matchesInt(dynamic value) { + if (value is int) { + return true; + } + if (value is num) { + return value == value.toInt(); + } + if (value is String) { + return int.tryParse(value) != null; + } + return false; + } + + bool _matchesBool(dynamic value) { + if (value is bool) { + return true; + } + if (value is num) { + return value == 0 || value == 1; + } + if (value is String) { + final lowered = value.trim().toLowerCase(); + return lowered == 'true' || + lowered == 'false' || + lowered == '1' || + lowered == '0' || + lowered == 'yes' || + lowered == 'no'; + } + return false; + } + + bool _matchesNum(dynamic value) { + if (value is num) { + return true; + } + if (value is String) { + return num.tryParse(value) != null; + } + return false; + } +} diff --git a/lib/src/model/device_info.dart b/lib/src/model/device_info.dart new file mode 100644 index 0000000..d1023c6 --- /dev/null +++ b/lib/src/model/device_info.dart @@ -0,0 +1,20 @@ +/// 设备信息。 +class DeviceInfo { + final String os; + final String model; + final String screenResolution; + + const DeviceInfo({ + required this.os, + required this.model, + required this.screenResolution, + }); + + Map toJson() { + return { + 'os': os, + 'model': model, + 'screenResolution': screenResolution, + }; + } +} diff --git a/lib/src/model/event.dart b/lib/src/model/event.dart new file mode 100644 index 0000000..16a59f5 --- /dev/null +++ b/lib/src/model/event.dart @@ -0,0 +1,178 @@ +import 'dart:convert'; + +import 'device_info.dart'; +import 'user_info.dart'; + +/// 统一事件模型。 +class Event { + final String systemCode; + final String eventType; + final UserInfo? userInfo; + final int clientType; + final int clientTimestamp; + final String timestamp; + final DeviceInfo deviceInfo; + final Map? eventParams; + final Map? customTags; + final DateTime createTime; + final int retryCount; + + const Event({ + required this.systemCode, + required this.eventType, + required this.userInfo, + required this.clientType, + required this.clientTimestamp, + required this.timestamp, + required this.deviceInfo, + required this.eventParams, + required this.customTags, + required this.createTime, + this.retryCount = 0, + }); + + Event copyWith({ + UserInfo? userInfo, + DeviceInfo? deviceInfo, + Map? eventParams, + Map? customTags, + DateTime? createTime, + int? retryCount, + }) { + return Event( + systemCode: systemCode, + eventType: eventType, + userInfo: userInfo ?? this.userInfo, + clientType: clientType, + clientTimestamp: clientTimestamp, + timestamp: timestamp, + deviceInfo: deviceInfo ?? this.deviceInfo, + eventParams: eventParams ?? this.eventParams, + customTags: customTags ?? this.customTags, + createTime: createTime ?? this.createTime, + retryCount: retryCount ?? this.retryCount, + ); + } + + Map toJson() { + return { + 'system_code': systemCode, + 'eventType': eventType, + 'userInfo': userInfo?.toJson(), + 'clientType': clientType, + 'clientTimestamp': clientTimestamp, + 'timestamp': timestamp, + 'deviceInfo': deviceInfo.toJson(), + 'eventParams': eventParams, + 'customTags': customTags, + }; + } + + String toPayload() => jsonEncode(toJson()); + + static Event fromPayload( + String payload, { + required DateTime createTime, + required int retryCount, + }) { + final decoded = jsonDecode(payload); + if (decoded is! Map) { + throw const FormatException('事件 payload 不是合法的 JSON 对象'); + } + return fromJson(decoded, createTime: createTime, retryCount: retryCount); + } + + static Event fromJson( + Map json, { + required DateTime createTime, + required int retryCount, + }) { + final userJson = json['userInfo']; + final deviceJson = json['deviceInfo']; + + if (deviceJson is! Map) { + throw const FormatException('deviceInfo 缺失或格式错误'); + } + + return Event( + systemCode: (json['system_code'] ?? '').toString(), + eventType: (json['eventType'] ?? '').toString(), + userInfo: userJson is Map + ? UserInfo( + userId: _toInt(userJson['userId']), + userName: userJson['userName']?.toString(), + account: userJson['account']?.toString(), + ) + : null, + clientType: _toInt(json['clientType']) ?? 0, + clientTimestamp: _toInt(json['clientTimestamp']) ?? 0, + timestamp: (json['timestamp'] ?? '').toString(), + deviceInfo: DeviceInfo( + os: deviceJson['os']?.toString() ?? 'unknown', + model: deviceJson['model']?.toString() ?? 'unknown', + screenResolution: deviceJson['screenResolution']?.toString() ?? 'unknown', + ), + eventParams: _toMap(json['eventParams']), + customTags: _toMap(json['customTags']), + createTime: createTime, + retryCount: retryCount, + ); + } + + static int? _toInt(dynamic value) { + if (value is int) { + return value; + } + if (value is num) { + return value.toInt(); + } + if (value is String) { + return int.tryParse(value); + } + return null; + } + + static Map? _toMap(dynamic value) { + if (value == null) { + return null; + } + if (value is Map) { + return value; + } + if (value is Map) { + return value.map( + (key, val) => MapEntry(key.toString(), val), + ); + } + return null; + } +} + +/// 带本地存储元数据的事件。 +class StoredEvent { + final int id; + final Event event; + final int retryCount; + final DateTime createTime; + + const StoredEvent({ + required this.id, + required this.event, + required this.retryCount, + required this.createTime, + }); + + StoredEvent copyWith({ + int? id, + Event? event, + int? retryCount, + DateTime? createTime, + }) { + return StoredEvent( + id: id ?? this.id, + event: event ?? this.event, + retryCount: retryCount ?? this.retryCount, + createTime: createTime ?? this.createTime, + ); + } +} diff --git a/lib/src/model/recent_event_summary.dart b/lib/src/model/recent_event_summary.dart new file mode 100644 index 0000000..486ab57 --- /dev/null +++ b/lib/src/model/recent_event_summary.dart @@ -0,0 +1,14 @@ +/// 最近事件摘要(用于调试面板)。 +class RecentEventSummary { + final int id; + final String eventType; + final DateTime createTime; + final int retryCount; + + const RecentEventSummary({ + required this.id, + required this.eventType, + required this.createTime, + required this.retryCount, + }); +} diff --git a/lib/src/model/system_dim_info.dart b/lib/src/model/system_dim_info.dart new file mode 100644 index 0000000..ad9b49e --- /dev/null +++ b/lib/src/model/system_dim_info.dart @@ -0,0 +1,392 @@ +/// Phase 2:后端下发的维度配置模型。 +class SystemDimInfo { + final SystemInfo? systemInfo; + final List eventDefinitions; + final List tagDefinitions; + final SdkStrategy? sdkStrategy; + final DateTime lastFetchedAt; + final String? version; + + const SystemDimInfo({ + required this.systemInfo, + required this.eventDefinitions, + required this.tagDefinitions, + required this.sdkStrategy, + required this.lastFetchedAt, + this.version, + }); + + bool hasEvent(String eventType) { + return eventDefinitions.any((e) => e.eventCode == eventType); + } + + List get requiredTags { + return tagDefinitions.where((t) => t.isRequired).toList(growable: false); + } + + bool get isStrategyEnabled => sdkStrategy?.enabled ?? true; + + EventStrategy? strategyFor(String eventType) { + final strategy = sdkStrategy; + if (strategy == null) { + return null; + } + return strategy.eventSettings[eventType]; + } + + double sampleRateFor(String eventType) { + final strategy = sdkStrategy; + if (strategy == null) { + return 1.0; + } + final eventStrategy = strategy.eventSettings[eventType]; + return eventStrategy?.sampleRate ?? strategy.defaultSampleRate; + } + + bool isEventEnabledByStrategy(String eventType) { + final strategy = sdkStrategy; + if (strategy == null) { + return true; + } + if (!strategy.enabled) { + return false; + } + final eventStrategy = strategy.eventSettings[eventType]; + return eventStrategy?.enabled ?? true; + } + + Map toCacheJson() { + return { + 'systemInfo': systemInfo?.toJson(), + 'eventDefinitions': eventDefinitions.map((e) => e.toJson()).toList(), + 'tagDefinitions': tagDefinitions.map((t) => t.toJson()).toList(), + 'sdkStrategy': sdkStrategy?.toJson(), + 'lastFetchedAt': lastFetchedAt.millisecondsSinceEpoch, + 'version': version, + }; + } + + static SystemDimInfo fromCacheJson(Map json) { + final lastFetchedMs = _toInt(json['lastFetchedAt']) ?? 0; + final fetchedAt = DateTime.fromMillisecondsSinceEpoch(lastFetchedMs); + + final systemInfoJson = json['systemInfo']; + final eventListJson = json['eventDefinitions']; + final tagListJson = json['tagDefinitions']; + final strategyJson = json['sdkStrategy']; + + return SystemDimInfo( + systemInfo: systemInfoJson is Map + ? SystemInfo.fromJson(systemInfoJson) + : null, + eventDefinitions: _parseEventDefinitions(eventListJson), + tagDefinitions: _parseTagDefinitions(tagListJson), + sdkStrategy: _parseSdkStrategy(strategyJson), + lastFetchedAt: fetchedAt, + version: json['version']?.toString(), + ); + } + + /// 从后端响应构造配置。 + /// + /// 兼容字段命名差异(例如 systemCustonTas 的拼写)。 + static SystemDimInfo fromResponse( + Map json, { + DateTime? fetchedAt, + String? version, + }) { + final now = fetchedAt ?? DateTime.now(); + + final systemInfoJson = json['systemInfo']; + final eventListJson = json['systemEventTypes']; + final tagListJson = json['systemCustonTas'] ?? json['systemCustomTags']; + final strategyJson = json['sdkStrategy'] ?? json['sdk_strategy']; + + return SystemDimInfo( + systemInfo: systemInfoJson is Map + ? SystemInfo.fromJson(systemInfoJson) + : null, + eventDefinitions: _parseEventDefinitions(eventListJson), + tagDefinitions: _parseTagDefinitions(tagListJson), + sdkStrategy: _parseSdkStrategy(strategyJson), + lastFetchedAt: now, + version: version, + ); + } + + static List _parseEventDefinitions(dynamic value) { + if (value is! List) { + return const []; + } + final results = []; + for (final item in value) { + if (item is! Map) { + continue; + } + final map = item.map((k, v) => MapEntry(k.toString(), v)); + final code = _stringFirst( + map, + const [ + 'eventCode', + 'event_code', + 'eventType', + 'event_type', + 'code', + ], + ); + if (code == null || code.isEmpty) { + continue; + } + final name = _stringFirst(map, const ['eventName', 'event_name']); + final desc = _stringFirst(map, const ['description', 'desc']); + results.add( + EventDefinition( + eventCode: code, + eventName: name, + description: desc, + ), + ); + } + return results; + } + + static List _parseTagDefinitions(dynamic value) { + if (value is! List) { + return const []; + } + final results = []; + for (final item in value) { + if (item is! Map) { + continue; + } + final map = item.map((k, v) => MapEntry(k.toString(), v)); + final tagName = _stringFirst( + map, + const ['tagName', 'tag_name', 'name'], + ); + if (tagName == null || tagName.isEmpty) { + continue; + } + final tagType = _stringFirst( + map, + const ['tagType', 'tag_type', 'type'], + ) ?? + 'string'; + final required = _toBool(map['isRequired']) ?? _toBool(map['is_required']) ?? false; + final desc = _stringFirst(map, const ['description', 'desc']); + + results.add( + TagDefinition( + tagName: tagName, + tagType: tagType, + isRequired: required, + description: desc, + ), + ); + } + return results; + } + + static SdkStrategy? _parseSdkStrategy(dynamic value) { + if (value is! Map) { + return null; + } + final map = value.map((k, v) => MapEntry(k.toString(), v)); + final enabled = _toBool(map['enabled']) ?? true; + final defaultSampleRate = + _clampSampleRate(_toDouble(map['defaultSampleRate']) ?? 1.0); + + final eventSettingsRaw = map['eventSettings']; + final eventSettings = {}; + if (eventSettingsRaw is Map) { + eventSettingsRaw.forEach((key, rawValue) { + if (rawValue is! Map) { + return; + } + final rawMap = rawValue.map((k, v) => MapEntry(k.toString(), v)); + final eventEnabled = _toBool(rawMap['enabled']) ?? true; + final sampleRate = + _clampSampleRate(_toDouble(rawMap['sampleRate']) ?? defaultSampleRate); + eventSettings[key.toString()] = EventStrategy( + enabled: eventEnabled, + sampleRate: sampleRate, + ); + }); + } + + return SdkStrategy( + enabled: enabled, + defaultSampleRate: defaultSampleRate, + eventSettings: eventSettings, + ); + } + + static String? _stringFirst(Map map, List keys) { + for (final key in keys) { + final value = map[key]; + if (value == null) { + continue; + } + final text = value.toString().trim(); + if (text.isNotEmpty) { + return text; + } + } + return null; + } + + static int? _toInt(dynamic value) { + if (value is int) { + return value; + } + if (value is num) { + return value.toInt(); + } + if (value is String) { + return int.tryParse(value); + } + return null; + } + + static double? _toDouble(dynamic value) { + if (value is double) { + return value; + } + if (value is num) { + return value.toDouble(); + } + if (value is String) { + return double.tryParse(value); + } + return null; + } + + static double _clampSampleRate(double value) { + if (value.isNaN || value.isInfinite) { + return 1.0; + } + if (value < 0) { + return 0; + } + if (value > 1) { + return 1; + } + return value; + } + + static bool? _toBool(dynamic value) { + if (value is bool) { + return value; + } + if (value is num) { + return value != 0; + } + if (value is String) { + final lowered = value.trim().toLowerCase(); + if (lowered == 'true' || lowered == '1' || lowered == 'yes') { + return true; + } + if (lowered == 'false' || lowered == '0' || lowered == 'no') { + return false; + } + } + return null; + } +} + +/// systemInfo 原始信息(当前以透传为主)。 +class SystemInfo { + final Map raw; + + const SystemInfo({required this.raw}); + + Map toJson() => raw; + + static SystemInfo fromJson(Map json) { + return SystemInfo(raw: json); + } +} + +class EventDefinition { + final String eventCode; + final String? eventName; + final String? description; + + const EventDefinition({ + required this.eventCode, + this.eventName, + this.description, + }); + + Map toJson() { + return { + 'eventCode': eventCode, + 'eventName': eventName, + 'description': description, + }; + } +} + +class TagDefinition { + final String tagName; + final String tagType; + final bool isRequired; + final String? description; + + const TagDefinition({ + required this.tagName, + required this.tagType, + required this.isRequired, + this.description, + }); + + Map toJson() { + return { + 'tagName': tagName, + 'tagType': tagType, + 'isRequired': isRequired, + 'description': description, + }; + } +} + +/// Phase 3:SDK 动态策略。 +class SdkStrategy { + final bool enabled; + final double defaultSampleRate; + final Map eventSettings; + + const SdkStrategy({ + required this.enabled, + required this.defaultSampleRate, + required this.eventSettings, + }); + + Map toJson() { + return { + 'enabled': enabled, + 'defaultSampleRate': defaultSampleRate, + 'eventSettings': eventSettings.map( + (key, value) => MapEntry(key, value.toJson()), + ), + }; + } +} + +/// Phase 3:单事件策略。 +class EventStrategy { + final bool enabled; + final double sampleRate; + + const EventStrategy({ + required this.enabled, + required this.sampleRate, + }); + + Map toJson() { + return { + 'enabled': enabled, + 'sampleRate': sampleRate, + }; + } +} diff --git a/lib/src/model/user_info.dart b/lib/src/model/user_info.dart new file mode 100644 index 0000000..da90110 --- /dev/null +++ b/lib/src/model/user_info.dart @@ -0,0 +1,22 @@ +/// 用户信息。 +class UserInfo { + final int? userId; + final String? userName; + final String? account; + + const UserInfo({ + this.userId, + this.userName, + this.account, + }); + + Map toJson() { + final map = { + 'userId': userId, + 'userName': userName, + 'account': account, + }; + map.removeWhere((_, value) => value == null); + return map; + } +} diff --git a/lib/src/network/api_client.dart b/lib/src/network/api_client.dart new file mode 100644 index 0000000..59d603e --- /dev/null +++ b/lib/src/network/api_client.dart @@ -0,0 +1,95 @@ +import 'package:dio/dio.dart'; + +import '../config/analytics_config.dart'; +import '../model/event.dart'; +import '../util/logger.dart'; +import 'http_client.dart'; + +/// API 调用异常,携带是否可重试等信息。 +class ApiException implements Exception { + final int? statusCode; + final String message; + final bool retryable; + final Object? data; + + const ApiException({ + required this.message, + required this.retryable, + this.statusCode, + this.data, + }); + + @override + String toString() { + return 'ApiException(statusCode: $statusCode, retryable: $retryable, message: $message)'; + } +} + +/// 与后端埋点接口通信的客户端。 +class ApiClient { + static const String _addEventListLogPath = 'AddEventListLog'; + + final HttpClient _httpClient; + + ApiClient(AnalyticsConfig config) : _httpClient = HttpClient(config); + + /// 批量发送事件。 + /// + /// 成功返回;失败时抛出 [ApiException],由上层决定是否重试。 + Future sendBatch(List events) async { + if (events.isEmpty) { + return; + } + + final payload = events.map((e) => e.toJson()).toList(growable: false); + + try { + final response = await _httpClient.post( + _addEventListLogPath, + data: payload, + ); + + final statusCode = response.statusCode ?? 0; + if (statusCode < 200 || statusCode >= 300) { + throw ApiException( + statusCode: response.statusCode, + retryable: statusCode >= 500 || statusCode == 0, + message: '批量上报失败,HTTP $statusCode', + data: response.data, + ); + } + + Logger.info('批量上报成功: size=${events.length}, status=$statusCode'); + } on DioException catch (e, st) { + final apiException = _mapDioException(e); + Logger.error('批量上报异常: ${apiException.message}', apiException, st); + throw apiException; + } catch (e, st) { + Logger.error('批量上报未知异常', e, st); + rethrow; + } + } + + ApiException _mapDioException(DioException e) { + final statusCode = e.response?.statusCode; + final isHttpError = statusCode != null; + + if (isHttpError) { + final retryable = statusCode >= 500; + return ApiException( + statusCode: statusCode, + retryable: retryable, + message: 'HTTP 错误: $statusCode', + data: e.response?.data, + ); + } + + // 无状态码通常意味着网络错误或超时,可重试。 + return ApiException( + statusCode: null, + retryable: true, + message: e.message ?? '网络异常或请求失败', + data: e.error, + ); + } +} diff --git a/lib/src/network/http_client.dart b/lib/src/network/http_client.dart new file mode 100644 index 0000000..306cb39 --- /dev/null +++ b/lib/src/network/http_client.dart @@ -0,0 +1,67 @@ +import 'package:dio/dio.dart'; + +import '../config/analytics_config.dart'; + +/// 对 Dio 的轻量封装,统一超时与基础配置。 +class HttpClient { + final Dio _dio; + + HttpClient(AnalyticsConfig config) + : _dio = Dio( + BaseOptions( + baseUrl: _normalizeBaseUrl(config.endpointBaseUrl), + connectTimeout: config.connectTimeout, + receiveTimeout: config.readTimeout, + sendTimeout: config.connectTimeout, + headers: { + Headers.contentTypeHeader: Headers.jsonContentType, + }, + ), + ); + + Dio get dio => _dio; + + Future> get( + String path, { + Map? queryParameters, + Map? headers, + CancelToken? cancelToken, + }) { + return _dio.get( + path, + queryParameters: queryParameters, + options: _withHeaders(headers), + cancelToken: cancelToken, + ); + } + + Future> post( + String path, { + Object? data, + Map? queryParameters, + Map? headers, + CancelToken? cancelToken, + }) { + return _dio.post( + path, + data: data, + queryParameters: queryParameters, + options: _withHeaders(headers), + cancelToken: cancelToken, + ); + } + + Options? _withHeaders(Map? headers) { + if (headers == null || headers.isEmpty) { + return null; + } + return Options(headers: headers); + } + + static String _normalizeBaseUrl(String baseUrl) { + if (baseUrl.endsWith('/')) { + return baseUrl.substring(0, baseUrl.length - 1); + } + return baseUrl; + } +} diff --git a/lib/src/storage/config_storage.dart b/lib/src/storage/config_storage.dart new file mode 100644 index 0000000..a832bb6 --- /dev/null +++ b/lib/src/storage/config_storage.dart @@ -0,0 +1,14 @@ +import '../model/system_dim_info.dart'; + +/// 配置缓存存储抽象。 +abstract class ConfigStorage { + Future init(); + + Future saveSystemDimInfo(SystemDimInfo info); + + Future loadSystemDimInfo(); + + Future clear(); + + Future dispose(); +} diff --git a/lib/src/storage/db_constants.dart b/lib/src/storage/db_constants.dart new file mode 100644 index 0000000..4744e1b --- /dev/null +++ b/lib/src/storage/db_constants.dart @@ -0,0 +1,7 @@ +/// SQLite 数据库常量。 +class DbConstants { + static const String dbName = 'yx_tracking_flutter.db'; + static const int dbVersion = 1; + + const DbConstants._(); +} diff --git a/lib/src/storage/event_storage.dart b/lib/src/storage/event_storage.dart new file mode 100644 index 0000000..ddf64ef --- /dev/null +++ b/lib/src/storage/event_storage.dart @@ -0,0 +1,28 @@ +import '../model/event.dart'; + +/// 事件存储抽象。 +abstract class EventStorage { + Future init(); + + /// 插入事件,返回本地自增 ID。 + Future insert(Event event); + + /// 获取一批最旧事件(按 create_time 升序)。 + Future> fetchBatch(int limit); + + /// 获取最近的事件(按 create_time 降序)。 + Future> fetchRecent(int limit); + + Future deleteByIds(List ids); + + Future count(); + + /// 控制本地缓存上限(删除最旧事件)。 + Future trimToMaxSize(int maxSize); + + /// 更新单条事件的重试次数。 + Future updateRetryCount(int id, int retryCount); + + /// 关闭底层资源。 + Future dispose(); +} diff --git a/lib/src/storage/sqflite_config_storage.dart b/lib/src/storage/sqflite_config_storage.dart new file mode 100644 index 0000000..8dd7869 --- /dev/null +++ b/lib/src/storage/sqflite_config_storage.dart @@ -0,0 +1,131 @@ +import 'dart:convert'; + +import 'package:path/path.dart' as p; +import 'package:path_provider/path_provider.dart'; +import 'package:sqflite/sqflite.dart'; + +import '../model/system_dim_info.dart'; +import '../util/logger.dart'; +import 'config_storage.dart'; +import 'db_constants.dart'; + +/// 基于 sqflite 的配置缓存存储。 +class SqfliteConfigStorage implements ConfigStorage { + static const String _tableConfigCache = 'config_cache'; + static const String _systemDimInfoKey = 'system_dim_info'; + + Database? _db; + + @override + Future init() async { + if (_db != null) { + return; + } + + final directory = await getApplicationDocumentsDirectory(); + final dbPath = p.join(directory.path, DbConstants.dbName); + + _db = await openDatabase( + dbPath, + version: DbConstants.dbVersion, + onCreate: (db, version) async { + await _createTables(db); + }, + onOpen: (db) async { + await _createTables(db); + }, + ); + + Logger.info('SqfliteConfigStorage 初始化完成: $dbPath'); + } + + Future _createTables(Database db) async { + await db.execute(''' + CREATE TABLE IF NOT EXISTS $_tableConfigCache ( + key TEXT PRIMARY KEY, + payload TEXT NOT NULL, + last_fetched_at INTEGER NOT NULL + ); + '''); + } + + Database _requireDb() { + final db = _db; + if (db == null) { + throw StateError('SqfliteConfigStorage 尚未初始化'); + } + return db; + } + + @override + Future saveSystemDimInfo(SystemDimInfo info) async { + final db = _requireDb(); + final payload = jsonEncode(info.toCacheJson()); + final values = { + 'key': _systemDimInfoKey, + 'payload': payload, + 'last_fetched_at': info.lastFetchedAt.millisecondsSinceEpoch, + }; + + await db.insert( + _tableConfigCache, + values, + conflictAlgorithm: ConflictAlgorithm.replace, + ); + } + + @override + Future loadSystemDimInfo() async { + final db = _requireDb(); + final rows = await db.query( + _tableConfigCache, + where: 'key = ?', + whereArgs: const [_systemDimInfoKey], + limit: 1, + ); + + if (rows.isEmpty) { + return null; + } + + final row = rows.first; + final payload = row['payload']; + if (payload is! String || payload.isEmpty) { + return null; + } + + try { + final decoded = jsonDecode(payload); + if (decoded is! Map) { + return null; + } + final map = decoded.map((k, v) => MapEntry(k.toString(), v)); + + // 优先使用 payload 中的 lastFetchedAt,必要时兜底 last_fetched_at。 + map.putIfAbsent('lastFetchedAt', () => row['last_fetched_at']); + return SystemDimInfo.fromCacheJson(map); + } catch (e, st) { + Logger.error('读取配置缓存失败', e, st); + return null; + } + } + + @override + Future clear() async { + final db = _requireDb(); + await db.delete( + _tableConfigCache, + where: 'key = ?', + whereArgs: const [_systemDimInfoKey], + ); + } + + @override + Future dispose() async { + final db = _db; + _db = null; + if (db != null && db.isOpen) { + await db.close(); + } + } +} diff --git a/lib/src/storage/sqflite_event_storage.dart b/lib/src/storage/sqflite_event_storage.dart new file mode 100644 index 0000000..93eea02 --- /dev/null +++ b/lib/src/storage/sqflite_event_storage.dart @@ -0,0 +1,256 @@ +import 'dart:async'; + +import 'package:path/path.dart' as p; +import 'package:path_provider/path_provider.dart'; +import 'package:sqflite/sqflite.dart'; + +import '../model/event.dart'; +import '../util/logger.dart'; +import 'db_constants.dart'; +import 'event_storage.dart'; + +/// 基于 sqflite 的事件存储实现。 +class SqfliteEventStorage implements EventStorage { + static const String _tableEvents = 'events'; + + Database? _db; + + @override + Future init() async { + if (_db != null) { + return; + } + + final directory = await getApplicationDocumentsDirectory(); + final dbPath = p.join(directory.path, DbConstants.dbName); + + _db = await openDatabase( + dbPath, + version: DbConstants.dbVersion, + onCreate: (db, version) async { + await _createTables(db); + }, + onUpgrade: (db, oldVersion, newVersion) async { + if (oldVersion < 1) { + await _createTables(db); + } + }, + ); + + Logger.info('SqfliteEventStorage 初始化完成: $dbPath'); + } + + Future _createTables(Database db) async { + await db.execute(''' + CREATE TABLE IF NOT EXISTS $_tableEvents ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + payload TEXT NOT NULL, + retry_count INTEGER NOT NULL DEFAULT 0, + create_time INTEGER NOT NULL + ); + '''); + + await db.execute( + 'CREATE INDEX IF NOT EXISTS idx_events_create_time ON $_tableEvents(create_time);', + ); + } + + Database _requireDb() { + final db = _db; + if (db == null) { + throw StateError('SqfliteEventStorage 尚未初始化'); + } + return db; + } + + @override + Future insert(Event event) async { + final db = _requireDb(); + final values = { + 'payload': event.toPayload(), + 'retry_count': event.retryCount, + 'create_time': event.createTime.millisecondsSinceEpoch, + }; + final id = await db.insert(_tableEvents, values); + return id; + } + + @override + Future> fetchBatch(int limit) async { + if (limit <= 0) { + return const []; + } + final db = _requireDb(); + final rows = await db.query( + _tableEvents, + orderBy: 'create_time ASC', + limit: limit, + ); + + return _parseRowsAndCleanup(db, rows); + } + + @override + Future> fetchRecent(int limit) async { + if (limit <= 0) { + return const []; + } + final db = _requireDb(); + final rows = await db.query( + _tableEvents, + orderBy: 'create_time DESC', + limit: limit, + ); + return _parseRowsAndCleanup(db, rows); + } + + @override + Future deleteByIds(List ids) async { + if (ids.isEmpty) { + return; + } + final db = _requireDb(); + + final placeholders = List.filled(ids.length, '?').join(','); + await db.delete( + _tableEvents, + where: 'id IN ($placeholders)', + whereArgs: ids, + ); + } + + @override + Future count() async { + final db = _requireDb(); + final result = await db.rawQuery('SELECT COUNT(*) AS c FROM $_tableEvents'); + if (result.isEmpty) { + return 0; + } + final value = result.first['c']; + return value is int ? value : int.tryParse(value.toString()) ?? 0; + } + + @override + Future trimToMaxSize(int maxSize) async { + if (maxSize <= 0) { + return 0; + } + final db = _requireDb(); + + final total = await count(); + final overflow = total - maxSize; + if (overflow <= 0) { + return 0; + } + + Logger.warn('事件缓存超限: total=$total, max=$maxSize, overflow=$overflow'); + + await db.rawDelete( + ''' + DELETE FROM $_tableEvents + WHERE id IN ( + SELECT id FROM $_tableEvents + ORDER BY create_time ASC + LIMIT ? + ); + ''', + [overflow], + ); + return overflow; + } + + @override + Future updateRetryCount(int id, int retryCount) async { + final db = _requireDb(); + await db.update( + _tableEvents, + {'retry_count': retryCount}, + where: 'id = ?', + whereArgs: [id], + ); + } + + @override + Future dispose() async { + final db = _db; + _db = null; + if (db != null && db.isOpen) { + await db.close(); + } + } + + Future> _parseRowsAndCleanup( + Database db, + List> rows, + ) async { + final parsed = _parseRows(rows); + final invalidIds = parsed.invalidIds; + if (invalidIds.isNotEmpty) { + Logger.warn('检测到无效事件数据,准备删除: count=${invalidIds.length}'); + final placeholders = List.filled(invalidIds.length, '?').join(','); + await db.delete( + _tableEvents, + where: 'id IN ($placeholders)', + whereArgs: invalidIds, + ); + } + return parsed.events; + } + + _ParsedRows _parseRows(List> rows) { + final results = []; + final invalidIds = []; + + for (final row in rows) { + try { + final id = row['id']; + final payload = row['payload']; + final retryCount = row['retry_count']; + final createTime = row['create_time']; + + if (id is! int || payload is! String || createTime is! int) { + Logger.warn('存储行格式不合法,已跳过: $row'); + if (id is int) { + invalidIds.add(id); + } + continue; + } + + final retry = retryCount is int ? retryCount : 0; + final createdAt = DateTime.fromMillisecondsSinceEpoch(createTime); + final event = Event.fromPayload( + payload, + createTime: createdAt, + retryCount: retry, + ); + + results.add( + StoredEvent( + id: id, + event: event, + retryCount: retry, + createTime: createdAt, + ), + ); + } catch (e, st) { + Logger.error('解析存储事件失败,已跳过该条', e, st); + final id = row['id']; + if (id is int) { + invalidIds.add(id); + } + } + } + + return _ParsedRows(events: results, invalidIds: invalidIds); + } +} + +class _ParsedRows { + final List events; + final List invalidIds; + + const _ParsedRows({ + required this.events, + required this.invalidIds, + }); +} diff --git a/lib/src/util/device_util.dart b/lib/src/util/device_util.dart new file mode 100644 index 0000000..add5ca7 --- /dev/null +++ b/lib/src/util/device_util.dart @@ -0,0 +1,44 @@ +import 'dart:io'; +import 'dart:ui'; + +import 'package:flutter/widgets.dart'; + +import '../model/device_info.dart'; + +/// 设备信息采集工具。 +class DeviceUtil { + const DeviceUtil._(); + + static Future collectDeviceInfo() async { + WidgetsFlutterBinding.ensureInitialized(); + + final os = Platform.operatingSystem; + final model = Platform.operatingSystemVersion; + final screenResolution = _screenResolution(); + + return DeviceInfo( + os: os, + model: model, + screenResolution: screenResolution, + ); + } + + static String _screenResolution() { + try { + final views = WidgetsBinding.instance.platformDispatcher.views; + if (views.isEmpty) { + return 'unknown'; + } + final FlutterView view = views.first; + final Size size = view.physicalSize; + final int width = size.width.round(); + final int height = size.height.round(); + if (width <= 0 || height <= 0) { + return 'unknown'; + } + return '${width}x$height'; + } catch (_) { + return 'unknown'; + } + } +} diff --git a/lib/src/util/id_generator.dart b/lib/src/util/id_generator.dart new file mode 100644 index 0000000..a9ba12d --- /dev/null +++ b/lib/src/util/id_generator.dart @@ -0,0 +1,17 @@ +import 'dart:math'; + +/// 本地事件 ID 生成器。 +class IdGenerator { + IdGenerator._(); + + static final Random _random = Random(); + static int _counter = 0; + + /// 生成一个足够唯一的字符串 ID。 + static String nextId() { + _counter = (_counter + 1) & 0x7fffffff; + final int ts = DateTime.now().microsecondsSinceEpoch; + final int rand = _random.nextInt(1 << 32); + return '$ts-${_counter.toRadixString(16)}-${rand.toRadixString(16)}'; + } +} diff --git a/lib/src/util/logger.dart b/lib/src/util/logger.dart new file mode 100644 index 0000000..cf0fbe3 --- /dev/null +++ b/lib/src/util/logger.dart @@ -0,0 +1,49 @@ +/// 简单日志工具。 +class Logger { + static const String _prefix = '[AnalyticsSDK]'; + static bool _debugEnabled = false; + + static bool get isDebugEnabled => _debugEnabled; + + static void setDebug(bool enabled) { + _debugEnabled = enabled; + debug('Debug 日志已${enabled ? '开启' : '关闭'}'); + } + + static void debug(String message) { + if (!_debugEnabled) { + return; + } + _print('DEBUG', message); + } + + static void info(String message) { + if (!_debugEnabled) { + return; + } + _print('INFO', message); + } + + static void warn(String message) { + if (!_debugEnabled) { + return; + } + _print('WARN', message); + } + + static void error(String message, [Object? error, StackTrace? stackTrace]) { + final buffer = StringBuffer(message); + if (error != null) { + buffer.write(' | error=$error'); + } + if (stackTrace != null && _debugEnabled) { + buffer.write('\n$stackTrace'); + } + _print('ERROR', buffer.toString()); + } + + static void _print(String level, String message) { + // ignore: avoid_print + print('$_prefix[$level] $message'); + } +} diff --git a/lib/src/util/sdk_info.dart b/lib/src/util/sdk_info.dart new file mode 100644 index 0000000..69d1f65 --- /dev/null +++ b/lib/src/util/sdk_info.dart @@ -0,0 +1,7 @@ +/// SDK 基础信息。 +class SdkInfo { + static const String sdkVersion = '0.1.0'; + static const String platform = 'flutter'; + + const SdkInfo._(); +} diff --git a/lib/src/util/time_util.dart b/lib/src/util/time_util.dart new file mode 100644 index 0000000..e2ab54d --- /dev/null +++ b/lib/src/util/time_util.dart @@ -0,0 +1,15 @@ +/// 时间工具。 +class TimeUtil { + const TimeUtil._(); + + /// 当前时间毫秒时间戳。 + static int nowMs() => DateTime.now().millisecondsSinceEpoch; + + /// 当前时间 ISO8601 字符串(UTC)。 + static String nowIso8601Utc() => DateTime.now().toUtc().toIso8601String(); + + /// 毫秒时间戳转 ISO8601 字符串(UTC)。 + static String iso8601FromMs(int ms) { + return DateTime.fromMillisecondsSinceEpoch(ms).toUtc().toIso8601String(); + } +} diff --git a/lib/yx_tracking_flutter.dart b/lib/yx_tracking_flutter.dart new file mode 100644 index 0000000..6baa161 --- /dev/null +++ b/lib/yx_tracking_flutter.dart @@ -0,0 +1,71 @@ +import 'dart:async'; + +import 'src/config/analytics_config.dart'; +import 'src/core/analytics_core.dart'; +import 'src/core/interceptors.dart'; +import 'src/model/device_info.dart'; +import 'src/model/recent_event_summary.dart'; +import 'src/model/user_info.dart'; + +export 'src/config/analytics_config.dart'; +export 'src/core/interceptors.dart'; +export 'src/model/device_info.dart'; +export 'src/model/event.dart'; +export 'src/model/recent_event_summary.dart'; +export 'src/model/user_info.dart'; + +/// 对外唯一入口(Facade)。 +class Analytics { + Analytics._(); + + static final AnalyticsCore _core = AnalyticsCore(); + + static Future init(AnalyticsConfig config) => _core.init(config); + + static Future track( + String eventType, { + Map? eventParams, + Map? customTags, + int? timestamp, + }) { + return _core.track( + eventType, + eventParams: eventParams, + customTags: customTags, + timestamp: timestamp, + ); + } + + static Future setUser(UserInfo? userInfo) => _core.setUser(userInfo); + + static Future setDeviceInfo(DeviceInfo deviceInfo) => + _core.setDeviceInfo(deviceInfo); + + static Future flush({bool force = false}) => _core.flush(force: force); + + /// 当前本地缓存事件数量(用于调试/演示)。 + static Future cachedEventCount() => _core.cachedEventCount(); + + /// 最近事件摘要(用于调试面板)。 + static Future> cachedRecentEvents({int limit = 20}) => + _core.cachedRecentEvents(limit: limit); + + /// Phase 2:手动触发一次配置刷新(默认强制刷新)。 + static Future refreshConfig({bool force = true}) => + _core.refreshConfig(force: force); + + /// Phase 3:立即上报一次 SDK 指标(调试/测试用)。 + static Future reportMetricsNow() => _core.reportMetricsNow(); + + /// Phase 3:注册事件拦截器。 + static void addInterceptor(AnalyticsInterceptor interceptor) { + _core.addInterceptor(interceptor); + } + + static void setDebug(bool enabled) { + unawaited(_core.setDebug(enabled)); + } + + /// 可选:当宿主确定不再需要 SDK 时调用。 + static Future dispose() => _core.dispose(); +} diff --git a/pubspec.yaml b/pubspec.yaml new file mode 100644 index 0000000..2affc83 --- /dev/null +++ b/pubspec.yaml @@ -0,0 +1,23 @@ +name: yx_tracking_flutter +description: "Enterprise analytics tracking SDK for Flutter." +version: 0.1.0 +homepage: + +environment: + sdk: ">=3.3.0 <4.0.0" + flutter: ">=3.22.0" + +dependencies: + flutter: + sdk: flutter + sqflite: ^2.3.3 + path_provider: ^2.1.4 + path: ^1.9.0 + dio: ^5.4.3+1 + +dev_dependencies: + flutter_test: + sdk: flutter + flutter_lints: ^5.0.0 + +flutter: diff --git a/test/analytics_core_test.dart b/test/analytics_core_test.dart new file mode 100644 index 0000000..bc0e435 --- /dev/null +++ b/test/analytics_core_test.dart @@ -0,0 +1,856 @@ +import 'dart:async'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:yx_tracking_flutter/src/config/analytics_config.dart'; +import 'package:yx_tracking_flutter/src/config/config_manager.dart'; +import 'package:yx_tracking_flutter/src/core/analytics_core.dart'; +import 'package:yx_tracking_flutter/src/core/interceptors.dart'; +import 'package:yx_tracking_flutter/src/core/scheduler.dart'; +import 'package:yx_tracking_flutter/src/model/device_info.dart'; +import 'package:yx_tracking_flutter/src/model/event.dart'; +import 'package:yx_tracking_flutter/src/model/system_dim_info.dart'; +import 'package:yx_tracking_flutter/src/network/api_client.dart'; +import 'package:yx_tracking_flutter/src/storage/event_storage.dart'; + +class MemoryEventStorage implements EventStorage { + int _nextId = 1; + final Map _store = {}; + final List insertedEvents = []; + + @override + Future init() async {} + + @override + Future insert(Event event) async { + final id = _nextId++; + insertedEvents.add(event); + _store[id] = StoredEvent( + id: id, + event: event, + retryCount: event.retryCount, + createTime: event.createTime, + ); + return id; + } + + @override + Future> fetchBatch(int limit) async { + final items = _store.values.toList() + ..sort((a, b) => a.createTime.compareTo(b.createTime)); + return items.take(limit).toList(growable: false); + } + + @override + Future> fetchRecent(int limit) async { + final items = _store.values.toList() + ..sort((a, b) => b.createTime.compareTo(a.createTime)); + return items.take(limit).toList(growable: false); + } + + @override + Future deleteByIds(List ids) async { + for (final id in ids) { + _store.remove(id); + } + } + + @override + Future count() async => _store.length; + + @override + Future trimToMaxSize(int maxSize) async { + if (maxSize <= 0 || _store.length <= maxSize) { + return 0; + } + final items = _store.values.toList() + ..sort((a, b) => a.createTime.compareTo(b.createTime)); + final overflow = items.length - maxSize; + for (var i = 0; i < overflow; i++) { + _store.remove(items[i].id); + } + return overflow; + } + + @override + Future updateRetryCount(int id, int retryCount) async { + final current = _store[id]; + if (current == null) { + return; + } + final updatedEvent = current.event.copyWith(retryCount: retryCount); + _store[id] = current.copyWith( + retryCount: retryCount, + event: updatedEvent, + ); + } + + @override + Future dispose() async {} + + StoredEvent? byId(int id) => _store[id]; + + StoredEvent? get singleOrNull { + if (_store.length != 1) { + return null; + } + return _store.values.first; + } +} + +class FakeApiClient extends ApiClient { + FakeApiClient(super.config); + + ApiException? exceptionToThrow; + final List> sentBatches = >[]; + + @override + Future sendBatch(List events) async { + sentBatches.add(events); + final exception = exceptionToThrow; + if (exception != null) { + throw exception; + } + } +} + +class TestConfigManager extends ConfigManager { + SystemDimInfo? _currentConfig; + + TestConfigManager({ + required super.config, + SystemDimInfo? initialConfig, + }) : _currentConfig = initialConfig, + super(refreshInterval: Duration.zero); + + @override + SystemDimInfo? get currentConfig => _currentConfig; + + void setCurrentConfig(SystemDimInfo? value) { + _currentConfig = value; + } + + @override + Future init() async {} + + @override + Future fetchAndCacheConfig({bool force = false}) async {} + + @override + Future forceRefresh() async {} + + @override + Future dispose() async {} +} + +class NoopScheduler extends Scheduler { + NoopScheduler({ + required super.interval, + required super.onTick, + }); + + @override + void start() {} + + @override + void stop() {} +} + +class RecordingInterceptor extends AnalyticsInterceptor { + RecordingInterceptor({ + this.onBefore, + this.onAfter, + }); + + final FutureOr Function(Event event)? onBefore; + final FutureOr Function(Event event, SendResult result)? onAfter; + + int beforeCalls = 0; + int afterCalls = 0; + final List afterResults = []; + + @override + FutureOr beforeSend(Event event) async { + beforeCalls += 1; + final handler = onBefore; + if (handler == null) { + return event; + } + return handler(event); + } + + @override + FutureOr afterSend(Event event, SendResult result) async { + afterCalls += 1; + afterResults.add(result); + final handler = onAfter; + if (handler == null) { + return; + } + await handler(event, result); + } +} + +const DeviceInfo _testDeviceInfo = DeviceInfo( + os: 'test-os', + model: 'test-model', + screenResolution: '100x200', +); + +AnalyticsConfig _testConfig({ + bool enableDebug = true, + int batchSize = 20, + int maxRetryCount = 2, + int maxCacheSize = 5000, +}) { + return AnalyticsConfig( + systemCode: 'TEST_APP', + endpointBaseUrl: 'https://example.com/api/ExternalEventlogs', + clientType: 3, + enableDebug: enableDebug, + batchSize: batchSize, + flushInterval: 3600, + maxRetryCount: maxRetryCount, + maxCacheSize: maxCacheSize, + enableMetrics: false, + ); +} + +SystemDimInfo _dimInfo({ + List events = const [], + List tags = const [], + SdkStrategy? strategy, +}) { + return SystemDimInfo( + systemInfo: const SystemInfo(raw: {}), + eventDefinitions: events, + tagDefinitions: tags, + sdkStrategy: strategy, + lastFetchedAt: DateTime.now(), + ); +} + +Future _drainMicrotasks() async { + await Future.delayed(Duration.zero); + await Future.delayed(Duration.zero); +} + +void main() { + group('AnalyticsCore.flush', () { + test('成功发送后删除事件', () async { + final storage = MemoryEventStorage(); + late FakeApiClient apiClient; + late TestConfigManager configManager; + final config = _testConfig(batchSize: 5); + + final core = AnalyticsCore( + storageFactory: () => storage, + apiClientFactory: (c) => apiClient = FakeApiClient(c), + configManagerFactory: (c) => + configManager = TestConfigManager(config: c), + deviceInfoCollector: () async => _testDeviceInfo, + schedulerFactory: (interval, onTick) => + NoopScheduler(interval: interval, onTick: onTick), + ); + + await core.init(config); + configManager.setCurrentConfig( + _dimInfo(events: const [ + EventDefinition(eventCode: 'EVENT_A'), + ]), + ); + + await core.track('EVENT_A'); + await core.track('EVENT_A'); + expect(await storage.count(), 2); + + await core.flush(force: true); + + expect(apiClient.sentBatches, isNotEmpty); + expect(await storage.count(), 0); + await core.dispose(); + }); + + test('可重试失败会增加 retryCount 并保留事件', () async { + final storage = MemoryEventStorage(); + late FakeApiClient apiClient; + late TestConfigManager configManager; + final config = + _testConfig(enableDebug: true, batchSize: 10, maxRetryCount: 3); + + final core = AnalyticsCore( + storageFactory: () => storage, + apiClientFactory: (c) => apiClient = FakeApiClient(c), + configManagerFactory: (c) => + configManager = TestConfigManager(config: c), + deviceInfoCollector: () async => _testDeviceInfo, + schedulerFactory: (interval, onTick) => + NoopScheduler(interval: interval, onTick: onTick), + ); + + await core.init(config); + configManager.setCurrentConfig( + _dimInfo(events: const [ + EventDefinition(eventCode: 'EVENT_RETRY'), + ]), + ); + + apiClient.exceptionToThrow = const ApiException( + message: 'network', + retryable: true, + ); + + await core.track('EVENT_RETRY'); + await core.flush(force: true); + + final stored = storage.singleOrNull; + expect(stored, isNotNull); + expect(stored!.retryCount, 1); + + apiClient.exceptionToThrow = null; + await core.flush(force: true); + expect(await storage.count(), 0); + await core.dispose(); + }); + + test('不可重试失败会直接删除事件', () async { + final storage = MemoryEventStorage(); + late FakeApiClient apiClient; + late TestConfigManager configManager; + final config = _testConfig(enableDebug: true, batchSize: 10); + + final core = AnalyticsCore( + storageFactory: () => storage, + apiClientFactory: (c) => apiClient = FakeApiClient(c), + configManagerFactory: (c) => + configManager = TestConfigManager(config: c), + deviceInfoCollector: () async => _testDeviceInfo, + schedulerFactory: (interval, onTick) => + NoopScheduler(interval: interval, onTick: onTick), + ); + + await core.init(config); + configManager.setCurrentConfig( + _dimInfo(events: const [ + EventDefinition(eventCode: 'EVENT_DROP'), + ]), + ); + + apiClient.exceptionToThrow = const ApiException( + message: 'bad request', + retryable: false, + statusCode: 400, + ); + + await core.track('EVENT_DROP'); + await core.flush(force: true); + + expect(await storage.count(), 0); + await core.dispose(); + }); + }); + + group('AnalyticsCore.validation (release)', () { + test('release 模式会写入校验标记', () async { + final storage = MemoryEventStorage(); + late TestConfigManager configManager; + final config = _testConfig(enableDebug: false, batchSize: 10); + + final core = AnalyticsCore( + storageFactory: () => storage, + apiClientFactory: (c) => FakeApiClient(c), + configManagerFactory: (c) => + configManager = TestConfigManager(config: c), + deviceInfoCollector: () async => _testDeviceInfo, + schedulerFactory: (interval, onTick) => + NoopScheduler(interval: interval, onTick: onTick), + ); + + await core.init(config); + + configManager.setCurrentConfig( + _dimInfo( + events: const [ + EventDefinition(eventCode: 'KNOWN_EVENT'), + ], + tags: const [ + TagDefinition( + tagName: 'requiredTag', + tagType: 'string', + isRequired: true, + ), + ], + ), + ); + + // 触发两个校验问题:未知事件 + 缺少必填 tag。 + await core.track('UNKNOWN_EVENT'); + await _drainMicrotasks(); + + final inserted = storage.insertedEvents.last; + final tags = inserted.customTags ?? const {}; + + expect(tags['_sdk_invalid_event'], true); + expect(tags['_sdk_missing_tags'], contains('requiredTag')); + await core.dispose(); + }); + }); + + group('AnalyticsCore.fallback', () { + test('无配置时仍可 track/flush(降级为 Phase 1 行为)', () async { + final storage = MemoryEventStorage(); + late FakeApiClient apiClient; + + final core = AnalyticsCore( + storageFactory: () => storage, + apiClientFactory: (c) => apiClient = FakeApiClient(c), + configManagerFactory: (c) => TestConfigManager(config: c), + deviceInfoCollector: () async => _testDeviceInfo, + schedulerFactory: (interval, onTick) => + NoopScheduler(interval: interval, onTick: onTick), + ); + + await core.init(_testConfig(enableDebug: true, batchSize: 10)); + await core.track('EVENT_NO_CONFIG'); + await core.flush(force: true); + + expect(apiClient.sentBatches, isNotEmpty); + await core.dispose(); + }); + }); + + group('AnalyticsCore.strategy', () { + test('全局策略关闭时直接丢弃事件', () async { + final storage = MemoryEventStorage(); + late TestConfigManager configManager; + final config = _testConfig(enableDebug: true, batchSize: 10); + + final core = AnalyticsCore( + storageFactory: () => storage, + apiClientFactory: (c) => FakeApiClient(c), + configManagerFactory: (c) => + configManager = TestConfigManager(config: c), + deviceInfoCollector: () async => _testDeviceInfo, + schedulerFactory: (interval, onTick) => + NoopScheduler(interval: interval, onTick: onTick), + ); + + await core.init(config); + configManager.setCurrentConfig( + _dimInfo( + events: const [ + EventDefinition(eventCode: 'EVENT_DISABLED'), + ], + strategy: const SdkStrategy( + enabled: false, + defaultSampleRate: 1.0, + eventSettings: {}, + ), + ), + ); + + await core.track('EVENT_DISABLED'); + expect(await storage.count(), 0); + await core.dispose(); + }); + + test('事件级策略 disabled 时丢弃事件', () async { + final storage = MemoryEventStorage(); + late TestConfigManager configManager; + final config = _testConfig(enableDebug: true, batchSize: 10); + + final core = AnalyticsCore( + storageFactory: () => storage, + apiClientFactory: (c) => FakeApiClient(c), + configManagerFactory: (c) => + configManager = TestConfigManager(config: c), + deviceInfoCollector: () async => _testDeviceInfo, + schedulerFactory: (interval, onTick) => + NoopScheduler(interval: interval, onTick: onTick), + ); + + await core.init(config); + configManager.setCurrentConfig( + _dimInfo( + events: const [ + EventDefinition(eventCode: 'EVENT_OFF'), + ], + strategy: const SdkStrategy( + enabled: true, + defaultSampleRate: 1.0, + eventSettings: { + 'EVENT_OFF': EventStrategy(enabled: false, sampleRate: 0.0), + }, + ), + ), + ); + + await core.track('EVENT_OFF'); + expect(await storage.count(), 0); + await core.dispose(); + }); + + test('采样策略根据随机数决定是否入库', () async { + final strategy = const SdkStrategy( + enabled: true, + defaultSampleRate: 1.0, + eventSettings: { + 'EVENT_SAMPLE': EventStrategy(enabled: true, sampleRate: 0.5), + }, + ); + + final storageDropped = MemoryEventStorage(); + late TestConfigManager configManagerDropped; + final coreDropped = AnalyticsCore( + storageFactory: () => storageDropped, + apiClientFactory: (c) => FakeApiClient(c), + configManagerFactory: (c) => + configManagerDropped = TestConfigManager(config: c), + deviceInfoCollector: () async => _testDeviceInfo, + schedulerFactory: (interval, onTick) => + NoopScheduler(interval: interval, onTick: onTick), + randomDouble: () => 0.9, + ); + + await coreDropped.init(_testConfig(enableDebug: true, batchSize: 10)); + configManagerDropped.setCurrentConfig( + _dimInfo( + events: const [ + EventDefinition(eventCode: 'EVENT_SAMPLE'), + ], + strategy: strategy, + ), + ); + await coreDropped.track('EVENT_SAMPLE'); + expect(await storageDropped.count(), 0); + await coreDropped.dispose(); + + final storageKept = MemoryEventStorage(); + late TestConfigManager configManagerKept; + final coreKept = AnalyticsCore( + storageFactory: () => storageKept, + apiClientFactory: (c) => FakeApiClient(c), + configManagerFactory: (c) => + configManagerKept = TestConfigManager(config: c), + deviceInfoCollector: () async => _testDeviceInfo, + schedulerFactory: (interval, onTick) => + NoopScheduler(interval: interval, onTick: onTick), + randomDouble: () => 0.1, + ); + + await coreKept.init(_testConfig(enableDebug: true, batchSize: 10)); + configManagerKept.setCurrentConfig( + _dimInfo( + events: const [ + EventDefinition(eventCode: 'EVENT_SAMPLE'), + ], + strategy: strategy, + ), + ); + await coreKept.track('EVENT_SAMPLE'); + expect(await storageKept.count(), 1); + await coreKept.dispose(); + }); + }); + + group('AnalyticsCore.interceptors', () { + test('拦截器可修改事件并收到 afterSend 回调', () async { + final storage = MemoryEventStorage(); + late FakeApiClient apiClient; + late TestConfigManager configManager; + final interceptor = RecordingInterceptor( + onBefore: (event) { + final tags = Map.from( + event.customTags ?? const {}, + ); + tags['intercepted'] = true; + return event.copyWith(customTags: tags); + }, + ); + + final core = AnalyticsCore( + storageFactory: () => storage, + apiClientFactory: (c) => apiClient = FakeApiClient(c), + configManagerFactory: (c) => + configManager = TestConfigManager(config: c), + deviceInfoCollector: () async => _testDeviceInfo, + schedulerFactory: (interval, onTick) => + NoopScheduler(interval: interval, onTick: onTick), + ); + + await core.init(_testConfig(enableDebug: true, batchSize: 10)); + configManager.setCurrentConfig( + _dimInfo(events: const [ + EventDefinition(eventCode: 'EVENT_INTERCEPT'), + ]), + ); + core.addInterceptor(interceptor); + + await core.track('EVENT_INTERCEPT'); + await core.flush(force: true); + + final sentEvent = apiClient.sentBatches.single.single; + expect(sentEvent.customTags?['intercepted'], true); + expect(interceptor.afterCalls, 1); + expect(interceptor.afterResults.single.success, true); + await core.dispose(); + }); + + test('拦截器返回 null 会拦截并删除事件', () async { + final storage = MemoryEventStorage(); + late TestConfigManager configManager; + final interceptor = RecordingInterceptor(onBefore: (_) => null); + + final core = AnalyticsCore( + storageFactory: () => storage, + apiClientFactory: (c) => FakeApiClient(c), + configManagerFactory: (c) => + configManager = TestConfigManager(config: c), + deviceInfoCollector: () async => _testDeviceInfo, + schedulerFactory: (interval, onTick) => + NoopScheduler(interval: interval, onTick: onTick), + ); + + await core.init(_testConfig(enableDebug: true, batchSize: 10)); + configManager.setCurrentConfig( + _dimInfo(events: const [ + EventDefinition(eventCode: 'EVENT_DROP_BY_INTERCEPTOR'), + ]), + ); + core.addInterceptor(interceptor); + + await core.track('EVENT_DROP_BY_INTERCEPTOR'); + await core.flush(force: true); + + expect(await storage.count(), 0); + await core.dispose(); + }); + + test('拦截器异常不会影响后续拦截器与发送', () async { + final storage = MemoryEventStorage(); + late FakeApiClient apiClient; + late TestConfigManager configManager; + + final throwing = RecordingInterceptor( + onBefore: (_) => throw StateError('boom'), + ); + final tagging = RecordingInterceptor( + onBefore: (event) { + final tags = Map.from( + event.customTags ?? const {}, + ); + tags['tagged'] = 'yes'; + return event.copyWith(customTags: tags); + }, + ); + + final core = AnalyticsCore( + storageFactory: () => storage, + apiClientFactory: (c) => apiClient = FakeApiClient(c), + configManagerFactory: (c) => + configManager = TestConfigManager(config: c), + deviceInfoCollector: () async => _testDeviceInfo, + schedulerFactory: (interval, onTick) => + NoopScheduler(interval: interval, onTick: onTick), + ); + + await core.init(_testConfig(enableDebug: true, batchSize: 10)); + configManager.setCurrentConfig( + _dimInfo(events: const [ + EventDefinition(eventCode: 'EVENT_THROW'), + ]), + ); + core.addInterceptor(throwing); + core.addInterceptor(tagging); + + await core.track('EVENT_THROW'); + await core.flush(force: true); + + final sentEvent = apiClient.sentBatches.single.single; + expect(sentEvent.customTags?['tagged'], 'yes'); + await core.dispose(); + }); + }); + + group('AnalyticsCore.metrics', () { + test('reportMetricsNow 会生成指标事件并包含计数', () async { + final storage = MemoryEventStorage(); + late FakeApiClient apiClient; + late TestConfigManager configManager; + final config = AnalyticsConfig( + systemCode: 'TEST_APP', + endpointBaseUrl: 'https://example.com/api/ExternalEventlogs', + clientType: 3, + enableDebug: true, + batchSize: 10, + flushInterval: 3600, + enableMetrics: true, + metricsReportInterval: const Duration(days: 1), + ); + + final core = AnalyticsCore( + storageFactory: () => storage, + apiClientFactory: (c) => apiClient = FakeApiClient(c), + configManagerFactory: (c) => + configManager = TestConfigManager(config: c), + deviceInfoCollector: () async => _testDeviceInfo, + schedulerFactory: (interval, onTick) => + NoopScheduler(interval: interval, onTick: onTick), + ); + + await core.init(config); + configManager.setCurrentConfig( + _dimInfo(events: const [ + EventDefinition(eventCode: 'EVENT_METRIC'), + ]), + ); + + await core.track('EVENT_METRIC'); + await core.track('EVENT_METRIC'); + await core.flush(force: true); + + await core.reportMetricsNow(); + + final metricsSendEvents = storage.insertedEvents + .where((e) => e.eventType == 'SDK_METRICS_SEND') + .toList(growable: false); + expect(metricsSendEvents, isNotEmpty); + final metricsParams = + metricsSendEvents.last.eventParams ?? const {}; + expect(metricsParams['sentCount'], 2); + expect(apiClient.sentBatches, isNotEmpty); + await core.dispose(); + }); + }); + + group('MemoryEventStorage contract', () { + Event buildEvent(String type, DateTime createTime) { + final ts = createTime.millisecondsSinceEpoch; + return Event( + systemCode: 'TEST_APP', + eventType: type, + userInfo: null, + clientType: 3, + clientTimestamp: ts, + timestamp: createTime.toUtc().toIso8601String(), + deviceInfo: _testDeviceInfo, + eventParams: null, + customTags: null, + createTime: createTime, + ); + } + + test('trimToMaxSize 会删除最旧事件并返回删除数', () async { + final storage = MemoryEventStorage(); + await storage.init(); + final now = DateTime.now(); + + await storage.insert(buildEvent('E1', now.subtract(const Duration(seconds: 3)))); + await storage.insert(buildEvent('E2', now.subtract(const Duration(seconds: 2)))); + await storage.insert(buildEvent('E3', now.subtract(const Duration(seconds: 1)))); + + final trimmed = await storage.trimToMaxSize(2); + expect(trimmed, 1); + expect(await storage.count(), 2); + expect(storage.byId(1), isNull); + }); + + test('fetchRecent 按时间降序返回', () async { + final storage = MemoryEventStorage(); + await storage.init(); + final now = DateTime.now(); + + await storage.insert(buildEvent('OLD', now.subtract(const Duration(seconds: 2)))); + await storage.insert(buildEvent('MID', now.subtract(const Duration(seconds: 1)))); + await storage.insert(buildEvent('NEW', now)); + + final recent = await storage.fetchRecent(2); + expect(recent.map((e) => e.event.eventType).toList(), ['NEW', 'MID']); + }); + + test('updateRetryCount 会同时更新 stored 与 event.retryCount', () async { + final storage = MemoryEventStorage(); + await storage.init(); + final now = DateTime.now(); + + final id = await storage.insert(buildEvent('RETRY', now)); + await storage.updateRetryCount(id, 2); + final stored = storage.byId(id); + expect(stored, isNotNull); + expect(stored!.retryCount, 2); + expect(stored.event.retryCount, 2); + }); + }); + + group('Integration & performance (mocked)', () { + test('断网失败后恢复可补发', () async { + final storage = MemoryEventStorage(); + late FakeApiClient apiClient; + late TestConfigManager configManager; + + final core = AnalyticsCore( + storageFactory: () => storage, + apiClientFactory: (c) => apiClient = FakeApiClient(c), + configManagerFactory: (c) => + configManager = TestConfigManager(config: c), + deviceInfoCollector: () async => _testDeviceInfo, + schedulerFactory: (interval, onTick) => + NoopScheduler(interval: interval, onTick: onTick), + ); + + await core.init(_testConfig(enableDebug: false, batchSize: 10)); + configManager.setCurrentConfig( + _dimInfo(events: const [ + EventDefinition(eventCode: 'EVENT_OFFLINE'), + ]), + ); + + apiClient.exceptionToThrow = const ApiException( + message: 'offline', + retryable: true, + ); + await core.track('EVENT_OFFLINE'); + await core.flush(force: true); + expect(await storage.count(), 1); + + apiClient.exceptionToThrow = null; + await core.flush(force: true); + expect(await storage.count(), 0); + await core.dispose(); + }); + + test('高频 track 1 万次不会崩溃且数据可入库', () async { + final storage = MemoryEventStorage(); + late TestConfigManager configManager; + + final core = AnalyticsCore( + storageFactory: () => storage, + apiClientFactory: (c) => FakeApiClient(c), + configManagerFactory: (c) => + configManager = TestConfigManager(config: c), + deviceInfoCollector: () async => _testDeviceInfo, + schedulerFactory: (interval, onTick) => + NoopScheduler(interval: interval, onTick: onTick), + ); + + await core.init( + _testConfig( + enableDebug: false, + batchSize: 20000, + maxCacheSize: 20000, + ), + ); + configManager.setCurrentConfig( + _dimInfo(events: const [ + EventDefinition(eventCode: 'EVENT_STRESS'), + ]), + ); + + for (var i = 0; i < 10000; i++) { + await core.track('EVENT_STRESS'); + } + + expect(await storage.count(), 10000); + await core.dispose(); + }); + }); +} diff --git a/test/config_manager_test.dart b/test/config_manager_test.dart new file mode 100644 index 0000000..bb83a30 --- /dev/null +++ b/test/config_manager_test.dart @@ -0,0 +1,172 @@ +import 'package:dio/dio.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:yx_tracking_flutter/src/config/analytics_config.dart'; +import 'package:yx_tracking_flutter/src/config/config_manager.dart'; +import 'package:yx_tracking_flutter/src/model/system_dim_info.dart'; +import 'package:yx_tracking_flutter/src/network/http_client.dart'; +import 'package:yx_tracking_flutter/src/storage/config_storage.dart'; + +class InMemoryConfigStorage implements ConfigStorage { + SystemDimInfo? _stored; + + @override + Future init() async {} + + @override + Future saveSystemDimInfo(SystemDimInfo info) async { + _stored = info; + } + + @override + Future loadSystemDimInfo() async => _stored; + + @override + Future clear() async { + _stored = null; + } + + @override + Future dispose() async {} +} + +class FakeHttpClient extends HttpClient { + FakeHttpClient(super.config); + + int getCallCount = 0; + dynamic responseData; + Headers responseHeaders = Headers(); + DioException? exceptionToThrow; + + @override + Future> get( + String path, { + Map? queryParameters, + Map? headers, + CancelToken? cancelToken, + }) async { + getCallCount += 1; + final exception = exceptionToThrow; + if (exception != null) { + throw exception; + } + return Response( + data: responseData as T?, + statusCode: 200, + headers: responseHeaders, + requestOptions: RequestOptions(path: path, queryParameters: queryParameters), + ); + } +} + +AnalyticsConfig _config() { + return const AnalyticsConfig( + systemCode: 'TEST_APP', + endpointBaseUrl: 'https://example.com/api/ExternalEventlogs', + clientType: 3, + enableMetrics: false, + ); +} + +SystemDimInfo _storedConfig(DateTime fetchedAt) { + return SystemDimInfo( + systemInfo: const SystemInfo(raw: {}), + eventDefinitions: const [], + tagDefinitions: const [], + sdkStrategy: null, + lastFetchedAt: fetchedAt, + ); +} + +void main() { + group('ConfigManager', () { + test('fetchAndCacheConfig 会解析配置并缓存', () async { + final storage = InMemoryConfigStorage(); + final httpClient = FakeHttpClient(_config()); + httpClient.responseData = { + 'data': { + 'systemEventTypes': >[ + {'eventCode': 'EVENT_A', 'eventName': 'A'}, + ], + 'systemCustonTas': >[ + { + 'tagName': 'tenantId', + 'tagType': 'string', + 'isRequired': true, + }, + ], + 'sdkStrategy': { + 'enabled': true, + 'defaultSampleRate': 1.0, + 'eventSettings': { + 'EVENT_A': { + 'enabled': true, + 'sampleRate': 0.25, + }, + }, + }, + }, + }; + httpClient.responseHeaders = Headers.fromMap(>{ + 'x-config-version': ['v1'], + }); + + final manager = ConfigManager( + config: _config(), + refreshInterval: const Duration(hours: 1), + storage: storage, + httpClient: httpClient, + ); + + await manager.init(); + await manager.fetchAndCacheConfig(force: true); + + final current = manager.currentConfig; + expect(current, isNotNull); + expect(current!.eventDefinitions.single.eventCode, 'EVENT_A'); + expect(current.requiredTags.single.tagName, 'tenantId'); + expect(current.sampleRateFor('EVENT_A'), 0.25); + expect(current.version, 'v1'); + }); + + test('配置未过期时会跳过拉取', () async { + final storage = InMemoryConfigStorage(); + final httpClient = FakeHttpClient(_config()); + final now = DateTime.now(); + await storage.saveSystemDimInfo(_storedConfig(now)); + + final manager = ConfigManager( + config: _config(), + refreshInterval: const Duration(hours: 12), + storage: storage, + httpClient: httpClient, + ); + + await manager.init(); + await manager.fetchAndCacheConfig(force: false); + + expect(httpClient.getCallCount, 0); + expect(manager.currentConfig, isNotNull); + }); + + test('响应结构不可解析时保持现有配置', () async { + final storage = InMemoryConfigStorage(); + final httpClient = FakeHttpClient(_config()); + final existing = _storedConfig(DateTime.now().subtract(const Duration(days: 1))); + await storage.saveSystemDimInfo(existing); + httpClient.responseData = 'not-a-map'; + + final manager = ConfigManager( + config: _config(), + refreshInterval: const Duration(hours: 1), + storage: storage, + httpClient: httpClient, + ); + + await manager.init(); + await manager.fetchAndCacheConfig(force: true); + + expect(manager.currentConfig, isNotNull); + expect(manager.currentConfig!.lastFetchedAt, existing.lastFetchedAt); + }); + }); +} diff --git a/test/validator_test.dart b/test/validator_test.dart new file mode 100644 index 0000000..cbd8bc1 --- /dev/null +++ b/test/validator_test.dart @@ -0,0 +1,135 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:yx_tracking_flutter/src/config/analytics_config.dart'; +import 'package:yx_tracking_flutter/src/config/config_manager.dart'; +import 'package:yx_tracking_flutter/src/core/validator.dart'; +import 'package:yx_tracking_flutter/src/model/device_info.dart'; +import 'package:yx_tracking_flutter/src/model/event.dart'; +import 'package:yx_tracking_flutter/src/model/system_dim_info.dart'; + +class StaticConfigManager extends ConfigManager { + StaticConfigManager({ + required super.config, + required SystemDimInfo configValue, + }) : _configValue = configValue, + super(refreshInterval: Duration.zero); + + final SystemDimInfo _configValue; + + @override + SystemDimInfo? get currentConfig => _configValue; + + @override + Future init() async {} + + @override + Future fetchAndCacheConfig({bool force = false}) async {} + + @override + Future forceRefresh() async {} + + @override + Future dispose() async {} +} + +const DeviceInfo _device = DeviceInfo( + os: 'test', + model: 'test', + screenResolution: '1x1', +); + +AnalyticsConfig _config() { + return const AnalyticsConfig( + systemCode: 'TEST_APP', + endpointBaseUrl: 'https://example.com/api/ExternalEventlogs', + clientType: 3, + enableMetrics: false, + ); +} + +Event _event({ + required String type, + Map? customTags, +}) { + final now = DateTime.now(); + final ts = now.millisecondsSinceEpoch; + return Event( + systemCode: 'TEST_APP', + eventType: type, + userInfo: null, + clientType: 3, + clientTimestamp: ts, + timestamp: now.toUtc().toIso8601String(), + deviceInfo: _device, + eventParams: null, + customTags: customTags, + createTime: now, + ); +} + +SystemDimInfo _dimInfo() { + return SystemDimInfo( + systemInfo: const SystemInfo(raw: {}), + eventDefinitions: const [ + EventDefinition(eventCode: 'KNOWN'), + ], + tagDefinitions: const [ + TagDefinition(tagName: 'tenantId', tagType: 'string', isRequired: true), + TagDefinition(tagName: 'count', tagType: 'int', isRequired: false), + ], + sdkStrategy: null, + lastFetchedAt: DateTime.now(), + ); +} + +void main() { + group('Validator', () { + test('已配置事件且必填 tag 满足时无告警', () { + final manager = StaticConfigManager(config: _config(), configValue: _dimInfo()); + final validator = Validator(manager); + + final result = validator.validate( + _event(type: 'KNOWN', customTags: const {'tenantId': 't1'}), + ); + + expect(result.isEmpty, true); + }); + + test('未知事件会产生 error', () { + final manager = StaticConfigManager(config: _config(), configValue: _dimInfo()); + final validator = Validator(manager); + + final result = validator.validate(_event(type: 'UNKNOWN')); + + expect(result.hasErrors, true); + expect(result.errors.first.code, Validator.unknownEventType); + }); + + test('缺失必填 tag 会产生 warning', () { + final manager = StaticConfigManager(config: _config(), configValue: _dimInfo()); + final validator = Validator(manager); + + final result = validator.validate(_event(type: 'KNOWN')); + + expect(result.hasWarnings, true); + expect(result.warnings.first.code, Validator.missingRequiredTag); + }); + + test('类型不匹配会产生 warning', () { + final manager = StaticConfigManager(config: _config(), configValue: _dimInfo()); + final validator = Validator(manager); + + final result = validator.validate( + _event( + type: 'KNOWN', + customTags: const { + 'tenantId': 't1', + 'count': 'not-an-int', + }, + ), + ); + + expect(result.hasWarnings, true); + expect(result.warnings.any((w) => w.code == Validator.typeMismatch), true); + }); + }); +} diff --git a/test/yx_tracking_flutter_test.dart b/test/yx_tracking_flutter_test.dart new file mode 100644 index 0000000..0ac837f --- /dev/null +++ b/test/yx_tracking_flutter_test.dart @@ -0,0 +1,64 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:yx_tracking_flutter/yx_tracking_flutter.dart'; +import 'package:yx_tracking_flutter/src/util/time_util.dart'; + +void main() { + group('AnalyticsConfig.validate', () { + test('https 配置通过校验', () { + const config = AnalyticsConfig( + systemCode: 'OA_APP', + endpointBaseUrl: 'https://example.com/api/ExternalEventlogs', + clientType: 3, + ); + + expect(config.validate, returnsNormally); + }); + + test('非 https 配置会抛错', () { + const config = AnalyticsConfig( + systemCode: 'OA_APP', + endpointBaseUrl: 'http://example.com/api/ExternalEventlogs', + clientType: 3, + ); + + expect(config.validate, throwsArgumentError); + }); + }); + + test('Event payload 序列化/反序列化', () { + final device = const DeviceInfo( + os: 'android', + model: 'pixel', + screenResolution: '1080x1920', + ); + final user = const UserInfo(userId: 1, userName: 'max', account: 'max'); + + final now = TimeUtil.nowMs(); + final event = Event( + systemCode: 'OA_APP', + eventType: 'PAGE_VIEW', + userInfo: user, + clientType: 3, + clientTimestamp: now, + timestamp: TimeUtil.iso8601FromMs(now), + deviceInfo: device, + eventParams: const {'page': 'home'}, + customTags: const {'tenantId': 't1'}, + createTime: DateTime.fromMillisecondsSinceEpoch(now), + ); + + final payload = event.toPayload(); + final decoded = Event.fromPayload( + payload, + createTime: event.createTime, + retryCount: 0, + ); + + expect(decoded.systemCode, event.systemCode); + expect(decoded.eventType, event.eventType); + expect(decoded.clientType, event.clientType); + expect(decoded.deviceInfo.screenResolution, device.screenResolution); + expect(decoded.eventParams?['page'], 'home'); + expect(decoded.customTags?['tenantId'], 't1'); + }); +}