diff --git a/codelabs/README.md b/codelabs/README.md index db06c04da..1a9c1f186 100644 --- a/codelabs/README.md +++ b/codelabs/README.md @@ -24,6 +24,15 @@ is organised. Skipping numbers is fine: the point of a step directory is to give someone a working app to resume from. +**Almost every step directory is an app.** The exception today is +`function-calling-flutter-gemma/step_04_finetune/`, whose step produces a model +rather than code: it holds the training data and the commands for a +[litetune](https://github.com/DenisovAV/litetune) run and has no +`pubspec.yaml`, so `tool/check_codelabs.sh` — which discovers apps by their +`pubspec.yaml` — does not see it. A step that ships something other than a +Flutter app belongs in the codelab's own directory all the same; a learner +looking for Step 4 should find it where Steps 3 and 5 are. + ## Dependencies Step apps are **not** members of the repo's pub workspace. They depend on the @@ -52,7 +61,10 @@ tool/check_codelabs.sh # pub get + analyze + format + test, every step The same script also enforces the cross-codelab invariants declared in its `MIRRORS` table: a later codelab's starter is an earlier codelab's finished app, `lib/` and `test/` byte for byte, because both texts tell the learner so. Add a -row there when a new codelab continues an existing one. +row there when a new codelab continues an existing one — and only then. A +starter may be its own app instead, and function-calling's is: inheriting a +finished app whose model the next step replaces makes a learner pay for a +download the codelab never uses. And it checks **application ids**, on Android, iOS, macOS and Linux: every app inside a codelab declares the same one — that is what lets a later step open the @@ -89,6 +101,9 @@ flutter test integration_test/engines_test.dart -d cd codelabs/multimodal-flutter-gemma/complete flutter test integration_test/multimodal_test.dart -d +cd codelabs/function-calling-flutter-gemma/complete +flutter test integration_test/function_calling_test.dart -d + cd codelabs/hybrid-ai-flutter-genkit/complete flutter test integration_test/smoke_test.dart -d \ --dart-define=HF_TOKEN=hf_xxx --dart-define=GEMINI_API_KEY=AIza... diff --git a/codelabs/function-calling-flutter-gemma/complete/.gitignore b/codelabs/function-calling-flutter-gemma/complete/.gitignore new file mode 100644 index 000000000..79f7ecabd --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/.gitignore @@ -0,0 +1,48 @@ +# 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 + +# Widget Preview related +.widget_preview/ diff --git a/codelabs/function-calling-flutter-gemma/complete/.metadata b/codelabs/function-calling-flutter-gemma/complete/.metadata new file mode 100644 index 000000000..615dfd47e --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/.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: "d3b14c876900e553bc736ca19295fc09e3853e8e" + channel: "stable" + +project_type: app + +# Tracks metadata for the flutter migrate command +migration: + platforms: + - platform: root + create_revision: d3b14c876900e553bc736ca19295fc09e3853e8e + base_revision: d3b14c876900e553bc736ca19295fc09e3853e8e + - platform: android + create_revision: d3b14c876900e553bc736ca19295fc09e3853e8e + base_revision: d3b14c876900e553bc736ca19295fc09e3853e8e + - platform: ios + create_revision: d3b14c876900e553bc736ca19295fc09e3853e8e + base_revision: d3b14c876900e553bc736ca19295fc09e3853e8e + - platform: linux + create_revision: d3b14c876900e553bc736ca19295fc09e3853e8e + base_revision: d3b14c876900e553bc736ca19295fc09e3853e8e + - platform: macos + create_revision: d3b14c876900e553bc736ca19295fc09e3853e8e + base_revision: d3b14c876900e553bc736ca19295fc09e3853e8e + - platform: web + create_revision: d3b14c876900e553bc736ca19295fc09e3853e8e + base_revision: d3b14c876900e553bc736ca19295fc09e3853e8e + - platform: windows + create_revision: d3b14c876900e553bc736ca19295fc09e3853e8e + base_revision: d3b14c876900e553bc736ca19295fc09e3853e8e + + # 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/codelabs/function-calling-flutter-gemma/complete/README.md b/codelabs/function-calling-flutter-gemma/complete/README.md new file mode 100644 index 000000000..1c831fead --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/README.md @@ -0,0 +1,17 @@ +# gemma_quickstart + +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: + +- [Learn Flutter](https://docs.flutter.dev/get-started/learn-flutter) +- [Write your first Flutter app](https://docs.flutter.dev/get-started/codelab) +- [Flutter learning resources](https://docs.flutter.dev/reference/learning-resources) + +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/codelabs/function-calling-flutter-gemma/complete/analysis_options.yaml b/codelabs/function-calling-flutter-gemma/complete/analysis_options.yaml new file mode 100644 index 000000000..78613972a --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/analysis_options.yaml @@ -0,0 +1,38 @@ +# 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 + +analyzer: + exclude: + - build/** + - android/** + - ios/** + - linux/** + - macos/** + - web/** + - windows/** + +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/codelabs/function-calling-flutter-gemma/complete/android/.gitignore b/codelabs/function-calling-flutter-gemma/complete/android/.gitignore new file mode 100644 index 000000000..be3943c96 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/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/codelabs/function-calling-flutter-gemma/complete/android/app/build.gradle.kts b/codelabs/function-calling-flutter-gemma/complete/android/app/build.gradle.kts new file mode 100644 index 000000000..1ec5366e9 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/android/app/build.gradle.kts @@ -0,0 +1,49 @@ +plugins { + id("com.android.application") + // The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins. + id("dev.flutter.flutter-gradle-plugin") +} + +android { + namespace = "dev.fluttergemma.functioncalling" + compileSdk = flutter.compileSdkVersion + ndkVersion = flutter.ndkVersion + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + } + + defaultConfig { + // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). + applicationId = "dev.fluttergemma.functioncalling" + // 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 + // Uses the version code from pubspec.yaml. When using split APKs, 1000 * ABI_VERSION + // is added automatically by Flutter. (https://developer.android.com/studio/build/configure-apk-splits#configure-APK-versions) + // You can force using the value of versionCode by specifying the `-P force-version-code-ignoring-abi=true` + // flag during build. + 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") + } + } +} + +kotlin { + compilerOptions { + jvmTarget = org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17 + } +} + +flutter { + source = "../.." +} diff --git a/codelabs/function-calling-flutter-gemma/complete/android/app/src/debug/AndroidManifest.xml b/codelabs/function-calling-flutter-gemma/complete/android/app/src/debug/AndroidManifest.xml new file mode 100644 index 000000000..399f6981d --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/android/app/src/debug/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + diff --git a/codelabs/function-calling-flutter-gemma/complete/android/app/src/main/AndroidManifest.xml b/codelabs/function-calling-flutter-gemma/complete/android/app/src/main/AndroidManifest.xml new file mode 100644 index 000000000..34daae5c0 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,47 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/codelabs/function-calling-flutter-gemma/complete/android/app/src/main/kotlin/dev/fluttergemma/functioncalling/MainActivity.kt b/codelabs/function-calling-flutter-gemma/complete/android/app/src/main/kotlin/dev/fluttergemma/functioncalling/MainActivity.kt new file mode 100644 index 000000000..e4e274d6e --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/android/app/src/main/kotlin/dev/fluttergemma/functioncalling/MainActivity.kt @@ -0,0 +1,5 @@ +package dev.fluttergemma.functioncalling + +import io.flutter.embedding.android.FlutterActivity + +class MainActivity : FlutterActivity() diff --git a/codelabs/function-calling-flutter-gemma/complete/android/app/src/main/res/drawable-v21/launch_background.xml b/codelabs/function-calling-flutter-gemma/complete/android/app/src/main/res/drawable-v21/launch_background.xml new file mode 100644 index 000000000..f74085f3f --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/android/app/src/main/res/drawable-v21/launch_background.xml @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/codelabs/function-calling-flutter-gemma/complete/android/app/src/main/res/drawable/launch_background.xml b/codelabs/function-calling-flutter-gemma/complete/android/app/src/main/res/drawable/launch_background.xml new file mode 100644 index 000000000..304732f88 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/android/app/src/main/res/drawable/launch_background.xml @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/codelabs/function-calling-flutter-gemma/complete/android/app/src/main/res/mipmap-hdpi/ic_launcher.png b/codelabs/function-calling-flutter-gemma/complete/android/app/src/main/res/mipmap-hdpi/ic_launcher.png new file mode 100644 index 000000000..db77bb4b7 Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/complete/android/app/src/main/res/mipmap-hdpi/ic_launcher.png differ diff --git a/codelabs/function-calling-flutter-gemma/complete/android/app/src/main/res/mipmap-mdpi/ic_launcher.png b/codelabs/function-calling-flutter-gemma/complete/android/app/src/main/res/mipmap-mdpi/ic_launcher.png new file mode 100644 index 000000000..17987b79b Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/complete/android/app/src/main/res/mipmap-mdpi/ic_launcher.png differ diff --git a/codelabs/function-calling-flutter-gemma/complete/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/codelabs/function-calling-flutter-gemma/complete/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png new file mode 100644 index 000000000..09d439148 Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/complete/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png differ diff --git a/codelabs/function-calling-flutter-gemma/complete/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/codelabs/function-calling-flutter-gemma/complete/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png new file mode 100644 index 000000000..d5f1c8d34 Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/complete/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png differ diff --git a/codelabs/function-calling-flutter-gemma/complete/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/codelabs/function-calling-flutter-gemma/complete/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 000000000..4d6372eeb Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/complete/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png differ diff --git a/codelabs/function-calling-flutter-gemma/complete/android/app/src/main/res/values-night/styles.xml b/codelabs/function-calling-flutter-gemma/complete/android/app/src/main/res/values-night/styles.xml new file mode 100644 index 000000000..06952be74 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/android/app/src/main/res/values-night/styles.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/codelabs/function-calling-flutter-gemma/complete/android/app/src/main/res/values/styles.xml b/codelabs/function-calling-flutter-gemma/complete/android/app/src/main/res/values/styles.xml new file mode 100644 index 000000000..cb1ef8805 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/android/app/src/main/res/values/styles.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/codelabs/function-calling-flutter-gemma/complete/android/app/src/profile/AndroidManifest.xml b/codelabs/function-calling-flutter-gemma/complete/android/app/src/profile/AndroidManifest.xml new file mode 100644 index 000000000..399f6981d --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/android/app/src/profile/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + diff --git a/codelabs/function-calling-flutter-gemma/complete/android/build.gradle.kts b/codelabs/function-calling-flutter-gemma/complete/android/build.gradle.kts new file mode 100644 index 000000000..dbee657bb --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/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/codelabs/function-calling-flutter-gemma/complete/android/gradle.properties b/codelabs/function-calling-flutter-gemma/complete/android/gradle.properties new file mode 100644 index 000000000..e96108cfe --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/android/gradle.properties @@ -0,0 +1,6 @@ +org.gradle.jvmargs=-Xmx8G -XX:MaxMetaspaceSize=4G -XX:ReservedCodeCacheSize=512m -XX:+HeapDumpOnOutOfMemoryError +android.useAndroidX=true +# This newDsl flag was added by the Flutter template +android.newDsl=false +# This builtInKotlin flag was added by the Flutter template +android.builtInKotlin=false diff --git a/codelabs/function-calling-flutter-gemma/complete/android/gradle/wrapper/gradle-wrapper.properties b/codelabs/function-calling-flutter-gemma/complete/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 000000000..a20f2c46d --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/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-9.3.1-all.zip diff --git a/codelabs/function-calling-flutter-gemma/complete/android/settings.gradle.kts b/codelabs/function-calling-flutter-gemma/complete/android/settings.gradle.kts new file mode 100644 index 000000000..b28021a91 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/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 "9.1.0" apply false + id("org.jetbrains.kotlin.android") version "2.4.0" apply false +} + +include(":app") diff --git a/codelabs/function-calling-flutter-gemma/complete/integration_test/function_calling_test.dart b/codelabs/function-calling-flutter-gemma/complete/integration_test/function_calling_test.dart new file mode 100644 index 000000000..5d6fd626f --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/integration_test/function_calling_test.dart @@ -0,0 +1,143 @@ +// End-to-end check of a tool-calling turn on a real device or desktop. +// +// Downloads Gemma 4 E2B (2.59 GB, ungated — no Hugging Face token), opens one +// chat with all three declarations and thinking on, and asks a question whose +// answer the model cannot produce on its own. The claim under test is the +// codelab's thesis: the model asks, the app answers, and the number in the +// reply is the one YOUR function computed. +// +// Not part of CI (needs a device and a 2.59 GB download): +// flutter test integration_test/function_calling_test.dart -d +import 'package:flutter/foundation.dart'; +import 'package:flutter_gemma/flutter_gemma.dart'; +import 'package:flutter_gemma_litertlm/flutter_gemma_litertlm.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:integration_test/integration_test.dart'; + +import 'package:gemma_quickstart/model.dart'; +import 'package:gemma_quickstart/tools.dart'; + +/// Downloads the model if it is not here, and makes it the active one either +/// way. `install()` is idempotent, so a second run costs nothing. +Future _install(ModelChoice model) async { + var last = -1; + await model + .locate( + FlutterGemma.installModel( + modelType: model.modelType, + fileType: ModelFileType.litertlm, + ), + ) + .withProgress((p) { + if (p >= last + 25) { + last = p; + debugPrint('[function-calling] download $p%'); + } + }) + .install(); +} + +void main() { + IntegrationTestWidgetsFlutterBinding.ensureInitialized(); + + testWidgets('the model asks, the app answers, the number is the app\'s', ( + tester, + ) async { + await FlutterGemma.initialize(inferenceEngines: [LiteRtLmEngine()]); + + const model = Models.gemma4; + await _install(model); + expect(await FlutterGemma.isModelInstalled(model.fileName), isTrue); + + // Nothing tool-related on this call: tools belong to the session. + final inference = await FlutterGemma.getActiveModel(maxTokens: 4096); + final chat = await inference.createChat( + modelType: model.modelType, + tools: toolbox, + supportsFunctionCalls: true, + toolChoice: ToolChoice.auto, + isThinking: model.supportsThinking, + maxOutputTokens: 512, + ); + + // A cap below 1 would answer the staged turn with nothing and close the + // stream — indistinguishable from a model with nothing to say. The SDK + // refuses instead, and it refuses before it generates, so this costs no + // tokens and disturbs no history. + await expectLater( + chat + .generateChatResponseWithTools( + onToolCall: (_) async => const {}, + maxToolTurns: 0, + ) + .toList(), + throwsA(isA()), + ); + + await chat.addQueryChunk( + Message.text( + text: 'What is 1234 times 5678? Use your tools.', + isUser: true, + ), + ); + + final calls = []; + final results = >[]; + final reply = StringBuffer(); + final thought = StringBuffer(); + + await for (final chunk in chat.generateChatResponseWithTools( + onToolCall: (call) async { + calls.add(call); + final result = runTool(call); + results.add(result); + debugPrint('[function-calling] ${call.name}(${call.args}) -> $result'); + return result; + }, + maxToolTurns: 6, + )) { + switch (chunk) { + case TextResponse(:final token): + reply.write(token); + case ThinkingResponse(:final content): + thought.write(content); + case FunctionCallResponse() || ParallelFunctionCallResponse(): + fail('the loop must consume calls itself, not yield them'); + } + } + + debugPrint('[function-calling] thinking: ${thought.toString().trim()}'); + debugPrint('[function-calling] reply: ${reply.toString().trim()}'); + + // The loop ran at least one round, and it ran the tool the question needs. + expect(calls, isNotEmpty, reason: 'the model never asked for a tool'); + final multiplied = calls.indexWhere((c) => c.name == 'multiply'); + expect(multiplied, isNot(-1), reason: 'multiply was never called'); + + // Ground truth, taken from the call the model actually made rather than + // from what it was asked: `isNotEmpty` on the reply would not tell a model + // that used the tool from one that invented a plausible number and ignored + // it. Whatever arguments it chose, the product in the reply must be the + // one THIS app computed for them. + final product = results[multiplied]['result']; + expect(product, isNotNull, reason: 'multiply returned an error map'); + // Models write large numbers with separators; the digits are the claim. + final digits = reply.toString().replaceAll(RegExp(r'[,\s_]'), ''); + expect(digits, contains('$product')); + + await inference.close(); + }, timeout: const Timeout(Duration(minutes: 60))); + + // No model, no device: the app's half of the loop is plain Dart and can be + // checked without any of it. + test('a name the app never declared is answered, not thrown', () { + final answer = runTool( + const FunctionCallResponse(name: 'launch_rocket', args: {}), + ); + expect(answer['error'], contains('launch_rocket')); + }); + + test('multiply is exact where a small model is not', () { + expect(runMultiply({'a': '1234', 'b': '5678'}), {'result': 7006652}); + }); +} diff --git a/codelabs/function-calling-flutter-gemma/complete/ios/.gitignore b/codelabs/function-calling-flutter-gemma/complete/ios/.gitignore new file mode 100644 index 000000000..7a7f9873a --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/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/codelabs/function-calling-flutter-gemma/complete/ios/Flutter/AppFrameworkInfo.plist b/codelabs/function-calling-flutter-gemma/complete/ios/Flutter/AppFrameworkInfo.plist new file mode 100644 index 000000000..391a902b2 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/ios/Flutter/AppFrameworkInfo.plist @@ -0,0 +1,24 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + App + CFBundleIdentifier + io.flutter.flutter.app + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + App + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.0 + CFBundleSignature + ???? + CFBundleVersion + 1.0 + + diff --git a/codelabs/function-calling-flutter-gemma/complete/ios/Flutter/Debug.xcconfig b/codelabs/function-calling-flutter-gemma/complete/ios/Flutter/Debug.xcconfig new file mode 100644 index 000000000..ec97fc6f3 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/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/codelabs/function-calling-flutter-gemma/complete/ios/Flutter/Release.xcconfig b/codelabs/function-calling-flutter-gemma/complete/ios/Flutter/Release.xcconfig new file mode 100644 index 000000000..c4855bfe2 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/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/codelabs/function-calling-flutter-gemma/complete/ios/Podfile b/codelabs/function-calling-flutter-gemma/complete/ios/Podfile new file mode 100644 index 000000000..9d7ef08d5 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/ios/Podfile @@ -0,0 +1,43 @@ +# Uncomment this line to define a global platform for your project +# platform :ios, '15.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/codelabs/function-calling-flutter-gemma/complete/ios/Runner.xcodeproj/project.pbxproj b/codelabs/function-calling-flutter-gemma/complete/ios/Runner.xcodeproj/project.pbxproj new file mode 100644 index 000000000..249dc6542 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/ios/Runner.xcodeproj/project.pbxproj @@ -0,0 +1,655 @@ +// !$*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 */; }; + 7884E8682EC3CC0700C636F2 /* SceneDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7884E8672EC3CC0400C636F2 /* SceneDelegate.swift */; }; + 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */ = {isa = PBXBuildFile; productRef = 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */; }; + 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 = ""; }; + 7884E8672EC3CC0400C636F2 /* SceneDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SceneDelegate.swift; sourceTree = ""; }; + 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */ = {isa = PBXFileReference; lastKnownFileType = wrapper; name = FlutterGeneratedPluginSwiftPackage; path = Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage; 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 = ""; }; + C0DE1AB52ED000000000E17E /* Runner.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = Runner.entitlements; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 97C146EB1CF9000F007C117D /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 331C8082294A63A400263BE5 /* RunnerTests */ = { + isa = PBXGroup; + children = ( + 331C807B294A618700263BE5 /* RunnerTests.swift */, + ); + path = RunnerTests; + sourceTree = ""; + }; + 9740EEB11CF90186004384FC /* Flutter */ = { + isa = PBXGroup; + children = ( + 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */, + 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 */, + C0DE1AB52ED000000000E17E /* Runner.entitlements */, + 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */, + 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */, + 74858FAE1ED2DC5600515810 /* AppDelegate.swift */, + 7884E8672EC3CC0400C636F2 /* SceneDelegate.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; + packageProductDependencies = ( + 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */, + ); + 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; + packageReferences = ( + 781AD8BC2B33823900A9FFBB /* XCLocalSwiftPackageReference "Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage" */, + ); + 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 */, + 7884E8682EC3CC0700C636F2 /* SceneDelegate.swift 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 = 15.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + STRING_CATALOG_GENERATE_SYMBOLS = YES; + 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; + CODE_SIGN_ENTITLEMENTS = Runner/Runner.entitlements; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + DEVELOPMENT_TEAM = 6ZHF6A3G28; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = dev.fluttergemma.functioncalling; + 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 = dev.fluttergemma.functioncalling.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 = dev.fluttergemma.functioncalling.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 = dev.fluttergemma.functioncalling.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 = 15.0; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = iphoneos; + STRING_CATALOG_GENERATE_SYMBOLS = YES; + 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 = 15.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + STRING_CATALOG_GENERATE_SYMBOLS = YES; + 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; + CODE_SIGN_ENTITLEMENTS = Runner/Runner.entitlements; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + DEVELOPMENT_TEAM = 6ZHF6A3G28; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = dev.fluttergemma.functioncalling; + 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; + CODE_SIGN_ENTITLEMENTS = Runner/Runner.entitlements; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + DEVELOPMENT_TEAM = 6ZHF6A3G28; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = dev.fluttergemma.functioncalling; + 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 */ + +/* Begin XCLocalSwiftPackageReference section */ + 781AD8BC2B33823900A9FFBB /* XCLocalSwiftPackageReference "Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage" */ = { + isa = XCLocalSwiftPackageReference; + relativePath = Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage; + }; +/* End XCLocalSwiftPackageReference section */ + +/* Begin XCSwiftPackageProductDependency section */ + 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */ = { + isa = XCSwiftPackageProductDependency; + productName = FlutterGeneratedPluginSwiftPackage; + }; +/* End XCSwiftPackageProductDependency section */ + }; + rootObject = 97C146E61CF9000F007C117D /* Project object */; +} diff --git a/codelabs/function-calling-flutter-gemma/complete/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/codelabs/function-calling-flutter-gemma/complete/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata new file mode 100644 index 000000000..919434a62 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/codelabs/function-calling-flutter-gemma/complete/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/codelabs/function-calling-flutter-gemma/complete/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 000000000..18d981003 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/codelabs/function-calling-flutter-gemma/complete/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/codelabs/function-calling-flutter-gemma/complete/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings new file mode 100644 index 000000000..f9b0d7c5e --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings @@ -0,0 +1,8 @@ + + + + + PreviewsEnabled + + + diff --git a/codelabs/function-calling-flutter-gemma/complete/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/codelabs/function-calling-flutter-gemma/complete/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme new file mode 100644 index 000000000..c3fedb29c --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -0,0 +1,119 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/codelabs/function-calling-flutter-gemma/complete/ios/Runner.xcworkspace/contents.xcworkspacedata b/codelabs/function-calling-flutter-gemma/complete/ios/Runner.xcworkspace/contents.xcworkspacedata new file mode 100644 index 000000000..1d526a16e --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/ios/Runner.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/codelabs/function-calling-flutter-gemma/complete/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/codelabs/function-calling-flutter-gemma/complete/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 000000000..18d981003 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/codelabs/function-calling-flutter-gemma/complete/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/codelabs/function-calling-flutter-gemma/complete/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings new file mode 100644 index 000000000..f9b0d7c5e --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings @@ -0,0 +1,8 @@ + + + + + PreviewsEnabled + + + diff --git a/codelabs/function-calling-flutter-gemma/complete/ios/Runner/AppDelegate.swift b/codelabs/function-calling-flutter-gemma/complete/ios/Runner/AppDelegate.swift new file mode 100644 index 000000000..c30b367ec --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/ios/Runner/AppDelegate.swift @@ -0,0 +1,16 @@ +import Flutter +import UIKit + +@main +@objc class AppDelegate: FlutterAppDelegate, FlutterImplicitEngineDelegate { + override func application( + _ application: UIApplication, + didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? + ) -> Bool { + return super.application(application, didFinishLaunchingWithOptions: launchOptions) + } + + func didInitializeImplicitFlutterEngine(_ engineBridge: FlutterImplicitEngineBridge) { + GeneratedPluginRegistrant.register(with: engineBridge.pluginRegistry) + } +} diff --git a/codelabs/function-calling-flutter-gemma/complete/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json b/codelabs/function-calling-flutter-gemma/complete/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 000000000..d36b1fab2 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/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/codelabs/function-calling-flutter-gemma/complete/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png b/codelabs/function-calling-flutter-gemma/complete/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png new file mode 100644 index 000000000..dc9ada472 Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/complete/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png differ diff --git a/codelabs/function-calling-flutter-gemma/complete/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png b/codelabs/function-calling-flutter-gemma/complete/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png new file mode 100644 index 000000000..7353c41ec Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/complete/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png differ diff --git a/codelabs/function-calling-flutter-gemma/complete/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png b/codelabs/function-calling-flutter-gemma/complete/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png new file mode 100644 index 000000000..797d452e4 Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/complete/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png differ diff --git a/codelabs/function-calling-flutter-gemma/complete/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png b/codelabs/function-calling-flutter-gemma/complete/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png new file mode 100644 index 000000000..6ed2d933e Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/complete/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png differ diff --git a/codelabs/function-calling-flutter-gemma/complete/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png b/codelabs/function-calling-flutter-gemma/complete/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png new file mode 100644 index 000000000..4cd7b0099 Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/complete/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png differ diff --git a/codelabs/function-calling-flutter-gemma/complete/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png b/codelabs/function-calling-flutter-gemma/complete/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png new file mode 100644 index 000000000..fe730945a Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/complete/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png differ diff --git a/codelabs/function-calling-flutter-gemma/complete/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png b/codelabs/function-calling-flutter-gemma/complete/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png new file mode 100644 index 000000000..321773cd8 Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/complete/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png differ diff --git a/codelabs/function-calling-flutter-gemma/complete/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png b/codelabs/function-calling-flutter-gemma/complete/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png new file mode 100644 index 000000000..797d452e4 Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/complete/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png differ diff --git a/codelabs/function-calling-flutter-gemma/complete/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png b/codelabs/function-calling-flutter-gemma/complete/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png new file mode 100644 index 000000000..502f463a9 Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/complete/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png differ diff --git a/codelabs/function-calling-flutter-gemma/complete/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png b/codelabs/function-calling-flutter-gemma/complete/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png new file mode 100644 index 000000000..0ec303439 Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/complete/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png differ diff --git a/codelabs/function-calling-flutter-gemma/complete/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png b/codelabs/function-calling-flutter-gemma/complete/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png new file mode 100644 index 000000000..0ec303439 Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/complete/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png differ diff --git a/codelabs/function-calling-flutter-gemma/complete/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png b/codelabs/function-calling-flutter-gemma/complete/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png new file mode 100644 index 000000000..e9f5fea27 Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/complete/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png differ diff --git a/codelabs/function-calling-flutter-gemma/complete/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png b/codelabs/function-calling-flutter-gemma/complete/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png new file mode 100644 index 000000000..84ac32ae7 Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/complete/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png differ diff --git a/codelabs/function-calling-flutter-gemma/complete/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png b/codelabs/function-calling-flutter-gemma/complete/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png new file mode 100644 index 000000000..8953cba09 Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/complete/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png differ diff --git a/codelabs/function-calling-flutter-gemma/complete/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png b/codelabs/function-calling-flutter-gemma/complete/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png new file mode 100644 index 000000000..0467bf12a Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/complete/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png differ diff --git a/codelabs/function-calling-flutter-gemma/complete/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json b/codelabs/function-calling-flutter-gemma/complete/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json new file mode 100644 index 000000000..0bedcf2fd --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/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/codelabs/function-calling-flutter-gemma/complete/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png b/codelabs/function-calling-flutter-gemma/complete/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png new file mode 100644 index 000000000..9da19eaca Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/complete/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png differ diff --git a/codelabs/function-calling-flutter-gemma/complete/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png b/codelabs/function-calling-flutter-gemma/complete/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png new file mode 100644 index 000000000..9da19eaca Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/complete/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png differ diff --git a/codelabs/function-calling-flutter-gemma/complete/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png b/codelabs/function-calling-flutter-gemma/complete/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png new file mode 100644 index 000000000..9da19eaca Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/complete/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png differ diff --git a/codelabs/function-calling-flutter-gemma/complete/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md b/codelabs/function-calling-flutter-gemma/complete/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md new file mode 100644 index 000000000..89c2725b7 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/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/codelabs/function-calling-flutter-gemma/complete/ios/Runner/Base.lproj/LaunchScreen.storyboard b/codelabs/function-calling-flutter-gemma/complete/ios/Runner/Base.lproj/LaunchScreen.storyboard new file mode 100644 index 000000000..f2e259c7c --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/ios/Runner/Base.lproj/LaunchScreen.storyboard @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/codelabs/function-calling-flutter-gemma/complete/ios/Runner/Base.lproj/Main.storyboard b/codelabs/function-calling-flutter-gemma/complete/ios/Runner/Base.lproj/Main.storyboard new file mode 100644 index 000000000..f3c28516f --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/ios/Runner/Base.lproj/Main.storyboard @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/codelabs/function-calling-flutter-gemma/complete/ios/Runner/Info.plist b/codelabs/function-calling-flutter-gemma/complete/ios/Runner/Info.plist new file mode 100644 index 000000000..c97226dba --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/ios/Runner/Info.plist @@ -0,0 +1,70 @@ + + + + + CADisableMinimumFrameDurationOnPhone + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleDisplayName + Gemma Function Calling + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + functioncalling + CFBundlePackageType + APPL + CFBundleShortVersionString + $(FLUTTER_BUILD_NAME) + CFBundleSignature + ???? + CFBundleVersion + $(FLUTTER_BUILD_NUMBER) + LSRequiresIPhoneOS + + UIApplicationSceneManifest + + UIApplicationSupportsMultipleScenes + + UISceneConfigurations + + UIWindowSceneSessionRoleApplication + + + UISceneClassName + UIWindowScene + UISceneConfigurationName + flutter + UISceneDelegateClassName + $(PRODUCT_MODULE_NAME).SceneDelegate + UISceneStoryboardFile + Main + + + + + UIApplicationSupportsIndirectInputEvents + + UILaunchStoryboardName + LaunchScreen + UIMainStoryboardFile + Main + UISupportedInterfaceOrientations + + UIInterfaceOrientationPortrait + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + UISupportedInterfaceOrientations~ipad + + UIInterfaceOrientationPortrait + UIInterfaceOrientationPortraitUpsideDown + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + + diff --git a/codelabs/function-calling-flutter-gemma/complete/ios/Runner/Runner-Bridging-Header.h b/codelabs/function-calling-flutter-gemma/complete/ios/Runner/Runner-Bridging-Header.h new file mode 100644 index 000000000..308a2a560 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/ios/Runner/Runner-Bridging-Header.h @@ -0,0 +1 @@ +#import "GeneratedPluginRegistrant.h" diff --git a/codelabs/function-calling-flutter-gemma/complete/ios/Runner/Runner.entitlements b/codelabs/function-calling-flutter-gemma/complete/ios/Runner/Runner.entitlements new file mode 100644 index 000000000..cd461aae4 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/ios/Runner/Runner.entitlements @@ -0,0 +1,12 @@ + + + + + com.apple.developer.kernel.extended-virtual-addressing + + com.apple.developer.kernel.increased-memory-limit + + com.apple.developer.kernel.increased-debugging-memory-limit + + + diff --git a/codelabs/function-calling-flutter-gemma/complete/ios/Runner/SceneDelegate.swift b/codelabs/function-calling-flutter-gemma/complete/ios/Runner/SceneDelegate.swift new file mode 100644 index 000000000..b9ce8ea2b --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/ios/Runner/SceneDelegate.swift @@ -0,0 +1,6 @@ +import Flutter +import UIKit + +class SceneDelegate: FlutterSceneDelegate { + +} diff --git a/codelabs/function-calling-flutter-gemma/complete/ios/RunnerTests/RunnerTests.swift b/codelabs/function-calling-flutter-gemma/complete/ios/RunnerTests/RunnerTests.swift new file mode 100644 index 000000000..86a7c3b1b --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/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/codelabs/function-calling-flutter-gemma/complete/lib/chat_page.dart b/codelabs/function-calling-flutter-gemma/complete/lib/chat_page.dart new file mode 100644 index 000000000..ab730b348 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/lib/chat_page.dart @@ -0,0 +1,640 @@ +import 'dart:convert'; + +import 'package:flutter/material.dart'; +import 'package:flutter_gemma/flutter_gemma.dart'; + +import 'model.dart'; +import 'tools.dart'; + +/// What a line in the transcript is. +/// +/// A chat with tools has five kinds of turn, not two. Showing only the first +/// and the last of them is how a tool-calling app becomes impossible to debug: +/// the answer is right or wrong and nothing on screen says which function +/// produced it, with which arguments, or what the model was thinking when it +/// chose. +enum _TurnKind { user, thinking, model, toolCall, toolResult } + +/// How many generations one message is allowed to cost. +/// +/// The loop stops when a turn comes back with no calls in it — a promise about +/// the model, not about the code — so a model that keeps asking would +/// otherwise run until the context window filled. Six is enough for a question +/// that chains three calls and small enough that a stuck model is over in +/// seconds. Below 1 is a `RangeError`, thrown on purpose: a cap of zero would +/// answer the message with nothing and close the stream, which looks exactly +/// like a model that had nothing to say. +const _maxToolTurns = 6; + +/// The finished app: three tools, a loop the SDK drives, and two session +/// settings you can change while it is running. +class ChatPage extends StatefulWidget { + const ChatPage({ + super.key, + required this.model, + required this.onModelRemoved, + }); + + final ModelChoice model; + + /// Lets the gate send the app back to the model list. + final VoidCallback onModelRemoved; + + @override + State createState() => _ChatPageState(); +} + +class _ChatPageState extends State { + final _input = TextEditingController(); + final _turns = <_Turn>[]; + + InferenceModel? _inference; + InferenceChat? _chat; + bool _busy = false; + Object? _loadError; + String? _notice; + + /// Both of these are SESSION settings, fixed for a chat's lifetime — which + /// is why changing either one closes the chat and opens a new one, and why + /// the transcript goes with it. + ToolChoice _toolChoice = ToolChoice.auto; + late bool _thinking = widget.model.supportsThinking; + + /// Where the CURRENT generation is writing, and what it has written. + /// + /// One message can produce several generations with tool calls between them, + /// so "the reply" is not "the last bubble": running a tool appends two lines + /// and starts a fresh bubble underneath them. Thinking gets its own index + /// because it arrives interleaved with the text and belongs above it. + final _reply = StringBuffer(); + final _thought = StringBuffer(); + int _replyAt = -1; + int _thinkAt = -1; + + @override + void initState() { + super.initState(); + _load(); + } + + Future _load() async { + try { + // maxTokens is the CONTEXT WINDOW — prompt + history + reply share it. + // It is NOT a reply-length cap; for that, pass maxOutputTokens below. + // Three declarations, every call and every tool response all live in + // this budget for the rest of the conversation, and thinking is spent + // out of it too. + // + // Note what this call does NOT take: `tools`. Unlike the modality flags + // of the multimodal codelab there is nothing to set in two places — + // `getActiveModel` builds the engine, and nothing about the weights + // changes when you declare a function. + final inference = await FlutterGemma.getActiveModel(maxTokens: 4096); + // Hold the runtime before opening a chat on it: `createChat` can throw, + // and a model this page never stored is a model `dispose` can never + // close. A page that is already gone holds nothing, so it closes it here. + if (!mounted) { + await inference.close(); + return; + } + setState(() => _inference = inference); + + final chat = await _openChat(inference); + // The same guard, one call later and for the same reason: a chat this + // page never stored is a native session `dispose` can never close. + if (!mounted) { + await chat.close(); + return; + } + setState(() => _chat = chat); + } catch (error) { + // Loading is the likeliest thing to fail on a real device: a forgotten + // engine package, too little memory, a half-written model file. Show it + // instead of sitting on the progress bar forever. + if (mounted) setState(() => _loadError = error); + } + } + + /// The session, with everything that is per-session on it. + Future _openChat(InferenceModel inference) => + inference.createChat( + // Which family's call syntax the SDK writes and reads. + modelType: widget.model.modelType, + // Three declarations now instead of one. Nothing else in this file + // changed to add the second and third: the loop dispatches by name. + tools: toolbox, + supportsFunctionCalls: true, + // Whether the model may, must, or must not call — and how much of that + // lands depends on who renders the declarations. On FunctionGemma the + // SDK renders them into the prompt, so `none` leaves them out and the + // model never learns the tools exist. On Gemma 4 the runtime renders + // them from `tools_json`, which `createChat` passes whatever you + // choose here — so `none` cannot take them back out. What it does + // switch off there is the SDK's suppression of tool-call JSON, which + // is why a call made under `none` can arrive as raw JSON in the bubble. + toolChoice: _toolChoice, + // Reason first, then answer. On weights with no thinking training this + // buys nothing, which is why the switch is disabled for those. + isThinking: _thinking, + // Thinking is generated text and comes out of the same budget as the + // answer, so a reasoning turn needs more room than a plain one. + maxOutputTokens: _thinking ? 512 : 256, + ); + + void _retryLoad() { + setState(() => _loadError = null); + _load(); + } + + /// Rebuilds the session because a session setting changed. + /// + /// There is no way to change `toolChoice` or `isThinking` on a live chat: + /// both are decided when the session is created — one renders the + /// declarations into the prompt, the other switches on a generation channel + /// — so the honest thing is to close this one and open another. The + /// transcript goes with it, because the new session's history is empty and a + /// transcript that survived would be describing a conversation the model can + /// no longer remember. + Future _reopenChat({ToolChoice? choice, bool? thinking}) async { + final inference = _inference; + final old = _chat; + if (inference == null || _busy) return; + + setState(() { + if (choice != null) _toolChoice = choice; + if (thinking != null) _thinking = thinking; + _chat = null; // disables the composer while the session is rebuilt + _turns.clear(); + _notice = + _toolChoice == ToolChoice.required && + !widget.model.supportsRequiredToolChoice + ? '${widget.model.label} cannot be forced to call a tool — nothing ' + 'in the prompt it is given can say "you must", so `required` ' + 'behaves as "auto".' + : null; + }); + + try { + await old?.close(); + final chat = await _openChat(inference); + if (!mounted) { + await chat.close(); + return; + } + setState(() => _chat = chat); + } catch (error) { + if (mounted) setState(() => _loadError = error); + } + } + + /// One message, however many generations it takes. + Future _send() async { + final chat = _chat; + final text = _input.text.trim(); + if (chat == null || text.isEmpty || _busy) return; + + setState(() { + _turns + ..add(_Turn(text, kind: _TurnKind.user)) + // The reply starts empty and grows as chunks arrive. + ..add(const _Turn('', kind: _TurnKind.model)); + _replyAt = _turns.length - 1; + _thinkAt = -1; + _reply.clear(); + _thought.clear(); + _input.clear(); + _notice = null; + _busy = true; + }); + + var hitCap = false; + try { + // The staged user message is a PRECONDITION, exactly as it is for + // `generateChatResponseAsync` — the loop drives generation, it does not + // send your turn for you. + await chat.addQueryChunk(Message.text(text: text, isUser: true)); + + await for (final chunk in chat.generateChatResponseWithTools( + onToolCall: _onToolCall, + maxToolTurns: _maxToolTurns, + // Called once, if the loop runs out of turns with calls still coming. + // Without it the reply is quietly empty or half-written and nothing + // says the cap is why. + onMaxToolTurns: () => hitCap = true, + )) { + switch (chunk) { + case TextResponse(:final token): + // Each TextResponse carries only the NEW text, not the whole reply + // so far — append, never replace. + _reply.write(token); + if (mounted) { + setState( + () => _turns[_replyAt] = _Turn( + _reply.toString(), + kind: _TurnKind.model, + ), + ); + } + case ThinkingResponse(:final content): + // These reach the stream only because the chat was opened with + // `isThinking: true`; with it false the SDK drops them before this + // loop ever sees one. + _thought.write(content); + if (mounted) setState(_paintThinking); + case FunctionCallResponse() || ParallelFunctionCallResponse(): + // Never arrives here: the loop consumes calls itself and passes + // only text and thinking through. The branch keeps the switch + // exhaustive over the sealed `ModelResponse`, so a case added to + // the SDK fails to compile instead of being treated as silence. + break; + } + } + + if (hitCap && mounted) { + setState( + () => _notice = + 'The model was still asking for tools after $_maxToolTurns ' + 'turns, so the loop stopped. The answer above may be missing ' + 'or cut short.', + ); + } + } catch (error) { + // The half-written reply becomes the error, so the empty bubble never + // just sits there. The SDK has already answered every call it committed + // before rethrowing, so the chat is still usable for the next message. + if (mounted) { + setState(() { + _reply.write('⚠️ $error'); + _turns[_replyAt] = _Turn(_reply.toString(), kind: _TurnKind.model); + }); + } + } finally { + // `_busy` is what disables the composer, so clearing it belongs in + // `finally` — a failed generation must not lock the app. + if (mounted) { + setState(() { + _dropEmptyReply(); + _replyAt = -1; + _thinkAt = -1; + _busy = false; + }); + } + } + } + + /// Puts the thinking above the answer it led to. + /// + /// The first thinking chunk of a generation inserts a bubble in front of the + /// reply rather than appending one, because the model reasons before it + /// speaks and a transcript that shows it afterwards reads backwards. + void _paintThinking() { + if (_thinkAt < 0) { + _turns.insert(_replyAt, const _Turn('', kind: _TurnKind.thinking)); + _thinkAt = _replyAt; + _replyAt += 1; + } + _turns[_thinkAt] = _Turn(_thought.toString(), kind: _TurnKind.thinking); + } + + /// Removes the reply bubble if this generation never wrote into it. + /// + /// A call-only turn produces no text, and an empty bubble reads as a model + /// that said nothing when in fact it asked a question. + void _dropEmptyReply() { + if (_reply.isEmpty && _replyAt >= 0 && _replyAt == _turns.length - 1) { + _turns.removeAt(_replyAt); + } + } + + /// Runs one call and shows it. The return value is what the model sees. + /// + /// This callback is the whole of the app's half of the loop. Everything + /// around it — collecting the calls, staging the responses, deciding whether + /// to generate again — is in the SDK. And it dispatches by NAME, which is + /// why the second and third tool cost this file nothing. + Future> _onToolCall(FunctionCallResponse call) async { + final result = runTool(call); + if (mounted) { + setState(() { + _dropEmptyReply(); + _turns + ..add(_Turn(_describeCall(call), kind: _TurnKind.toolCall)) + ..add(_Turn(jsonEncode(result), kind: _TurnKind.toolResult)) + // The next generation writes underneath the work it was given, + // not above it. + ..add(const _Turn('', kind: _TurnKind.model)); + _replyAt = _turns.length - 1; + _thinkAt = -1; + _reply.clear(); + _thought.clear(); + }); + } + return result; + } + + String _describeCall(FunctionCallResponse call) { + final args = call.args.entries + .map((e) => '${e.key}: ${e.value}') + .join(', '); + return '${call.name}($args)'; + } + + /// Forgets the model. For a downloaded one that frees the disk; for a file + /// you opened from disk it does NOT — `uninstallModel` deliberately leaves a + /// `FileSource` alone, because the app never owned that file. The model you + /// tuned survives being removed here. + /// + /// Close the runtime first either way: the file is mapped while a model is + /// open, and deleting it underneath the engine is a crash waiting to happen. + Future _removeModel() async { + try { + await _inference?.close(); + // Inside `setState`: dropping the chat has to repaint, or the screen + // keeps showing an enabled composer over a runtime that is gone. + if (mounted) { + setState(() { + _inference = null; + _chat = null; + }); + } + await FlutterGemma.uninstallModel(widget.model.fileName); + if (mounted) widget.onModelRemoved(); + } catch (error) { + // Deleting can fail too — a missing install record, a file the OS still + // holds. Show it the way a failed load is shown, and drop the chat with + // it: a `close()` that threw leaves `_chat` non-null, and "The model did + // not load." over a working composer is a lie. + if (mounted) { + setState(() { + _chat = null; + _loadError = error; + }); + } + } + } + + @override + void dispose() { + // Sessions and models hold native memory — always close them. `dispose` + // cannot await, so the future is dropped on purpose, and caught so a + // failing native teardown does not escape as an unhandled async error. + _inference?.close().catchError((Object _) {}); + _input.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final ready = _chat != null; + final error = _loadError; + final settable = ready && !_busy; + + return Scaffold( + appBar: AppBar( + title: Text(widget.model.label), + bottom: PreferredSize( + preferredSize: const Size.fromHeight(20), + child: Padding( + padding: const EdgeInsets.only(bottom: 6), + child: Text( + '${toolbox.length} tools · ' + '${toolbox.map((t) => t.name).join(', ')}', + style: theme.textTheme.labelSmall, + ), + ), + ), + actions: [ + IconButton( + tooltip: widget.model.path != null + ? 'Forget this model (the file stays where it is)' + : 'Delete the downloaded model', + // Not while the model is still opening: deleting the file + // underneath an in-flight `getActiveModel()` is the crash the + // comment on `_removeModel` warns about. + onPressed: _busy || (!ready && error == null) ? null : _removeModel, + icon: const Icon(Icons.delete_outline), + ), + ], + ), + body: Column( + children: [ + if (error != null) + _LoadFailed(error: error, onRetry: _retryLoad) + else if (!ready) + const LinearProgressIndicator(), + _SessionSettings( + model: widget.model, + toolChoice: _toolChoice, + thinking: _thinking, + enabled: settable, + onToolChoice: (v) => _reopenChat(choice: v), + onThinking: (v) => _reopenChat(thinking: v), + ), + Expanded( + child: ListView.builder( + padding: const EdgeInsets.all(16), + itemCount: _turns.length, + itemBuilder: (context, i) => _Bubble(turn: _turns[i]), + ), + ), + if (_notice case final notice?) + Padding( + padding: const EdgeInsets.fromLTRB(16, 0, 16, 8), + child: Text( + notice, + style: theme.textTheme.bodySmall?.copyWith( + color: theme.colorScheme.error, + ), + ), + ), + SafeArea( + child: Padding( + padding: const EdgeInsets.fromLTRB(12, 0, 12, 12), + child: Row( + children: [ + Expanded( + child: TextField( + controller: _input, + enabled: ready && !_busy, + onSubmitted: (_) => _send(), + decoration: InputDecoration( + hintText: ready + ? 'Try: what time is it, and what is 47 times 89?' + : error != null + ? 'No model loaded' + : 'Loading the model…', + border: const OutlineInputBorder(), + ), + ), + ), + const SizedBox(width: 8), + IconButton.filled( + onPressed: ready && !_busy ? _send : null, + icon: const Icon(Icons.send), + ), + ], + ), + ), + ), + ], + ), + ); + } +} + +/// The two settings that belong to the session rather than to the message. +/// +/// They are here, above the transcript, rather than in a settings screen, +/// because changing one throws the conversation away — and a control that +/// does that should be visible while you use it. +class _SessionSettings extends StatelessWidget { + const _SessionSettings({ + required this.model, + required this.toolChoice, + required this.thinking, + required this.enabled, + required this.onToolChoice, + required this.onThinking, + }); + + final ModelChoice model; + final ToolChoice toolChoice; + final bool thinking; + final bool enabled; + final ValueChanged onToolChoice; + final ValueChanged onThinking; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + return SingleChildScrollView( + scrollDirection: Axis.horizontal, + padding: const EdgeInsets.fromLTRB(12, 8, 12, 0), + child: Row( + children: [ + SegmentedButton( + segments: const [ + ButtonSegment(value: ToolChoice.auto, label: Text('auto')), + ButtonSegment( + value: ToolChoice.required, + label: Text('required'), + ), + ButtonSegment(value: ToolChoice.none, label: Text('none')), + ], + selected: {toolChoice}, + showSelectedIcon: false, + onSelectionChanged: enabled + ? (selection) => onToolChoice(selection.first) + : null, + ), + const SizedBox(width: 16), + Text('thinking', style: theme.textTheme.labelLarge), + Switch( + value: thinking, + // Not a greyed-out control with no explanation: the tooltip names + // the side that refused, the way the multimodal codelab's + // capability line does. + onChanged: enabled && model.supportsThinking ? onThinking : null, + ), + if (!model.supportsThinking) + Text( + '${model.label} does not reason out loud', + style: theme.textTheme.labelSmall, + ), + ], + ), + ); + } +} + +/// Shown in place of the loading bar when the model could not be opened. +class _LoadFailed extends StatelessWidget { + const _LoadFailed({required this.error, required this.onRetry}); + + final Object error; + final VoidCallback onRetry; + + @override + Widget build(BuildContext context) { + return Padding( + padding: const EdgeInsets.all(16), + child: Column( + children: [ + Text('The model did not load.\n$error', textAlign: TextAlign.center), + const SizedBox(height: 8), + FilledButton(onPressed: onRetry, child: const Text('Try again')), + ], + ), + ); + } +} + +class _Turn { + const _Turn(this.text, {required this.kind}); + + final String text; + final _TurnKind kind; +} + +/// One line of the transcript, drawn so the five kinds are told apart at a +/// glance. The three middle ones are the point of this screen. +class _Bubble extends StatelessWidget { + const _Bubble({required this.turn}); + + final _Turn turn; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final scheme = theme.colorScheme; + final (label, colour) = switch (turn.kind) { + _TurnKind.user => (null, scheme.primaryContainer), + _TurnKind.model => (null, scheme.surfaceContainerHighest), + _TurnKind.thinking => ('thinking', scheme.surfaceContainerLow), + _TurnKind.toolCall => ('the model asked for', scheme.tertiaryContainer), + _TurnKind.toolResult => ( + 'your function answered', + scheme.secondaryContainer, + ), + }; + return Align( + alignment: turn.kind == _TurnKind.user + ? Alignment.centerRight + : Alignment.centerLeft, + child: Container( + margin: const EdgeInsets.symmetric(vertical: 4), + padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10), + constraints: const BoxConstraints(maxWidth: 520), + decoration: BoxDecoration( + color: colour, + borderRadius: BorderRadius.circular(12), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + if (label != null) ...[ + Text(label, style: theme.textTheme.labelSmall), + const SizedBox(height: 4), + ], + SelectableText( + turn.text, + style: switch (turn.kind) { + _TurnKind.toolCall || _TurnKind.toolResult => + theme.textTheme.bodyMedium?.copyWith(fontFamily: 'monospace'), + // Reasoning is not the answer, and it should not be read as + // one: same size, quieter. + _TurnKind.thinking => theme.textTheme.bodySmall?.copyWith( + fontStyle: FontStyle.italic, + color: scheme.onSurfaceVariant, + ), + _ => null, + }, + ), + ], + ), + ), + ); + } +} diff --git a/codelabs/function-calling-flutter-gemma/complete/lib/download_page.dart b/codelabs/function-calling-flutter-gemma/complete/lib/download_page.dart new file mode 100644 index 000000000..b08e885bc --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/lib/download_page.dart @@ -0,0 +1,154 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_gemma/flutter_gemma.dart'; + +import 'model.dart'; + +/// Installs the model, reporting progress as it goes. +/// +/// Nothing here knows about tools: `installModel` takes the model's identity +/// (what it is) and the source says where the bytes are. A function-calling +/// model installs exactly like a text one — tools are a property of the +/// SESSION you open later, not of the file you install. +/// +/// And nothing here knows whether the bytes travel: [ModelChoice.locate] +/// picks `fromNetwork` or `fromFile`, and a file already on disk finishes at +/// 100% immediately because there is nothing to fetch. +class DownloadPage extends StatefulWidget { + const DownloadPage({ + super.key, + required this.model, + required this.onInstalled, + }); + + final ModelChoice model; + + /// Called once the model is installed, so the app can move on. + final VoidCallback onInstalled; + + @override + State createState() => _DownloadPageState(); +} + +class _DownloadPageState extends State { + int _percent = 0; + bool _downloading = false; + Object? _error; + + Future _install() async { + setState(() { + _downloading = true; + _error = null; + }); + + try { + await widget.model + .locate( + FlutterGemma.installModel( + // What the model IS — used to pick the right chat template and + // the right function-call format. + modelType: widget.model.modelType, + // Which runtime reads it. `.litertlm` routes to LiteRtLmEngine; + // the default is `task` (MediaPipe), so this line is load-bearing. + fileType: ModelFileType.litertlm, + ), + ) + .withProgress((percent) { + if (mounted) setState(() => _percent = percent); + }) + .install(); + + if (mounted) widget.onInstalled(); + } catch (error) { + if (mounted) setState(() => _error = error); + } finally { + if (mounted) setState(() => _downloading = false); + } + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final fromDisk = widget.model.path != null; + + return Scaffold( + appBar: AppBar(title: Text(fromDisk ? 'Use this file' : 'Get the model')), + body: Center( + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 420), + child: Padding( + padding: const EdgeInsets.all(24), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Text(widget.model.label, style: theme.textTheme.headlineSmall), + const SizedBox(height: 8), + Text( + fromDisk + ? '${widget.model.path}\n\nNothing is copied. The app ' + 'records where this file is and opens it there.' + : '${widget.model.sizeLabel} — downloaded once, then it ' + 'lives on the device and runs with the network ' + 'off.', + style: theme.textTheme.bodyMedium, + ), + const SizedBox(height: 24), + if (_downloading) ...[ + LinearProgressIndicator(value: _percent / 100), + const SizedBox(height: 8), + Text('$_percent%', textAlign: TextAlign.center), + ] else + FilledButton( + onPressed: _install, + child: Text(fromDisk ? 'Open it' : 'Download model'), + ), + if (_error != null) ...[ + const SizedBox(height: 16), + _ErrorCard(error: _error!), + ], + ], + ), + ), + ), + ), + ); + } +} + +/// Says what failed, in the plugin's own words where it has any. +class _ErrorCard extends StatelessWidget { + const _ErrorCard({required this.error}); + + final Object error; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + // The plugin reports a failed download as a typed `DownloadException` + // wrapping a sealed `DownloadError`, so match on the type rather than + // sniffing the message for a status code. A file that is not there is not + // a download at all, and falls through to the second branch. + final (title, body) = switch (error) { + DownloadException(:final error) => ( + 'Download failed', + error.toUserMessage(), + ), + _ => ('Could not install the model', '$error'), + }; + + return Card( + color: theme.colorScheme.errorContainer, + child: Padding( + padding: const EdgeInsets.all(16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(title, style: theme.textTheme.titleSmall), + const SizedBox(height: 8), + Text(body), + ], + ), + ), + ); + } +} diff --git a/codelabs/function-calling-flutter-gemma/complete/lib/main.dart b/codelabs/function-calling-flutter-gemma/complete/lib/main.dart new file mode 100644 index 000000000..d6fc01d8d --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/lib/main.dart @@ -0,0 +1,71 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_gemma/flutter_gemma.dart'; +import 'package:flutter_gemma_litertlm/flutter_gemma_litertlm.dart'; + +import 'models_page.dart'; + +Future main() async { + WidgetsFlutterBinding.ensureInitialized(); + + // Engines are fully opt-in: the core package registers none by itself. + // Without LiteRtLmEngine here, the first model call throws a StateError + // that tells you to add an engine package. + // + // No `huggingFaceToken:` — both repositories this app downloads from are + // ungated, so every `flutter run` is a plain `flutter run` with no + // `--dart-define`. + // + // Guarded, because every other failure in this app reaches the screen — the + // gate's error card, the chat's load error, the notice line — and this is the + // earliest one, so it is the one a learner meets first. Hot-restarting after + // adding a plugin throws `MissingPluginException` right here; unguarded, it + // never reaches `runApp` and the symptom is a blank window and a stack trace + // in a console nobody is looking at. + try { + await FlutterGemma.initialize(inferenceEngines: [LiteRtLmEngine()]); + } catch (error) { + runApp(_StartupFailed(error: error)); + return; + } + + runApp(const FunctionCallingApp()); +} + +/// Shown in place of the app when `FlutterGemma.initialize` throws, so a +/// failure before the first frame is a sentence instead of a blank window. +class _StartupFailed extends StatelessWidget { + const _StartupFailed({required this.error}); + + final Object error; + + @override + Widget build(BuildContext context) { + return MaterialApp( + title: 'Gemma Function Calling', + home: Scaffold( + body: Center( + child: Padding( + padding: const EdgeInsets.all(24), + child: Text( + 'flutter_gemma could not start.\n$error', + textAlign: TextAlign.center, + ), + ), + ), + ), + ); + } +} + +class FunctionCallingApp extends StatelessWidget { + const FunctionCallingApp({super.key}); + + @override + Widget build(BuildContext context) { + return MaterialApp( + title: 'Gemma Function Calling', + theme: ThemeData(colorSchemeSeed: Colors.indigo), + home: const ModelsPage(), + ); + } +} diff --git a/codelabs/function-calling-flutter-gemma/complete/lib/model.dart b/codelabs/function-calling-flutter-gemma/complete/lib/model.dart new file mode 100644 index 000000000..e27fa3d85 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/lib/model.dart @@ -0,0 +1,143 @@ +import 'package:flutter_gemma/flutter_gemma.dart'; + +/// One model this app knows how to install. +/// +/// [fileName] doubles as the model's id: `FlutterGemma.isModelInstalled` takes +/// the file name the model was installed under, not a display name. +/// +/// Exactly one of [url] and [path] is set. A downloaded model has a URL; a +/// model you built yourself in Step 4 has a path on this machine, and nothing +/// else about it is different — which is the point of that step. +class ModelChoice { + const ModelChoice({ + required this.label, + required this.fileName, + required this.modelType, + required this.sizeLabel, + required this.supportsThinking, + required this.supportsRequiredToolChoice, + this.url, + this.path, + }) : assert( + (url == null) != (path == null), + 'a model comes from a URL or from a file, not both and not neither', + ); + + /// A `.litertlm` already on this machine — the file `litetune convert` + /// wrote, or any other one. + /// + /// The family is fixed to FunctionGemma because that is what Step 4 + /// produces, and nothing on disk records which family a `.litertlm` belongs + /// to. Tune a different base and this is the line to change. + factory ModelChoice.fromDisk(String path) { + final fileName = path.split(RegExp(r'[/\\]')).last; + return ModelChoice( + label: fileName, + fileName: fileName, + path: path, + modelType: ModelType.functionGemma, + sizeLabel: 'on this machine', + supportsThinking: false, + supportsRequiredToolChoice: false, + ); + } + + final String label; + final String fileName; + + /// Which family's function-call format the SDK writes and reads. + /// + /// This is not decoration. `functionGemma` renders the declarations into a + /// developer turn and parses `call:name{…}` back out; + /// `gemma4` hands the declarations to the runtime as structured `tools_json` + /// and reads the call back from the SDK's own parsed response. Name the + /// wrong family and the SDK writes a prompt these weights never saw and + /// waits for a syntax they never emit — every turn comes back as plain text + /// and nothing says why. + final ModelType modelType; + + final String sizeLabel; + + /// Where the bytes are. Exactly one of these is non-null. + final String? url; + final String? path; + + /// Can these weights reason out loud before answering? + /// + /// A property of the checkpoint, not of the app: `isThinking: true` on a + /// model with no thinking training does not produce reasoning, it produces + /// an empty channel. FunctionGemma is a 270M model specialised for one + /// thing, and reasoning is not it. + final bool supportsThinking; + + /// Can this model be *forced* to call a tool? + /// + /// `ToolChoice.required` needs a way to say "you must call a function" in + /// the prompt the model actually reads, and neither of these has one. + /// FunctionGemma's format cannot express it, so the SDK logs a warning and + /// behaves as `auto`. Gemma 4's declarations go to the runtime as + /// `tools_json`, which carries no `tool_choice` — so `required` is `auto` + /// there too, without even the warning. Reasonable behaviour on the SDK's + /// part, and very confusing to watch if the app does not say so. + final bool supportsRequiredToolChoice; + + /// Points an install at wherever this model's bytes are. + /// + /// The two branches are the whole difference between a model you downloaded + /// and a model you tuned: `fromNetwork` fetches the file, `fromFile` + /// registers one that is already here. Everything after this line — the + /// session, the tools, the loop — cannot tell them apart. + InferenceInstallationBuilder locate(InferenceInstallationBuilder builder) => + path != null ? builder.fromFile(path!) : builder.fromNetwork(url!); +} + +/// The two models this app ships. +/// +/// Both repositories are ungated, so nothing here needs a Hugging Face token +/// and no run needs `--dart-define`. +abstract final class Models { + /// A 270M model whose whole job is function calling. + /// + /// 284 MB, and it does very little else — ask it a general question and the + /// answer will be thin. That is the trade: calling a function is a narrow + /// skill, and a model specialised for it can be a fraction of the size of + /// one that also has to hold a conversation. It is also the base Step 4 + /// fine-tunes. + static const functionGemma = ModelChoice( + label: 'FunctionGemma 270M', + url: + 'https://huggingface.co/sasha-denisov/function-gemma-270M-it/' + 'resolve/main/functiongemma-270M-it.litertlm', + fileName: 'functiongemma-270M-it.litertlm', + modelType: ModelType.functionGemma, + sizeLabel: '284 MB', + supportsThinking: false, + supportsRequiredToolChoice: false, + ); + + /// The reason to pay 2.59 GB instead of 284 MB. + /// + /// Same three tools, same loop — but these weights can reason out loud + /// before deciding which function to call, and they hold a conversation + /// either side of it. Nine times the download for the thing the small model + /// cannot do at all. + /// + /// What it does NOT buy is `ToolChoice.required`: its declarations reach the + /// runtime as `tools_json`, which has no `tool_choice` field, so `required` + /// is `auto` here exactly as it is on FunctionGemma — see + /// [supportsRequiredToolChoice]. + static const gemma4 = ModelChoice( + label: 'Gemma 4 E2B', + url: + 'https://huggingface.co/litert-community/gemma-4-E2B-it-litert-lm/' + 'resolve/main/gemma-4-E2B-it.litertlm', + fileName: 'gemma-4-E2B-it.litertlm', + modelType: ModelType.gemma4, + sizeLabel: '2.59 GB', + supportsThinking: true, + supportsRequiredToolChoice: false, + ); + + /// The ones with a download, in the order the list shows them. + static const downloadable = [gemma4, functionGemma]; +} diff --git a/codelabs/function-calling-flutter-gemma/complete/lib/model_gate.dart b/codelabs/function-calling-flutter-gemma/complete/lib/model_gate.dart new file mode 100644 index 000000000..e2bed10b2 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/lib/model_gate.dart @@ -0,0 +1,113 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_gemma/flutter_gemma.dart'; + +import 'chat_page.dart'; +import 'download_page.dart'; +import 'model.dart'; + +/// Asks, for one model, whether it is already installed — and makes it the +/// active one either way. +/// +/// `install()` is idempotent, so the bytes are only ever fetched once. What a +/// drifted id costs you is this gate: it answers "no" forever, so the app +/// shows the download screen on every launch, the "download" there finishes +/// instantly, and you land straight back here. +class ModelGate extends StatefulWidget { + const ModelGate({super.key, required this.model}); + + final ModelChoice model; + + @override + State createState() => _ModelGateState(); +} + +class _ModelGateState extends State { + late Future _installed = _check(); + + /// Installed is not the same as active. + /// + /// This app puts three models in one container — two downloads and whatever + /// you built in Step 4 — and `getActiveModel` opens whichever was installed + /// LAST. So finding the file on disk is not enough: the gate has to say + /// which model it means before the chat asks for one. `install()` is + /// idempotent, so on a file already here it fetches nothing and only records + /// this model as the current one. + Future _check() async { + if (!await FlutterGemma.isModelInstalled(widget.model.fileName)) { + return false; + } + await widget.model + .locate( + FlutterGemma.installModel( + modelType: widget.model.modelType, + fileType: ModelFileType.litertlm, + ), + ) + .install(); + return true; + } + + @override + Widget build(BuildContext context) { + return FutureBuilder( + future: _installed, + builder: (context, snapshot) { + if (snapshot.connectionState != ConnectionState.done) { + return const Scaffold( + body: Center(child: CircularProgressIndicator()), + ); + } + if (snapshot.hasError) { + // A FutureBuilder that ignores `hasError` renders the download + // screen as if nothing had gone wrong. Say what failed instead — + // "External file does not exist" is what a moved or deleted tuned + // model looks like, and it belongs on screen. + return _GateError( + error: snapshot.error!, + onRetry: () => setState(() => _installed = _check()), + ); + } + if (snapshot.data ?? false) { + return ChatPage( + model: widget.model, + // The model this route existed for is gone, so the route is too. + onModelRemoved: () => Navigator.of(context).pop(), + ); + } + return DownloadPage( + model: widget.model, + onInstalled: () => setState(() => _installed = _check()), + ); + }, + ); + } +} + +/// Shown when the gate's own check fails, rather than falling through to the +/// download screen as if the answer had been "no". +class _GateError extends StatelessWidget { + const _GateError({required this.error, required this.onRetry}); + + final Object error; + final VoidCallback onRetry; + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar(), + body: Center( + child: Padding( + padding: const EdgeInsets.all(24), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Text('$error', textAlign: TextAlign.center), + const SizedBox(height: 12), + FilledButton(onPressed: onRetry, child: const Text('Try again')), + ], + ), + ), + ), + ); + } +} diff --git a/codelabs/function-calling-flutter-gemma/complete/lib/models_page.dart b/codelabs/function-calling-flutter-gemma/complete/lib/models_page.dart new file mode 100644 index 000000000..7b5ae8fd2 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/lib/models_page.dart @@ -0,0 +1,186 @@ +import 'package:flutter/foundation.dart' show kIsWeb; +import 'package:flutter/material.dart'; +import 'package:flutter_gemma/flutter_gemma.dart'; + +import 'model.dart'; +import 'model_gate.dart'; + +/// The list of models this app can open. +/// +/// Two it can download, and any others it finds already installed — which is +/// how the model you fine-tuned in Step 4 turns up here after the first time +/// you point the app at it. Nothing below treats it as a special case: it is a +/// `.litertlm`, and the chat opens it exactly like the other two. +class ModelsPage extends StatefulWidget { + const ModelsPage({super.key}); + + @override + State createState() => _ModelsPageState(); +} + +class _ModelsPageState extends State { + late Future> _yours = _findYourOwn(); + + /// Everything installed that this app did not ship a constant for. + /// + /// `listInstalledModels` returns the ids — which are file names — and + /// `getModelPath` turns one back into where the file actually is. For a + /// model installed from disk that is the original path, not a copy: the + /// install registered the file where it lay. + Future> _findYourOwn() async { + final shipped = {for (final m in Models.downloadable) m.fileName}; + final installed = await FlutterGemma.listInstalledModels(); + final yours = []; + for (final id in installed) { + if (shipped.contains(id)) continue; + yours.add(ModelChoice.fromDisk(await FlutterGemma.getModelPath(id))); + } + return yours; + } + + Future _open(ModelChoice model) async { + await Navigator.of( + context, + ).push(MaterialPageRoute(builder: (_) => ModelGate(model: model))); + // A model may have been installed or deleted behind that route. + if (mounted) setState(() => _yours = _findYourOwn()); + } + + /// Asks for a path rather than opening a file picker. + /// + /// The file this is for was written by a command line — `litetune convert` + /// prints where it put it — so the path is already on the learner's screen, + /// and a picker would be a sixth dependency to avoid retyping it. + Future _addFromDisk() async { + final controller = TextEditingController(); + final path = await showDialog( + context: context, + builder: (context) => AlertDialog( + title: const Text('Open a .litertlm from disk'), + content: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text( + 'The absolute path to the file. Nothing is copied — the app ' + 'records where the file is, so moving or deleting it later ' + 'takes the model with it.', + ), + const SizedBox(height: 12), + TextField( + controller: controller, + autofocus: true, + decoration: const InputDecoration( + hintText: '/Users/you/tuning/artifacts/…/model.litertlm', + border: OutlineInputBorder(), + ), + onSubmitted: (v) => Navigator.of(context).pop(v.trim()), + ), + ], + ), + actions: [ + TextButton( + onPressed: () => Navigator.of(context).pop(), + child: const Text('Cancel'), + ), + FilledButton( + onPressed: () => Navigator.of(context).pop(controller.text.trim()), + child: const Text('Open'), + ), + ], + ), + ); + controller.dispose(); + if (path == null || path.isEmpty || !mounted) return; + await _open(ModelChoice.fromDisk(path)); + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + + return Scaffold( + appBar: AppBar(title: const Text('Models')), + body: FutureBuilder>( + future: _yours, + builder: (context, snapshot) { + final yours = snapshot.data ?? const []; + return ListView( + children: [ + for (final model in Models.downloadable) + _ModelTile(model: model, onTap: () => _open(model)), + if (yours.isNotEmpty) ...[ + Padding( + padding: const EdgeInsets.fromLTRB(16, 24, 16, 4), + child: Text( + 'Your own models', + style: theme.textTheme.titleSmall, + ), + ), + for (final model in yours) + _ModelTile(model: model, onTap: () => _open(model)), + ], + const Divider(height: 32), + if (kIsWeb) + // `fromFile` on the web has no filesystem to read: the browser + // arm registers a URL, not a path. Saying so beats a text + // field that cannot work. + const ListTile( + leading: Icon(Icons.folder_off_outlined), + title: Text('Opening a file from disk needs a native build'), + subtitle: Text( + 'A browser has no path to give. Run this app on a desktop ' + 'or a phone to try the model you tuned in Step 4.', + ), + ) + else + ListTile( + leading: const Icon(Icons.folder_open_outlined), + title: const Text('Open a .litertlm from disk'), + subtitle: const Text( + 'The file Step 4 produced — or any other .litertlm.', + ), + onTap: _addFromDisk, + ), + if (snapshot.hasError) + Padding( + padding: const EdgeInsets.all(16), + child: Text( + 'Could not read what is installed: ${snapshot.error}', + style: theme.textTheme.bodySmall?.copyWith( + color: theme.colorScheme.error, + ), + ), + ), + ], + ); + }, + ), + ); + } +} + +class _ModelTile extends StatelessWidget { + const _ModelTile({required this.model, required this.onTap}); + + final ModelChoice model; + final VoidCallback onTap; + + @override + Widget build(BuildContext context) { + final abilities = [ + if (model.supportsThinking) 'thinking' else 'no thinking', + if (model.supportsRequiredToolChoice) + 'can be forced to call' + else + 'auto only', + ].join(' · '); + + return ListTile( + title: Text(model.label), + subtitle: Text('${model.sizeLabel} — $abilities'), + trailing: const Icon(Icons.chevron_right), + onTap: onTap, + ); + } +} diff --git a/codelabs/function-calling-flutter-gemma/complete/lib/tools.dart b/codelabs/function-calling-flutter-gemma/complete/lib/tools.dart new file mode 100644 index 000000000..a8248db52 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/lib/tools.dart @@ -0,0 +1,150 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter_gemma/flutter_gemma.dart'; + +/// What a tool actually is, on the app's side: a Dart function from the +/// arguments the model wrote to the map the model will be shown. +/// +/// Synchronous on purpose. Everything these three do is local and instant — +/// arithmetic, a clock, a constant — which is what keeps this codelab offline +/// and its answers checkable. A tool that talks to the network returns a +/// `Future` and the loop awaits it; nothing else changes. +typedef ToolRunner = Map Function(Map args); + +/// Multiply two numbers. +/// +/// The answer is checkable. Ask a small model for 1234 × 5678 and it produces +/// a confident number of about the right length; ask it to call this instead +/// and the number is exact, offline, and you can verify it on a pocket +/// calculator. A weather tool would demonstrate the same mechanism and prove +/// nothing about the answer. +const multiplyTool = Tool( + name: 'multiply', + // The model reads this. It is the only thing telling it WHEN to call — so + // "instead of working it out yourself" is instruction, not prose. + description: + 'Multiply two numbers and return the exact product. Use this for any ' + 'multiplication instead of working it out yourself.', + parameters: { + 'type': 'object', + 'properties': { + 'a': {'type': 'number', 'description': 'The first number.'}, + 'b': {'type': 'number', 'description': 'The second number.'}, + }, + 'required': ['a', 'b'], + }, +); + +/// The device clock. +/// +/// A tool with no arguments, which is worth having one of: the declaration +/// still carries `parameters`, and the SDK still renders a `type: OBJECT` for +/// it. Drop the map entirely and FunctionGemma's prompt loses the parameters +/// block, which reads to the model as a declaration that was cut off. +const clockTool = Tool( + name: 'get_current_time', + description: + 'Return the current local date and time on this device. Use this ' + 'whenever the answer depends on what time it is now.', + parameters: {'type': 'object', 'properties': {}}, +); + +/// What the app is running on. +/// +/// The other kind of checkable answer: you know what device you are holding, +/// so a wrong answer here is obvious without a calculator. +const deviceTool = Tool( + name: 'get_device_info', + description: + 'Return the platform this app is running on. Use this when asked about ' + 'the device, the operating system, or where the app is running.', + parameters: {'type': 'object', 'properties': {}}, +); + +/// Everything the model is told it can call. +const toolbox = [multiplyTool, clockTool, deviceTool]; + +/// Everything the app can actually run, keyed by the name in the declaration. +/// +/// A map rather than a `switch` because the two halves — what is declared and +/// what is implemented — are then two collections a test can compare. A tool +/// declared with no runner is a call the app answers with an error forever, +/// and the model never finds out why. +const toolRunners = { + 'multiply': runMultiply, + 'get_current_time': runClock, + 'get_device_info': runDeviceInfo, +}; + +/// Runs a call, or says it cannot. +/// +/// The miss branch is not defensive padding: the model writes the name, and a +/// model can write a name you never declared. That is a turn to answer, not a +/// crash — returned as a map so the model reads it and can correct itself on +/// the next turn, where an exception would end the conversation. +Map runTool(FunctionCallResponse call) { + final runner = toolRunners[call.name]; + if (runner == null) { + return {'error': 'This app has no tool named "${call.name}".'}; + } + return runner(call.args); +} + +/// Multiplies, and returns the map the model will be shown. +/// +/// Everything returned here becomes the model's only knowledge of what +/// happened, so the keys are part of the interface: `result` is what it will +/// read back to the user, and `error` is what it will apologise about. +Map runMultiply(Map args) { + final a = asNumber(args['a']); + final b = asNumber(args['b']); + if (a == null || b == null) { + return { + 'error': + 'multiply needs two numbers. Got a=${args['a']}, b=${args['b']}.', + }; + } + final product = a * b; + // `12 * 13` arriving as doubles comes back as `156.0`, and the model has to + // read that number out loud. Say 156. + return { + 'result': product is double && product == product.truncateToDouble() + ? product.toInt() + : product, + }; +} + +/// The device clock, in two forms. +/// +/// `time` is what a person checks against their own watch; `iso8601` is what +/// the model should use if it has to compute with it. Giving both costs a few +/// tokens and removes a whole class of "it read the date as the year". +Map runClock(Map args) { + final now = DateTime.now(); + String two(int v) => v.toString().padLeft(2, '0'); + return { + 'time': '${two(now.hour)}:${two(now.minute)}', + 'date': '${now.year}-${two(now.month)}-${two(now.day)}', + 'iso8601': now.toIso8601String(), + }; +} + +/// Where the app is running. +/// +/// `kIsWeb` is asked first because `defaultTargetPlatform` in a browser +/// reports the HOST operating system — a Chrome tab on a Mac answers +/// `macOS`, which is true about the machine and wrong about the app. +Map runDeviceInfo(Map args) => { + 'platform': kIsWeb ? 'web' : defaultTargetPlatform.name, + 'build': kDebugMode ? 'debug' : 'release', +}; + +/// Arguments arrive as whatever JSON the model produced. +/// +/// FunctionGemma is trained to emit tool-call arguments as strings, so `"12"` +/// is the common case there and `12` or `12.0` are the others. All three are +/// the same number and the app should not care which one it got. +num? asNumber(Object? value) => switch (value) { + final num n => n, + final String s => num.tryParse(s.trim()), + _ => null, +}; diff --git a/codelabs/function-calling-flutter-gemma/complete/linux/.gitignore b/codelabs/function-calling-flutter-gemma/complete/linux/.gitignore new file mode 100644 index 000000000..d3896c984 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/linux/.gitignore @@ -0,0 +1 @@ +flutter/ephemeral diff --git a/codelabs/function-calling-flutter-gemma/complete/linux/CMakeLists.txt b/codelabs/function-calling-flutter-gemma/complete/linux/CMakeLists.txt new file mode 100644 index 000000000..f21ac7bae --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/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 "functioncalling") +# The unique GTK application identifier for this application. See: +# https://wiki.gnome.org/HowDoI/ChooseApplicationID +set(APPLICATION_ID "dev.fluttergemma.functioncalling") + +# 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/codelabs/function-calling-flutter-gemma/complete/linux/flutter/CMakeLists.txt b/codelabs/function-calling-flutter-gemma/complete/linux/flutter/CMakeLists.txt new file mode 100644 index 000000000..d5bd01648 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/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/codelabs/function-calling-flutter-gemma/complete/linux/flutter/generated_plugin_registrant.cc b/codelabs/function-calling-flutter-gemma/complete/linux/flutter/generated_plugin_registrant.cc new file mode 100644 index 000000000..198e9645a --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/linux/flutter/generated_plugin_registrant.cc @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + +#include + +void fl_register_plugins(FlPluginRegistry* registry) { + g_autoptr(FlPluginRegistrar) flutter_gemma_registrar = + fl_plugin_registry_get_registrar_for_plugin(registry, "FlutterGemmaPlugin"); + flutter_gemma_plugin_register_with_registrar(flutter_gemma_registrar); +} diff --git a/codelabs/function-calling-flutter-gemma/complete/linux/flutter/generated_plugin_registrant.h b/codelabs/function-calling-flutter-gemma/complete/linux/flutter/generated_plugin_registrant.h new file mode 100644 index 000000000..e0f0a47bc --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/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/codelabs/function-calling-flutter-gemma/complete/linux/flutter/generated_plugins.cmake b/codelabs/function-calling-flutter-gemma/complete/linux/flutter/generated_plugins.cmake new file mode 100644 index 000000000..3b0705d0f --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/linux/flutter/generated_plugins.cmake @@ -0,0 +1,25 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST + flutter_gemma +) + +list(APPEND FLUTTER_FFI_PLUGIN_LIST + jni +) + +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/codelabs/function-calling-flutter-gemma/complete/linux/runner/CMakeLists.txt b/codelabs/function-calling-flutter-gemma/complete/linux/runner/CMakeLists.txt new file mode 100644 index 000000000..e97dabc70 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/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/codelabs/function-calling-flutter-gemma/complete/linux/runner/main.cc b/codelabs/function-calling-flutter-gemma/complete/linux/runner/main.cc new file mode 100644 index 000000000..e7c5c5437 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/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/codelabs/function-calling-flutter-gemma/complete/linux/runner/my_application.cc b/codelabs/function-calling-flutter-gemma/complete/linux/runner/my_application.cc new file mode 100644 index 000000000..917c019cf --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/linux/runner/my_application.cc @@ -0,0 +1,148 @@ +#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, "Gemma Function Calling"); + 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, "Gemma Function Calling"); + } + + 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/codelabs/function-calling-flutter-gemma/complete/linux/runner/my_application.h b/codelabs/function-calling-flutter-gemma/complete/linux/runner/my_application.h new file mode 100644 index 000000000..db16367a7 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/linux/runner/my_application.h @@ -0,0 +1,21 @@ +#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/codelabs/function-calling-flutter-gemma/complete/macos/.gitignore b/codelabs/function-calling-flutter-gemma/complete/macos/.gitignore new file mode 100644 index 000000000..746adbb6b --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/macos/.gitignore @@ -0,0 +1,7 @@ +# Flutter-related +**/Flutter/ephemeral/ +**/Pods/ + +# Xcode-related +**/dgph +**/xcuserdata/ diff --git a/codelabs/function-calling-flutter-gemma/complete/macos/Flutter/Flutter-Debug.xcconfig b/codelabs/function-calling-flutter-gemma/complete/macos/Flutter/Flutter-Debug.xcconfig new file mode 100644 index 000000000..4b81f9b2d --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/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/codelabs/function-calling-flutter-gemma/complete/macos/Flutter/Flutter-Release.xcconfig b/codelabs/function-calling-flutter-gemma/complete/macos/Flutter/Flutter-Release.xcconfig new file mode 100644 index 000000000..5caa9d157 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/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/codelabs/function-calling-flutter-gemma/complete/macos/Flutter/GeneratedPluginRegistrant.swift b/codelabs/function-calling-flutter-gemma/complete/macos/Flutter/GeneratedPluginRegistrant.swift new file mode 100644 index 000000000..0be86a9b4 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/macos/Flutter/GeneratedPluginRegistrant.swift @@ -0,0 +1,18 @@ +// +// Generated file. Do not edit. +// + +import FlutterMacOS +import Foundation + +import connectivity_plus +import flutter_gemma +import large_file_handler +import shared_preferences_foundation + +func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { + ConnectivityPlusPlugin.register(with: registry.registrar(forPlugin: "ConnectivityPlusPlugin")) + FlutterGemmaPlugin.register(with: registry.registrar(forPlugin: "FlutterGemmaPlugin")) + LargeFileHandlerPlugin.register(with: registry.registrar(forPlugin: "LargeFileHandlerPlugin")) + SharedPreferencesPlugin.register(with: registry.registrar(forPlugin: "SharedPreferencesPlugin")) +} diff --git a/codelabs/function-calling-flutter-gemma/complete/macos/Podfile b/codelabs/function-calling-flutter-gemma/complete/macos/Podfile new file mode 100644 index 000000000..32aafe8bf --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/macos/Podfile @@ -0,0 +1,98 @@ +platform :osx, '12.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', '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 + + # flutter_gemma: stage the upstream Apple companion dylibs into the built + # .app. `hook/build.dart` deliberately skips them from Native Assets on macOS + # (#247 — Google ships them without `-Wl,-headerpad_max_install_names`, so the + # JIT bundling path cannot rewrite their install_name), which leaves this + # build phase to stage them. + # + # The phase only LOCATES and RUNS a script; the staging logic itself lives in + # flutter_gemma_litertlm and is delivered next to the dylibs it stages. That + # is deliberate: this block is frozen into your Xcode project, and a copy of + # the logic frozen there cannot be fixed by upgrading the package. + installer.aggregate_targets.each do |aggregate_target| + aggregate_target.user_targets.each do |user_target| + phase_name = '[flutter_gemma] Setup LiteRT-LM macOS' + + # Only the app target embeds the Frameworks/ this phase patches. + # RunnerTests inherits Runner's framework search paths and has no + # Contents/Frameworks of its own — having the phase there creates a + # cross-target dependency on Runner's framework output that Xcode reports + # as "Cycle inside Flutter Assemble" (#300). Remove any stale copy from + # non-app targets and skip them. + unless user_target.name == 'Runner' + user_target.build_phases + .select { |p| p.respond_to?(:name) && p.name == phase_name } + .each { |p| user_target.build_phases.delete(p) } + next + end + + existing = user_target.shell_script_build_phases.find { |p| p.name == phase_name } + phase = existing || user_target.new_shell_script_build_phase(phase_name) + # The embedded LiteRtLm binary is an INPUT so the phase re-runs whenever + # Flutter's always-out-of-date `embed` phase re-copies the raw, unpatched + # binary over the patched one. Without it Xcode caches the phase after the + # first build and the second incremental build ships an unpatched + # LiteRtLm that fails dlopen at runtime (#368). + phase.input_paths = [ + '$(BUILT_PRODUCTS_DIR)/$(PRODUCT_NAME).app/Contents/Frameworks/LiteRtLm.framework/Versions/A/LiteRtLm', + ] + # A declared output lets Xcode order the phase in its dependency graph + # instead of treating it as "runs every build with no outputs" — the other + # half of the cycle warning (#300). The script touches this file. + phase.output_paths = ['$(DERIVED_FILE_DIR)/flutter_gemma_litertlm_macos.stamp'] + phase.shell_script = <<~SHELL + set -e + STAGER="${HOME}/Library/Caches/flutter_gemma/native/macos_arm64/stage_macos_companions.sh" + if [ ! -f "${STAGER}" ]; then + echo "[flutter_gemma] ERROR: ${STAGER} not found." >&2 + echo " flutter_gemma_litertlm 1.6.2+ installs it there from its build hook." >&2 + echo " Upgrade the package, then: flutter clean && flutter pub get" >&2 + exit 1 + fi + sh "${STAGER}" "${BUILT_PRODUCTS_DIR}/${PRODUCT_NAME}.app/Contents/Frameworks" + mkdir -p "$(dirname "${SCRIPT_OUTPUT_FILE_0}")" + touch "${SCRIPT_OUTPUT_FILE_0}" + SHELL + end + end +end diff --git a/codelabs/function-calling-flutter-gemma/complete/macos/Runner.xcodeproj/project.pbxproj b/codelabs/function-calling-flutter-gemma/complete/macos/Runner.xcodeproj/project.pbxproj new file mode 100644 index 000000000..4b6591456 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/macos/Runner.xcodeproj/project.pbxproj @@ -0,0 +1,846 @@ +// !$*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 */; }; + 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */ = {isa = PBXBuildFile; productRef = 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */; }; + 8EAA73FE849CEF3B431B4AF6 /* Pods_Runner.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 364496E5DD090209850A1D71 /* Pods_Runner.framework */; }; + 91E89CE7511CD75A2C99F217 /* Pods_RunnerTests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = F71B6BAD036F01EEB2EEBE3D /* Pods_RunnerTests.framework */; }; +/* 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 /* Gemma Function Calling.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "Gemma Function Calling.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 = ""; }; + 364496E5DD090209850A1D71 /* Pods_Runner.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Runner.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 4398758F6887938877C2B528 /* Pods-RunnerTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.debug.xcconfig"; path = "Target Support Files/Pods-RunnerTests/Pods-RunnerTests.debug.xcconfig"; sourceTree = ""; }; + 710FA8AF0215638FFD8C4B46 /* Pods-Runner.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.release.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"; sourceTree = ""; }; + 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */ = {isa = PBXFileReference; lastKnownFileType = wrapper; name = FlutterGeneratedPluginSwiftPackage; path = ephemeral/Packages/FlutterGeneratedPluginSwiftPackage; 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 = ""; }; + E9F8C1AD11BFD603DAA0C6CB /* Pods-RunnerTests.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.profile.xcconfig"; path = "Target Support Files/Pods-RunnerTests/Pods-RunnerTests.profile.xcconfig"; sourceTree = ""; }; + EA5E47FD9C85B2242AAF6C0D /* Pods-Runner.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.debug.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"; sourceTree = ""; }; + F71B6BAD036F01EEB2EEBE3D /* Pods_RunnerTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_RunnerTests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + FCD49997F2B346BE256F3BB0 /* Pods-Runner.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.profile.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.profile.xcconfig"; sourceTree = ""; }; + FF5FBDDC35B6703AD272BEE9 /* Pods-RunnerTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.release.xcconfig"; path = "Target Support Files/Pods-RunnerTests/Pods-RunnerTests.release.xcconfig"; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 331C80D2294CF70F00263BE5 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 91E89CE7511CD75A2C99F217 /* Pods_RunnerTests.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 33CC10EA2044A3C60003C045 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */, + 8EAA73FE849CEF3B431B4AF6 /* Pods_Runner.framework in Frameworks */, + ); + 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 */, + 4F1824E70EA554BEBC823C3A /* Pods */, + ); + sourceTree = ""; + }; + 33CC10EE2044A3C60003C045 /* Products */ = { + isa = PBXGroup; + children = ( + 33CC10ED2044A3C60003C045 /* Gemma Function Calling.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 = ( + 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */, + 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 = ""; + }; + 4F1824E70EA554BEBC823C3A /* Pods */ = { + isa = PBXGroup; + children = ( + EA5E47FD9C85B2242AAF6C0D /* Pods-Runner.debug.xcconfig */, + 710FA8AF0215638FFD8C4B46 /* Pods-Runner.release.xcconfig */, + FCD49997F2B346BE256F3BB0 /* Pods-Runner.profile.xcconfig */, + 4398758F6887938877C2B528 /* Pods-RunnerTests.debug.xcconfig */, + FF5FBDDC35B6703AD272BEE9 /* Pods-RunnerTests.release.xcconfig */, + E9F8C1AD11BFD603DAA0C6CB /* Pods-RunnerTests.profile.xcconfig */, + ); + name = Pods; + path = Pods; + sourceTree = ""; + }; + D73912EC22F37F3D000D13A0 /* Frameworks */ = { + isa = PBXGroup; + children = ( + 364496E5DD090209850A1D71 /* Pods_Runner.framework */, + F71B6BAD036F01EEB2EEBE3D /* Pods_RunnerTests.framework */, + ); + name = Frameworks; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 331C80D4294CF70F00263BE5 /* RunnerTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 331C80DE294CF71000263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */; + buildPhases = ( + 574214855AA3429412BDB64F /* [CP] Check Pods Manifest.lock */, + 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 = ( + 23D0A1A403B8155DC3263B79 /* [CP] Check Pods Manifest.lock */, + 33CC10E92044A3C60003C045 /* Sources */, + 33CC10EA2044A3C60003C045 /* Frameworks */, + 33CC10EB2044A3C60003C045 /* Resources */, + 33CC110E2044A8840003C045 /* Bundle Framework */, + 3399D490228B24CF009A79C7 /* ShellScript */, + 873C31A378C00B903D8D8A93 /* [flutter_gemma] Setup LiteRT-LM macOS */, + 4DB6A19CA8AB43F4519ABE75 /* [CP] Embed Pods Frameworks */, + ); + buildRules = ( + ); + dependencies = ( + 33CC11202044C79F0003C045 /* PBXTargetDependency */, + ); + name = Runner; + packageProductDependencies = ( + 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */, + ); + productName = Runner; + productReference = 33CC10ED2044A3C60003C045 /* Gemma Function Calling.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; + packageReferences = ( + 781AD8BC2B33823900A9FFBB /* XCLocalSwiftPackageReference "FlutterGeneratedPluginSwiftPackage" */, + ); + 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 */ + 23D0A1A403B8155DC3263B79 /* [CP] Check Pods Manifest.lock */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + "${PODS_PODFILE_DIR_PATH}/Podfile.lock", + "${PODS_ROOT}/Manifest.lock", + ); + name = "[CP] Check Pods Manifest.lock"; + outputFileListPaths = ( + ); + outputPaths = ( + "$(DERIVED_FILE_DIR)/Pods-Runner-checkManifestLockResult.txt", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; + showEnvVarsInLog = 0; + }; + 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"; + }; + 4DB6A19CA8AB43F4519ABE75 /* [CP] Embed Pods Frameworks */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + "${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks-${CONFIGURATION}-input-files.xcfilelist", + ); + name = "[CP] Embed Pods Frameworks"; + outputFileListPaths = ( + "${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks-${CONFIGURATION}-output-files.xcfilelist", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks.sh\"\n"; + showEnvVarsInLog = 0; + }; + 574214855AA3429412BDB64F /* [CP] Check Pods Manifest.lock */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + "${PODS_PODFILE_DIR_PATH}/Podfile.lock", + "${PODS_ROOT}/Manifest.lock", + ); + name = "[CP] Check Pods Manifest.lock"; + outputFileListPaths = ( + ); + outputPaths = ( + "$(DERIVED_FILE_DIR)/Pods-RunnerTests-checkManifestLockResult.txt", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; + showEnvVarsInLog = 0; + }; + 873C31A378C00B903D8D8A93 /* [flutter_gemma] Setup LiteRT-LM macOS */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + "$(BUILT_PRODUCTS_DIR)/$(PRODUCT_NAME).app/Contents/Frameworks/LiteRtLm.framework/Versions/A/LiteRtLm", + ); + name = "[flutter_gemma] Setup LiteRT-LM macOS"; + outputFileListPaths = ( + ); + outputPaths = ( + "$(DERIVED_FILE_DIR)/flutter_gemma_litertlm_macos.stamp", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "set -e\nSTAGER=\"${HOME}/Library/Caches/flutter_gemma/native/macos_arm64/stage_macos_companions.sh\"\nif [ ! -f \"${STAGER}\" ]; then\n echo \"[flutter_gemma] ERROR: ${STAGER} not found.\" >&2\n echo \" flutter_gemma_litertlm 1.6.2+ installs it there from its build hook.\" >&2\n echo \" Upgrade the package, then: flutter clean && flutter pub get\" >&2\n exit 1\nfi\nsh \"${STAGER}\" \"${BUILT_PRODUCTS_DIR}/${PRODUCT_NAME}.app/Contents/Frameworks\"\nmkdir -p \"$(dirname \"${SCRIPT_OUTPUT_FILE_0}\")\"\ntouch \"${SCRIPT_OUTPUT_FILE_0}\"\n"; + }; +/* 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; + baseConfigurationReference = 4398758F6887938877C2B528 /* Pods-RunnerTests.debug.xcconfig */; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = dev.fluttergemma.functioncalling.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/$(PRODUCT_NAME).app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/$(PRODUCT_NAME)"; + }; + name = Debug; + }; + 331C80DC294CF71000263BE5 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = FF5FBDDC35B6703AD272BEE9 /* Pods-RunnerTests.release.xcconfig */; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = dev.fluttergemma.functioncalling.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/$(PRODUCT_NAME).app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/$(PRODUCT_NAME)"; + }; + name = Release; + }; + 331C80DD294CF71000263BE5 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = E9F8C1AD11BFD603DAA0C6CB /* Pods-RunnerTests.profile.xcconfig */; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = dev.fluttergemma.functioncalling.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/$(PRODUCT_NAME).app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/$(PRODUCT_NAME)"; + }; + 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 = 12.0; + 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 = 12.0; + 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 = 12.0; + 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 */ + +/* Begin XCLocalSwiftPackageReference section */ + 781AD8BC2B33823900A9FFBB /* XCLocalSwiftPackageReference "FlutterGeneratedPluginSwiftPackage" */ = { + isa = XCLocalSwiftPackageReference; + relativePath = Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage; + }; +/* End XCLocalSwiftPackageReference section */ + +/* Begin XCSwiftPackageProductDependency section */ + 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */ = { + isa = XCSwiftPackageProductDependency; + productName = FlutterGeneratedPluginSwiftPackage; + }; +/* End XCSwiftPackageProductDependency section */ + }; + rootObject = 33CC10E52044A3C60003C045 /* Project object */; +} diff --git a/codelabs/function-calling-flutter-gemma/complete/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/codelabs/function-calling-flutter-gemma/complete/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 000000000..18d981003 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/codelabs/function-calling-flutter-gemma/complete/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/codelabs/function-calling-flutter-gemma/complete/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme new file mode 100644 index 000000000..822174206 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/codelabs/function-calling-flutter-gemma/complete/macos/Runner.xcworkspace/contents.xcworkspacedata b/codelabs/function-calling-flutter-gemma/complete/macos/Runner.xcworkspace/contents.xcworkspacedata new file mode 100644 index 000000000..21a3cc14c --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/macos/Runner.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,10 @@ + + + + + + + diff --git a/codelabs/function-calling-flutter-gemma/complete/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/codelabs/function-calling-flutter-gemma/complete/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 000000000..18d981003 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/codelabs/function-calling-flutter-gemma/complete/macos/Runner/AppDelegate.swift b/codelabs/function-calling-flutter-gemma/complete/macos/Runner/AppDelegate.swift new file mode 100644 index 000000000..b3c176141 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/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/codelabs/function-calling-flutter-gemma/complete/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json b/codelabs/function-calling-flutter-gemma/complete/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 000000000..a2ec33f19 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/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/codelabs/function-calling-flutter-gemma/complete/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png b/codelabs/function-calling-flutter-gemma/complete/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png new file mode 100644 index 000000000..82b6f9d9a Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/complete/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png differ diff --git a/codelabs/function-calling-flutter-gemma/complete/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png b/codelabs/function-calling-flutter-gemma/complete/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png new file mode 100644 index 000000000..13b35eba5 Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/complete/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png differ diff --git a/codelabs/function-calling-flutter-gemma/complete/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png b/codelabs/function-calling-flutter-gemma/complete/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png new file mode 100644 index 000000000..0a3f5fa40 Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/complete/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png differ diff --git a/codelabs/function-calling-flutter-gemma/complete/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png b/codelabs/function-calling-flutter-gemma/complete/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png new file mode 100644 index 000000000..bdb57226d Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/complete/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png differ diff --git a/codelabs/function-calling-flutter-gemma/complete/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png b/codelabs/function-calling-flutter-gemma/complete/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png new file mode 100644 index 000000000..f083318e0 Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/complete/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png differ diff --git a/codelabs/function-calling-flutter-gemma/complete/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png b/codelabs/function-calling-flutter-gemma/complete/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png new file mode 100644 index 000000000..326c0e72c Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/complete/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png differ diff --git a/codelabs/function-calling-flutter-gemma/complete/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png b/codelabs/function-calling-flutter-gemma/complete/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png new file mode 100644 index 000000000..2f1632cfd Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/complete/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png differ diff --git a/codelabs/function-calling-flutter-gemma/complete/macos/Runner/Base.lproj/MainMenu.xib b/codelabs/function-calling-flutter-gemma/complete/macos/Runner/Base.lproj/MainMenu.xib new file mode 100644 index 000000000..80e867a4e --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/macos/Runner/Base.lproj/MainMenu.xib @@ -0,0 +1,343 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/codelabs/function-calling-flutter-gemma/complete/macos/Runner/Configs/AppInfo.xcconfig b/codelabs/function-calling-flutter-gemma/complete/macos/Runner/Configs/AppInfo.xcconfig new file mode 100644 index 000000000..0fcdf0410 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/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 = Gemma Function Calling + +// The application's bundle identifier +PRODUCT_BUNDLE_IDENTIFIER = dev.fluttergemma.functioncalling + +// The copyright displayed in application information +PRODUCT_COPYRIGHT = Copyright © 2026 dev.fluttergemma. All rights reserved. diff --git a/codelabs/function-calling-flutter-gemma/complete/macos/Runner/Configs/Debug.xcconfig b/codelabs/function-calling-flutter-gemma/complete/macos/Runner/Configs/Debug.xcconfig new file mode 100644 index 000000000..36b0fd946 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/macos/Runner/Configs/Debug.xcconfig @@ -0,0 +1,2 @@ +#include "../../Flutter/Flutter-Debug.xcconfig" +#include "Warnings.xcconfig" diff --git a/codelabs/function-calling-flutter-gemma/complete/macos/Runner/Configs/Release.xcconfig b/codelabs/function-calling-flutter-gemma/complete/macos/Runner/Configs/Release.xcconfig new file mode 100644 index 000000000..dff4f4956 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/macos/Runner/Configs/Release.xcconfig @@ -0,0 +1,2 @@ +#include "../../Flutter/Flutter-Release.xcconfig" +#include "Warnings.xcconfig" diff --git a/codelabs/function-calling-flutter-gemma/complete/macos/Runner/Configs/Warnings.xcconfig b/codelabs/function-calling-flutter-gemma/complete/macos/Runner/Configs/Warnings.xcconfig new file mode 100644 index 000000000..42bcbf478 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/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/codelabs/function-calling-flutter-gemma/complete/macos/Runner/DebugProfile.entitlements b/codelabs/function-calling-flutter-gemma/complete/macos/Runner/DebugProfile.entitlements new file mode 100644 index 000000000..8eb23d1c4 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/macos/Runner/DebugProfile.entitlements @@ -0,0 +1,16 @@ + + + + + com.apple.security.app-sandbox + + com.apple.security.cs.allow-jit + + com.apple.security.cs.disable-library-validation + + com.apple.security.network.client + + com.apple.security.network.server + + + diff --git a/codelabs/function-calling-flutter-gemma/complete/macos/Runner/Info.plist b/codelabs/function-calling-flutter-gemma/complete/macos/Runner/Info.plist new file mode 100644 index 000000000..4789daa6a --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/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/codelabs/function-calling-flutter-gemma/complete/macos/Runner/MainFlutterWindow.swift b/codelabs/function-calling-flutter-gemma/complete/macos/Runner/MainFlutterWindow.swift new file mode 100644 index 000000000..3cc05eb23 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/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/codelabs/function-calling-flutter-gemma/complete/macos/Runner/Release.entitlements b/codelabs/function-calling-flutter-gemma/complete/macos/Runner/Release.entitlements new file mode 100644 index 000000000..d7c971d31 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/macos/Runner/Release.entitlements @@ -0,0 +1,12 @@ + + + + + com.apple.security.app-sandbox + + com.apple.security.cs.disable-library-validation + + com.apple.security.network.client + + + diff --git a/codelabs/function-calling-flutter-gemma/complete/macos/RunnerTests/RunnerTests.swift b/codelabs/function-calling-flutter-gemma/complete/macos/RunnerTests/RunnerTests.swift new file mode 100644 index 000000000..61f3bd1fc --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/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/codelabs/function-calling-flutter-gemma/complete/pubspec.yaml b/codelabs/function-calling-flutter-gemma/complete/pubspec.yaml new file mode 100644 index 000000000..324dd18bb --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/pubspec.yaml @@ -0,0 +1,97 @@ +name: gemma_quickstart +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.12.0 + +# 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 + + # The following adds the Cupertino Icons font to your application. + # Use with the CupertinoIcons class for iOS style icons. + cupertino_icons: ^1.0.8 + + # The engine-agnostic core: registry, install/runtime API, chat. + flutter_gemma: ^1.7.1 + # The .litertlm inference engine. Engines are opt-in — core + # registers none, so this package must be added explicitly. + flutter_gemma_litertlm: ^1.6.2 + +dev_dependencies: + flutter_test: + sdk: flutter + integration_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: ^6.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/codelabs/function-calling-flutter-gemma/complete/test/widget_test.dart b/codelabs/function-calling-flutter-gemma/complete/test/widget_test.dart new file mode 100644 index 000000000..03ef02922 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/test/widget_test.dart @@ -0,0 +1,155 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_gemma/flutter_gemma.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:gemma_quickstart/download_page.dart'; +import 'package:gemma_quickstart/model.dart'; +import 'package:gemma_quickstart/tools.dart'; + +void main() { + // `isModelInstalled` is keyed by file name. `install()` skips bytes it + // already has, so a name that drifts from its URL does not re-download — it + // strands the app on a download screen the gate is never satisfied by. At + // 2.59 GB that is not a small mistake. + test('every downloadable model id matches the last segment of its URL', () { + for (final model in Models.downloadable) { + expect(model.fileName, model.url!.split('/').last, reason: model.label); + } + }); + + // The two halves of the toolbox are the two things that can drift apart: a + // declaration with no runner is a call the app answers with an error + // forever, and a runner with no declaration is code the model is never told + // about. + test('every declared tool has a runner, and no runner is undeclared', () { + expect( + toolbox.map((t) => t.name).toSet(), + toolRunners.keys.toSet(), + reason: 'toolbox and toolRunners must name the same tools', + ); + }); + + // The declaration is the model's only description of a function, so its + // shape is part of the app's behaviour and not a comment. + test('multiply declares the two arguments its runner reads', () { + final properties = + multiplyTool.parameters['properties'] as Map; + expect(properties.keys, containsAll(['a', 'b'])); + expect(multiplyTool.parameters['required'], ['a', 'b']); + }); + + // A no-argument tool still carries `parameters`. Dropping the map makes + // FunctionGemma's rendered declaration lose its parameters block, which + // reads to the model as a declaration that was cut off. + test('the no-argument tools still declare an object type', () { + for (final tool in [clockTool, deviceTool]) { + expect(tool.parameters['type'], 'object', reason: tool.name); + expect(tool.parameters['properties'], isEmpty, reason: tool.name); + } + }); + + group('runMultiply answers whatever the model wrote', () { + // FunctionGemma is trained to emit arguments as strings, so this is the + // ordinary case, not the exotic one. + test('strings', () { + expect(runMultiply({'a': '1234', 'b': '5678'}), {'result': 7006652}); + }); + + test('numbers', () { + expect(runMultiply({'a': 47, 'b': 89}), {'result': 4183}); + }); + + // An integer product that arrives as doubles must not be read back to the + // user as "156.0". + test('doubles that are whole numbers come back whole', () { + expect(runMultiply({'a': 12.0, 'b': 13.0}), {'result': 156}); + }); + + test('a genuine fraction stays one', () { + expect(runMultiply({'a': 0.5, 'b': 3}), {'result': 1.5}); + }); + + // Returned, not thrown: the model has to be able to read this and try + // again, and an exception would end the turn instead. + test('nonsense is an error map, not an exception', () { + final answer = runMultiply({'a': 'twelve', 'b': 13}); + expect(answer.containsKey('error'), isTrue); + expect(answer.containsKey('result'), isFalse); + }); + }); + + test('an undeclared name is answered, not thrown', () { + final answer = runTool( + const FunctionCallResponse(name: 'launch_rocket', args: {}), + ); + expect(answer['error'], contains('launch_rocket')); + }); + + test('the clock answers in a shape a person can check', () { + final now = runClock(const {}); + expect(now['time'], matches(RegExp(r'^\d{2}:\d{2}$'))); + expect(now['date'], matches(RegExp(r'^\d{4}-\d{2}-\d{2}$'))); + expect(DateTime.parse(now['iso8601'] as String), isA()); + }); + + group('ModelChoice', () { + // The whole point of Step 4: what comes out of `litetune convert` is a + // `.litertlm` like any other, and the only thing that differs is where the + // bytes are. + test('a model from disk carries a path and no URL', () { + final tuned = ModelChoice.fromDisk('/tmp/artifacts/my-model.litertlm'); + expect(tuned.path, '/tmp/artifacts/my-model.litertlm'); + expect(tuned.url, isNull); + // The id is the basename, because that is what the install registers it + // under and what `isModelInstalled` will be asked about later. + expect(tuned.fileName, 'my-model.litertlm'); + }); + + test('a downloadable model carries a URL and no path', () { + expect(Models.gemma4.path, isNull); + expect(Models.gemma4.url, isNotNull); + }); + + // The two capabilities the chat reads before it offers a control. + test('only Gemma 4 reasons out loud', () { + expect(Models.gemma4.supportsThinking, isTrue); + expect(Models.functionGemma.supportsThinking, isFalse); + }); + + // Neither, and that is the point of recording it per checkpoint rather + // than assuming the larger model can do more. FunctionGemma's prompt + // format cannot express "you must call"; Gemma 4's declarations reach the + // runtime as `tools_json`, which carries no `tool_choice` at all. A model + // whose format did express it would set this true — none here does. + test('neither model can be forced to call a tool', () { + expect(Models.gemma4.supportsRequiredToolChoice, isFalse); + expect(Models.functionGemma.supportsRequiredToolChoice, isFalse); + }); + }); + + testWidgets('the install screen offers the model before any plugin call', ( + tester, + ) async { + await tester.pumpWidget( + MaterialApp( + home: DownloadPage(model: Models.gemma4, onInstalled: () {}), + ), + ); + expect(find.text('Gemma 4 E2B'), findsOneWidget); + expect(find.text('Download model'), findsOneWidget); + }); + + testWidgets('a model from disk is offered as a file, not a download', ( + tester, + ) async { + await tester.pumpWidget( + MaterialApp( + home: DownloadPage( + model: ModelChoice.fromDisk('/tmp/artifacts/my-model.litertlm'), + onInstalled: () {}, + ), + ), + ); + expect(find.text('Open it'), findsOneWidget); + expect(find.text('Download model'), findsNothing); + }); +} diff --git a/codelabs/function-calling-flutter-gemma/complete/web/favicon.png b/codelabs/function-calling-flutter-gemma/complete/web/favicon.png new file mode 100644 index 000000000..8aaa46ac1 Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/complete/web/favicon.png differ diff --git a/codelabs/function-calling-flutter-gemma/complete/web/icons/Icon-192.png b/codelabs/function-calling-flutter-gemma/complete/web/icons/Icon-192.png new file mode 100644 index 000000000..b749bfef0 Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/complete/web/icons/Icon-192.png differ diff --git a/codelabs/function-calling-flutter-gemma/complete/web/icons/Icon-512.png b/codelabs/function-calling-flutter-gemma/complete/web/icons/Icon-512.png new file mode 100644 index 000000000..88cfd48df Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/complete/web/icons/Icon-512.png differ diff --git a/codelabs/function-calling-flutter-gemma/complete/web/icons/Icon-maskable-192.png b/codelabs/function-calling-flutter-gemma/complete/web/icons/Icon-maskable-192.png new file mode 100644 index 000000000..eb9b4d76e Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/complete/web/icons/Icon-maskable-192.png differ diff --git a/codelabs/function-calling-flutter-gemma/complete/web/icons/Icon-maskable-512.png b/codelabs/function-calling-flutter-gemma/complete/web/icons/Icon-maskable-512.png new file mode 100644 index 000000000..d69c56691 Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/complete/web/icons/Icon-maskable-512.png differ diff --git a/codelabs/function-calling-flutter-gemma/complete/web/index.html b/codelabs/function-calling-flutter-gemma/complete/web/index.html new file mode 100644 index 000000000..4dc25043a --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/web/index.html @@ -0,0 +1,58 @@ + + + + + + + + + + + + + + + + + + + + Gemma Function Calling + + + + + + + + + + diff --git a/codelabs/function-calling-flutter-gemma/complete/web/manifest.json b/codelabs/function-calling-flutter-gemma/complete/web/manifest.json new file mode 100644 index 000000000..747e60366 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/web/manifest.json @@ -0,0 +1,35 @@ +{ + "name": "Gemma Function Calling", + "short_name": "Gemma Function Calling", + "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/codelabs/function-calling-flutter-gemma/complete/windows/.gitignore b/codelabs/function-calling-flutter-gemma/complete/windows/.gitignore new file mode 100644 index 000000000..d492d0d98 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/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/codelabs/function-calling-flutter-gemma/complete/windows/CMakeLists.txt b/codelabs/function-calling-flutter-gemma/complete/windows/CMakeLists.txt new file mode 100644 index 000000000..ed760319f --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/windows/CMakeLists.txt @@ -0,0 +1,108 @@ +# Project-level configuration. +cmake_minimum_required(VERSION 3.14) +project(functioncalling 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 "functioncalling") + +# 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/codelabs/function-calling-flutter-gemma/complete/windows/flutter/CMakeLists.txt b/codelabs/function-calling-flutter-gemma/complete/windows/flutter/CMakeLists.txt new file mode 100644 index 000000000..903f4899d --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/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/codelabs/function-calling-flutter-gemma/complete/windows/flutter/generated_plugin_registrant.cc b/codelabs/function-calling-flutter-gemma/complete/windows/flutter/generated_plugin_registrant.cc new file mode 100644 index 000000000..38c2332a8 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/windows/flutter/generated_plugin_registrant.cc @@ -0,0 +1,17 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + +#include +#include + +void RegisterPlugins(flutter::PluginRegistry* registry) { + ConnectivityPlusWindowsPluginRegisterWithRegistrar( + registry->GetRegistrarForPlugin("ConnectivityPlusWindowsPlugin")); + FlutterGemmaPluginRegisterWithRegistrar( + registry->GetRegistrarForPlugin("FlutterGemmaPlugin")); +} diff --git a/codelabs/function-calling-flutter-gemma/complete/windows/flutter/generated_plugin_registrant.h b/codelabs/function-calling-flutter-gemma/complete/windows/flutter/generated_plugin_registrant.h new file mode 100644 index 000000000..dc139d85a --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/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/codelabs/function-calling-flutter-gemma/complete/windows/flutter/generated_plugins.cmake b/codelabs/function-calling-flutter-gemma/complete/windows/flutter/generated_plugins.cmake new file mode 100644 index 000000000..8dcbac209 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/windows/flutter/generated_plugins.cmake @@ -0,0 +1,26 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST + connectivity_plus + flutter_gemma +) + +list(APPEND FLUTTER_FFI_PLUGIN_LIST + jni +) + +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/codelabs/function-calling-flutter-gemma/complete/windows/runner/CMakeLists.txt b/codelabs/function-calling-flutter-gemma/complete/windows/runner/CMakeLists.txt new file mode 100644 index 000000000..394917c05 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/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/codelabs/function-calling-flutter-gemma/complete/windows/runner/Runner.rc b/codelabs/function-calling-flutter-gemma/complete/windows/runner/Runner.rc new file mode 100644 index 000000000..967d1c9d1 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/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", "dev.fluttergemma" "\0" + VALUE "FileDescription", "Gemma Function Calling" "\0" + VALUE "FileVersion", VERSION_AS_STRING "\0" + VALUE "InternalName", "functioncalling" "\0" + VALUE "LegalCopyright", "Copyright (C) 2026 dev.fluttergemma. All rights reserved." "\0" + VALUE "OriginalFilename", "functioncalling.exe" "\0" + VALUE "ProductName", "Gemma Function Calling" "\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/codelabs/function-calling-flutter-gemma/complete/windows/runner/flutter_window.cpp b/codelabs/function-calling-flutter-gemma/complete/windows/runner/flutter_window.cpp new file mode 100644 index 000000000..955ee3038 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/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/codelabs/function-calling-flutter-gemma/complete/windows/runner/flutter_window.h b/codelabs/function-calling-flutter-gemma/complete/windows/runner/flutter_window.h new file mode 100644 index 000000000..6da0652f0 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/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/codelabs/function-calling-flutter-gemma/complete/windows/runner/main.cpp b/codelabs/function-calling-flutter-gemma/complete/windows/runner/main.cpp new file mode 100644 index 000000000..38dad4a50 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/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"Gemma Function Calling", 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/codelabs/function-calling-flutter-gemma/complete/windows/runner/resource.h b/codelabs/function-calling-flutter-gemma/complete/windows/runner/resource.h new file mode 100644 index 000000000..66a65d1e4 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/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/codelabs/function-calling-flutter-gemma/complete/windows/runner/resources/app_icon.ico b/codelabs/function-calling-flutter-gemma/complete/windows/runner/resources/app_icon.ico new file mode 100644 index 000000000..c04e20caf Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/complete/windows/runner/resources/app_icon.ico differ diff --git a/codelabs/function-calling-flutter-gemma/complete/windows/runner/runner.exe.manifest b/codelabs/function-calling-flutter-gemma/complete/windows/runner/runner.exe.manifest new file mode 100644 index 000000000..153653e8d --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/windows/runner/runner.exe.manifest @@ -0,0 +1,14 @@ + + + + + PerMonitorV2 + + + + + + + + + diff --git a/codelabs/function-calling-flutter-gemma/complete/windows/runner/utils.cpp b/codelabs/function-calling-flutter-gemma/complete/windows/runner/utils.cpp new file mode 100644 index 000000000..3cb714665 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/windows/runner/utils.cpp @@ -0,0 +1,69 @@ +#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(); + } + // First, find the length of the string with a safe upper bound (CWE-126). + // UNICODE_STRING_MAX_CHARS (32767) is the maximum length of a UNICODE_STRING. + int input_length = static_cast(wcsnlen(utf16_string, UNICODE_STRING_MAX_CHARS)); + // Now use that bounded length to determine the required buffer size. + // When an explicit length is passed, WideCharToMultiByte does not include + // the null terminator in its returned size. + int target_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + input_length, nullptr, 0, nullptr, nullptr); + std::string utf8_string; + if (target_length == 0 || static_cast(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/codelabs/function-calling-flutter-gemma/complete/windows/runner/utils.h b/codelabs/function-calling-flutter-gemma/complete/windows/runner/utils.h new file mode 100644 index 000000000..3879d5475 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/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/codelabs/function-calling-flutter-gemma/complete/windows/runner/win32_window.cpp b/codelabs/function-calling-flutter-gemma/complete/windows/runner/win32_window.cpp new file mode 100644 index 000000000..60608d0fe --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/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/codelabs/function-calling-flutter-gemma/complete/windows/runner/win32_window.h b/codelabs/function-calling-flutter-gemma/complete/windows/runner/win32_window.h new file mode 100644 index 000000000..e901dde68 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/complete/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/codelabs/function-calling-flutter-gemma/step_01_starter/.gitignore b/codelabs/function-calling-flutter-gemma/step_01_starter/.gitignore new file mode 100644 index 000000000..79f7ecabd --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/.gitignore @@ -0,0 +1,48 @@ +# 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 + +# Widget Preview related +.widget_preview/ diff --git a/codelabs/function-calling-flutter-gemma/step_01_starter/.metadata b/codelabs/function-calling-flutter-gemma/step_01_starter/.metadata new file mode 100644 index 000000000..615dfd47e --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/.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: "d3b14c876900e553bc736ca19295fc09e3853e8e" + channel: "stable" + +project_type: app + +# Tracks metadata for the flutter migrate command +migration: + platforms: + - platform: root + create_revision: d3b14c876900e553bc736ca19295fc09e3853e8e + base_revision: d3b14c876900e553bc736ca19295fc09e3853e8e + - platform: android + create_revision: d3b14c876900e553bc736ca19295fc09e3853e8e + base_revision: d3b14c876900e553bc736ca19295fc09e3853e8e + - platform: ios + create_revision: d3b14c876900e553bc736ca19295fc09e3853e8e + base_revision: d3b14c876900e553bc736ca19295fc09e3853e8e + - platform: linux + create_revision: d3b14c876900e553bc736ca19295fc09e3853e8e + base_revision: d3b14c876900e553bc736ca19295fc09e3853e8e + - platform: macos + create_revision: d3b14c876900e553bc736ca19295fc09e3853e8e + base_revision: d3b14c876900e553bc736ca19295fc09e3853e8e + - platform: web + create_revision: d3b14c876900e553bc736ca19295fc09e3853e8e + base_revision: d3b14c876900e553bc736ca19295fc09e3853e8e + - platform: windows + create_revision: d3b14c876900e553bc736ca19295fc09e3853e8e + base_revision: d3b14c876900e553bc736ca19295fc09e3853e8e + + # 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/codelabs/function-calling-flutter-gemma/step_01_starter/README.md b/codelabs/function-calling-flutter-gemma/step_01_starter/README.md new file mode 100644 index 000000000..1c831fead --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/README.md @@ -0,0 +1,17 @@ +# gemma_quickstart + +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: + +- [Learn Flutter](https://docs.flutter.dev/get-started/learn-flutter) +- [Write your first Flutter app](https://docs.flutter.dev/get-started/codelab) +- [Flutter learning resources](https://docs.flutter.dev/reference/learning-resources) + +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/codelabs/function-calling-flutter-gemma/step_01_starter/analysis_options.yaml b/codelabs/function-calling-flutter-gemma/step_01_starter/analysis_options.yaml new file mode 100644 index 000000000..78613972a --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/analysis_options.yaml @@ -0,0 +1,38 @@ +# 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 + +analyzer: + exclude: + - build/** + - android/** + - ios/** + - linux/** + - macos/** + - web/** + - windows/** + +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/codelabs/function-calling-flutter-gemma/step_01_starter/android/.gitignore b/codelabs/function-calling-flutter-gemma/step_01_starter/android/.gitignore new file mode 100644 index 000000000..be3943c96 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/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/codelabs/function-calling-flutter-gemma/step_01_starter/android/app/build.gradle.kts b/codelabs/function-calling-flutter-gemma/step_01_starter/android/app/build.gradle.kts new file mode 100644 index 000000000..1ec5366e9 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/android/app/build.gradle.kts @@ -0,0 +1,49 @@ +plugins { + id("com.android.application") + // The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins. + id("dev.flutter.flutter-gradle-plugin") +} + +android { + namespace = "dev.fluttergemma.functioncalling" + compileSdk = flutter.compileSdkVersion + ndkVersion = flutter.ndkVersion + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + } + + defaultConfig { + // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). + applicationId = "dev.fluttergemma.functioncalling" + // 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 + // Uses the version code from pubspec.yaml. When using split APKs, 1000 * ABI_VERSION + // is added automatically by Flutter. (https://developer.android.com/studio/build/configure-apk-splits#configure-APK-versions) + // You can force using the value of versionCode by specifying the `-P force-version-code-ignoring-abi=true` + // flag during build. + 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") + } + } +} + +kotlin { + compilerOptions { + jvmTarget = org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17 + } +} + +flutter { + source = "../.." +} diff --git a/codelabs/function-calling-flutter-gemma/step_01_starter/android/app/src/debug/AndroidManifest.xml b/codelabs/function-calling-flutter-gemma/step_01_starter/android/app/src/debug/AndroidManifest.xml new file mode 100644 index 000000000..399f6981d --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/android/app/src/debug/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + diff --git a/codelabs/function-calling-flutter-gemma/step_01_starter/android/app/src/main/AndroidManifest.xml b/codelabs/function-calling-flutter-gemma/step_01_starter/android/app/src/main/AndroidManifest.xml new file mode 100644 index 000000000..34daae5c0 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,47 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/codelabs/function-calling-flutter-gemma/step_01_starter/android/app/src/main/kotlin/dev/fluttergemma/functioncalling/MainActivity.kt b/codelabs/function-calling-flutter-gemma/step_01_starter/android/app/src/main/kotlin/dev/fluttergemma/functioncalling/MainActivity.kt new file mode 100644 index 000000000..e4e274d6e --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/android/app/src/main/kotlin/dev/fluttergemma/functioncalling/MainActivity.kt @@ -0,0 +1,5 @@ +package dev.fluttergemma.functioncalling + +import io.flutter.embedding.android.FlutterActivity + +class MainActivity : FlutterActivity() diff --git a/codelabs/function-calling-flutter-gemma/step_01_starter/android/app/src/main/res/drawable-v21/launch_background.xml b/codelabs/function-calling-flutter-gemma/step_01_starter/android/app/src/main/res/drawable-v21/launch_background.xml new file mode 100644 index 000000000..f74085f3f --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/android/app/src/main/res/drawable-v21/launch_background.xml @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/codelabs/function-calling-flutter-gemma/step_01_starter/android/app/src/main/res/drawable/launch_background.xml b/codelabs/function-calling-flutter-gemma/step_01_starter/android/app/src/main/res/drawable/launch_background.xml new file mode 100644 index 000000000..304732f88 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/android/app/src/main/res/drawable/launch_background.xml @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/codelabs/function-calling-flutter-gemma/step_01_starter/android/app/src/main/res/mipmap-hdpi/ic_launcher.png b/codelabs/function-calling-flutter-gemma/step_01_starter/android/app/src/main/res/mipmap-hdpi/ic_launcher.png new file mode 100644 index 000000000..db77bb4b7 Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_01_starter/android/app/src/main/res/mipmap-hdpi/ic_launcher.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_01_starter/android/app/src/main/res/mipmap-mdpi/ic_launcher.png b/codelabs/function-calling-flutter-gemma/step_01_starter/android/app/src/main/res/mipmap-mdpi/ic_launcher.png new file mode 100644 index 000000000..17987b79b Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_01_starter/android/app/src/main/res/mipmap-mdpi/ic_launcher.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_01_starter/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/codelabs/function-calling-flutter-gemma/step_01_starter/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png new file mode 100644 index 000000000..09d439148 Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_01_starter/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_01_starter/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/codelabs/function-calling-flutter-gemma/step_01_starter/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png new file mode 100644 index 000000000..d5f1c8d34 Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_01_starter/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_01_starter/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/codelabs/function-calling-flutter-gemma/step_01_starter/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 000000000..4d6372eeb Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_01_starter/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_01_starter/android/app/src/main/res/values-night/styles.xml b/codelabs/function-calling-flutter-gemma/step_01_starter/android/app/src/main/res/values-night/styles.xml new file mode 100644 index 000000000..06952be74 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/android/app/src/main/res/values-night/styles.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/codelabs/function-calling-flutter-gemma/step_01_starter/android/app/src/main/res/values/styles.xml b/codelabs/function-calling-flutter-gemma/step_01_starter/android/app/src/main/res/values/styles.xml new file mode 100644 index 000000000..cb1ef8805 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/android/app/src/main/res/values/styles.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/codelabs/function-calling-flutter-gemma/step_01_starter/android/app/src/profile/AndroidManifest.xml b/codelabs/function-calling-flutter-gemma/step_01_starter/android/app/src/profile/AndroidManifest.xml new file mode 100644 index 000000000..399f6981d --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/android/app/src/profile/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + diff --git a/codelabs/function-calling-flutter-gemma/step_01_starter/android/build.gradle.kts b/codelabs/function-calling-flutter-gemma/step_01_starter/android/build.gradle.kts new file mode 100644 index 000000000..dbee657bb --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/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/codelabs/function-calling-flutter-gemma/step_01_starter/android/gradle.properties b/codelabs/function-calling-flutter-gemma/step_01_starter/android/gradle.properties new file mode 100644 index 000000000..e96108cfe --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/android/gradle.properties @@ -0,0 +1,6 @@ +org.gradle.jvmargs=-Xmx8G -XX:MaxMetaspaceSize=4G -XX:ReservedCodeCacheSize=512m -XX:+HeapDumpOnOutOfMemoryError +android.useAndroidX=true +# This newDsl flag was added by the Flutter template +android.newDsl=false +# This builtInKotlin flag was added by the Flutter template +android.builtInKotlin=false diff --git a/codelabs/function-calling-flutter-gemma/step_01_starter/android/gradle/wrapper/gradle-wrapper.properties b/codelabs/function-calling-flutter-gemma/step_01_starter/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 000000000..a20f2c46d --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/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-9.3.1-all.zip diff --git a/codelabs/function-calling-flutter-gemma/step_01_starter/android/settings.gradle.kts b/codelabs/function-calling-flutter-gemma/step_01_starter/android/settings.gradle.kts new file mode 100644 index 000000000..b28021a91 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/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 "9.1.0" apply false + id("org.jetbrains.kotlin.android") version "2.4.0" apply false +} + +include(":app") diff --git a/codelabs/function-calling-flutter-gemma/step_01_starter/ios/.gitignore b/codelabs/function-calling-flutter-gemma/step_01_starter/ios/.gitignore new file mode 100644 index 000000000..7a7f9873a --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/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/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Flutter/AppFrameworkInfo.plist b/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Flutter/AppFrameworkInfo.plist new file mode 100644 index 000000000..391a902b2 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Flutter/AppFrameworkInfo.plist @@ -0,0 +1,24 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + App + CFBundleIdentifier + io.flutter.flutter.app + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + App + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.0 + CFBundleSignature + ???? + CFBundleVersion + 1.0 + + diff --git a/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Flutter/Debug.xcconfig b/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Flutter/Debug.xcconfig new file mode 100644 index 000000000..592ceee85 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Flutter/Debug.xcconfig @@ -0,0 +1 @@ +#include "Generated.xcconfig" diff --git a/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Flutter/Release.xcconfig b/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Flutter/Release.xcconfig new file mode 100644 index 000000000..592ceee85 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Flutter/Release.xcconfig @@ -0,0 +1 @@ +#include "Generated.xcconfig" diff --git a/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner.xcodeproj/project.pbxproj b/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner.xcodeproj/project.pbxproj new file mode 100644 index 000000000..249dc6542 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner.xcodeproj/project.pbxproj @@ -0,0 +1,655 @@ +// !$*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 */; }; + 7884E8682EC3CC0700C636F2 /* SceneDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7884E8672EC3CC0400C636F2 /* SceneDelegate.swift */; }; + 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */ = {isa = PBXBuildFile; productRef = 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */; }; + 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 = ""; }; + 7884E8672EC3CC0400C636F2 /* SceneDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SceneDelegate.swift; sourceTree = ""; }; + 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */ = {isa = PBXFileReference; lastKnownFileType = wrapper; name = FlutterGeneratedPluginSwiftPackage; path = Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage; 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 = ""; }; + C0DE1AB52ED000000000E17E /* Runner.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = Runner.entitlements; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 97C146EB1CF9000F007C117D /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 331C8082294A63A400263BE5 /* RunnerTests */ = { + isa = PBXGroup; + children = ( + 331C807B294A618700263BE5 /* RunnerTests.swift */, + ); + path = RunnerTests; + sourceTree = ""; + }; + 9740EEB11CF90186004384FC /* Flutter */ = { + isa = PBXGroup; + children = ( + 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */, + 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 */, + C0DE1AB52ED000000000E17E /* Runner.entitlements */, + 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */, + 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */, + 74858FAE1ED2DC5600515810 /* AppDelegate.swift */, + 7884E8672EC3CC0400C636F2 /* SceneDelegate.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; + packageProductDependencies = ( + 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */, + ); + 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; + packageReferences = ( + 781AD8BC2B33823900A9FFBB /* XCLocalSwiftPackageReference "Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage" */, + ); + 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 */, + 7884E8682EC3CC0700C636F2 /* SceneDelegate.swift 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 = 15.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + STRING_CATALOG_GENERATE_SYMBOLS = YES; + 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; + CODE_SIGN_ENTITLEMENTS = Runner/Runner.entitlements; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + DEVELOPMENT_TEAM = 6ZHF6A3G28; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = dev.fluttergemma.functioncalling; + 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 = dev.fluttergemma.functioncalling.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 = dev.fluttergemma.functioncalling.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 = dev.fluttergemma.functioncalling.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 = 15.0; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = iphoneos; + STRING_CATALOG_GENERATE_SYMBOLS = YES; + 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 = 15.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + STRING_CATALOG_GENERATE_SYMBOLS = YES; + 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; + CODE_SIGN_ENTITLEMENTS = Runner/Runner.entitlements; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + DEVELOPMENT_TEAM = 6ZHF6A3G28; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = dev.fluttergemma.functioncalling; + 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; + CODE_SIGN_ENTITLEMENTS = Runner/Runner.entitlements; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + DEVELOPMENT_TEAM = 6ZHF6A3G28; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = dev.fluttergemma.functioncalling; + 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 */ + +/* Begin XCLocalSwiftPackageReference section */ + 781AD8BC2B33823900A9FFBB /* XCLocalSwiftPackageReference "Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage" */ = { + isa = XCLocalSwiftPackageReference; + relativePath = Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage; + }; +/* End XCLocalSwiftPackageReference section */ + +/* Begin XCSwiftPackageProductDependency section */ + 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */ = { + isa = XCSwiftPackageProductDependency; + productName = FlutterGeneratedPluginSwiftPackage; + }; +/* End XCSwiftPackageProductDependency section */ + }; + rootObject = 97C146E61CF9000F007C117D /* Project object */; +} diff --git a/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata new file mode 100644 index 000000000..919434a62 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 000000000..18d981003 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings new file mode 100644 index 000000000..f9b0d7c5e --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings @@ -0,0 +1,8 @@ + + + + + PreviewsEnabled + + + diff --git a/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme new file mode 100644 index 000000000..c3fedb29c --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -0,0 +1,119 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner.xcworkspace/contents.xcworkspacedata b/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner.xcworkspace/contents.xcworkspacedata new file mode 100644 index 000000000..1d526a16e --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 000000000..18d981003 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings new file mode 100644 index 000000000..f9b0d7c5e --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings @@ -0,0 +1,8 @@ + + + + + PreviewsEnabled + + + diff --git a/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner/AppDelegate.swift b/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner/AppDelegate.swift new file mode 100644 index 000000000..c30b367ec --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner/AppDelegate.swift @@ -0,0 +1,16 @@ +import Flutter +import UIKit + +@main +@objc class AppDelegate: FlutterAppDelegate, FlutterImplicitEngineDelegate { + override func application( + _ application: UIApplication, + didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? + ) -> Bool { + return super.application(application, didFinishLaunchingWithOptions: launchOptions) + } + + func didInitializeImplicitFlutterEngine(_ engineBridge: FlutterImplicitEngineBridge) { + GeneratedPluginRegistrant.register(with: engineBridge.pluginRegistry) + } +} diff --git a/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json b/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 000000000..d36b1fab2 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/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/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png b/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png new file mode 100644 index 000000000..dc9ada472 Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png b/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png new file mode 100644 index 000000000..7353c41ec Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png b/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png new file mode 100644 index 000000000..797d452e4 Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png b/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png new file mode 100644 index 000000000..6ed2d933e Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png b/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png new file mode 100644 index 000000000..4cd7b0099 Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png b/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png new file mode 100644 index 000000000..fe730945a Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png b/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png new file mode 100644 index 000000000..321773cd8 Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png b/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png new file mode 100644 index 000000000..797d452e4 Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png b/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png new file mode 100644 index 000000000..502f463a9 Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png b/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png new file mode 100644 index 000000000..0ec303439 Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png b/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png new file mode 100644 index 000000000..0ec303439 Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png b/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png new file mode 100644 index 000000000..e9f5fea27 Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png b/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png new file mode 100644 index 000000000..84ac32ae7 Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png b/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png new file mode 100644 index 000000000..8953cba09 Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png b/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png new file mode 100644 index 000000000..0467bf12a Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json b/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json new file mode 100644 index 000000000..0bedcf2fd --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/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/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png b/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png new file mode 100644 index 000000000..9da19eaca Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png b/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png new file mode 100644 index 000000000..9da19eaca Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png b/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png new file mode 100644 index 000000000..9da19eaca Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md b/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md new file mode 100644 index 000000000..89c2725b7 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/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/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner/Base.lproj/LaunchScreen.storyboard b/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner/Base.lproj/LaunchScreen.storyboard new file mode 100644 index 000000000..f2e259c7c --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner/Base.lproj/LaunchScreen.storyboard @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner/Base.lproj/Main.storyboard b/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner/Base.lproj/Main.storyboard new file mode 100644 index 000000000..f3c28516f --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner/Base.lproj/Main.storyboard @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner/Info.plist b/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner/Info.plist new file mode 100644 index 000000000..c97226dba --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner/Info.plist @@ -0,0 +1,70 @@ + + + + + CADisableMinimumFrameDurationOnPhone + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleDisplayName + Gemma Function Calling + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + functioncalling + CFBundlePackageType + APPL + CFBundleShortVersionString + $(FLUTTER_BUILD_NAME) + CFBundleSignature + ???? + CFBundleVersion + $(FLUTTER_BUILD_NUMBER) + LSRequiresIPhoneOS + + UIApplicationSceneManifest + + UIApplicationSupportsMultipleScenes + + UISceneConfigurations + + UIWindowSceneSessionRoleApplication + + + UISceneClassName + UIWindowScene + UISceneConfigurationName + flutter + UISceneDelegateClassName + $(PRODUCT_MODULE_NAME).SceneDelegate + UISceneStoryboardFile + Main + + + + + UIApplicationSupportsIndirectInputEvents + + UILaunchStoryboardName + LaunchScreen + UIMainStoryboardFile + Main + UISupportedInterfaceOrientations + + UIInterfaceOrientationPortrait + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + UISupportedInterfaceOrientations~ipad + + UIInterfaceOrientationPortrait + UIInterfaceOrientationPortraitUpsideDown + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + + diff --git a/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner/Runner-Bridging-Header.h b/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner/Runner-Bridging-Header.h new file mode 100644 index 000000000..308a2a560 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner/Runner-Bridging-Header.h @@ -0,0 +1 @@ +#import "GeneratedPluginRegistrant.h" diff --git a/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner/Runner.entitlements b/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner/Runner.entitlements new file mode 100644 index 000000000..cd461aae4 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner/Runner.entitlements @@ -0,0 +1,12 @@ + + + + + com.apple.developer.kernel.extended-virtual-addressing + + com.apple.developer.kernel.increased-memory-limit + + com.apple.developer.kernel.increased-debugging-memory-limit + + + diff --git a/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner/SceneDelegate.swift b/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner/SceneDelegate.swift new file mode 100644 index 000000000..b9ce8ea2b --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/ios/Runner/SceneDelegate.swift @@ -0,0 +1,6 @@ +import Flutter +import UIKit + +class SceneDelegate: FlutterSceneDelegate { + +} diff --git a/codelabs/function-calling-flutter-gemma/step_01_starter/ios/RunnerTests/RunnerTests.swift b/codelabs/function-calling-flutter-gemma/step_01_starter/ios/RunnerTests/RunnerTests.swift new file mode 100644 index 000000000..86a7c3b1b --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/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/codelabs/function-calling-flutter-gemma/step_01_starter/lib/chat_page.dart b/codelabs/function-calling-flutter-gemma/step_01_starter/lib/chat_page.dart new file mode 100644 index 000000000..2924930c6 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/lib/chat_page.dart @@ -0,0 +1,302 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_gemma/flutter_gemma.dart'; + +import 'model.dart'; + +/// A chat that shows the reply as it is generated. +/// +/// `generateChatResponseAsync` emits one [ModelResponse] per decoded chunk, +/// so the first words appear long before the last one is computed. +class ChatPage extends StatefulWidget { + const ChatPage({ + super.key, + required this.model, + required this.onModelRemoved, + }); + + final ModelChoice model; + + /// Lets the gate send the app back to the download screen. + final VoidCallback onModelRemoved; + + @override + State createState() => _ChatPageState(); +} + +class _ChatPageState extends State { + final _input = TextEditingController(); + final _turns = <_Turn>[]; + + InferenceModel? _inference; + InferenceChat? _chat; + bool _busy = false; + Object? _loadError; + + @override + void initState() { + super.initState(); + _load(); + } + + Future _load() async { + try { + // maxTokens is the CONTEXT WINDOW — prompt + history + reply share it. + // It is NOT a reply-length cap; for that, pass maxOutputTokens below. + // maxTokens 1024 is what this checkpoint is built for; the example app + // uses the same, and it is the value this was measured at. + // + // This checkpoint is asked to run on the CPU, and the reason is the + // FILE, not the platform and not the model. The published artifact was + // converted before litetune 0.1.4 began setting `prefer_activation_type=fp32`, + // and without that key the GPU path answers every prompt with `` to + // the token limit — measured on Android and on macOS Metal alike, with no + // exception and no warning, a chat that looks alive and returns filler. + // + // Re-converted with a current litetune — which Step 4 does — the same + // weights score identically on GPU and run about 1.5x faster. So this is + // a workaround for one downloadable file, not a property of FunctionGemma. + final inference = await FlutterGemma.getActiveModel( + maxTokens: 1024, + preferredBackend: PreferredBackend.cpu, + ); + // Hold the runtime before opening a chat on it: `createChat` can throw, + // and a model this page never stored is a model `dispose` can never + // close. A page that is already gone holds nothing, so it closes it here. + if (!mounted) { + await inference.close(); + return; + } + setState(() => _inference = inference); + + final chat = await inference.createChat( + modelType: widget.model.modelType, + maxOutputTokens: 256, + ); + // The same guard, one call later and for the same reason: a chat this + // page never stored is a native session `dispose` can never close. + if (!mounted) { + await chat.close(); + return; + } + setState(() => _chat = chat); + } catch (error) { + // Loading is the likeliest thing to fail on a real device: a forgotten + // engine package, too little memory, a half-written model file. Show it + // instead of sitting on the progress bar forever. + if (mounted) setState(() => _loadError = error); + } + } + + void _retryLoad() { + setState(() => _loadError = null); + _load(); + } + + Future _send() async { + final chat = _chat; + final text = _input.text.trim(); + if (chat == null || text.isEmpty || _busy) return; + + setState(() { + _turns + ..add(_Turn(text, fromUser: true)) + // The reply starts empty and grows as chunks arrive. + ..add(_Turn('', fromUser: false)); + _input.clear(); + _busy = true; + }); + + try { + await chat.addQueryChunk(Message.text(text: text, isUser: true)); + + final buffer = StringBuffer(); + await for (final chunk in chat.generateChatResponseAsync()) { + // Each TextResponse carries only the NEW text, not the whole reply + // so far — append, never replace. + if (chunk is TextResponse) { + buffer.write(chunk.token); + if (!mounted) return; + setState( + () => _turns[_turns.length - 1] = _Turn( + buffer.toString(), + fromUser: false, + ), + ); + } + } + } catch (error) { + // The half-written reply becomes the error, so the empty bubble never + // just sits there. The chat's own history now holds a user turn the model + // never answered; a production app would reset it with `clearHistory`. + if (mounted) { + setState( + () => _turns[_turns.length - 1] = _Turn('⚠️ $error', fromUser: false), + ); + } + } finally { + // `_busy` is what disables the composer, so clearing it belongs in + // `finally` — a failed generation must not lock the app. + if (mounted) setState(() => _busy = false); + } + } + + /// Frees the disk. Close the runtime first — the file is mapped while a + /// model is open, and deleting it underneath the engine is a crash waiting + /// to happen. + Future _removeModel() async { + try { + await _inference?.close(); + // Inside `setState`: dropping the chat has to repaint, or the screen + // keeps showing an enabled composer over a runtime that is gone. + if (mounted) { + setState(() { + _inference = null; + _chat = null; + }); + } + await FlutterGemma.uninstallModel(widget.model.fileName); + if (mounted) widget.onModelRemoved(); + } catch (error) { + // Deleting can fail too — a missing install record, a file the OS still + // holds. Show it the way a failed load is shown, and drop the chat with + // it: a `close()` that threw leaves `_chat` non-null, and "The model did + // not load." over a working composer is a lie. + if (mounted) { + setState(() { + _chat = null; + _loadError = error; + }); + } + } + } + + @override + void dispose() { + // Sessions and models hold native memory — always close them. `dispose` + // cannot await, so the future is dropped on purpose, and caught so a + // failing native teardown does not escape as an unhandled async error. + _inference?.close().catchError((Object _) {}); + _input.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final ready = _chat != null; + final error = _loadError; + + return Scaffold( + appBar: AppBar( + title: Text(widget.model.label), + actions: [ + IconButton( + tooltip: 'Delete the downloaded model', + // Not while the model is still opening: deleting the file + // underneath an in-flight `getActiveModel()` is the crash the + // comment on `_removeModel` warns about. + onPressed: _busy || (!ready && error == null) ? null : _removeModel, + icon: const Icon(Icons.delete_outline), + ), + ], + ), + body: Column( + children: [ + if (error != null) + _LoadFailed(error: error, onRetry: _retryLoad) + else if (!ready) + const LinearProgressIndicator(), + Expanded( + child: ListView.builder( + padding: const EdgeInsets.all(16), + itemCount: _turns.length, + itemBuilder: (context, i) => _Bubble(turn: _turns[i]), + ), + ), + SafeArea( + child: Padding( + padding: const EdgeInsets.fromLTRB(12, 0, 12, 12), + child: Row( + children: [ + Expanded( + child: TextField( + controller: _input, + enabled: ready && !_busy, + onSubmitted: (_) => _send(), + decoration: InputDecoration( + hintText: ready + ? 'Ask something' + : error != null + ? 'No model loaded' + : 'Loading the model…', + border: const OutlineInputBorder(), + ), + ), + ), + const SizedBox(width: 8), + IconButton.filled( + onPressed: ready && !_busy ? _send : null, + icon: const Icon(Icons.send), + ), + ], + ), + ), + ), + ], + ), + ); + } +} + +/// Shown in place of the loading bar when the model could not be opened. +class _LoadFailed extends StatelessWidget { + const _LoadFailed({required this.error, required this.onRetry}); + + final Object error; + final VoidCallback onRetry; + + @override + Widget build(BuildContext context) { + return Padding( + padding: const EdgeInsets.all(16), + child: Column( + children: [ + Text('The model did not load.\n$error', textAlign: TextAlign.center), + const SizedBox(height: 8), + FilledButton(onPressed: onRetry, child: const Text('Try again')), + ], + ), + ); + } +} + +class _Turn { + const _Turn(this.text, {required this.fromUser}); + final String text; + final bool fromUser; +} + +class _Bubble extends StatelessWidget { + const _Bubble({required this.turn}); + + final _Turn turn; + + @override + Widget build(BuildContext context) { + final scheme = Theme.of(context).colorScheme; + return Align( + alignment: turn.fromUser ? Alignment.centerRight : Alignment.centerLeft, + child: Container( + margin: const EdgeInsets.symmetric(vertical: 4), + padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10), + constraints: const BoxConstraints(maxWidth: 520), + decoration: BoxDecoration( + color: turn.fromUser + ? scheme.primaryContainer + : scheme.surfaceContainerHighest, + borderRadius: BorderRadius.circular(12), + ), + child: SelectableText(turn.text), + ), + ); + } +} diff --git a/codelabs/function-calling-flutter-gemma/step_01_starter/lib/download_page.dart b/codelabs/function-calling-flutter-gemma/step_01_starter/lib/download_page.dart new file mode 100644 index 000000000..0e0ebf030 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/lib/download_page.dart @@ -0,0 +1,138 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_gemma/flutter_gemma.dart'; + +import 'model.dart'; + +/// Installs the model file, reporting progress as it goes. +/// +/// Nothing here knows about tools: `installModel` takes the model's identity +/// (what it is) and `fromNetwork` takes the source (where the bytes are). A +/// function-calling model installs exactly like a text one — tools are a +/// property of the SESSION you open later, not of the file you download. +class DownloadPage extends StatefulWidget { + const DownloadPage({ + super.key, + required this.model, + required this.onInstalled, + }); + + final ModelChoice model; + + /// Called once the model is installed, so the app can move on. + final VoidCallback onInstalled; + + @override + State createState() => _DownloadPageState(); +} + +class _DownloadPageState extends State { + int _percent = 0; + bool _downloading = false; + Object? _error; + + Future _download() async { + setState(() { + _downloading = true; + _error = null; + }); + + try { + await FlutterGemma.installModel( + // What the model IS — used to pick the right chat template. + modelType: widget.model.modelType, + // Which runtime reads it. `.litertlm` routes to LiteRtLmEngine; + // the default is `task` (MediaPipe), so this line is load-bearing. + fileType: ModelFileType.litertlm, + ).fromNetwork(widget.model.url).withProgress((percent) { + if (mounted) setState(() => _percent = percent); + }).install(); + + if (mounted) widget.onInstalled(); + } catch (error) { + if (mounted) setState(() => _error = error); + } finally { + if (mounted) setState(() => _downloading = false); + } + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + + return Scaffold( + appBar: AppBar(title: const Text('Get the model')), + body: Center( + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 420), + child: Padding( + padding: const EdgeInsets.all(24), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Text(widget.model.label, style: theme.textTheme.headlineSmall), + const SizedBox(height: 8), + Text( + '${widget.model.sizeLabel} — downloaded once, then it lives ' + 'on the device and runs with the network off.', + style: theme.textTheme.bodyMedium, + ), + const SizedBox(height: 24), + if (_downloading) ...[ + LinearProgressIndicator(value: _percent / 100), + const SizedBox(height: 8), + Text('$_percent%', textAlign: TextAlign.center), + ] else + FilledButton( + onPressed: _download, + child: const Text('Download model'), + ), + if (_error != null) ...[ + const SizedBox(height: 16), + _ErrorCard(error: _error!), + ], + ], + ), + ), + ), + ), + ); + } +} + +/// Says what failed, in the plugin's own words where it has any. +class _ErrorCard extends StatelessWidget { + const _ErrorCard({required this.error}); + + final Object error; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + // The plugin reports a failed download as a typed `DownloadException` + // wrapping a sealed `DownloadError`, so match on the type rather than + // sniffing the message for a status code. + final (title, body) = switch (error) { + DownloadException(:final error) => ( + 'Download failed', + error.toUserMessage(), + ), + _ => ('Download failed', '$error'), + }; + + return Card( + color: theme.colorScheme.errorContainer, + child: Padding( + padding: const EdgeInsets.all(16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(title, style: theme.textTheme.titleSmall), + const SizedBox(height: 8), + Text(body), + ], + ), + ), + ); + } +} diff --git a/codelabs/function-calling-flutter-gemma/step_01_starter/lib/main.dart b/codelabs/function-calling-flutter-gemma/step_01_starter/lib/main.dart new file mode 100644 index 000000000..8241664e4 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/lib/main.dart @@ -0,0 +1,173 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_gemma/flutter_gemma.dart'; +import 'package:flutter_gemma_litertlm/flutter_gemma_litertlm.dart'; + +import 'chat_page.dart'; +import 'download_page.dart'; +import 'model.dart'; + +/// The model this step runs: 284 MB, and function calling is what it is for. +const _model = Models.functionGemma; + +Future main() async { + WidgetsFlutterBinding.ensureInitialized(); + + // Engines are fully opt-in: the core package registers none by itself. + // Without LiteRtLmEngine here, the first model call throws a StateError + // that tells you to add an engine package. + // + // No `huggingFaceToken:` — the repository this codelab downloads from is + // ungated, so every `flutter run` is a plain `flutter run` with no + // `--dart-define`. + // + // Guarded, because every other failure in this app reaches the screen — the + // gate's error card, the chat's load error, the notice line — and this is the + // earliest one, so it is the one a learner meets first. Hot-restarting after + // adding a plugin throws `MissingPluginException` right here; unguarded, it + // never reaches `runApp` and the symptom is a blank window and a stack trace + // in a console nobody is looking at. + try { + await FlutterGemma.initialize(inferenceEngines: [LiteRtLmEngine()]); + } catch (error) { + runApp(_StartupFailed(error: error)); + return; + } + + runApp(const FunctionCallingApp()); +} + +/// Shown in place of the app when `FlutterGemma.initialize` throws, so a +/// failure before the first frame is a sentence instead of a blank window. +class _StartupFailed extends StatelessWidget { + const _StartupFailed({required this.error}); + + final Object error; + + @override + Widget build(BuildContext context) { + return MaterialApp( + title: 'Gemma Function Calling', + home: Scaffold( + body: Center( + child: Padding( + padding: const EdgeInsets.all(24), + child: Text( + 'flutter_gemma could not start.\n$error', + textAlign: TextAlign.center, + ), + ), + ), + ), + ); + } +} + +class FunctionCallingApp extends StatelessWidget { + const FunctionCallingApp({super.key}); + + @override + Widget build(BuildContext context) { + return MaterialApp( + title: 'Gemma Function Calling', + theme: ThemeData(colorSchemeSeed: Colors.indigo), + home: const ModelGate(model: _model), + ); + } +} + +/// Asks, on every cold start, whether the model is already installed. +/// +/// `install()` is idempotent, so the bytes are only ever fetched once. What a +/// drifted id costs you is this gate: it answers "no" forever, so the app +/// shows the download screen on every launch, the "download" there finishes +/// instantly, and you land straight back here. Delete the model with the chat's +/// delete button and relaunch to watch this branch flip back. +class ModelGate extends StatefulWidget { + const ModelGate({super.key, required this.model}); + + final ModelChoice model; + + @override + State createState() => _ModelGateState(); +} + +class _ModelGateState extends State { + late Future _installed = _check(); + + /// Installed is not the same as active. `getActiveModel` opens whichever + /// model was installed LAST, and this codelab's steps install two different + /// ones into a single application identity — so a run that finds the file + /// already here still has to say which model it means. `install()` is + /// idempotent: on a file already on disk it downloads nothing and just + /// records this model as the current one. + Future _check() async { + if (!await FlutterGemma.isModelInstalled(widget.model.fileName)) { + return false; + } + await FlutterGemma.installModel( + modelType: widget.model.modelType, + fileType: ModelFileType.litertlm, + ).fromNetwork(widget.model.url).install(); + return true; + } + + @override + Widget build(BuildContext context) { + return FutureBuilder( + future: _installed, + builder: (context, snapshot) { + if (snapshot.connectionState != ConnectionState.done) { + return const Scaffold( + body: Center(child: CircularProgressIndicator()), + ); + } + if (snapshot.hasError) { + // A FutureBuilder that ignores `hasError` renders the download + // screen as if nothing had gone wrong. Say what failed instead. + return _GateError( + error: snapshot.error!, + onRetry: () => setState(() => _installed = _check()), + ); + } + if (snapshot.data ?? false) { + return ChatPage( + model: widget.model, + onModelRemoved: () => setState(() => _installed = _check()), + ); + } + return DownloadPage( + model: widget.model, + onInstalled: () => setState(() => _installed = _check()), + ); + }, + ); + } +} + +/// Shown when the gate's own check fails, rather than falling through to the +/// download screen as if the answer had been "no". +class _GateError extends StatelessWidget { + const _GateError({required this.error, required this.onRetry}); + + final Object error; + final VoidCallback onRetry; + + @override + Widget build(BuildContext context) { + return Scaffold( + body: Center( + child: Padding( + padding: const EdgeInsets.all(24), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Text('$error', textAlign: TextAlign.center), + const SizedBox(height: 12), + FilledButton(onPressed: onRetry, child: const Text('Try again')), + ], + ), + ), + ), + ); + } +} diff --git a/codelabs/function-calling-flutter-gemma/step_01_starter/lib/model.dart b/codelabs/function-calling-flutter-gemma/step_01_starter/lib/model.dart new file mode 100644 index 000000000..2cefb1425 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/lib/model.dart @@ -0,0 +1,54 @@ +import 'package:flutter_gemma/flutter_gemma.dart'; + +/// One model this app knows how to install. +/// +/// [fileName] doubles as the model's id: `FlutterGemma.isModelInstalled` takes +/// the file name the model was installed under, not a display name. +class ModelChoice { + const ModelChoice({ + required this.label, + required this.url, + required this.fileName, + required this.modelType, + required this.sizeLabel, + }); + + final String label; + final String url; + final String fileName; + + /// Which family's function-call format the SDK should read and write. + /// + /// This is not decoration. `ModelType.functionGemma` selects + /// `FunctionGemmaCallFormat`, which renders the tool declarations into a + /// developer turn and parses `call:name{…}` back out + /// again. Name a different family and the SDK writes a prompt these weights + /// were never trained on and looks for a call in a syntax they never emit — + /// so every turn comes back as plain text and nothing says why. + final ModelType modelType; + + final String sizeLabel; +} + +/// The one model this step ships. +/// +/// The repository is ungated, so nothing here needs a Hugging Face token and +/// no run needs `--dart-define`. +abstract final class Models { + /// A 270M model whose whole job is function calling. + /// + /// 284 MB — small enough to download while you read this page, and small + /// enough that it does very little else: ask it a general question and the + /// answer will be thin. That is the trade this step is making on purpose. + /// Calling a function is a narrow skill, and a model specialised for it can + /// be a fraction of the size of one that also has to hold a conversation. + static const functionGemma = ModelChoice( + label: 'FunctionGemma 270M', + url: + 'https://huggingface.co/sasha-denisov/function-gemma-270M-it/' + 'resolve/main/functiongemma-270M-it.litertlm', + fileName: 'functiongemma-270M-it.litertlm', + modelType: ModelType.functionGemma, + sizeLabel: '284 MB', + ); +} diff --git a/codelabs/function-calling-flutter-gemma/step_01_starter/linux/.gitignore b/codelabs/function-calling-flutter-gemma/step_01_starter/linux/.gitignore new file mode 100644 index 000000000..d3896c984 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/linux/.gitignore @@ -0,0 +1 @@ +flutter/ephemeral diff --git a/codelabs/function-calling-flutter-gemma/step_01_starter/linux/CMakeLists.txt b/codelabs/function-calling-flutter-gemma/step_01_starter/linux/CMakeLists.txt new file mode 100644 index 000000000..f21ac7bae --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/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 "functioncalling") +# The unique GTK application identifier for this application. See: +# https://wiki.gnome.org/HowDoI/ChooseApplicationID +set(APPLICATION_ID "dev.fluttergemma.functioncalling") + +# 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/codelabs/function-calling-flutter-gemma/step_01_starter/linux/flutter/CMakeLists.txt b/codelabs/function-calling-flutter-gemma/step_01_starter/linux/flutter/CMakeLists.txt new file mode 100644 index 000000000..d5bd01648 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/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/codelabs/function-calling-flutter-gemma/step_01_starter/linux/flutter/generated_plugin_registrant.cc b/codelabs/function-calling-flutter-gemma/step_01_starter/linux/flutter/generated_plugin_registrant.cc new file mode 100644 index 000000000..198e9645a --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/linux/flutter/generated_plugin_registrant.cc @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + +#include + +void fl_register_plugins(FlPluginRegistry* registry) { + g_autoptr(FlPluginRegistrar) flutter_gemma_registrar = + fl_plugin_registry_get_registrar_for_plugin(registry, "FlutterGemmaPlugin"); + flutter_gemma_plugin_register_with_registrar(flutter_gemma_registrar); +} diff --git a/codelabs/function-calling-flutter-gemma/step_01_starter/linux/flutter/generated_plugin_registrant.h b/codelabs/function-calling-flutter-gemma/step_01_starter/linux/flutter/generated_plugin_registrant.h new file mode 100644 index 000000000..e0f0a47bc --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/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/codelabs/function-calling-flutter-gemma/step_01_starter/linux/flutter/generated_plugins.cmake b/codelabs/function-calling-flutter-gemma/step_01_starter/linux/flutter/generated_plugins.cmake new file mode 100644 index 000000000..3b0705d0f --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/linux/flutter/generated_plugins.cmake @@ -0,0 +1,25 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST + flutter_gemma +) + +list(APPEND FLUTTER_FFI_PLUGIN_LIST + jni +) + +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/codelabs/function-calling-flutter-gemma/step_01_starter/linux/runner/CMakeLists.txt b/codelabs/function-calling-flutter-gemma/step_01_starter/linux/runner/CMakeLists.txt new file mode 100644 index 000000000..e97dabc70 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/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/codelabs/function-calling-flutter-gemma/step_01_starter/linux/runner/main.cc b/codelabs/function-calling-flutter-gemma/step_01_starter/linux/runner/main.cc new file mode 100644 index 000000000..e7c5c5437 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/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/codelabs/function-calling-flutter-gemma/step_01_starter/linux/runner/my_application.cc b/codelabs/function-calling-flutter-gemma/step_01_starter/linux/runner/my_application.cc new file mode 100644 index 000000000..917c019cf --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/linux/runner/my_application.cc @@ -0,0 +1,148 @@ +#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, "Gemma Function Calling"); + 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, "Gemma Function Calling"); + } + + 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/codelabs/function-calling-flutter-gemma/step_01_starter/linux/runner/my_application.h b/codelabs/function-calling-flutter-gemma/step_01_starter/linux/runner/my_application.h new file mode 100644 index 000000000..db16367a7 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/linux/runner/my_application.h @@ -0,0 +1,21 @@ +#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/codelabs/function-calling-flutter-gemma/step_01_starter/macos/.gitignore b/codelabs/function-calling-flutter-gemma/step_01_starter/macos/.gitignore new file mode 100644 index 000000000..746adbb6b --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/macos/.gitignore @@ -0,0 +1,7 @@ +# Flutter-related +**/Flutter/ephemeral/ +**/Pods/ + +# Xcode-related +**/dgph +**/xcuserdata/ diff --git a/codelabs/function-calling-flutter-gemma/step_01_starter/macos/Flutter/Flutter-Debug.xcconfig b/codelabs/function-calling-flutter-gemma/step_01_starter/macos/Flutter/Flutter-Debug.xcconfig new file mode 100644 index 000000000..4b81f9b2d --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/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/codelabs/function-calling-flutter-gemma/step_01_starter/macos/Flutter/Flutter-Release.xcconfig b/codelabs/function-calling-flutter-gemma/step_01_starter/macos/Flutter/Flutter-Release.xcconfig new file mode 100644 index 000000000..5caa9d157 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/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/codelabs/function-calling-flutter-gemma/step_01_starter/macos/Flutter/GeneratedPluginRegistrant.swift b/codelabs/function-calling-flutter-gemma/step_01_starter/macos/Flutter/GeneratedPluginRegistrant.swift new file mode 100644 index 000000000..0be86a9b4 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/macos/Flutter/GeneratedPluginRegistrant.swift @@ -0,0 +1,18 @@ +// +// Generated file. Do not edit. +// + +import FlutterMacOS +import Foundation + +import connectivity_plus +import flutter_gemma +import large_file_handler +import shared_preferences_foundation + +func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { + ConnectivityPlusPlugin.register(with: registry.registrar(forPlugin: "ConnectivityPlusPlugin")) + FlutterGemmaPlugin.register(with: registry.registrar(forPlugin: "FlutterGemmaPlugin")) + LargeFileHandlerPlugin.register(with: registry.registrar(forPlugin: "LargeFileHandlerPlugin")) + SharedPreferencesPlugin.register(with: registry.registrar(forPlugin: "SharedPreferencesPlugin")) +} diff --git a/codelabs/function-calling-flutter-gemma/step_01_starter/macos/Podfile b/codelabs/function-calling-flutter-gemma/step_01_starter/macos/Podfile new file mode 100644 index 000000000..32aafe8bf --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/macos/Podfile @@ -0,0 +1,98 @@ +platform :osx, '12.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', '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 + + # flutter_gemma: stage the upstream Apple companion dylibs into the built + # .app. `hook/build.dart` deliberately skips them from Native Assets on macOS + # (#247 — Google ships them without `-Wl,-headerpad_max_install_names`, so the + # JIT bundling path cannot rewrite their install_name), which leaves this + # build phase to stage them. + # + # The phase only LOCATES and RUNS a script; the staging logic itself lives in + # flutter_gemma_litertlm and is delivered next to the dylibs it stages. That + # is deliberate: this block is frozen into your Xcode project, and a copy of + # the logic frozen there cannot be fixed by upgrading the package. + installer.aggregate_targets.each do |aggregate_target| + aggregate_target.user_targets.each do |user_target| + phase_name = '[flutter_gemma] Setup LiteRT-LM macOS' + + # Only the app target embeds the Frameworks/ this phase patches. + # RunnerTests inherits Runner's framework search paths and has no + # Contents/Frameworks of its own — having the phase there creates a + # cross-target dependency on Runner's framework output that Xcode reports + # as "Cycle inside Flutter Assemble" (#300). Remove any stale copy from + # non-app targets and skip them. + unless user_target.name == 'Runner' + user_target.build_phases + .select { |p| p.respond_to?(:name) && p.name == phase_name } + .each { |p| user_target.build_phases.delete(p) } + next + end + + existing = user_target.shell_script_build_phases.find { |p| p.name == phase_name } + phase = existing || user_target.new_shell_script_build_phase(phase_name) + # The embedded LiteRtLm binary is an INPUT so the phase re-runs whenever + # Flutter's always-out-of-date `embed` phase re-copies the raw, unpatched + # binary over the patched one. Without it Xcode caches the phase after the + # first build and the second incremental build ships an unpatched + # LiteRtLm that fails dlopen at runtime (#368). + phase.input_paths = [ + '$(BUILT_PRODUCTS_DIR)/$(PRODUCT_NAME).app/Contents/Frameworks/LiteRtLm.framework/Versions/A/LiteRtLm', + ] + # A declared output lets Xcode order the phase in its dependency graph + # instead of treating it as "runs every build with no outputs" — the other + # half of the cycle warning (#300). The script touches this file. + phase.output_paths = ['$(DERIVED_FILE_DIR)/flutter_gemma_litertlm_macos.stamp'] + phase.shell_script = <<~SHELL + set -e + STAGER="${HOME}/Library/Caches/flutter_gemma/native/macos_arm64/stage_macos_companions.sh" + if [ ! -f "${STAGER}" ]; then + echo "[flutter_gemma] ERROR: ${STAGER} not found." >&2 + echo " flutter_gemma_litertlm 1.6.2+ installs it there from its build hook." >&2 + echo " Upgrade the package, then: flutter clean && flutter pub get" >&2 + exit 1 + fi + sh "${STAGER}" "${BUILT_PRODUCTS_DIR}/${PRODUCT_NAME}.app/Contents/Frameworks" + mkdir -p "$(dirname "${SCRIPT_OUTPUT_FILE_0}")" + touch "${SCRIPT_OUTPUT_FILE_0}" + SHELL + end + end +end diff --git a/codelabs/function-calling-flutter-gemma/step_01_starter/macos/Runner.xcodeproj/project.pbxproj b/codelabs/function-calling-flutter-gemma/step_01_starter/macos/Runner.xcodeproj/project.pbxproj new file mode 100644 index 000000000..8c78df2ee --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/macos/Runner.xcodeproj/project.pbxproj @@ -0,0 +1,729 @@ +// !$*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 */; }; + 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */ = {isa = PBXBuildFile; productRef = 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */; }; +/* 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 /* Gemma Function Calling.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "Gemma Function Calling.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 = ""; }; + 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */ = {isa = PBXFileReference; lastKnownFileType = wrapper; name = FlutterGeneratedPluginSwiftPackage; path = ephemeral/Packages/FlutterGeneratedPluginSwiftPackage; 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 = ( + 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */, + ); + 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 /* Gemma Function Calling.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 = ( + 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */, + 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; + packageProductDependencies = ( + 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */, + ); + productName = Runner; + productReference = 33CC10ED2044A3C60003C045 /* Gemma Function Calling.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; + packageReferences = ( + 781AD8BC2B33823900A9FFBB /* XCLocalSwiftPackageReference "Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage" */, + ); + 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 = dev.fluttergemma.functioncalling.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/$(PRODUCT_NAME).app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/$(PRODUCT_NAME)"; + }; + 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 = dev.fluttergemma.functioncalling.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/$(PRODUCT_NAME).app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/$(PRODUCT_NAME)"; + }; + 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 = dev.fluttergemma.functioncalling.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/$(PRODUCT_NAME).app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/$(PRODUCT_NAME)"; + }; + 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 = 12.0; + 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 = 12.0; + 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 = 12.0; + 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 */ + +/* Begin XCLocalSwiftPackageReference section */ + 781AD8BC2B33823900A9FFBB /* XCLocalSwiftPackageReference "Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage" */ = { + isa = XCLocalSwiftPackageReference; + relativePath = Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage; + }; +/* End XCLocalSwiftPackageReference section */ + +/* Begin XCSwiftPackageProductDependency section */ + 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */ = { + isa = XCSwiftPackageProductDependency; + productName = FlutterGeneratedPluginSwiftPackage; + }; +/* End XCSwiftPackageProductDependency section */ + }; + rootObject = 33CC10E52044A3C60003C045 /* Project object */; +} diff --git a/codelabs/function-calling-flutter-gemma/step_01_starter/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/codelabs/function-calling-flutter-gemma/step_01_starter/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 000000000..18d981003 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/codelabs/function-calling-flutter-gemma/step_01_starter/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/codelabs/function-calling-flutter-gemma/step_01_starter/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme new file mode 100644 index 000000000..822174206 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/codelabs/function-calling-flutter-gemma/step_01_starter/macos/Runner.xcworkspace/contents.xcworkspacedata b/codelabs/function-calling-flutter-gemma/step_01_starter/macos/Runner.xcworkspace/contents.xcworkspacedata new file mode 100644 index 000000000..21a3cc14c --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/macos/Runner.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,10 @@ + + + + + + + diff --git a/codelabs/function-calling-flutter-gemma/step_01_starter/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/codelabs/function-calling-flutter-gemma/step_01_starter/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 000000000..18d981003 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/codelabs/function-calling-flutter-gemma/step_01_starter/macos/Runner/AppDelegate.swift b/codelabs/function-calling-flutter-gemma/step_01_starter/macos/Runner/AppDelegate.swift new file mode 100644 index 000000000..b3c176141 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/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/codelabs/function-calling-flutter-gemma/step_01_starter/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json b/codelabs/function-calling-flutter-gemma/step_01_starter/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 000000000..a2ec33f19 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/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/codelabs/function-calling-flutter-gemma/step_01_starter/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png b/codelabs/function-calling-flutter-gemma/step_01_starter/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png new file mode 100644 index 000000000..82b6f9d9a Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_01_starter/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_01_starter/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png b/codelabs/function-calling-flutter-gemma/step_01_starter/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png new file mode 100644 index 000000000..13b35eba5 Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_01_starter/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_01_starter/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png b/codelabs/function-calling-flutter-gemma/step_01_starter/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png new file mode 100644 index 000000000..0a3f5fa40 Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_01_starter/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_01_starter/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png b/codelabs/function-calling-flutter-gemma/step_01_starter/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png new file mode 100644 index 000000000..bdb57226d Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_01_starter/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_01_starter/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png b/codelabs/function-calling-flutter-gemma/step_01_starter/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png new file mode 100644 index 000000000..f083318e0 Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_01_starter/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_01_starter/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png b/codelabs/function-calling-flutter-gemma/step_01_starter/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png new file mode 100644 index 000000000..326c0e72c Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_01_starter/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_01_starter/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png b/codelabs/function-calling-flutter-gemma/step_01_starter/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png new file mode 100644 index 000000000..2f1632cfd Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_01_starter/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_01_starter/macos/Runner/Base.lproj/MainMenu.xib b/codelabs/function-calling-flutter-gemma/step_01_starter/macos/Runner/Base.lproj/MainMenu.xib new file mode 100644 index 000000000..80e867a4e --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/macos/Runner/Base.lproj/MainMenu.xib @@ -0,0 +1,343 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/codelabs/function-calling-flutter-gemma/step_01_starter/macos/Runner/Configs/AppInfo.xcconfig b/codelabs/function-calling-flutter-gemma/step_01_starter/macos/Runner/Configs/AppInfo.xcconfig new file mode 100644 index 000000000..0fcdf0410 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/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 = Gemma Function Calling + +// The application's bundle identifier +PRODUCT_BUNDLE_IDENTIFIER = dev.fluttergemma.functioncalling + +// The copyright displayed in application information +PRODUCT_COPYRIGHT = Copyright © 2026 dev.fluttergemma. All rights reserved. diff --git a/codelabs/function-calling-flutter-gemma/step_01_starter/macos/Runner/Configs/Debug.xcconfig b/codelabs/function-calling-flutter-gemma/step_01_starter/macos/Runner/Configs/Debug.xcconfig new file mode 100644 index 000000000..36b0fd946 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/macos/Runner/Configs/Debug.xcconfig @@ -0,0 +1,2 @@ +#include "../../Flutter/Flutter-Debug.xcconfig" +#include "Warnings.xcconfig" diff --git a/codelabs/function-calling-flutter-gemma/step_01_starter/macos/Runner/Configs/Release.xcconfig b/codelabs/function-calling-flutter-gemma/step_01_starter/macos/Runner/Configs/Release.xcconfig new file mode 100644 index 000000000..dff4f4956 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/macos/Runner/Configs/Release.xcconfig @@ -0,0 +1,2 @@ +#include "../../Flutter/Flutter-Release.xcconfig" +#include "Warnings.xcconfig" diff --git a/codelabs/function-calling-flutter-gemma/step_01_starter/macos/Runner/Configs/Warnings.xcconfig b/codelabs/function-calling-flutter-gemma/step_01_starter/macos/Runner/Configs/Warnings.xcconfig new file mode 100644 index 000000000..42bcbf478 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/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/codelabs/function-calling-flutter-gemma/step_01_starter/macos/Runner/DebugProfile.entitlements b/codelabs/function-calling-flutter-gemma/step_01_starter/macos/Runner/DebugProfile.entitlements new file mode 100644 index 000000000..8eb23d1c4 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/macos/Runner/DebugProfile.entitlements @@ -0,0 +1,16 @@ + + + + + com.apple.security.app-sandbox + + com.apple.security.cs.allow-jit + + com.apple.security.cs.disable-library-validation + + com.apple.security.network.client + + com.apple.security.network.server + + + diff --git a/codelabs/function-calling-flutter-gemma/step_01_starter/macos/Runner/Info.plist b/codelabs/function-calling-flutter-gemma/step_01_starter/macos/Runner/Info.plist new file mode 100644 index 000000000..4789daa6a --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/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/codelabs/function-calling-flutter-gemma/step_01_starter/macos/Runner/MainFlutterWindow.swift b/codelabs/function-calling-flutter-gemma/step_01_starter/macos/Runner/MainFlutterWindow.swift new file mode 100644 index 000000000..3cc05eb23 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/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/codelabs/function-calling-flutter-gemma/step_01_starter/macos/Runner/Release.entitlements b/codelabs/function-calling-flutter-gemma/step_01_starter/macos/Runner/Release.entitlements new file mode 100644 index 000000000..d7c971d31 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/macos/Runner/Release.entitlements @@ -0,0 +1,12 @@ + + + + + com.apple.security.app-sandbox + + com.apple.security.cs.disable-library-validation + + com.apple.security.network.client + + + diff --git a/codelabs/function-calling-flutter-gemma/step_01_starter/macos/RunnerTests/RunnerTests.swift b/codelabs/function-calling-flutter-gemma/step_01_starter/macos/RunnerTests/RunnerTests.swift new file mode 100644 index 000000000..61f3bd1fc --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/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/codelabs/function-calling-flutter-gemma/step_01_starter/pubspec.yaml b/codelabs/function-calling-flutter-gemma/step_01_starter/pubspec.yaml new file mode 100644 index 000000000..324dd18bb --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/pubspec.yaml @@ -0,0 +1,97 @@ +name: gemma_quickstart +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.12.0 + +# 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 + + # The following adds the Cupertino Icons font to your application. + # Use with the CupertinoIcons class for iOS style icons. + cupertino_icons: ^1.0.8 + + # The engine-agnostic core: registry, install/runtime API, chat. + flutter_gemma: ^1.7.1 + # The .litertlm inference engine. Engines are opt-in — core + # registers none, so this package must be added explicitly. + flutter_gemma_litertlm: ^1.6.2 + +dev_dependencies: + flutter_test: + sdk: flutter + integration_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: ^6.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/codelabs/function-calling-flutter-gemma/step_01_starter/test/widget_test.dart b/codelabs/function-calling-flutter-gemma/step_01_starter/test/widget_test.dart new file mode 100644 index 000000000..d48957854 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/test/widget_test.dart @@ -0,0 +1,26 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:gemma_quickstart/download_page.dart'; +import 'package:gemma_quickstart/model.dart'; + +void main() { + // `isModelInstalled` is keyed by file name. `install()` skips bytes it + // already has, so a name that drifts from its URL does not re-download — it + // strands the app on a download screen the gate is never satisfied by. + test('the model id matches the last segment of its URL', () { + const model = Models.functionGemma; + expect(model.fileName, model.url.split('/').last, reason: model.label); + }); + + testWidgets('the download screen offers the model before any plugin call', ( + tester, + ) async { + await tester.pumpWidget( + MaterialApp( + home: DownloadPage(model: Models.functionGemma, onInstalled: () {}), + ), + ); + expect(find.text('FunctionGemma 270M'), findsOneWidget); + expect(find.text('Download model'), findsOneWidget); + }); +} diff --git a/codelabs/function-calling-flutter-gemma/step_01_starter/web/favicon.png b/codelabs/function-calling-flutter-gemma/step_01_starter/web/favicon.png new file mode 100644 index 000000000..8aaa46ac1 Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_01_starter/web/favicon.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_01_starter/web/icons/Icon-192.png b/codelabs/function-calling-flutter-gemma/step_01_starter/web/icons/Icon-192.png new file mode 100644 index 000000000..b749bfef0 Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_01_starter/web/icons/Icon-192.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_01_starter/web/icons/Icon-512.png b/codelabs/function-calling-flutter-gemma/step_01_starter/web/icons/Icon-512.png new file mode 100644 index 000000000..88cfd48df Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_01_starter/web/icons/Icon-512.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_01_starter/web/icons/Icon-maskable-192.png b/codelabs/function-calling-flutter-gemma/step_01_starter/web/icons/Icon-maskable-192.png new file mode 100644 index 000000000..eb9b4d76e Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_01_starter/web/icons/Icon-maskable-192.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_01_starter/web/icons/Icon-maskable-512.png b/codelabs/function-calling-flutter-gemma/step_01_starter/web/icons/Icon-maskable-512.png new file mode 100644 index 000000000..d69c56691 Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_01_starter/web/icons/Icon-maskable-512.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_01_starter/web/index.html b/codelabs/function-calling-flutter-gemma/step_01_starter/web/index.html new file mode 100644 index 000000000..4dc25043a --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/web/index.html @@ -0,0 +1,58 @@ + + + + + + + + + + + + + + + + + + + + Gemma Function Calling + + + + + + + + + + diff --git a/codelabs/function-calling-flutter-gemma/step_01_starter/web/manifest.json b/codelabs/function-calling-flutter-gemma/step_01_starter/web/manifest.json new file mode 100644 index 000000000..747e60366 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/web/manifest.json @@ -0,0 +1,35 @@ +{ + "name": "Gemma Function Calling", + "short_name": "Gemma Function Calling", + "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/codelabs/function-calling-flutter-gemma/step_01_starter/windows/.gitignore b/codelabs/function-calling-flutter-gemma/step_01_starter/windows/.gitignore new file mode 100644 index 000000000..d492d0d98 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/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/codelabs/function-calling-flutter-gemma/step_01_starter/windows/CMakeLists.txt b/codelabs/function-calling-flutter-gemma/step_01_starter/windows/CMakeLists.txt new file mode 100644 index 000000000..ed760319f --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/windows/CMakeLists.txt @@ -0,0 +1,108 @@ +# Project-level configuration. +cmake_minimum_required(VERSION 3.14) +project(functioncalling 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 "functioncalling") + +# 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/codelabs/function-calling-flutter-gemma/step_01_starter/windows/flutter/CMakeLists.txt b/codelabs/function-calling-flutter-gemma/step_01_starter/windows/flutter/CMakeLists.txt new file mode 100644 index 000000000..903f4899d --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/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/codelabs/function-calling-flutter-gemma/step_01_starter/windows/flutter/generated_plugin_registrant.cc b/codelabs/function-calling-flutter-gemma/step_01_starter/windows/flutter/generated_plugin_registrant.cc new file mode 100644 index 000000000..38c2332a8 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/windows/flutter/generated_plugin_registrant.cc @@ -0,0 +1,17 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + +#include +#include + +void RegisterPlugins(flutter::PluginRegistry* registry) { + ConnectivityPlusWindowsPluginRegisterWithRegistrar( + registry->GetRegistrarForPlugin("ConnectivityPlusWindowsPlugin")); + FlutterGemmaPluginRegisterWithRegistrar( + registry->GetRegistrarForPlugin("FlutterGemmaPlugin")); +} diff --git a/codelabs/function-calling-flutter-gemma/step_01_starter/windows/flutter/generated_plugin_registrant.h b/codelabs/function-calling-flutter-gemma/step_01_starter/windows/flutter/generated_plugin_registrant.h new file mode 100644 index 000000000..dc139d85a --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/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/codelabs/function-calling-flutter-gemma/step_01_starter/windows/flutter/generated_plugins.cmake b/codelabs/function-calling-flutter-gemma/step_01_starter/windows/flutter/generated_plugins.cmake new file mode 100644 index 000000000..8dcbac209 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/windows/flutter/generated_plugins.cmake @@ -0,0 +1,26 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST + connectivity_plus + flutter_gemma +) + +list(APPEND FLUTTER_FFI_PLUGIN_LIST + jni +) + +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/codelabs/function-calling-flutter-gemma/step_01_starter/windows/runner/CMakeLists.txt b/codelabs/function-calling-flutter-gemma/step_01_starter/windows/runner/CMakeLists.txt new file mode 100644 index 000000000..394917c05 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/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/codelabs/function-calling-flutter-gemma/step_01_starter/windows/runner/Runner.rc b/codelabs/function-calling-flutter-gemma/step_01_starter/windows/runner/Runner.rc new file mode 100644 index 000000000..967d1c9d1 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/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", "dev.fluttergemma" "\0" + VALUE "FileDescription", "Gemma Function Calling" "\0" + VALUE "FileVersion", VERSION_AS_STRING "\0" + VALUE "InternalName", "functioncalling" "\0" + VALUE "LegalCopyright", "Copyright (C) 2026 dev.fluttergemma. All rights reserved." "\0" + VALUE "OriginalFilename", "functioncalling.exe" "\0" + VALUE "ProductName", "Gemma Function Calling" "\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/codelabs/function-calling-flutter-gemma/step_01_starter/windows/runner/flutter_window.cpp b/codelabs/function-calling-flutter-gemma/step_01_starter/windows/runner/flutter_window.cpp new file mode 100644 index 000000000..955ee3038 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/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/codelabs/function-calling-flutter-gemma/step_01_starter/windows/runner/flutter_window.h b/codelabs/function-calling-flutter-gemma/step_01_starter/windows/runner/flutter_window.h new file mode 100644 index 000000000..6da0652f0 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/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/codelabs/function-calling-flutter-gemma/step_01_starter/windows/runner/main.cpp b/codelabs/function-calling-flutter-gemma/step_01_starter/windows/runner/main.cpp new file mode 100644 index 000000000..38dad4a50 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/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"Gemma Function Calling", 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/codelabs/function-calling-flutter-gemma/step_01_starter/windows/runner/resource.h b/codelabs/function-calling-flutter-gemma/step_01_starter/windows/runner/resource.h new file mode 100644 index 000000000..66a65d1e4 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/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/codelabs/function-calling-flutter-gemma/step_01_starter/windows/runner/resources/app_icon.ico b/codelabs/function-calling-flutter-gemma/step_01_starter/windows/runner/resources/app_icon.ico new file mode 100644 index 000000000..c04e20caf Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_01_starter/windows/runner/resources/app_icon.ico differ diff --git a/codelabs/function-calling-flutter-gemma/step_01_starter/windows/runner/runner.exe.manifest b/codelabs/function-calling-flutter-gemma/step_01_starter/windows/runner/runner.exe.manifest new file mode 100644 index 000000000..153653e8d --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/windows/runner/runner.exe.manifest @@ -0,0 +1,14 @@ + + + + + PerMonitorV2 + + + + + + + + + diff --git a/codelabs/function-calling-flutter-gemma/step_01_starter/windows/runner/utils.cpp b/codelabs/function-calling-flutter-gemma/step_01_starter/windows/runner/utils.cpp new file mode 100644 index 000000000..3cb714665 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/windows/runner/utils.cpp @@ -0,0 +1,69 @@ +#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(); + } + // First, find the length of the string with a safe upper bound (CWE-126). + // UNICODE_STRING_MAX_CHARS (32767) is the maximum length of a UNICODE_STRING. + int input_length = static_cast(wcsnlen(utf16_string, UNICODE_STRING_MAX_CHARS)); + // Now use that bounded length to determine the required buffer size. + // When an explicit length is passed, WideCharToMultiByte does not include + // the null terminator in its returned size. + int target_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + input_length, nullptr, 0, nullptr, nullptr); + std::string utf8_string; + if (target_length == 0 || static_cast(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/codelabs/function-calling-flutter-gemma/step_01_starter/windows/runner/utils.h b/codelabs/function-calling-flutter-gemma/step_01_starter/windows/runner/utils.h new file mode 100644 index 000000000..3879d5475 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/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/codelabs/function-calling-flutter-gemma/step_01_starter/windows/runner/win32_window.cpp b/codelabs/function-calling-flutter-gemma/step_01_starter/windows/runner/win32_window.cpp new file mode 100644 index 000000000..60608d0fe --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/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/codelabs/function-calling-flutter-gemma/step_01_starter/windows/runner/win32_window.h b/codelabs/function-calling-flutter-gemma/step_01_starter/windows/runner/win32_window.h new file mode 100644 index 000000000..e901dde68 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_01_starter/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/codelabs/function-calling-flutter-gemma/step_02_one_tool/.gitignore b/codelabs/function-calling-flutter-gemma/step_02_one_tool/.gitignore new file mode 100644 index 000000000..79f7ecabd --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/.gitignore @@ -0,0 +1,48 @@ +# 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 + +# Widget Preview related +.widget_preview/ diff --git a/codelabs/function-calling-flutter-gemma/step_02_one_tool/.metadata b/codelabs/function-calling-flutter-gemma/step_02_one_tool/.metadata new file mode 100644 index 000000000..615dfd47e --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/.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: "d3b14c876900e553bc736ca19295fc09e3853e8e" + channel: "stable" + +project_type: app + +# Tracks metadata for the flutter migrate command +migration: + platforms: + - platform: root + create_revision: d3b14c876900e553bc736ca19295fc09e3853e8e + base_revision: d3b14c876900e553bc736ca19295fc09e3853e8e + - platform: android + create_revision: d3b14c876900e553bc736ca19295fc09e3853e8e + base_revision: d3b14c876900e553bc736ca19295fc09e3853e8e + - platform: ios + create_revision: d3b14c876900e553bc736ca19295fc09e3853e8e + base_revision: d3b14c876900e553bc736ca19295fc09e3853e8e + - platform: linux + create_revision: d3b14c876900e553bc736ca19295fc09e3853e8e + base_revision: d3b14c876900e553bc736ca19295fc09e3853e8e + - platform: macos + create_revision: d3b14c876900e553bc736ca19295fc09e3853e8e + base_revision: d3b14c876900e553bc736ca19295fc09e3853e8e + - platform: web + create_revision: d3b14c876900e553bc736ca19295fc09e3853e8e + base_revision: d3b14c876900e553bc736ca19295fc09e3853e8e + - platform: windows + create_revision: d3b14c876900e553bc736ca19295fc09e3853e8e + base_revision: d3b14c876900e553bc736ca19295fc09e3853e8e + + # 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/codelabs/function-calling-flutter-gemma/step_02_one_tool/README.md b/codelabs/function-calling-flutter-gemma/step_02_one_tool/README.md new file mode 100644 index 000000000..1c831fead --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/README.md @@ -0,0 +1,17 @@ +# gemma_quickstart + +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: + +- [Learn Flutter](https://docs.flutter.dev/get-started/learn-flutter) +- [Write your first Flutter app](https://docs.flutter.dev/get-started/codelab) +- [Flutter learning resources](https://docs.flutter.dev/reference/learning-resources) + +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/codelabs/function-calling-flutter-gemma/step_02_one_tool/analysis_options.yaml b/codelabs/function-calling-flutter-gemma/step_02_one_tool/analysis_options.yaml new file mode 100644 index 000000000..78613972a --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/analysis_options.yaml @@ -0,0 +1,38 @@ +# 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 + +analyzer: + exclude: + - build/** + - android/** + - ios/** + - linux/** + - macos/** + - web/** + - windows/** + +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/codelabs/function-calling-flutter-gemma/step_02_one_tool/android/.gitignore b/codelabs/function-calling-flutter-gemma/step_02_one_tool/android/.gitignore new file mode 100644 index 000000000..be3943c96 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/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/codelabs/function-calling-flutter-gemma/step_02_one_tool/android/app/build.gradle.kts b/codelabs/function-calling-flutter-gemma/step_02_one_tool/android/app/build.gradle.kts new file mode 100644 index 000000000..1ec5366e9 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/android/app/build.gradle.kts @@ -0,0 +1,49 @@ +plugins { + id("com.android.application") + // The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins. + id("dev.flutter.flutter-gradle-plugin") +} + +android { + namespace = "dev.fluttergemma.functioncalling" + compileSdk = flutter.compileSdkVersion + ndkVersion = flutter.ndkVersion + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + } + + defaultConfig { + // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). + applicationId = "dev.fluttergemma.functioncalling" + // 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 + // Uses the version code from pubspec.yaml. When using split APKs, 1000 * ABI_VERSION + // is added automatically by Flutter. (https://developer.android.com/studio/build/configure-apk-splits#configure-APK-versions) + // You can force using the value of versionCode by specifying the `-P force-version-code-ignoring-abi=true` + // flag during build. + 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") + } + } +} + +kotlin { + compilerOptions { + jvmTarget = org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17 + } +} + +flutter { + source = "../.." +} diff --git a/codelabs/function-calling-flutter-gemma/step_02_one_tool/android/app/src/debug/AndroidManifest.xml b/codelabs/function-calling-flutter-gemma/step_02_one_tool/android/app/src/debug/AndroidManifest.xml new file mode 100644 index 000000000..399f6981d --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/android/app/src/debug/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + diff --git a/codelabs/function-calling-flutter-gemma/step_02_one_tool/android/app/src/main/AndroidManifest.xml b/codelabs/function-calling-flutter-gemma/step_02_one_tool/android/app/src/main/AndroidManifest.xml new file mode 100644 index 000000000..34daae5c0 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,47 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/codelabs/function-calling-flutter-gemma/step_02_one_tool/android/app/src/main/kotlin/dev/fluttergemma/functioncalling/MainActivity.kt b/codelabs/function-calling-flutter-gemma/step_02_one_tool/android/app/src/main/kotlin/dev/fluttergemma/functioncalling/MainActivity.kt new file mode 100644 index 000000000..e4e274d6e --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/android/app/src/main/kotlin/dev/fluttergemma/functioncalling/MainActivity.kt @@ -0,0 +1,5 @@ +package dev.fluttergemma.functioncalling + +import io.flutter.embedding.android.FlutterActivity + +class MainActivity : FlutterActivity() diff --git a/codelabs/function-calling-flutter-gemma/step_02_one_tool/android/app/src/main/res/drawable-v21/launch_background.xml b/codelabs/function-calling-flutter-gemma/step_02_one_tool/android/app/src/main/res/drawable-v21/launch_background.xml new file mode 100644 index 000000000..f74085f3f --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/android/app/src/main/res/drawable-v21/launch_background.xml @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/codelabs/function-calling-flutter-gemma/step_02_one_tool/android/app/src/main/res/drawable/launch_background.xml b/codelabs/function-calling-flutter-gemma/step_02_one_tool/android/app/src/main/res/drawable/launch_background.xml new file mode 100644 index 000000000..304732f88 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/android/app/src/main/res/drawable/launch_background.xml @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/codelabs/function-calling-flutter-gemma/step_02_one_tool/android/app/src/main/res/mipmap-hdpi/ic_launcher.png b/codelabs/function-calling-flutter-gemma/step_02_one_tool/android/app/src/main/res/mipmap-hdpi/ic_launcher.png new file mode 100644 index 000000000..db77bb4b7 Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_02_one_tool/android/app/src/main/res/mipmap-hdpi/ic_launcher.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_02_one_tool/android/app/src/main/res/mipmap-mdpi/ic_launcher.png b/codelabs/function-calling-flutter-gemma/step_02_one_tool/android/app/src/main/res/mipmap-mdpi/ic_launcher.png new file mode 100644 index 000000000..17987b79b Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_02_one_tool/android/app/src/main/res/mipmap-mdpi/ic_launcher.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_02_one_tool/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/codelabs/function-calling-flutter-gemma/step_02_one_tool/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png new file mode 100644 index 000000000..09d439148 Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_02_one_tool/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_02_one_tool/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/codelabs/function-calling-flutter-gemma/step_02_one_tool/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png new file mode 100644 index 000000000..d5f1c8d34 Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_02_one_tool/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_02_one_tool/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/codelabs/function-calling-flutter-gemma/step_02_one_tool/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 000000000..4d6372eeb Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_02_one_tool/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_02_one_tool/android/app/src/main/res/values-night/styles.xml b/codelabs/function-calling-flutter-gemma/step_02_one_tool/android/app/src/main/res/values-night/styles.xml new file mode 100644 index 000000000..06952be74 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/android/app/src/main/res/values-night/styles.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/codelabs/function-calling-flutter-gemma/step_02_one_tool/android/app/src/main/res/values/styles.xml b/codelabs/function-calling-flutter-gemma/step_02_one_tool/android/app/src/main/res/values/styles.xml new file mode 100644 index 000000000..cb1ef8805 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/android/app/src/main/res/values/styles.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/codelabs/function-calling-flutter-gemma/step_02_one_tool/android/app/src/profile/AndroidManifest.xml b/codelabs/function-calling-flutter-gemma/step_02_one_tool/android/app/src/profile/AndroidManifest.xml new file mode 100644 index 000000000..399f6981d --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/android/app/src/profile/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + diff --git a/codelabs/function-calling-flutter-gemma/step_02_one_tool/android/build.gradle.kts b/codelabs/function-calling-flutter-gemma/step_02_one_tool/android/build.gradle.kts new file mode 100644 index 000000000..dbee657bb --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/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/codelabs/function-calling-flutter-gemma/step_02_one_tool/android/gradle.properties b/codelabs/function-calling-flutter-gemma/step_02_one_tool/android/gradle.properties new file mode 100644 index 000000000..e96108cfe --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/android/gradle.properties @@ -0,0 +1,6 @@ +org.gradle.jvmargs=-Xmx8G -XX:MaxMetaspaceSize=4G -XX:ReservedCodeCacheSize=512m -XX:+HeapDumpOnOutOfMemoryError +android.useAndroidX=true +# This newDsl flag was added by the Flutter template +android.newDsl=false +# This builtInKotlin flag was added by the Flutter template +android.builtInKotlin=false diff --git a/codelabs/function-calling-flutter-gemma/step_02_one_tool/android/gradle/wrapper/gradle-wrapper.properties b/codelabs/function-calling-flutter-gemma/step_02_one_tool/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 000000000..a20f2c46d --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/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-9.3.1-all.zip diff --git a/codelabs/function-calling-flutter-gemma/step_02_one_tool/android/settings.gradle.kts b/codelabs/function-calling-flutter-gemma/step_02_one_tool/android/settings.gradle.kts new file mode 100644 index 000000000..b28021a91 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/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 "9.1.0" apply false + id("org.jetbrains.kotlin.android") version "2.4.0" apply false +} + +include(":app") diff --git a/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/.gitignore b/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/.gitignore new file mode 100644 index 000000000..7a7f9873a --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/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/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Flutter/AppFrameworkInfo.plist b/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Flutter/AppFrameworkInfo.plist new file mode 100644 index 000000000..391a902b2 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Flutter/AppFrameworkInfo.plist @@ -0,0 +1,24 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + App + CFBundleIdentifier + io.flutter.flutter.app + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + App + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.0 + CFBundleSignature + ???? + CFBundleVersion + 1.0 + + diff --git a/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Flutter/Debug.xcconfig b/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Flutter/Debug.xcconfig new file mode 100644 index 000000000..592ceee85 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Flutter/Debug.xcconfig @@ -0,0 +1 @@ +#include "Generated.xcconfig" diff --git a/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Flutter/Release.xcconfig b/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Flutter/Release.xcconfig new file mode 100644 index 000000000..592ceee85 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Flutter/Release.xcconfig @@ -0,0 +1 @@ +#include "Generated.xcconfig" diff --git a/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner.xcodeproj/project.pbxproj b/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner.xcodeproj/project.pbxproj new file mode 100644 index 000000000..249dc6542 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner.xcodeproj/project.pbxproj @@ -0,0 +1,655 @@ +// !$*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 */; }; + 7884E8682EC3CC0700C636F2 /* SceneDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7884E8672EC3CC0400C636F2 /* SceneDelegate.swift */; }; + 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */ = {isa = PBXBuildFile; productRef = 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */; }; + 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 = ""; }; + 7884E8672EC3CC0400C636F2 /* SceneDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SceneDelegate.swift; sourceTree = ""; }; + 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */ = {isa = PBXFileReference; lastKnownFileType = wrapper; name = FlutterGeneratedPluginSwiftPackage; path = Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage; 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 = ""; }; + C0DE1AB52ED000000000E17E /* Runner.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = Runner.entitlements; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 97C146EB1CF9000F007C117D /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 331C8082294A63A400263BE5 /* RunnerTests */ = { + isa = PBXGroup; + children = ( + 331C807B294A618700263BE5 /* RunnerTests.swift */, + ); + path = RunnerTests; + sourceTree = ""; + }; + 9740EEB11CF90186004384FC /* Flutter */ = { + isa = PBXGroup; + children = ( + 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */, + 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 */, + C0DE1AB52ED000000000E17E /* Runner.entitlements */, + 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */, + 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */, + 74858FAE1ED2DC5600515810 /* AppDelegate.swift */, + 7884E8672EC3CC0400C636F2 /* SceneDelegate.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; + packageProductDependencies = ( + 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */, + ); + 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; + packageReferences = ( + 781AD8BC2B33823900A9FFBB /* XCLocalSwiftPackageReference "Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage" */, + ); + 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 */, + 7884E8682EC3CC0700C636F2 /* SceneDelegate.swift 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 = 15.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + STRING_CATALOG_GENERATE_SYMBOLS = YES; + 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; + CODE_SIGN_ENTITLEMENTS = Runner/Runner.entitlements; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + DEVELOPMENT_TEAM = 6ZHF6A3G28; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = dev.fluttergemma.functioncalling; + 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 = dev.fluttergemma.functioncalling.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 = dev.fluttergemma.functioncalling.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 = dev.fluttergemma.functioncalling.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 = 15.0; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = iphoneos; + STRING_CATALOG_GENERATE_SYMBOLS = YES; + 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 = 15.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + STRING_CATALOG_GENERATE_SYMBOLS = YES; + 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; + CODE_SIGN_ENTITLEMENTS = Runner/Runner.entitlements; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + DEVELOPMENT_TEAM = 6ZHF6A3G28; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = dev.fluttergemma.functioncalling; + 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; + CODE_SIGN_ENTITLEMENTS = Runner/Runner.entitlements; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + DEVELOPMENT_TEAM = 6ZHF6A3G28; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = dev.fluttergemma.functioncalling; + 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 */ + +/* Begin XCLocalSwiftPackageReference section */ + 781AD8BC2B33823900A9FFBB /* XCLocalSwiftPackageReference "Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage" */ = { + isa = XCLocalSwiftPackageReference; + relativePath = Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage; + }; +/* End XCLocalSwiftPackageReference section */ + +/* Begin XCSwiftPackageProductDependency section */ + 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */ = { + isa = XCSwiftPackageProductDependency; + productName = FlutterGeneratedPluginSwiftPackage; + }; +/* End XCSwiftPackageProductDependency section */ + }; + rootObject = 97C146E61CF9000F007C117D /* Project object */; +} diff --git a/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata new file mode 100644 index 000000000..919434a62 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 000000000..18d981003 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings new file mode 100644 index 000000000..f9b0d7c5e --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings @@ -0,0 +1,8 @@ + + + + + PreviewsEnabled + + + diff --git a/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme new file mode 100644 index 000000000..c3fedb29c --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -0,0 +1,119 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner.xcworkspace/contents.xcworkspacedata b/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner.xcworkspace/contents.xcworkspacedata new file mode 100644 index 000000000..1d526a16e --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 000000000..18d981003 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings new file mode 100644 index 000000000..f9b0d7c5e --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings @@ -0,0 +1,8 @@ + + + + + PreviewsEnabled + + + diff --git a/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner/AppDelegate.swift b/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner/AppDelegate.swift new file mode 100644 index 000000000..c30b367ec --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner/AppDelegate.swift @@ -0,0 +1,16 @@ +import Flutter +import UIKit + +@main +@objc class AppDelegate: FlutterAppDelegate, FlutterImplicitEngineDelegate { + override func application( + _ application: UIApplication, + didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? + ) -> Bool { + return super.application(application, didFinishLaunchingWithOptions: launchOptions) + } + + func didInitializeImplicitFlutterEngine(_ engineBridge: FlutterImplicitEngineBridge) { + GeneratedPluginRegistrant.register(with: engineBridge.pluginRegistry) + } +} diff --git a/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json b/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 000000000..d36b1fab2 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/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/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png b/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png new file mode 100644 index 000000000..dc9ada472 Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png b/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png new file mode 100644 index 000000000..7353c41ec Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png b/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png new file mode 100644 index 000000000..797d452e4 Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png b/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png new file mode 100644 index 000000000..6ed2d933e Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png b/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png new file mode 100644 index 000000000..4cd7b0099 Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png b/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png new file mode 100644 index 000000000..fe730945a Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png b/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png new file mode 100644 index 000000000..321773cd8 Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png b/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png new file mode 100644 index 000000000..797d452e4 Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png b/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png new file mode 100644 index 000000000..502f463a9 Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png b/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png new file mode 100644 index 000000000..0ec303439 Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png b/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png new file mode 100644 index 000000000..0ec303439 Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png b/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png new file mode 100644 index 000000000..e9f5fea27 Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png b/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png new file mode 100644 index 000000000..84ac32ae7 Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png b/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png new file mode 100644 index 000000000..8953cba09 Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png b/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png new file mode 100644 index 000000000..0467bf12a Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json b/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json new file mode 100644 index 000000000..0bedcf2fd --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/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/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png b/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png new file mode 100644 index 000000000..9da19eaca Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png b/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png new file mode 100644 index 000000000..9da19eaca Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png b/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png new file mode 100644 index 000000000..9da19eaca Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md b/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md new file mode 100644 index 000000000..89c2725b7 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/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/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner/Base.lproj/LaunchScreen.storyboard b/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner/Base.lproj/LaunchScreen.storyboard new file mode 100644 index 000000000..f2e259c7c --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner/Base.lproj/LaunchScreen.storyboard @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner/Base.lproj/Main.storyboard b/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner/Base.lproj/Main.storyboard new file mode 100644 index 000000000..f3c28516f --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner/Base.lproj/Main.storyboard @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner/Info.plist b/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner/Info.plist new file mode 100644 index 000000000..c97226dba --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner/Info.plist @@ -0,0 +1,70 @@ + + + + + CADisableMinimumFrameDurationOnPhone + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleDisplayName + Gemma Function Calling + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + functioncalling + CFBundlePackageType + APPL + CFBundleShortVersionString + $(FLUTTER_BUILD_NAME) + CFBundleSignature + ???? + CFBundleVersion + $(FLUTTER_BUILD_NUMBER) + LSRequiresIPhoneOS + + UIApplicationSceneManifest + + UIApplicationSupportsMultipleScenes + + UISceneConfigurations + + UIWindowSceneSessionRoleApplication + + + UISceneClassName + UIWindowScene + UISceneConfigurationName + flutter + UISceneDelegateClassName + $(PRODUCT_MODULE_NAME).SceneDelegate + UISceneStoryboardFile + Main + + + + + UIApplicationSupportsIndirectInputEvents + + UILaunchStoryboardName + LaunchScreen + UIMainStoryboardFile + Main + UISupportedInterfaceOrientations + + UIInterfaceOrientationPortrait + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + UISupportedInterfaceOrientations~ipad + + UIInterfaceOrientationPortrait + UIInterfaceOrientationPortraitUpsideDown + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + + diff --git a/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner/Runner-Bridging-Header.h b/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner/Runner-Bridging-Header.h new file mode 100644 index 000000000..308a2a560 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner/Runner-Bridging-Header.h @@ -0,0 +1 @@ +#import "GeneratedPluginRegistrant.h" diff --git a/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner/Runner.entitlements b/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner/Runner.entitlements new file mode 100644 index 000000000..cd461aae4 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner/Runner.entitlements @@ -0,0 +1,12 @@ + + + + + com.apple.developer.kernel.extended-virtual-addressing + + com.apple.developer.kernel.increased-memory-limit + + com.apple.developer.kernel.increased-debugging-memory-limit + + + diff --git a/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner/SceneDelegate.swift b/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner/SceneDelegate.swift new file mode 100644 index 000000000..b9ce8ea2b --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/Runner/SceneDelegate.swift @@ -0,0 +1,6 @@ +import Flutter +import UIKit + +class SceneDelegate: FlutterSceneDelegate { + +} diff --git a/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/RunnerTests/RunnerTests.swift b/codelabs/function-calling-flutter-gemma/step_02_one_tool/ios/RunnerTests/RunnerTests.swift new file mode 100644 index 000000000..86a7c3b1b --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/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/codelabs/function-calling-flutter-gemma/step_02_one_tool/lib/chat_page.dart b/codelabs/function-calling-flutter-gemma/step_02_one_tool/lib/chat_page.dart new file mode 100644 index 000000000..dc3eed371 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/lib/chat_page.dart @@ -0,0 +1,527 @@ +import 'dart:convert'; + +import 'package:flutter/material.dart'; +import 'package:flutter_gemma/flutter_gemma.dart'; + +import 'model.dart'; +import 'tools.dart'; + +/// What a line in the transcript is. +/// +/// A chat with tools has four kinds of turn, not two, and showing only the +/// first and last of them is how a tool-calling app becomes impossible to +/// debug: the answer is right or wrong and nothing on screen says which +/// function produced it, with which arguments. +enum _TurnKind { user, model, toolCall, toolResult } + +/// A chat where the model can ask the app to run a function. +/// +/// The loop is written out by hand here — generate, see a call, run it, send +/// the result back, generate again — because that is the thing worth seeing +/// once. Step 3 replaces all of it with one SDK call. +class ChatPage extends StatefulWidget { + const ChatPage({ + super.key, + required this.model, + required this.onModelRemoved, + }); + + final ModelChoice model; + + /// Lets the gate send the app back to the download screen. + final VoidCallback onModelRemoved; + + @override + State createState() => _ChatPageState(); +} + +class _ChatPageState extends State { + final _input = TextEditingController(); + final _turns = <_Turn>[]; + + InferenceModel? _inference; + InferenceChat? _chat; + bool _busy = false; + Object? _loadError; + + /// A one-line problem that is not worth losing the chat over. + String? _notice; + + @override + void initState() { + super.initState(); + _load(); + } + + Future _load() async { + try { + // maxTokens is the CONTEXT WINDOW — prompt + history + reply share it. + // It is NOT a reply-length cap; for that, pass maxOutputTokens below. + // Tools are not free inside it: the declarations below are rendered into + // the prompt once and stay in the history for the rest of the + // conversation, and every call and every tool response is another turn in + // the same window — so a tool-calling chat runs out of room sooner than a + // plain one does. + // + // Note what this call does NOT take: `tools`. There is no modality flag + // to set in two places here — `getActiveModel` builds the engine, and + // nothing about the weights changes when you declare a function. Tools + // belong to the SESSION, and the session is opened one call down. + // maxTokens 1024 is what this checkpoint is built for; the example app + // uses the same, and it is the value this was measured at. + // + // This checkpoint is asked to run on the CPU, and the reason is the + // FILE, not the platform and not the model. The published artifact was + // converted before litetune 0.1.4 began setting `prefer_activation_type=fp32`, + // and without that key the GPU path answers every prompt with `` to + // the token limit — measured on Android and on macOS Metal alike, with no + // exception and no warning, a chat that looks alive and returns filler. + // + // Re-converted with a current litetune — which Step 4 does — the same + // weights score identically on GPU and run about 1.5x faster. So this is + // a workaround for one downloadable file, not a property of FunctionGemma. + final inference = await FlutterGemma.getActiveModel( + maxTokens: 1024, + preferredBackend: PreferredBackend.cpu, + ); + // Hold the runtime before opening a chat on it: `createChat` can throw, + // and a model this page never stored is a model `dispose` can never + // close. A page that is already gone holds nothing, so it closes it here. + if (!mounted) { + await inference.close(); + return; + } + setState(() => _inference = inference); + + final chat = await inference.createChat( + // Which family's call syntax the SDK writes and reads. With + // `ModelType.functionGemma` it renders the declarations into a + // developer turn these weights were trained on, and parses + // `call:multiply{…}` back into the + // `FunctionCallResponse` the loop below waits for. + modelType: widget.model.modelType, + // The declarations. This is the whole of "the model can call your + // code": a list of names, descriptions and argument schemas. + tools: const [multiplyTool], + // And the switch that turns the machinery on. `tools` without this is + // the quiet failure worth knowing about: `InferenceChat` logs + // "Model does not support function calls, but tools were provided. + // Tools will be ignored", never renders the declarations, and the + // model answers every question out of its own head — fluently, and + // with arithmetic it made up. + supportsFunctionCalls: true, + maxOutputTokens: 256, + ); + // The same guard, one call later and for the same reason: a chat this + // page never stored is a native session `dispose` can never close. + if (!mounted) { + await chat.close(); + return; + } + setState(() => _chat = chat); + } catch (error) { + // Loading is the likeliest thing to fail on a real device: a forgotten + // engine package, too little memory, a half-written model file. Show it + // instead of sitting on the progress bar forever. + if (mounted) setState(() => _loadError = error); + } + } + + void _retryLoad() { + setState(() => _loadError = null); + _load(); + } + + /// The loop, by hand. + /// + /// Read it as three questions asked in order: what does the model say, does + /// it want a function run, and what does it say once it has the answer. + Future _send() async { + final chat = _chat; + final text = _input.text.trim(); + if (chat == null || text.isEmpty || _busy) return; + + setState(() { + _turns.add(_Turn(text, kind: _TurnKind.user)); + _input.clear(); + _notice = null; + _busy = true; + }); + + try { + await chat.addQueryChunk(Message.text(text: text, isUser: true)); + + // ROUND ONE. The model either answers, or asks for the function. + final calls = await _generate(chat); + if (calls.isEmpty) return; // a plain answer — nothing to run + + // The app runs it. This half is never the SDK's: a tool is an action in + // your program, and only your program knows what `multiply` means. + for (final call in calls) { + final result = _run(call); + if (mounted) { + setState(() { + _turns + ..add(_Turn(_describeCall(call), kind: _TurnKind.toolCall)) + ..add(_Turn(jsonEncode(result), kind: _TurnKind.toolResult)); + }); + } + // Handing the answer back is a MESSAGE, not a return value. Until this + // reaches the session the model has not seen the number at all. + await chat.addQueryChunk( + Message.toolResponse(toolName: call.name, response: result), + ); + } + + // ROUND TWO. Same session, same history — now with the result in it. + final again = await _generate(chat); + if (again.isEmpty) return; + + // The model asked for another call. Every call the stream yielded is + // ALREADY in the chat's history, and a call left without a response + // poisons the next turn on this chat — the model re-issues it, or + // answers nothing at all. So the ones this step will not run still get + // an answer, and it says what happened. + for (final call in again) { + if (mounted) { + setState( + () => _turns.add( + _Turn(_describeCall(call), kind: _TurnKind.toolCall), + ), + ); + } + await chat.addQueryChunk( + Message.toolResponse( + toolName: call.name, + response: const { + 'status': 'not run — this app runs one round of tool calls', + }, + ), + ); + } + if (mounted) { + setState( + () => _notice = + 'The model asked for another call. This hand-written loop runs ' + 'one round and stops. Step 3 hands the loop to the SDK, which ' + 'keeps going up to a limit you set.', + ); + } + } catch (error) { + // The half-written reply becomes the error, so the bubble `_generate` + // opened never just sits there empty. A failure between generations — + // staging the tool response, say — has no bubble to overwrite, and gets + // its own. + // + // What this does NOT do is balance the history, and that is the hole in + // the hand-written loop. If `generateChatResponseAsync` throws + // mid-stream, the calls it had already yielded are committed and now + // have no response — exactly the dangling state the round-two branch + // above takes such care to avoid. Closing it means tracking what + // `_generate` collected before it threw and answering those calls here. + // Step 3 hands the loop to the SDK, which already does. + if (mounted) { + setState(() { + final at = _turns.length - 1; + if (at >= 0 && _turns[at].kind == _TurnKind.model) { + _turns[at] = _Turn('⚠️ $error', kind: _TurnKind.model); + } else { + _turns.add(_Turn('⚠️ $error', kind: _TurnKind.model)); + } + }); + } + } finally { + // `_busy` is what disables the composer, so clearing it belongs in + // `finally` — a failed generation must not lock the app. + if (mounted) setState(() => _busy = false); + } + } + + /// Streams ONE generation into a fresh bubble and collects any calls it made. + /// + /// The text and the calls arrive on the same stream: `ModelResponse` is a + /// sealed type, and a turn is a mixture of its cases rather than one or the + /// other. Switching over it exhaustively is what stops a future case from + /// being silently treated as text. + Future> _generate(InferenceChat chat) async { + final pending = []; + final buffer = StringBuffer(); + + // Guarded like every other `setState` in this file: `_generate` is called + // after an `await`, so the page can be gone by the time it runs. With no + // page there is nothing to paint into, and the two writes to `at` below + // are guarded the same way. + if (mounted) { + setState(() => _turns.add(const _Turn('', kind: _TurnKind.model))); + } + final at = _turns.length - 1; + + await for (final chunk in chat.generateChatResponseAsync()) { + switch (chunk) { + case TextResponse(:final token): + // Each TextResponse carries only the NEW text, not the whole reply + // so far — append, never replace. + buffer.write(token); + // Guarded rather than returned: a call this stream has already + // yielded is committed to the chat's history and still has to be + // answered, so the loop keeps draining even with no screen to paint. + if (mounted) { + setState( + () => + _turns[at] = _Turn(buffer.toString(), kind: _TurnKind.model), + ); + } + case FunctionCallResponse(): + pending.add(chunk); + case ParallelFunctionCallResponse(:final calls): + // One turn, several calls. FunctionGemma with a single declared tool + // will rarely do this, but the case exists and dropping it would + // leave committed calls unanswered. + pending.addAll(calls); + case ThinkingResponse(): + // Filtered out upstream unless the chat was opened with + // `isThinking: true` — `complete` does exactly that. Here the branch + // exists so the switch stays exhaustive. + break; + } + } + + // A call-only turn generates no text, and an empty bubble under it reads + // as a model that said nothing when in fact it asked a question. + if (buffer.isEmpty && mounted) { + setState(() => _turns.removeAt(at)); + } + return pending; + } + + /// Maps a call the model made onto the Dart that answers it. + /// + /// Keyed by name and with a real miss branch: the model writes the name, and + /// a model can write a name you never declared. That is a turn to answer, + /// not a crash. + Map _run(FunctionCallResponse call) => switch (call.name) { + 'multiply' => runMultiply(call.args), + _ => {'error': 'This app has no tool named "${call.name}".'}, + }; + + String _describeCall(FunctionCallResponse call) { + final args = call.args.entries + .map((e) => '${e.key}: ${e.value}') + .join(', '); + return '${call.name}($args)'; + } + + /// Frees the disk. Close the runtime first — the file is mapped while a + /// model is open, and deleting it underneath the engine is a crash waiting + /// to happen. + Future _removeModel() async { + try { + await _inference?.close(); + // Inside `setState`: dropping the chat has to repaint, or the screen + // keeps showing an enabled composer over a runtime that is gone. + if (mounted) { + setState(() { + _inference = null; + _chat = null; + }); + } + await FlutterGemma.uninstallModel(widget.model.fileName); + if (mounted) widget.onModelRemoved(); + } catch (error) { + // Deleting can fail too — a missing install record, a file the OS still + // holds. Show it the way a failed load is shown, and drop the chat with + // it: a `close()` that threw leaves `_chat` non-null, and "The model did + // not load." over a working composer is a lie. + if (mounted) { + setState(() { + _chat = null; + _loadError = error; + }); + } + } + } + + @override + void dispose() { + // Sessions and models hold native memory — always close them. `dispose` + // cannot await, so the future is dropped on purpose, and caught so a + // failing native teardown does not escape as an unhandled async error. + _inference?.close().catchError((Object _) {}); + _input.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final ready = _chat != null; + final error = _loadError; + + return Scaffold( + appBar: AppBar( + title: Text(widget.model.label), + bottom: PreferredSize( + preferredSize: const Size.fromHeight(20), + child: Padding( + padding: const EdgeInsets.only(bottom: 6), + child: Text( + '1 tool · ${multiplyTool.name}', + style: theme.textTheme.labelSmall, + ), + ), + ), + actions: [ + IconButton( + tooltip: 'Delete the downloaded model', + // Not while the model is still opening: deleting the file + // underneath an in-flight `getActiveModel()` is the crash the + // comment on `_removeModel` warns about. + onPressed: _busy || (!ready && error == null) ? null : _removeModel, + icon: const Icon(Icons.delete_outline), + ), + ], + ), + body: Column( + children: [ + if (error != null) + _LoadFailed(error: error, onRetry: _retryLoad) + else if (!ready) + const LinearProgressIndicator(), + Expanded( + child: ListView.builder( + padding: const EdgeInsets.all(16), + itemCount: _turns.length, + itemBuilder: (context, i) => _Bubble(turn: _turns[i]), + ), + ), + if (_notice case final notice?) + Padding( + padding: const EdgeInsets.fromLTRB(16, 0, 16, 8), + child: Text( + notice, + style: theme.textTheme.bodySmall?.copyWith( + color: theme.colorScheme.error, + ), + ), + ), + SafeArea( + child: Padding( + padding: const EdgeInsets.fromLTRB(12, 0, 12, 12), + child: Row( + children: [ + Expanded( + child: TextField( + controller: _input, + enabled: ready && !_busy, + onSubmitted: (_) => _send(), + decoration: InputDecoration( + hintText: ready + ? 'Try: what is 1234 times 5678?' + : error != null + ? 'No model loaded' + : 'Loading the model…', + border: const OutlineInputBorder(), + ), + ), + ), + const SizedBox(width: 8), + IconButton.filled( + onPressed: ready && !_busy ? _send : null, + icon: const Icon(Icons.send), + ), + ], + ), + ), + ), + ], + ), + ); + } +} + +/// Shown in place of the loading bar when the model could not be opened. +class _LoadFailed extends StatelessWidget { + const _LoadFailed({required this.error, required this.onRetry}); + + final Object error; + final VoidCallback onRetry; + + @override + Widget build(BuildContext context) { + return Padding( + padding: const EdgeInsets.all(16), + child: Column( + children: [ + Text('The model did not load.\n$error', textAlign: TextAlign.center), + const SizedBox(height: 8), + FilledButton(onPressed: onRetry, child: const Text('Try again')), + ], + ), + ); + } +} + +class _Turn { + const _Turn(this.text, {required this.kind}); + + final String text; + final _TurnKind kind; +} + +/// One line of the transcript, drawn so the four kinds are told apart at a +/// glance. The two middle ones are the point of this screen. +class _Bubble extends StatelessWidget { + const _Bubble({required this.turn}); + + final _Turn turn; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final scheme = theme.colorScheme; + final (label, colour) = switch (turn.kind) { + _TurnKind.user => (null, scheme.primaryContainer), + _TurnKind.model => (null, scheme.surfaceContainerHighest), + _TurnKind.toolCall => ('the model asked for', scheme.tertiaryContainer), + _TurnKind.toolResult => ( + 'your function answered', + scheme.secondaryContainer, + ), + }; + final mono = + turn.kind == _TurnKind.toolCall || turn.kind == _TurnKind.toolResult; + + return Align( + alignment: turn.kind == _TurnKind.user + ? Alignment.centerRight + : Alignment.centerLeft, + child: Container( + margin: const EdgeInsets.symmetric(vertical: 4), + padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10), + constraints: const BoxConstraints(maxWidth: 520), + decoration: BoxDecoration( + color: colour, + borderRadius: BorderRadius.circular(12), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + if (label != null) ...[ + Text(label, style: theme.textTheme.labelSmall), + const SizedBox(height: 4), + ], + SelectableText( + turn.text, + style: mono + ? theme.textTheme.bodyMedium?.copyWith( + fontFamily: 'monospace', + ) + : null, + ), + ], + ), + ), + ); + } +} diff --git a/codelabs/function-calling-flutter-gemma/step_02_one_tool/lib/download_page.dart b/codelabs/function-calling-flutter-gemma/step_02_one_tool/lib/download_page.dart new file mode 100644 index 000000000..0e0ebf030 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/lib/download_page.dart @@ -0,0 +1,138 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_gemma/flutter_gemma.dart'; + +import 'model.dart'; + +/// Installs the model file, reporting progress as it goes. +/// +/// Nothing here knows about tools: `installModel` takes the model's identity +/// (what it is) and `fromNetwork` takes the source (where the bytes are). A +/// function-calling model installs exactly like a text one — tools are a +/// property of the SESSION you open later, not of the file you download. +class DownloadPage extends StatefulWidget { + const DownloadPage({ + super.key, + required this.model, + required this.onInstalled, + }); + + final ModelChoice model; + + /// Called once the model is installed, so the app can move on. + final VoidCallback onInstalled; + + @override + State createState() => _DownloadPageState(); +} + +class _DownloadPageState extends State { + int _percent = 0; + bool _downloading = false; + Object? _error; + + Future _download() async { + setState(() { + _downloading = true; + _error = null; + }); + + try { + await FlutterGemma.installModel( + // What the model IS — used to pick the right chat template. + modelType: widget.model.modelType, + // Which runtime reads it. `.litertlm` routes to LiteRtLmEngine; + // the default is `task` (MediaPipe), so this line is load-bearing. + fileType: ModelFileType.litertlm, + ).fromNetwork(widget.model.url).withProgress((percent) { + if (mounted) setState(() => _percent = percent); + }).install(); + + if (mounted) widget.onInstalled(); + } catch (error) { + if (mounted) setState(() => _error = error); + } finally { + if (mounted) setState(() => _downloading = false); + } + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + + return Scaffold( + appBar: AppBar(title: const Text('Get the model')), + body: Center( + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 420), + child: Padding( + padding: const EdgeInsets.all(24), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Text(widget.model.label, style: theme.textTheme.headlineSmall), + const SizedBox(height: 8), + Text( + '${widget.model.sizeLabel} — downloaded once, then it lives ' + 'on the device and runs with the network off.', + style: theme.textTheme.bodyMedium, + ), + const SizedBox(height: 24), + if (_downloading) ...[ + LinearProgressIndicator(value: _percent / 100), + const SizedBox(height: 8), + Text('$_percent%', textAlign: TextAlign.center), + ] else + FilledButton( + onPressed: _download, + child: const Text('Download model'), + ), + if (_error != null) ...[ + const SizedBox(height: 16), + _ErrorCard(error: _error!), + ], + ], + ), + ), + ), + ), + ); + } +} + +/// Says what failed, in the plugin's own words where it has any. +class _ErrorCard extends StatelessWidget { + const _ErrorCard({required this.error}); + + final Object error; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + // The plugin reports a failed download as a typed `DownloadException` + // wrapping a sealed `DownloadError`, so match on the type rather than + // sniffing the message for a status code. + final (title, body) = switch (error) { + DownloadException(:final error) => ( + 'Download failed', + error.toUserMessage(), + ), + _ => ('Download failed', '$error'), + }; + + return Card( + color: theme.colorScheme.errorContainer, + child: Padding( + padding: const EdgeInsets.all(16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(title, style: theme.textTheme.titleSmall), + const SizedBox(height: 8), + Text(body), + ], + ), + ), + ); + } +} diff --git a/codelabs/function-calling-flutter-gemma/step_02_one_tool/lib/main.dart b/codelabs/function-calling-flutter-gemma/step_02_one_tool/lib/main.dart new file mode 100644 index 000000000..8241664e4 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/lib/main.dart @@ -0,0 +1,173 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_gemma/flutter_gemma.dart'; +import 'package:flutter_gemma_litertlm/flutter_gemma_litertlm.dart'; + +import 'chat_page.dart'; +import 'download_page.dart'; +import 'model.dart'; + +/// The model this step runs: 284 MB, and function calling is what it is for. +const _model = Models.functionGemma; + +Future main() async { + WidgetsFlutterBinding.ensureInitialized(); + + // Engines are fully opt-in: the core package registers none by itself. + // Without LiteRtLmEngine here, the first model call throws a StateError + // that tells you to add an engine package. + // + // No `huggingFaceToken:` — the repository this codelab downloads from is + // ungated, so every `flutter run` is a plain `flutter run` with no + // `--dart-define`. + // + // Guarded, because every other failure in this app reaches the screen — the + // gate's error card, the chat's load error, the notice line — and this is the + // earliest one, so it is the one a learner meets first. Hot-restarting after + // adding a plugin throws `MissingPluginException` right here; unguarded, it + // never reaches `runApp` and the symptom is a blank window and a stack trace + // in a console nobody is looking at. + try { + await FlutterGemma.initialize(inferenceEngines: [LiteRtLmEngine()]); + } catch (error) { + runApp(_StartupFailed(error: error)); + return; + } + + runApp(const FunctionCallingApp()); +} + +/// Shown in place of the app when `FlutterGemma.initialize` throws, so a +/// failure before the first frame is a sentence instead of a blank window. +class _StartupFailed extends StatelessWidget { + const _StartupFailed({required this.error}); + + final Object error; + + @override + Widget build(BuildContext context) { + return MaterialApp( + title: 'Gemma Function Calling', + home: Scaffold( + body: Center( + child: Padding( + padding: const EdgeInsets.all(24), + child: Text( + 'flutter_gemma could not start.\n$error', + textAlign: TextAlign.center, + ), + ), + ), + ), + ); + } +} + +class FunctionCallingApp extends StatelessWidget { + const FunctionCallingApp({super.key}); + + @override + Widget build(BuildContext context) { + return MaterialApp( + title: 'Gemma Function Calling', + theme: ThemeData(colorSchemeSeed: Colors.indigo), + home: const ModelGate(model: _model), + ); + } +} + +/// Asks, on every cold start, whether the model is already installed. +/// +/// `install()` is idempotent, so the bytes are only ever fetched once. What a +/// drifted id costs you is this gate: it answers "no" forever, so the app +/// shows the download screen on every launch, the "download" there finishes +/// instantly, and you land straight back here. Delete the model with the chat's +/// delete button and relaunch to watch this branch flip back. +class ModelGate extends StatefulWidget { + const ModelGate({super.key, required this.model}); + + final ModelChoice model; + + @override + State createState() => _ModelGateState(); +} + +class _ModelGateState extends State { + late Future _installed = _check(); + + /// Installed is not the same as active. `getActiveModel` opens whichever + /// model was installed LAST, and this codelab's steps install two different + /// ones into a single application identity — so a run that finds the file + /// already here still has to say which model it means. `install()` is + /// idempotent: on a file already on disk it downloads nothing and just + /// records this model as the current one. + Future _check() async { + if (!await FlutterGemma.isModelInstalled(widget.model.fileName)) { + return false; + } + await FlutterGemma.installModel( + modelType: widget.model.modelType, + fileType: ModelFileType.litertlm, + ).fromNetwork(widget.model.url).install(); + return true; + } + + @override + Widget build(BuildContext context) { + return FutureBuilder( + future: _installed, + builder: (context, snapshot) { + if (snapshot.connectionState != ConnectionState.done) { + return const Scaffold( + body: Center(child: CircularProgressIndicator()), + ); + } + if (snapshot.hasError) { + // A FutureBuilder that ignores `hasError` renders the download + // screen as if nothing had gone wrong. Say what failed instead. + return _GateError( + error: snapshot.error!, + onRetry: () => setState(() => _installed = _check()), + ); + } + if (snapshot.data ?? false) { + return ChatPage( + model: widget.model, + onModelRemoved: () => setState(() => _installed = _check()), + ); + } + return DownloadPage( + model: widget.model, + onInstalled: () => setState(() => _installed = _check()), + ); + }, + ); + } +} + +/// Shown when the gate's own check fails, rather than falling through to the +/// download screen as if the answer had been "no". +class _GateError extends StatelessWidget { + const _GateError({required this.error, required this.onRetry}); + + final Object error; + final VoidCallback onRetry; + + @override + Widget build(BuildContext context) { + return Scaffold( + body: Center( + child: Padding( + padding: const EdgeInsets.all(24), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Text('$error', textAlign: TextAlign.center), + const SizedBox(height: 12), + FilledButton(onPressed: onRetry, child: const Text('Try again')), + ], + ), + ), + ), + ); + } +} diff --git a/codelabs/function-calling-flutter-gemma/step_02_one_tool/lib/model.dart b/codelabs/function-calling-flutter-gemma/step_02_one_tool/lib/model.dart new file mode 100644 index 000000000..2cefb1425 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/lib/model.dart @@ -0,0 +1,54 @@ +import 'package:flutter_gemma/flutter_gemma.dart'; + +/// One model this app knows how to install. +/// +/// [fileName] doubles as the model's id: `FlutterGemma.isModelInstalled` takes +/// the file name the model was installed under, not a display name. +class ModelChoice { + const ModelChoice({ + required this.label, + required this.url, + required this.fileName, + required this.modelType, + required this.sizeLabel, + }); + + final String label; + final String url; + final String fileName; + + /// Which family's function-call format the SDK should read and write. + /// + /// This is not decoration. `ModelType.functionGemma` selects + /// `FunctionGemmaCallFormat`, which renders the tool declarations into a + /// developer turn and parses `call:name{…}` back out + /// again. Name a different family and the SDK writes a prompt these weights + /// were never trained on and looks for a call in a syntax they never emit — + /// so every turn comes back as plain text and nothing says why. + final ModelType modelType; + + final String sizeLabel; +} + +/// The one model this step ships. +/// +/// The repository is ungated, so nothing here needs a Hugging Face token and +/// no run needs `--dart-define`. +abstract final class Models { + /// A 270M model whose whole job is function calling. + /// + /// 284 MB — small enough to download while you read this page, and small + /// enough that it does very little else: ask it a general question and the + /// answer will be thin. That is the trade this step is making on purpose. + /// Calling a function is a narrow skill, and a model specialised for it can + /// be a fraction of the size of one that also has to hold a conversation. + static const functionGemma = ModelChoice( + label: 'FunctionGemma 270M', + url: + 'https://huggingface.co/sasha-denisov/function-gemma-270M-it/' + 'resolve/main/functiongemma-270M-it.litertlm', + fileName: 'functiongemma-270M-it.litertlm', + modelType: ModelType.functionGemma, + sizeLabel: '284 MB', + ); +} diff --git a/codelabs/function-calling-flutter-gemma/step_02_one_tool/lib/tools.dart b/codelabs/function-calling-flutter-gemma/step_02_one_tool/lib/tools.dart new file mode 100644 index 000000000..c37060c2e --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/lib/tools.dart @@ -0,0 +1,71 @@ +import 'package:flutter_gemma/flutter_gemma.dart'; + +/// The one function this app lets the model ask for. +/// +/// A [Tool] is a DECLARATION and nothing else — a name, a description the +/// model reads, and a JSON Schema for the arguments. It holds no code and it +/// cannot run: the SDK renders this into the prompt and parses a call back +/// out, and running the call is the app's job. [runMultiply] below is the half +/// that actually computes something, and `chat_page.dart` is where the two are +/// wired together. +/// +/// Multiplication, because the answer is checkable. Ask a 270M model for +/// 1234 × 5678 and it will produce a confident number of about the right +/// length; ask it to call this instead and the number is exact, offline, and +/// you can verify it on a pocket calculator. A weather tool would demonstrate +/// the same mechanism and prove nothing about the answer. +const multiplyTool = Tool( + name: 'multiply', + // The model reads this. It is the only thing telling it WHEN to call — so + // "use this instead of working it out yourself" is instruction, not prose. + description: + 'Multiply two numbers and return the exact product. Use this for any ' + 'multiplication instead of working it out yourself.', + parameters: { + 'type': 'object', + 'properties': { + 'a': {'type': 'number', 'description': 'The first number.'}, + 'b': {'type': 'number', 'description': 'The second number.'}, + }, + 'required': ['a', 'b'], + }, +); + +/// Runs [multiplyTool] and returns the map the model will be shown. +/// +/// Everything this function returns becomes the model's only knowledge of what +/// happened, so the keys are part of the interface: `result` is what it will +/// read back to the user, and `error` is what it will apologise about. +Map runMultiply(Map args) { + final a = asNumber(args['a']); + final b = asNumber(args['b']); + if (a == null || b == null) { + // Returned, not thrown. A model wrote these arguments and a model can + // write nonsense; an error map is a turn it can read and correct on the + // next one, while an exception ends the conversation and takes the + // committed call with it. + return { + 'error': + 'multiply needs two numbers. Got a=${args['a']}, b=${args['b']}.', + }; + } + final product = a * b; + // `12 * 13` arriving as doubles comes back as `156.0`, and the model has to + // read that number out loud. Say 156. + return { + 'result': product is double && product == product.truncateToDouble() + ? product.toInt() + : product, + }; +} + +/// Arguments arrive as whatever JSON the model produced. +/// +/// It is trained to emit tool-call arguments as strings, so `"12"` is the +/// common case and `12` or `12.0` are the others. All three are the same +/// number and the app should not care which one it got. +num? asNumber(Object? value) => switch (value) { + final num n => n, + final String s => num.tryParse(s.trim()), + _ => null, +}; diff --git a/codelabs/function-calling-flutter-gemma/step_02_one_tool/linux/.gitignore b/codelabs/function-calling-flutter-gemma/step_02_one_tool/linux/.gitignore new file mode 100644 index 000000000..d3896c984 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/linux/.gitignore @@ -0,0 +1 @@ +flutter/ephemeral diff --git a/codelabs/function-calling-flutter-gemma/step_02_one_tool/linux/CMakeLists.txt b/codelabs/function-calling-flutter-gemma/step_02_one_tool/linux/CMakeLists.txt new file mode 100644 index 000000000..f21ac7bae --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/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 "functioncalling") +# The unique GTK application identifier for this application. See: +# https://wiki.gnome.org/HowDoI/ChooseApplicationID +set(APPLICATION_ID "dev.fluttergemma.functioncalling") + +# 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/codelabs/function-calling-flutter-gemma/step_02_one_tool/linux/flutter/CMakeLists.txt b/codelabs/function-calling-flutter-gemma/step_02_one_tool/linux/flutter/CMakeLists.txt new file mode 100644 index 000000000..d5bd01648 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/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/codelabs/function-calling-flutter-gemma/step_02_one_tool/linux/flutter/generated_plugin_registrant.cc b/codelabs/function-calling-flutter-gemma/step_02_one_tool/linux/flutter/generated_plugin_registrant.cc new file mode 100644 index 000000000..198e9645a --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/linux/flutter/generated_plugin_registrant.cc @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + +#include + +void fl_register_plugins(FlPluginRegistry* registry) { + g_autoptr(FlPluginRegistrar) flutter_gemma_registrar = + fl_plugin_registry_get_registrar_for_plugin(registry, "FlutterGemmaPlugin"); + flutter_gemma_plugin_register_with_registrar(flutter_gemma_registrar); +} diff --git a/codelabs/function-calling-flutter-gemma/step_02_one_tool/linux/flutter/generated_plugin_registrant.h b/codelabs/function-calling-flutter-gemma/step_02_one_tool/linux/flutter/generated_plugin_registrant.h new file mode 100644 index 000000000..e0f0a47bc --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/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/codelabs/function-calling-flutter-gemma/step_02_one_tool/linux/flutter/generated_plugins.cmake b/codelabs/function-calling-flutter-gemma/step_02_one_tool/linux/flutter/generated_plugins.cmake new file mode 100644 index 000000000..3b0705d0f --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/linux/flutter/generated_plugins.cmake @@ -0,0 +1,25 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST + flutter_gemma +) + +list(APPEND FLUTTER_FFI_PLUGIN_LIST + jni +) + +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/codelabs/function-calling-flutter-gemma/step_02_one_tool/linux/runner/CMakeLists.txt b/codelabs/function-calling-flutter-gemma/step_02_one_tool/linux/runner/CMakeLists.txt new file mode 100644 index 000000000..e97dabc70 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/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/codelabs/function-calling-flutter-gemma/step_02_one_tool/linux/runner/main.cc b/codelabs/function-calling-flutter-gemma/step_02_one_tool/linux/runner/main.cc new file mode 100644 index 000000000..e7c5c5437 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/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/codelabs/function-calling-flutter-gemma/step_02_one_tool/linux/runner/my_application.cc b/codelabs/function-calling-flutter-gemma/step_02_one_tool/linux/runner/my_application.cc new file mode 100644 index 000000000..917c019cf --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/linux/runner/my_application.cc @@ -0,0 +1,148 @@ +#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, "Gemma Function Calling"); + 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, "Gemma Function Calling"); + } + + 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/codelabs/function-calling-flutter-gemma/step_02_one_tool/linux/runner/my_application.h b/codelabs/function-calling-flutter-gemma/step_02_one_tool/linux/runner/my_application.h new file mode 100644 index 000000000..db16367a7 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/linux/runner/my_application.h @@ -0,0 +1,21 @@ +#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/codelabs/function-calling-flutter-gemma/step_02_one_tool/macos/.gitignore b/codelabs/function-calling-flutter-gemma/step_02_one_tool/macos/.gitignore new file mode 100644 index 000000000..746adbb6b --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/macos/.gitignore @@ -0,0 +1,7 @@ +# Flutter-related +**/Flutter/ephemeral/ +**/Pods/ + +# Xcode-related +**/dgph +**/xcuserdata/ diff --git a/codelabs/function-calling-flutter-gemma/step_02_one_tool/macos/Flutter/Flutter-Debug.xcconfig b/codelabs/function-calling-flutter-gemma/step_02_one_tool/macos/Flutter/Flutter-Debug.xcconfig new file mode 100644 index 000000000..4b81f9b2d --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/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/codelabs/function-calling-flutter-gemma/step_02_one_tool/macos/Flutter/Flutter-Release.xcconfig b/codelabs/function-calling-flutter-gemma/step_02_one_tool/macos/Flutter/Flutter-Release.xcconfig new file mode 100644 index 000000000..5caa9d157 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/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/codelabs/function-calling-flutter-gemma/step_02_one_tool/macos/Flutter/GeneratedPluginRegistrant.swift b/codelabs/function-calling-flutter-gemma/step_02_one_tool/macos/Flutter/GeneratedPluginRegistrant.swift new file mode 100644 index 000000000..0be86a9b4 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/macos/Flutter/GeneratedPluginRegistrant.swift @@ -0,0 +1,18 @@ +// +// Generated file. Do not edit. +// + +import FlutterMacOS +import Foundation + +import connectivity_plus +import flutter_gemma +import large_file_handler +import shared_preferences_foundation + +func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { + ConnectivityPlusPlugin.register(with: registry.registrar(forPlugin: "ConnectivityPlusPlugin")) + FlutterGemmaPlugin.register(with: registry.registrar(forPlugin: "FlutterGemmaPlugin")) + LargeFileHandlerPlugin.register(with: registry.registrar(forPlugin: "LargeFileHandlerPlugin")) + SharedPreferencesPlugin.register(with: registry.registrar(forPlugin: "SharedPreferencesPlugin")) +} diff --git a/codelabs/function-calling-flutter-gemma/step_02_one_tool/macos/Podfile b/codelabs/function-calling-flutter-gemma/step_02_one_tool/macos/Podfile new file mode 100644 index 000000000..32aafe8bf --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/macos/Podfile @@ -0,0 +1,98 @@ +platform :osx, '12.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', '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 + + # flutter_gemma: stage the upstream Apple companion dylibs into the built + # .app. `hook/build.dart` deliberately skips them from Native Assets on macOS + # (#247 — Google ships them without `-Wl,-headerpad_max_install_names`, so the + # JIT bundling path cannot rewrite their install_name), which leaves this + # build phase to stage them. + # + # The phase only LOCATES and RUNS a script; the staging logic itself lives in + # flutter_gemma_litertlm and is delivered next to the dylibs it stages. That + # is deliberate: this block is frozen into your Xcode project, and a copy of + # the logic frozen there cannot be fixed by upgrading the package. + installer.aggregate_targets.each do |aggregate_target| + aggregate_target.user_targets.each do |user_target| + phase_name = '[flutter_gemma] Setup LiteRT-LM macOS' + + # Only the app target embeds the Frameworks/ this phase patches. + # RunnerTests inherits Runner's framework search paths and has no + # Contents/Frameworks of its own — having the phase there creates a + # cross-target dependency on Runner's framework output that Xcode reports + # as "Cycle inside Flutter Assemble" (#300). Remove any stale copy from + # non-app targets and skip them. + unless user_target.name == 'Runner' + user_target.build_phases + .select { |p| p.respond_to?(:name) && p.name == phase_name } + .each { |p| user_target.build_phases.delete(p) } + next + end + + existing = user_target.shell_script_build_phases.find { |p| p.name == phase_name } + phase = existing || user_target.new_shell_script_build_phase(phase_name) + # The embedded LiteRtLm binary is an INPUT so the phase re-runs whenever + # Flutter's always-out-of-date `embed` phase re-copies the raw, unpatched + # binary over the patched one. Without it Xcode caches the phase after the + # first build and the second incremental build ships an unpatched + # LiteRtLm that fails dlopen at runtime (#368). + phase.input_paths = [ + '$(BUILT_PRODUCTS_DIR)/$(PRODUCT_NAME).app/Contents/Frameworks/LiteRtLm.framework/Versions/A/LiteRtLm', + ] + # A declared output lets Xcode order the phase in its dependency graph + # instead of treating it as "runs every build with no outputs" — the other + # half of the cycle warning (#300). The script touches this file. + phase.output_paths = ['$(DERIVED_FILE_DIR)/flutter_gemma_litertlm_macos.stamp'] + phase.shell_script = <<~SHELL + set -e + STAGER="${HOME}/Library/Caches/flutter_gemma/native/macos_arm64/stage_macos_companions.sh" + if [ ! -f "${STAGER}" ]; then + echo "[flutter_gemma] ERROR: ${STAGER} not found." >&2 + echo " flutter_gemma_litertlm 1.6.2+ installs it there from its build hook." >&2 + echo " Upgrade the package, then: flutter clean && flutter pub get" >&2 + exit 1 + fi + sh "${STAGER}" "${BUILT_PRODUCTS_DIR}/${PRODUCT_NAME}.app/Contents/Frameworks" + mkdir -p "$(dirname "${SCRIPT_OUTPUT_FILE_0}")" + touch "${SCRIPT_OUTPUT_FILE_0}" + SHELL + end + end +end diff --git a/codelabs/function-calling-flutter-gemma/step_02_one_tool/macos/Runner.xcodeproj/project.pbxproj b/codelabs/function-calling-flutter-gemma/step_02_one_tool/macos/Runner.xcodeproj/project.pbxproj new file mode 100644 index 000000000..8c78df2ee --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/macos/Runner.xcodeproj/project.pbxproj @@ -0,0 +1,729 @@ +// !$*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 */; }; + 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */ = {isa = PBXBuildFile; productRef = 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */; }; +/* 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 /* Gemma Function Calling.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "Gemma Function Calling.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 = ""; }; + 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */ = {isa = PBXFileReference; lastKnownFileType = wrapper; name = FlutterGeneratedPluginSwiftPackage; path = ephemeral/Packages/FlutterGeneratedPluginSwiftPackage; 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 = ( + 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */, + ); + 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 /* Gemma Function Calling.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 = ( + 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */, + 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; + packageProductDependencies = ( + 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */, + ); + productName = Runner; + productReference = 33CC10ED2044A3C60003C045 /* Gemma Function Calling.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; + packageReferences = ( + 781AD8BC2B33823900A9FFBB /* XCLocalSwiftPackageReference "Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage" */, + ); + 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 = dev.fluttergemma.functioncalling.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/$(PRODUCT_NAME).app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/$(PRODUCT_NAME)"; + }; + 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 = dev.fluttergemma.functioncalling.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/$(PRODUCT_NAME).app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/$(PRODUCT_NAME)"; + }; + 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 = dev.fluttergemma.functioncalling.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/$(PRODUCT_NAME).app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/$(PRODUCT_NAME)"; + }; + 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 = 12.0; + 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 = 12.0; + 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 = 12.0; + 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 */ + +/* Begin XCLocalSwiftPackageReference section */ + 781AD8BC2B33823900A9FFBB /* XCLocalSwiftPackageReference "Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage" */ = { + isa = XCLocalSwiftPackageReference; + relativePath = Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage; + }; +/* End XCLocalSwiftPackageReference section */ + +/* Begin XCSwiftPackageProductDependency section */ + 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */ = { + isa = XCSwiftPackageProductDependency; + productName = FlutterGeneratedPluginSwiftPackage; + }; +/* End XCSwiftPackageProductDependency section */ + }; + rootObject = 33CC10E52044A3C60003C045 /* Project object */; +} diff --git a/codelabs/function-calling-flutter-gemma/step_02_one_tool/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/codelabs/function-calling-flutter-gemma/step_02_one_tool/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 000000000..18d981003 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/codelabs/function-calling-flutter-gemma/step_02_one_tool/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/codelabs/function-calling-flutter-gemma/step_02_one_tool/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme new file mode 100644 index 000000000..822174206 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/codelabs/function-calling-flutter-gemma/step_02_one_tool/macos/Runner.xcworkspace/contents.xcworkspacedata b/codelabs/function-calling-flutter-gemma/step_02_one_tool/macos/Runner.xcworkspace/contents.xcworkspacedata new file mode 100644 index 000000000..21a3cc14c --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/macos/Runner.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,10 @@ + + + + + + + diff --git a/codelabs/function-calling-flutter-gemma/step_02_one_tool/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/codelabs/function-calling-flutter-gemma/step_02_one_tool/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 000000000..18d981003 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/codelabs/function-calling-flutter-gemma/step_02_one_tool/macos/Runner/AppDelegate.swift b/codelabs/function-calling-flutter-gemma/step_02_one_tool/macos/Runner/AppDelegate.swift new file mode 100644 index 000000000..b3c176141 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/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/codelabs/function-calling-flutter-gemma/step_02_one_tool/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json b/codelabs/function-calling-flutter-gemma/step_02_one_tool/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 000000000..a2ec33f19 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/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/codelabs/function-calling-flutter-gemma/step_02_one_tool/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png b/codelabs/function-calling-flutter-gemma/step_02_one_tool/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png new file mode 100644 index 000000000..82b6f9d9a Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_02_one_tool/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_02_one_tool/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png b/codelabs/function-calling-flutter-gemma/step_02_one_tool/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png new file mode 100644 index 000000000..13b35eba5 Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_02_one_tool/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_02_one_tool/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png b/codelabs/function-calling-flutter-gemma/step_02_one_tool/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png new file mode 100644 index 000000000..0a3f5fa40 Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_02_one_tool/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_02_one_tool/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png b/codelabs/function-calling-flutter-gemma/step_02_one_tool/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png new file mode 100644 index 000000000..bdb57226d Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_02_one_tool/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_02_one_tool/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png b/codelabs/function-calling-flutter-gemma/step_02_one_tool/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png new file mode 100644 index 000000000..f083318e0 Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_02_one_tool/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_02_one_tool/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png b/codelabs/function-calling-flutter-gemma/step_02_one_tool/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png new file mode 100644 index 000000000..326c0e72c Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_02_one_tool/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_02_one_tool/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png b/codelabs/function-calling-flutter-gemma/step_02_one_tool/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png new file mode 100644 index 000000000..2f1632cfd Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_02_one_tool/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_02_one_tool/macos/Runner/Base.lproj/MainMenu.xib b/codelabs/function-calling-flutter-gemma/step_02_one_tool/macos/Runner/Base.lproj/MainMenu.xib new file mode 100644 index 000000000..80e867a4e --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/macos/Runner/Base.lproj/MainMenu.xib @@ -0,0 +1,343 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/codelabs/function-calling-flutter-gemma/step_02_one_tool/macos/Runner/Configs/AppInfo.xcconfig b/codelabs/function-calling-flutter-gemma/step_02_one_tool/macos/Runner/Configs/AppInfo.xcconfig new file mode 100644 index 000000000..0fcdf0410 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/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 = Gemma Function Calling + +// The application's bundle identifier +PRODUCT_BUNDLE_IDENTIFIER = dev.fluttergemma.functioncalling + +// The copyright displayed in application information +PRODUCT_COPYRIGHT = Copyright © 2026 dev.fluttergemma. All rights reserved. diff --git a/codelabs/function-calling-flutter-gemma/step_02_one_tool/macos/Runner/Configs/Debug.xcconfig b/codelabs/function-calling-flutter-gemma/step_02_one_tool/macos/Runner/Configs/Debug.xcconfig new file mode 100644 index 000000000..36b0fd946 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/macos/Runner/Configs/Debug.xcconfig @@ -0,0 +1,2 @@ +#include "../../Flutter/Flutter-Debug.xcconfig" +#include "Warnings.xcconfig" diff --git a/codelabs/function-calling-flutter-gemma/step_02_one_tool/macos/Runner/Configs/Release.xcconfig b/codelabs/function-calling-flutter-gemma/step_02_one_tool/macos/Runner/Configs/Release.xcconfig new file mode 100644 index 000000000..dff4f4956 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/macos/Runner/Configs/Release.xcconfig @@ -0,0 +1,2 @@ +#include "../../Flutter/Flutter-Release.xcconfig" +#include "Warnings.xcconfig" diff --git a/codelabs/function-calling-flutter-gemma/step_02_one_tool/macos/Runner/Configs/Warnings.xcconfig b/codelabs/function-calling-flutter-gemma/step_02_one_tool/macos/Runner/Configs/Warnings.xcconfig new file mode 100644 index 000000000..42bcbf478 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/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/codelabs/function-calling-flutter-gemma/step_02_one_tool/macos/Runner/DebugProfile.entitlements b/codelabs/function-calling-flutter-gemma/step_02_one_tool/macos/Runner/DebugProfile.entitlements new file mode 100644 index 000000000..8eb23d1c4 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/macos/Runner/DebugProfile.entitlements @@ -0,0 +1,16 @@ + + + + + com.apple.security.app-sandbox + + com.apple.security.cs.allow-jit + + com.apple.security.cs.disable-library-validation + + com.apple.security.network.client + + com.apple.security.network.server + + + diff --git a/codelabs/function-calling-flutter-gemma/step_02_one_tool/macos/Runner/Info.plist b/codelabs/function-calling-flutter-gemma/step_02_one_tool/macos/Runner/Info.plist new file mode 100644 index 000000000..4789daa6a --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/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/codelabs/function-calling-flutter-gemma/step_02_one_tool/macos/Runner/MainFlutterWindow.swift b/codelabs/function-calling-flutter-gemma/step_02_one_tool/macos/Runner/MainFlutterWindow.swift new file mode 100644 index 000000000..3cc05eb23 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/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/codelabs/function-calling-flutter-gemma/step_02_one_tool/macos/Runner/Release.entitlements b/codelabs/function-calling-flutter-gemma/step_02_one_tool/macos/Runner/Release.entitlements new file mode 100644 index 000000000..d7c971d31 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/macos/Runner/Release.entitlements @@ -0,0 +1,12 @@ + + + + + com.apple.security.app-sandbox + + com.apple.security.cs.disable-library-validation + + com.apple.security.network.client + + + diff --git a/codelabs/function-calling-flutter-gemma/step_02_one_tool/macos/RunnerTests/RunnerTests.swift b/codelabs/function-calling-flutter-gemma/step_02_one_tool/macos/RunnerTests/RunnerTests.swift new file mode 100644 index 000000000..61f3bd1fc --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/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/codelabs/function-calling-flutter-gemma/step_02_one_tool/pubspec.yaml b/codelabs/function-calling-flutter-gemma/step_02_one_tool/pubspec.yaml new file mode 100644 index 000000000..324dd18bb --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/pubspec.yaml @@ -0,0 +1,97 @@ +name: gemma_quickstart +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.12.0 + +# 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 + + # The following adds the Cupertino Icons font to your application. + # Use with the CupertinoIcons class for iOS style icons. + cupertino_icons: ^1.0.8 + + # The engine-agnostic core: registry, install/runtime API, chat. + flutter_gemma: ^1.7.1 + # The .litertlm inference engine. Engines are opt-in — core + # registers none, so this package must be added explicitly. + flutter_gemma_litertlm: ^1.6.2 + +dev_dependencies: + flutter_test: + sdk: flutter + integration_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: ^6.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/codelabs/function-calling-flutter-gemma/step_02_one_tool/test/widget_test.dart b/codelabs/function-calling-flutter-gemma/step_02_one_tool/test/widget_test.dart new file mode 100644 index 000000000..5ef21261c --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/test/widget_test.dart @@ -0,0 +1,68 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:gemma_quickstart/download_page.dart'; +import 'package:gemma_quickstart/model.dart'; +import 'package:gemma_quickstart/tools.dart'; + +void main() { + // `isModelInstalled` is keyed by file name. `install()` skips bytes it + // already has, so a name that drifts from its URL does not re-download — it + // strands the app on a download screen the gate is never satisfied by. + test('the model id matches the last segment of its URL', () { + const model = Models.functionGemma; + expect(model.fileName, model.url.split('/').last, reason: model.label); + }); + + // The declaration is the model's only description of the function, so its + // shape is part of the app's behaviour and not a comment. A renamed + // parameter here is a call the app cannot answer. + test('the tool declares the two arguments the runner reads', () { + expect(multiplyTool.name, 'multiply'); + final properties = + multiplyTool.parameters['properties'] as Map; + expect(properties.keys, containsAll(['a', 'b'])); + expect(multiplyTool.parameters['required'], ['a', 'b']); + }); + + group('runMultiply answers whatever the model wrote', () { + // The model is trained to emit arguments as strings, so this is the + // ordinary case, not the exotic one. + test('strings', () { + expect(runMultiply({'a': '1234', 'b': '5678'}), {'result': 7006652}); + }); + + test('numbers', () { + expect(runMultiply({'a': 12, 'b': 13}), {'result': 156}); + }); + + // An integer product that arrives as doubles must not be read back to the + // user as "156.0". + test('doubles that are whole numbers come back whole', () { + expect(runMultiply({'a': 12.0, 'b': 13.0}), {'result': 156}); + }); + + test('a genuine fraction stays one', () { + expect(runMultiply({'a': 0.5, 'b': 3}), {'result': 1.5}); + }); + + // Returned, not thrown: the model has to be able to read this and try + // again, and an exception would end the turn instead. + test('nonsense is an error map, not an exception', () { + final answer = runMultiply({'a': 'twelve', 'b': 13}); + expect(answer.containsKey('error'), isTrue); + expect(answer.containsKey('result'), isFalse); + }); + }); + + testWidgets('the download screen offers the model before any plugin call', ( + tester, + ) async { + await tester.pumpWidget( + MaterialApp( + home: DownloadPage(model: Models.functionGemma, onInstalled: () {}), + ), + ); + expect(find.text('FunctionGemma 270M'), findsOneWidget); + expect(find.text('Download model'), findsOneWidget); + }); +} diff --git a/codelabs/function-calling-flutter-gemma/step_02_one_tool/web/favicon.png b/codelabs/function-calling-flutter-gemma/step_02_one_tool/web/favicon.png new file mode 100644 index 000000000..8aaa46ac1 Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_02_one_tool/web/favicon.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_02_one_tool/web/icons/Icon-192.png b/codelabs/function-calling-flutter-gemma/step_02_one_tool/web/icons/Icon-192.png new file mode 100644 index 000000000..b749bfef0 Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_02_one_tool/web/icons/Icon-192.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_02_one_tool/web/icons/Icon-512.png b/codelabs/function-calling-flutter-gemma/step_02_one_tool/web/icons/Icon-512.png new file mode 100644 index 000000000..88cfd48df Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_02_one_tool/web/icons/Icon-512.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_02_one_tool/web/icons/Icon-maskable-192.png b/codelabs/function-calling-flutter-gemma/step_02_one_tool/web/icons/Icon-maskable-192.png new file mode 100644 index 000000000..eb9b4d76e Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_02_one_tool/web/icons/Icon-maskable-192.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_02_one_tool/web/icons/Icon-maskable-512.png b/codelabs/function-calling-flutter-gemma/step_02_one_tool/web/icons/Icon-maskable-512.png new file mode 100644 index 000000000..d69c56691 Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_02_one_tool/web/icons/Icon-maskable-512.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_02_one_tool/web/index.html b/codelabs/function-calling-flutter-gemma/step_02_one_tool/web/index.html new file mode 100644 index 000000000..4dc25043a --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/web/index.html @@ -0,0 +1,58 @@ + + + + + + + + + + + + + + + + + + + + Gemma Function Calling + + + + + + + + + + diff --git a/codelabs/function-calling-flutter-gemma/step_02_one_tool/web/manifest.json b/codelabs/function-calling-flutter-gemma/step_02_one_tool/web/manifest.json new file mode 100644 index 000000000..747e60366 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/web/manifest.json @@ -0,0 +1,35 @@ +{ + "name": "Gemma Function Calling", + "short_name": "Gemma Function Calling", + "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/codelabs/function-calling-flutter-gemma/step_02_one_tool/windows/.gitignore b/codelabs/function-calling-flutter-gemma/step_02_one_tool/windows/.gitignore new file mode 100644 index 000000000..d492d0d98 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/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/codelabs/function-calling-flutter-gemma/step_02_one_tool/windows/CMakeLists.txt b/codelabs/function-calling-flutter-gemma/step_02_one_tool/windows/CMakeLists.txt new file mode 100644 index 000000000..ed760319f --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/windows/CMakeLists.txt @@ -0,0 +1,108 @@ +# Project-level configuration. +cmake_minimum_required(VERSION 3.14) +project(functioncalling 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 "functioncalling") + +# 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/codelabs/function-calling-flutter-gemma/step_02_one_tool/windows/flutter/CMakeLists.txt b/codelabs/function-calling-flutter-gemma/step_02_one_tool/windows/flutter/CMakeLists.txt new file mode 100644 index 000000000..903f4899d --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/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/codelabs/function-calling-flutter-gemma/step_02_one_tool/windows/flutter/generated_plugin_registrant.cc b/codelabs/function-calling-flutter-gemma/step_02_one_tool/windows/flutter/generated_plugin_registrant.cc new file mode 100644 index 000000000..38c2332a8 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/windows/flutter/generated_plugin_registrant.cc @@ -0,0 +1,17 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + +#include +#include + +void RegisterPlugins(flutter::PluginRegistry* registry) { + ConnectivityPlusWindowsPluginRegisterWithRegistrar( + registry->GetRegistrarForPlugin("ConnectivityPlusWindowsPlugin")); + FlutterGemmaPluginRegisterWithRegistrar( + registry->GetRegistrarForPlugin("FlutterGemmaPlugin")); +} diff --git a/codelabs/function-calling-flutter-gemma/step_02_one_tool/windows/flutter/generated_plugin_registrant.h b/codelabs/function-calling-flutter-gemma/step_02_one_tool/windows/flutter/generated_plugin_registrant.h new file mode 100644 index 000000000..dc139d85a --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/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/codelabs/function-calling-flutter-gemma/step_02_one_tool/windows/flutter/generated_plugins.cmake b/codelabs/function-calling-flutter-gemma/step_02_one_tool/windows/flutter/generated_plugins.cmake new file mode 100644 index 000000000..8dcbac209 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/windows/flutter/generated_plugins.cmake @@ -0,0 +1,26 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST + connectivity_plus + flutter_gemma +) + +list(APPEND FLUTTER_FFI_PLUGIN_LIST + jni +) + +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/codelabs/function-calling-flutter-gemma/step_02_one_tool/windows/runner/CMakeLists.txt b/codelabs/function-calling-flutter-gemma/step_02_one_tool/windows/runner/CMakeLists.txt new file mode 100644 index 000000000..394917c05 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/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/codelabs/function-calling-flutter-gemma/step_02_one_tool/windows/runner/Runner.rc b/codelabs/function-calling-flutter-gemma/step_02_one_tool/windows/runner/Runner.rc new file mode 100644 index 000000000..967d1c9d1 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/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", "dev.fluttergemma" "\0" + VALUE "FileDescription", "Gemma Function Calling" "\0" + VALUE "FileVersion", VERSION_AS_STRING "\0" + VALUE "InternalName", "functioncalling" "\0" + VALUE "LegalCopyright", "Copyright (C) 2026 dev.fluttergemma. All rights reserved." "\0" + VALUE "OriginalFilename", "functioncalling.exe" "\0" + VALUE "ProductName", "Gemma Function Calling" "\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/codelabs/function-calling-flutter-gemma/step_02_one_tool/windows/runner/flutter_window.cpp b/codelabs/function-calling-flutter-gemma/step_02_one_tool/windows/runner/flutter_window.cpp new file mode 100644 index 000000000..955ee3038 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/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/codelabs/function-calling-flutter-gemma/step_02_one_tool/windows/runner/flutter_window.h b/codelabs/function-calling-flutter-gemma/step_02_one_tool/windows/runner/flutter_window.h new file mode 100644 index 000000000..6da0652f0 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/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/codelabs/function-calling-flutter-gemma/step_02_one_tool/windows/runner/main.cpp b/codelabs/function-calling-flutter-gemma/step_02_one_tool/windows/runner/main.cpp new file mode 100644 index 000000000..38dad4a50 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/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"Gemma Function Calling", 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/codelabs/function-calling-flutter-gemma/step_02_one_tool/windows/runner/resource.h b/codelabs/function-calling-flutter-gemma/step_02_one_tool/windows/runner/resource.h new file mode 100644 index 000000000..66a65d1e4 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/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/codelabs/function-calling-flutter-gemma/step_02_one_tool/windows/runner/resources/app_icon.ico b/codelabs/function-calling-flutter-gemma/step_02_one_tool/windows/runner/resources/app_icon.ico new file mode 100644 index 000000000..c04e20caf Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_02_one_tool/windows/runner/resources/app_icon.ico differ diff --git a/codelabs/function-calling-flutter-gemma/step_02_one_tool/windows/runner/runner.exe.manifest b/codelabs/function-calling-flutter-gemma/step_02_one_tool/windows/runner/runner.exe.manifest new file mode 100644 index 000000000..153653e8d --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/windows/runner/runner.exe.manifest @@ -0,0 +1,14 @@ + + + + + PerMonitorV2 + + + + + + + + + diff --git a/codelabs/function-calling-flutter-gemma/step_02_one_tool/windows/runner/utils.cpp b/codelabs/function-calling-flutter-gemma/step_02_one_tool/windows/runner/utils.cpp new file mode 100644 index 000000000..3cb714665 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/windows/runner/utils.cpp @@ -0,0 +1,69 @@ +#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(); + } + // First, find the length of the string with a safe upper bound (CWE-126). + // UNICODE_STRING_MAX_CHARS (32767) is the maximum length of a UNICODE_STRING. + int input_length = static_cast(wcsnlen(utf16_string, UNICODE_STRING_MAX_CHARS)); + // Now use that bounded length to determine the required buffer size. + // When an explicit length is passed, WideCharToMultiByte does not include + // the null terminator in its returned size. + int target_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + input_length, nullptr, 0, nullptr, nullptr); + std::string utf8_string; + if (target_length == 0 || static_cast(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/codelabs/function-calling-flutter-gemma/step_02_one_tool/windows/runner/utils.h b/codelabs/function-calling-flutter-gemma/step_02_one_tool/windows/runner/utils.h new file mode 100644 index 000000000..3879d5475 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/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/codelabs/function-calling-flutter-gemma/step_02_one_tool/windows/runner/win32_window.cpp b/codelabs/function-calling-flutter-gemma/step_02_one_tool/windows/runner/win32_window.cpp new file mode 100644 index 000000000..60608d0fe --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/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/codelabs/function-calling-flutter-gemma/step_02_one_tool/windows/runner/win32_window.h b/codelabs/function-calling-flutter-gemma/step_02_one_tool/windows/runner/win32_window.h new file mode 100644 index 000000000..e901dde68 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_02_one_tool/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/codelabs/function-calling-flutter-gemma/step_03_the_loop/.gitignore b/codelabs/function-calling-flutter-gemma/step_03_the_loop/.gitignore new file mode 100644 index 000000000..79f7ecabd --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/.gitignore @@ -0,0 +1,48 @@ +# 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 + +# Widget Preview related +.widget_preview/ diff --git a/codelabs/function-calling-flutter-gemma/step_03_the_loop/.metadata b/codelabs/function-calling-flutter-gemma/step_03_the_loop/.metadata new file mode 100644 index 000000000..615dfd47e --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/.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: "d3b14c876900e553bc736ca19295fc09e3853e8e" + channel: "stable" + +project_type: app + +# Tracks metadata for the flutter migrate command +migration: + platforms: + - platform: root + create_revision: d3b14c876900e553bc736ca19295fc09e3853e8e + base_revision: d3b14c876900e553bc736ca19295fc09e3853e8e + - platform: android + create_revision: d3b14c876900e553bc736ca19295fc09e3853e8e + base_revision: d3b14c876900e553bc736ca19295fc09e3853e8e + - platform: ios + create_revision: d3b14c876900e553bc736ca19295fc09e3853e8e + base_revision: d3b14c876900e553bc736ca19295fc09e3853e8e + - platform: linux + create_revision: d3b14c876900e553bc736ca19295fc09e3853e8e + base_revision: d3b14c876900e553bc736ca19295fc09e3853e8e + - platform: macos + create_revision: d3b14c876900e553bc736ca19295fc09e3853e8e + base_revision: d3b14c876900e553bc736ca19295fc09e3853e8e + - platform: web + create_revision: d3b14c876900e553bc736ca19295fc09e3853e8e + base_revision: d3b14c876900e553bc736ca19295fc09e3853e8e + - platform: windows + create_revision: d3b14c876900e553bc736ca19295fc09e3853e8e + base_revision: d3b14c876900e553bc736ca19295fc09e3853e8e + + # 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/codelabs/function-calling-flutter-gemma/step_03_the_loop/README.md b/codelabs/function-calling-flutter-gemma/step_03_the_loop/README.md new file mode 100644 index 000000000..1c831fead --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/README.md @@ -0,0 +1,17 @@ +# gemma_quickstart + +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: + +- [Learn Flutter](https://docs.flutter.dev/get-started/learn-flutter) +- [Write your first Flutter app](https://docs.flutter.dev/get-started/codelab) +- [Flutter learning resources](https://docs.flutter.dev/reference/learning-resources) + +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/codelabs/function-calling-flutter-gemma/step_03_the_loop/analysis_options.yaml b/codelabs/function-calling-flutter-gemma/step_03_the_loop/analysis_options.yaml new file mode 100644 index 000000000..78613972a --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/analysis_options.yaml @@ -0,0 +1,38 @@ +# 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 + +analyzer: + exclude: + - build/** + - android/** + - ios/** + - linux/** + - macos/** + - web/** + - windows/** + +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/codelabs/function-calling-flutter-gemma/step_03_the_loop/android/.gitignore b/codelabs/function-calling-flutter-gemma/step_03_the_loop/android/.gitignore new file mode 100644 index 000000000..be3943c96 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/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/codelabs/function-calling-flutter-gemma/step_03_the_loop/android/app/build.gradle.kts b/codelabs/function-calling-flutter-gemma/step_03_the_loop/android/app/build.gradle.kts new file mode 100644 index 000000000..1ec5366e9 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/android/app/build.gradle.kts @@ -0,0 +1,49 @@ +plugins { + id("com.android.application") + // The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins. + id("dev.flutter.flutter-gradle-plugin") +} + +android { + namespace = "dev.fluttergemma.functioncalling" + compileSdk = flutter.compileSdkVersion + ndkVersion = flutter.ndkVersion + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + } + + defaultConfig { + // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). + applicationId = "dev.fluttergemma.functioncalling" + // 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 + // Uses the version code from pubspec.yaml. When using split APKs, 1000 * ABI_VERSION + // is added automatically by Flutter. (https://developer.android.com/studio/build/configure-apk-splits#configure-APK-versions) + // You can force using the value of versionCode by specifying the `-P force-version-code-ignoring-abi=true` + // flag during build. + 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") + } + } +} + +kotlin { + compilerOptions { + jvmTarget = org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17 + } +} + +flutter { + source = "../.." +} diff --git a/codelabs/function-calling-flutter-gemma/step_03_the_loop/android/app/src/debug/AndroidManifest.xml b/codelabs/function-calling-flutter-gemma/step_03_the_loop/android/app/src/debug/AndroidManifest.xml new file mode 100644 index 000000000..399f6981d --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/android/app/src/debug/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + diff --git a/codelabs/function-calling-flutter-gemma/step_03_the_loop/android/app/src/main/AndroidManifest.xml b/codelabs/function-calling-flutter-gemma/step_03_the_loop/android/app/src/main/AndroidManifest.xml new file mode 100644 index 000000000..34daae5c0 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,47 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/codelabs/function-calling-flutter-gemma/step_03_the_loop/android/app/src/main/kotlin/dev/fluttergemma/functioncalling/MainActivity.kt b/codelabs/function-calling-flutter-gemma/step_03_the_loop/android/app/src/main/kotlin/dev/fluttergemma/functioncalling/MainActivity.kt new file mode 100644 index 000000000..e4e274d6e --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/android/app/src/main/kotlin/dev/fluttergemma/functioncalling/MainActivity.kt @@ -0,0 +1,5 @@ +package dev.fluttergemma.functioncalling + +import io.flutter.embedding.android.FlutterActivity + +class MainActivity : FlutterActivity() diff --git a/codelabs/function-calling-flutter-gemma/step_03_the_loop/android/app/src/main/res/drawable-v21/launch_background.xml b/codelabs/function-calling-flutter-gemma/step_03_the_loop/android/app/src/main/res/drawable-v21/launch_background.xml new file mode 100644 index 000000000..f74085f3f --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/android/app/src/main/res/drawable-v21/launch_background.xml @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/codelabs/function-calling-flutter-gemma/step_03_the_loop/android/app/src/main/res/drawable/launch_background.xml b/codelabs/function-calling-flutter-gemma/step_03_the_loop/android/app/src/main/res/drawable/launch_background.xml new file mode 100644 index 000000000..304732f88 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/android/app/src/main/res/drawable/launch_background.xml @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/codelabs/function-calling-flutter-gemma/step_03_the_loop/android/app/src/main/res/mipmap-hdpi/ic_launcher.png b/codelabs/function-calling-flutter-gemma/step_03_the_loop/android/app/src/main/res/mipmap-hdpi/ic_launcher.png new file mode 100644 index 000000000..db77bb4b7 Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_03_the_loop/android/app/src/main/res/mipmap-hdpi/ic_launcher.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_03_the_loop/android/app/src/main/res/mipmap-mdpi/ic_launcher.png b/codelabs/function-calling-flutter-gemma/step_03_the_loop/android/app/src/main/res/mipmap-mdpi/ic_launcher.png new file mode 100644 index 000000000..17987b79b Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_03_the_loop/android/app/src/main/res/mipmap-mdpi/ic_launcher.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_03_the_loop/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/codelabs/function-calling-flutter-gemma/step_03_the_loop/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png new file mode 100644 index 000000000..09d439148 Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_03_the_loop/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_03_the_loop/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/codelabs/function-calling-flutter-gemma/step_03_the_loop/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png new file mode 100644 index 000000000..d5f1c8d34 Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_03_the_loop/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_03_the_loop/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/codelabs/function-calling-flutter-gemma/step_03_the_loop/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 000000000..4d6372eeb Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_03_the_loop/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_03_the_loop/android/app/src/main/res/values-night/styles.xml b/codelabs/function-calling-flutter-gemma/step_03_the_loop/android/app/src/main/res/values-night/styles.xml new file mode 100644 index 000000000..06952be74 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/android/app/src/main/res/values-night/styles.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/codelabs/function-calling-flutter-gemma/step_03_the_loop/android/app/src/main/res/values/styles.xml b/codelabs/function-calling-flutter-gemma/step_03_the_loop/android/app/src/main/res/values/styles.xml new file mode 100644 index 000000000..cb1ef8805 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/android/app/src/main/res/values/styles.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/codelabs/function-calling-flutter-gemma/step_03_the_loop/android/app/src/profile/AndroidManifest.xml b/codelabs/function-calling-flutter-gemma/step_03_the_loop/android/app/src/profile/AndroidManifest.xml new file mode 100644 index 000000000..399f6981d --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/android/app/src/profile/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + diff --git a/codelabs/function-calling-flutter-gemma/step_03_the_loop/android/build.gradle.kts b/codelabs/function-calling-flutter-gemma/step_03_the_loop/android/build.gradle.kts new file mode 100644 index 000000000..dbee657bb --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/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/codelabs/function-calling-flutter-gemma/step_03_the_loop/android/gradle.properties b/codelabs/function-calling-flutter-gemma/step_03_the_loop/android/gradle.properties new file mode 100644 index 000000000..e96108cfe --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/android/gradle.properties @@ -0,0 +1,6 @@ +org.gradle.jvmargs=-Xmx8G -XX:MaxMetaspaceSize=4G -XX:ReservedCodeCacheSize=512m -XX:+HeapDumpOnOutOfMemoryError +android.useAndroidX=true +# This newDsl flag was added by the Flutter template +android.newDsl=false +# This builtInKotlin flag was added by the Flutter template +android.builtInKotlin=false diff --git a/codelabs/function-calling-flutter-gemma/step_03_the_loop/android/gradle/wrapper/gradle-wrapper.properties b/codelabs/function-calling-flutter-gemma/step_03_the_loop/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 000000000..a20f2c46d --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/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-9.3.1-all.zip diff --git a/codelabs/function-calling-flutter-gemma/step_03_the_loop/android/settings.gradle.kts b/codelabs/function-calling-flutter-gemma/step_03_the_loop/android/settings.gradle.kts new file mode 100644 index 000000000..b28021a91 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/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 "9.1.0" apply false + id("org.jetbrains.kotlin.android") version "2.4.0" apply false +} + +include(":app") diff --git a/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/.gitignore b/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/.gitignore new file mode 100644 index 000000000..7a7f9873a --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/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/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Flutter/AppFrameworkInfo.plist b/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Flutter/AppFrameworkInfo.plist new file mode 100644 index 000000000..391a902b2 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Flutter/AppFrameworkInfo.plist @@ -0,0 +1,24 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + App + CFBundleIdentifier + io.flutter.flutter.app + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + App + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.0 + CFBundleSignature + ???? + CFBundleVersion + 1.0 + + diff --git a/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Flutter/Debug.xcconfig b/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Flutter/Debug.xcconfig new file mode 100644 index 000000000..592ceee85 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Flutter/Debug.xcconfig @@ -0,0 +1 @@ +#include "Generated.xcconfig" diff --git a/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Flutter/Release.xcconfig b/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Flutter/Release.xcconfig new file mode 100644 index 000000000..592ceee85 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Flutter/Release.xcconfig @@ -0,0 +1 @@ +#include "Generated.xcconfig" diff --git a/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner.xcodeproj/project.pbxproj b/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner.xcodeproj/project.pbxproj new file mode 100644 index 000000000..249dc6542 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner.xcodeproj/project.pbxproj @@ -0,0 +1,655 @@ +// !$*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 */; }; + 7884E8682EC3CC0700C636F2 /* SceneDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7884E8672EC3CC0400C636F2 /* SceneDelegate.swift */; }; + 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */ = {isa = PBXBuildFile; productRef = 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */; }; + 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 = ""; }; + 7884E8672EC3CC0400C636F2 /* SceneDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SceneDelegate.swift; sourceTree = ""; }; + 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */ = {isa = PBXFileReference; lastKnownFileType = wrapper; name = FlutterGeneratedPluginSwiftPackage; path = Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage; 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 = ""; }; + C0DE1AB52ED000000000E17E /* Runner.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = Runner.entitlements; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 97C146EB1CF9000F007C117D /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 331C8082294A63A400263BE5 /* RunnerTests */ = { + isa = PBXGroup; + children = ( + 331C807B294A618700263BE5 /* RunnerTests.swift */, + ); + path = RunnerTests; + sourceTree = ""; + }; + 9740EEB11CF90186004384FC /* Flutter */ = { + isa = PBXGroup; + children = ( + 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */, + 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 */, + C0DE1AB52ED000000000E17E /* Runner.entitlements */, + 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */, + 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */, + 74858FAE1ED2DC5600515810 /* AppDelegate.swift */, + 7884E8672EC3CC0400C636F2 /* SceneDelegate.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; + packageProductDependencies = ( + 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */, + ); + 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; + packageReferences = ( + 781AD8BC2B33823900A9FFBB /* XCLocalSwiftPackageReference "Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage" */, + ); + 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 */, + 7884E8682EC3CC0700C636F2 /* SceneDelegate.swift 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 = 15.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + STRING_CATALOG_GENERATE_SYMBOLS = YES; + 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; + CODE_SIGN_ENTITLEMENTS = Runner/Runner.entitlements; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + DEVELOPMENT_TEAM = 6ZHF6A3G28; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = dev.fluttergemma.functioncalling; + 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 = dev.fluttergemma.functioncalling.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 = dev.fluttergemma.functioncalling.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 = dev.fluttergemma.functioncalling.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 = 15.0; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = iphoneos; + STRING_CATALOG_GENERATE_SYMBOLS = YES; + 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 = 15.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + STRING_CATALOG_GENERATE_SYMBOLS = YES; + 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; + CODE_SIGN_ENTITLEMENTS = Runner/Runner.entitlements; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + DEVELOPMENT_TEAM = 6ZHF6A3G28; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = dev.fluttergemma.functioncalling; + 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; + CODE_SIGN_ENTITLEMENTS = Runner/Runner.entitlements; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + DEVELOPMENT_TEAM = 6ZHF6A3G28; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = dev.fluttergemma.functioncalling; + 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 */ + +/* Begin XCLocalSwiftPackageReference section */ + 781AD8BC2B33823900A9FFBB /* XCLocalSwiftPackageReference "Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage" */ = { + isa = XCLocalSwiftPackageReference; + relativePath = Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage; + }; +/* End XCLocalSwiftPackageReference section */ + +/* Begin XCSwiftPackageProductDependency section */ + 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */ = { + isa = XCSwiftPackageProductDependency; + productName = FlutterGeneratedPluginSwiftPackage; + }; +/* End XCSwiftPackageProductDependency section */ + }; + rootObject = 97C146E61CF9000F007C117D /* Project object */; +} diff --git a/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata new file mode 100644 index 000000000..919434a62 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 000000000..18d981003 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings new file mode 100644 index 000000000..f9b0d7c5e --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings @@ -0,0 +1,8 @@ + + + + + PreviewsEnabled + + + diff --git a/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme new file mode 100644 index 000000000..c3fedb29c --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -0,0 +1,119 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner.xcworkspace/contents.xcworkspacedata b/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner.xcworkspace/contents.xcworkspacedata new file mode 100644 index 000000000..1d526a16e --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 000000000..18d981003 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings new file mode 100644 index 000000000..f9b0d7c5e --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings @@ -0,0 +1,8 @@ + + + + + PreviewsEnabled + + + diff --git a/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner/AppDelegate.swift b/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner/AppDelegate.swift new file mode 100644 index 000000000..c30b367ec --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner/AppDelegate.swift @@ -0,0 +1,16 @@ +import Flutter +import UIKit + +@main +@objc class AppDelegate: FlutterAppDelegate, FlutterImplicitEngineDelegate { + override func application( + _ application: UIApplication, + didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? + ) -> Bool { + return super.application(application, didFinishLaunchingWithOptions: launchOptions) + } + + func didInitializeImplicitFlutterEngine(_ engineBridge: FlutterImplicitEngineBridge) { + GeneratedPluginRegistrant.register(with: engineBridge.pluginRegistry) + } +} diff --git a/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json b/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 000000000..d36b1fab2 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/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/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png b/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png new file mode 100644 index 000000000..dc9ada472 Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png b/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png new file mode 100644 index 000000000..7353c41ec Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png b/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png new file mode 100644 index 000000000..797d452e4 Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png b/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png new file mode 100644 index 000000000..6ed2d933e Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png b/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png new file mode 100644 index 000000000..4cd7b0099 Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png b/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png new file mode 100644 index 000000000..fe730945a Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png b/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png new file mode 100644 index 000000000..321773cd8 Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png b/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png new file mode 100644 index 000000000..797d452e4 Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png b/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png new file mode 100644 index 000000000..502f463a9 Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png b/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png new file mode 100644 index 000000000..0ec303439 Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png b/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png new file mode 100644 index 000000000..0ec303439 Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png b/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png new file mode 100644 index 000000000..e9f5fea27 Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png b/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png new file mode 100644 index 000000000..84ac32ae7 Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png b/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png new file mode 100644 index 000000000..8953cba09 Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png b/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png new file mode 100644 index 000000000..0467bf12a Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json b/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json new file mode 100644 index 000000000..0bedcf2fd --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/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/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png b/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png new file mode 100644 index 000000000..9da19eaca Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png b/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png new file mode 100644 index 000000000..9da19eaca Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png b/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png new file mode 100644 index 000000000..9da19eaca Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md b/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md new file mode 100644 index 000000000..89c2725b7 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/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/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner/Base.lproj/LaunchScreen.storyboard b/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner/Base.lproj/LaunchScreen.storyboard new file mode 100644 index 000000000..f2e259c7c --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner/Base.lproj/LaunchScreen.storyboard @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner/Base.lproj/Main.storyboard b/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner/Base.lproj/Main.storyboard new file mode 100644 index 000000000..f3c28516f --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner/Base.lproj/Main.storyboard @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner/Info.plist b/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner/Info.plist new file mode 100644 index 000000000..c97226dba --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner/Info.plist @@ -0,0 +1,70 @@ + + + + + CADisableMinimumFrameDurationOnPhone + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleDisplayName + Gemma Function Calling + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + functioncalling + CFBundlePackageType + APPL + CFBundleShortVersionString + $(FLUTTER_BUILD_NAME) + CFBundleSignature + ???? + CFBundleVersion + $(FLUTTER_BUILD_NUMBER) + LSRequiresIPhoneOS + + UIApplicationSceneManifest + + UIApplicationSupportsMultipleScenes + + UISceneConfigurations + + UIWindowSceneSessionRoleApplication + + + UISceneClassName + UIWindowScene + UISceneConfigurationName + flutter + UISceneDelegateClassName + $(PRODUCT_MODULE_NAME).SceneDelegate + UISceneStoryboardFile + Main + + + + + UIApplicationSupportsIndirectInputEvents + + UILaunchStoryboardName + LaunchScreen + UIMainStoryboardFile + Main + UISupportedInterfaceOrientations + + UIInterfaceOrientationPortrait + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + UISupportedInterfaceOrientations~ipad + + UIInterfaceOrientationPortrait + UIInterfaceOrientationPortraitUpsideDown + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + + diff --git a/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner/Runner-Bridging-Header.h b/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner/Runner-Bridging-Header.h new file mode 100644 index 000000000..308a2a560 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner/Runner-Bridging-Header.h @@ -0,0 +1 @@ +#import "GeneratedPluginRegistrant.h" diff --git a/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner/Runner.entitlements b/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner/Runner.entitlements new file mode 100644 index 000000000..cd461aae4 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner/Runner.entitlements @@ -0,0 +1,12 @@ + + + + + com.apple.developer.kernel.extended-virtual-addressing + + com.apple.developer.kernel.increased-memory-limit + + com.apple.developer.kernel.increased-debugging-memory-limit + + + diff --git a/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner/SceneDelegate.swift b/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner/SceneDelegate.swift new file mode 100644 index 000000000..b9ce8ea2b --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/Runner/SceneDelegate.swift @@ -0,0 +1,6 @@ +import Flutter +import UIKit + +class SceneDelegate: FlutterSceneDelegate { + +} diff --git a/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/RunnerTests/RunnerTests.swift b/codelabs/function-calling-flutter-gemma/step_03_the_loop/ios/RunnerTests/RunnerTests.swift new file mode 100644 index 000000000..86a7c3b1b --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/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/codelabs/function-calling-flutter-gemma/step_03_the_loop/lib/chat_page.dart b/codelabs/function-calling-flutter-gemma/step_03_the_loop/lib/chat_page.dart new file mode 100644 index 000000000..9e88b1142 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/lib/chat_page.dart @@ -0,0 +1,503 @@ +import 'dart:convert'; + +import 'package:flutter/material.dart'; +import 'package:flutter_gemma/flutter_gemma.dart'; + +import 'model.dart'; +import 'tools.dart'; + +/// What a line in the transcript is. +/// +/// A chat with tools has four kinds of turn, not two, and showing only the +/// first and last of them is how a tool-calling app becomes impossible to +/// debug: the answer is right or wrong and nothing on screen says which +/// function produced it, with which arguments. +enum _TurnKind { user, model, toolCall, toolResult } + +/// How many generations one message is allowed to cost. +/// +/// The loop stops when a turn comes back with no calls in it — which is a +/// promise about the model, not about the code, and a model that keeps asking +/// would otherwise run until the context window filled. Four is enough for a +/// question that chains two or three calls and small enough that a stuck model +/// is over in seconds. +/// +/// Below 1 is a `RangeError`, thrown on purpose: a cap of zero would answer +/// the message with nothing and close the stream, which looks exactly like a +/// model that had nothing to say. +const _maxToolTurns = 4; + +/// The same chat as Step 2, with the loop handed to the SDK. +/// +/// `generateChatResponseWithTools` is the loop from Step 2 written once, in +/// the package: generate, collect the calls, run them through the callback you +/// pass, feed each result back, generate again — until a turn has no calls in +/// it. What it adds is the three exits the hand-written version did not have: +/// a cancelled turn, a tool that throws, and a stream that errors mid-turn all +/// still answer every call that was committed to the history. +class ChatPage extends StatefulWidget { + const ChatPage({ + super.key, + required this.model, + required this.onModelRemoved, + }); + + final ModelChoice model; + + /// Lets the gate send the app back to the download screen. + final VoidCallback onModelRemoved; + + @override + State createState() => _ChatPageState(); +} + +class _ChatPageState extends State { + final _input = TextEditingController(); + final _turns = <_Turn>[]; + + InferenceModel? _inference; + InferenceChat? _chat; + bool _busy = false; + Object? _loadError; + + /// A one-line problem that is not worth losing the chat over. + String? _notice; + + /// Where the CURRENT generation is writing, and what it has written. + /// + /// One message can now produce several generations with tool calls between + /// them, so "the reply" is no longer "the last bubble": running a tool + /// appends two lines to the transcript and starts a fresh bubble underneath + /// them. Holding the index is what keeps the reply below the work it did. + final _reply = StringBuffer(); + int _replyAt = -1; + + @override + void initState() { + super.initState(); + _load(); + } + + Future _load() async { + try { + // maxTokens is the CONTEXT WINDOW — prompt + history + reply share it. + // It is NOT a reply-length cap; for that, pass maxOutputTokens below. + // A driven loop spends more of it than Step 2's single round did: every + // call and every tool response stays in the history for the rest of the + // conversation. + // maxTokens 1024 is what this checkpoint is built for; the example app + // uses the same, and it is the value this was measured at. + // + // This checkpoint is asked to run on the CPU, and the reason is the + // FILE, not the platform and not the model. The published artifact was + // converted before litetune 0.1.4 began setting `prefer_activation_type=fp32`, + // and without that key the GPU path answers every prompt with `` to + // the token limit — measured on Android and on macOS Metal alike, with no + // exception and no warning, a chat that looks alive and returns filler. + // + // Re-converted with a current litetune — which Step 4 does — the same + // weights score identically on GPU and run about 1.5x faster. So this is + // a workaround for one downloadable file, not a property of FunctionGemma. + final inference = await FlutterGemma.getActiveModel( + maxTokens: 1024, + preferredBackend: PreferredBackend.cpu, + ); + // Hold the runtime before opening a chat on it: `createChat` can throw, + // and a model this page never stored is a model `dispose` can never + // close. A page that is already gone holds nothing, so it closes it here. + if (!mounted) { + await inference.close(); + return; + } + setState(() => _inference = inference); + + // Unchanged from Step 2. The declarations and the switch are properties + // of the session; what changes below is only who drives the turns. + final chat = await inference.createChat( + modelType: widget.model.modelType, + tools: const [multiplyTool], + supportsFunctionCalls: true, + maxOutputTokens: 256, + ); + // The same guard, one call later and for the same reason: a chat this + // page never stored is a native session `dispose` can never close. + if (!mounted) { + await chat.close(); + return; + } + setState(() => _chat = chat); + } catch (error) { + // Loading is the likeliest thing to fail on a real device: a forgotten + // engine package, too little memory, a half-written model file. Show it + // instead of sitting on the progress bar forever. + if (mounted) setState(() => _loadError = error); + } + } + + void _retryLoad() { + setState(() => _loadError = null); + _load(); + } + + /// One message, however many generations it takes. + /// + /// Compare with Step 2: there is no second `generateChatResponseAsync` here, + /// no `addQueryChunk(Message.toolResponse(...))`, and no balancing of calls + /// the app declined to run. All three are inside the stream below. + Future _send() async { + final chat = _chat; + final text = _input.text.trim(); + if (chat == null || text.isEmpty || _busy) return; + + setState(() { + _turns + ..add(_Turn(text, kind: _TurnKind.user)) + // The reply starts empty and grows as chunks arrive. + ..add(const _Turn('', kind: _TurnKind.model)); + _replyAt = _turns.length - 1; + _reply.clear(); + _input.clear(); + _notice = null; + _busy = true; + }); + + var hitCap = false; + try { + // The staged user message is a PRECONDITION, exactly as it is for + // `generateChatResponseAsync` — the loop drives generation, it does not + // send your turn for you. + await chat.addQueryChunk(Message.text(text: text, isUser: true)); + + await for (final chunk in chat.generateChatResponseWithTools( + // Run the function. Returning the map is what feeds the model; the + // SDK wraps it in `Message.toolResponse` and stages it before the + // next generation. + onToolCall: _onToolCall, + maxToolTurns: _maxToolTurns, + // Called once, if the loop runs out of turns with calls still coming. + // Without it the reply is quietly empty or half-written and nothing + // says the cap is why. + onMaxToolTurns: () => hitCap = true, + )) { + switch (chunk) { + case TextResponse(:final token): + // Each TextResponse carries only the NEW text, not the whole reply + // so far — append, never replace. + _reply.write(token); + if (mounted) { + setState( + () => _turns[_replyAt] = _Turn( + _reply.toString(), + kind: _TurnKind.model, + ), + ); + } + case ThinkingResponse(): + // Discarded upstream unless the chat was opened with + // `isThinking: true` — `complete` does exactly that. + break; + case FunctionCallResponse() || ParallelFunctionCallResponse(): + // Never arrives here: the loop consumes calls itself and passes + // only text and thinking through. The branch keeps the switch + // exhaustive over the sealed `ModelResponse`, so a case added to + // the SDK fails to compile instead of being treated as silence. + break; + } + } + + if (hitCap && mounted) { + setState( + () => _notice = + 'The model was still asking for tools after $_maxToolTurns ' + 'turns, so the loop stopped. The answer above may be missing ' + 'or cut short.', + ); + } + } catch (error) { + // The half-written reply becomes the error, so the empty bubble never + // just sits there. The SDK has already answered every call it committed + // before rethrowing, so the chat is still usable for the next message. + if (mounted) { + setState(() { + _reply.write('⚠️ $error'); + _turns[_replyAt] = _Turn(_reply.toString(), kind: _TurnKind.model); + }); + } + } finally { + // `_busy` is what disables the composer, so clearing it belongs in + // `finally` — a failed generation must not lock the app. + if (mounted) { + setState(() { + // A last generation that produced no text — the cap was hit on a + // call-only turn — leaves an empty bubble at the bottom. + if (_reply.isEmpty && + _replyAt >= 0 && + _replyAt == _turns.length - 1) { + _turns.removeAt(_replyAt); + } + _replyAt = -1; + _busy = false; + }); + } + } + } + + /// Runs one call and shows it. The return value is what the model sees. + /// + /// This callback is the whole of the app's half of the loop. Everything + /// around it — collecting the calls, staging the responses, deciding whether + /// to generate again — moved into the SDK. + Future> _onToolCall(FunctionCallResponse call) async { + final result = _run(call); + if (mounted) { + setState(() { + // A call-only generation wrote no text, and an empty bubble above the + // call reads as a model that said nothing when in fact it asked. + if (_reply.isEmpty && _replyAt >= 0 && _replyAt == _turns.length - 1) { + _turns.removeAt(_replyAt); + } + _turns + ..add(_Turn(_describeCall(call), kind: _TurnKind.toolCall)) + ..add(_Turn(jsonEncode(result), kind: _TurnKind.toolResult)) + // The next generation writes underneath the work it was given, + // not above it. + ..add(const _Turn('', kind: _TurnKind.model)); + _replyAt = _turns.length - 1; + _reply.clear(); + }); + } + return result; + } + + /// Maps a call the model made onto the Dart that answers it. + /// + /// Keyed by name and with a real miss branch: the model writes the name, and + /// a model can write a name you never declared. Returning an error map keeps + /// the loop going — throwing here would end the turn, and the SDK would + /// answer the committed call with `{'error': …}` and rethrow. + Map _run(FunctionCallResponse call) => switch (call.name) { + 'multiply' => runMultiply(call.args), + _ => {'error': 'This app has no tool named "${call.name}".'}, + }; + + String _describeCall(FunctionCallResponse call) { + final args = call.args.entries + .map((e) => '${e.key}: ${e.value}') + .join(', '); + return '${call.name}($args)'; + } + + /// Frees the disk. Close the runtime first — the file is mapped while a + /// model is open, and deleting it underneath the engine is a crash waiting + /// to happen. + Future _removeModel() async { + try { + await _inference?.close(); + // Inside `setState`: dropping the chat has to repaint, or the screen + // keeps showing an enabled composer over a runtime that is gone. + if (mounted) { + setState(() { + _inference = null; + _chat = null; + }); + } + await FlutterGemma.uninstallModel(widget.model.fileName); + if (mounted) widget.onModelRemoved(); + } catch (error) { + // Deleting can fail too — a missing install record, a file the OS still + // holds. Show it the way a failed load is shown, and drop the chat with + // it: a `close()` that threw leaves `_chat` non-null, and "The model did + // not load." over a working composer is a lie. + if (mounted) { + setState(() { + _chat = null; + _loadError = error; + }); + } + } + } + + @override + void dispose() { + // Sessions and models hold native memory — always close them. `dispose` + // cannot await, so the future is dropped on purpose, and caught so a + // failing native teardown does not escape as an unhandled async error. + _inference?.close().catchError((Object _) {}); + _input.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final ready = _chat != null; + final error = _loadError; + + return Scaffold( + appBar: AppBar( + title: Text(widget.model.label), + bottom: PreferredSize( + preferredSize: const Size.fromHeight(20), + child: Padding( + padding: const EdgeInsets.only(bottom: 6), + child: Text( + '1 tool · ${multiplyTool.name} · up to $_maxToolTurns tool turns', + style: theme.textTheme.labelSmall, + ), + ), + ), + actions: [ + IconButton( + tooltip: 'Delete the downloaded model', + // Not while the model is still opening: deleting the file + // underneath an in-flight `getActiveModel()` is the crash the + // comment on `_removeModel` warns about. + onPressed: _busy || (!ready && error == null) ? null : _removeModel, + icon: const Icon(Icons.delete_outline), + ), + ], + ), + body: Column( + children: [ + if (error != null) + _LoadFailed(error: error, onRetry: _retryLoad) + else if (!ready) + const LinearProgressIndicator(), + Expanded( + child: ListView.builder( + padding: const EdgeInsets.all(16), + itemCount: _turns.length, + itemBuilder: (context, i) => _Bubble(turn: _turns[i]), + ), + ), + if (_notice case final notice?) + Padding( + padding: const EdgeInsets.fromLTRB(16, 0, 16, 8), + child: Text( + notice, + style: theme.textTheme.bodySmall?.copyWith( + color: theme.colorScheme.error, + ), + ), + ), + SafeArea( + child: Padding( + padding: const EdgeInsets.fromLTRB(12, 0, 12, 12), + child: Row( + children: [ + Expanded( + child: TextField( + controller: _input, + enabled: ready && !_busy, + onSubmitted: (_) => _send(), + decoration: InputDecoration( + hintText: ready + ? 'Try: 12 times 12, then that times 3' + : error != null + ? 'No model loaded' + : 'Loading the model…', + border: const OutlineInputBorder(), + ), + ), + ), + const SizedBox(width: 8), + IconButton.filled( + onPressed: ready && !_busy ? _send : null, + icon: const Icon(Icons.send), + ), + ], + ), + ), + ), + ], + ), + ); + } +} + +/// Shown in place of the loading bar when the model could not be opened. +class _LoadFailed extends StatelessWidget { + const _LoadFailed({required this.error, required this.onRetry}); + + final Object error; + final VoidCallback onRetry; + + @override + Widget build(BuildContext context) { + return Padding( + padding: const EdgeInsets.all(16), + child: Column( + children: [ + Text('The model did not load.\n$error', textAlign: TextAlign.center), + const SizedBox(height: 8), + FilledButton(onPressed: onRetry, child: const Text('Try again')), + ], + ), + ); + } +} + +class _Turn { + const _Turn(this.text, {required this.kind}); + + final String text; + final _TurnKind kind; +} + +/// One line of the transcript, drawn so the four kinds are told apart at a +/// glance. The two middle ones are the point of this screen. +class _Bubble extends StatelessWidget { + const _Bubble({required this.turn}); + + final _Turn turn; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final scheme = theme.colorScheme; + final (label, colour) = switch (turn.kind) { + _TurnKind.user => (null, scheme.primaryContainer), + _TurnKind.model => (null, scheme.surfaceContainerHighest), + _TurnKind.toolCall => ('the model asked for', scheme.tertiaryContainer), + _TurnKind.toolResult => ( + 'your function answered', + scheme.secondaryContainer, + ), + }; + final mono = + turn.kind == _TurnKind.toolCall || turn.kind == _TurnKind.toolResult; + + return Align( + alignment: turn.kind == _TurnKind.user + ? Alignment.centerRight + : Alignment.centerLeft, + child: Container( + margin: const EdgeInsets.symmetric(vertical: 4), + padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10), + constraints: const BoxConstraints(maxWidth: 520), + decoration: BoxDecoration( + color: colour, + borderRadius: BorderRadius.circular(12), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + if (label != null) ...[ + Text(label, style: theme.textTheme.labelSmall), + const SizedBox(height: 4), + ], + SelectableText( + turn.text, + style: mono + ? theme.textTheme.bodyMedium?.copyWith( + fontFamily: 'monospace', + ) + : null, + ), + ], + ), + ), + ); + } +} diff --git a/codelabs/function-calling-flutter-gemma/step_03_the_loop/lib/download_page.dart b/codelabs/function-calling-flutter-gemma/step_03_the_loop/lib/download_page.dart new file mode 100644 index 000000000..0e0ebf030 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/lib/download_page.dart @@ -0,0 +1,138 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_gemma/flutter_gemma.dart'; + +import 'model.dart'; + +/// Installs the model file, reporting progress as it goes. +/// +/// Nothing here knows about tools: `installModel` takes the model's identity +/// (what it is) and `fromNetwork` takes the source (where the bytes are). A +/// function-calling model installs exactly like a text one — tools are a +/// property of the SESSION you open later, not of the file you download. +class DownloadPage extends StatefulWidget { + const DownloadPage({ + super.key, + required this.model, + required this.onInstalled, + }); + + final ModelChoice model; + + /// Called once the model is installed, so the app can move on. + final VoidCallback onInstalled; + + @override + State createState() => _DownloadPageState(); +} + +class _DownloadPageState extends State { + int _percent = 0; + bool _downloading = false; + Object? _error; + + Future _download() async { + setState(() { + _downloading = true; + _error = null; + }); + + try { + await FlutterGemma.installModel( + // What the model IS — used to pick the right chat template. + modelType: widget.model.modelType, + // Which runtime reads it. `.litertlm` routes to LiteRtLmEngine; + // the default is `task` (MediaPipe), so this line is load-bearing. + fileType: ModelFileType.litertlm, + ).fromNetwork(widget.model.url).withProgress((percent) { + if (mounted) setState(() => _percent = percent); + }).install(); + + if (mounted) widget.onInstalled(); + } catch (error) { + if (mounted) setState(() => _error = error); + } finally { + if (mounted) setState(() => _downloading = false); + } + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + + return Scaffold( + appBar: AppBar(title: const Text('Get the model')), + body: Center( + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 420), + child: Padding( + padding: const EdgeInsets.all(24), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Text(widget.model.label, style: theme.textTheme.headlineSmall), + const SizedBox(height: 8), + Text( + '${widget.model.sizeLabel} — downloaded once, then it lives ' + 'on the device and runs with the network off.', + style: theme.textTheme.bodyMedium, + ), + const SizedBox(height: 24), + if (_downloading) ...[ + LinearProgressIndicator(value: _percent / 100), + const SizedBox(height: 8), + Text('$_percent%', textAlign: TextAlign.center), + ] else + FilledButton( + onPressed: _download, + child: const Text('Download model'), + ), + if (_error != null) ...[ + const SizedBox(height: 16), + _ErrorCard(error: _error!), + ], + ], + ), + ), + ), + ), + ); + } +} + +/// Says what failed, in the plugin's own words where it has any. +class _ErrorCard extends StatelessWidget { + const _ErrorCard({required this.error}); + + final Object error; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + // The plugin reports a failed download as a typed `DownloadException` + // wrapping a sealed `DownloadError`, so match on the type rather than + // sniffing the message for a status code. + final (title, body) = switch (error) { + DownloadException(:final error) => ( + 'Download failed', + error.toUserMessage(), + ), + _ => ('Download failed', '$error'), + }; + + return Card( + color: theme.colorScheme.errorContainer, + child: Padding( + padding: const EdgeInsets.all(16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(title, style: theme.textTheme.titleSmall), + const SizedBox(height: 8), + Text(body), + ], + ), + ), + ); + } +} diff --git a/codelabs/function-calling-flutter-gemma/step_03_the_loop/lib/main.dart b/codelabs/function-calling-flutter-gemma/step_03_the_loop/lib/main.dart new file mode 100644 index 000000000..8241664e4 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/lib/main.dart @@ -0,0 +1,173 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_gemma/flutter_gemma.dart'; +import 'package:flutter_gemma_litertlm/flutter_gemma_litertlm.dart'; + +import 'chat_page.dart'; +import 'download_page.dart'; +import 'model.dart'; + +/// The model this step runs: 284 MB, and function calling is what it is for. +const _model = Models.functionGemma; + +Future main() async { + WidgetsFlutterBinding.ensureInitialized(); + + // Engines are fully opt-in: the core package registers none by itself. + // Without LiteRtLmEngine here, the first model call throws a StateError + // that tells you to add an engine package. + // + // No `huggingFaceToken:` — the repository this codelab downloads from is + // ungated, so every `flutter run` is a plain `flutter run` with no + // `--dart-define`. + // + // Guarded, because every other failure in this app reaches the screen — the + // gate's error card, the chat's load error, the notice line — and this is the + // earliest one, so it is the one a learner meets first. Hot-restarting after + // adding a plugin throws `MissingPluginException` right here; unguarded, it + // never reaches `runApp` and the symptom is a blank window and a stack trace + // in a console nobody is looking at. + try { + await FlutterGemma.initialize(inferenceEngines: [LiteRtLmEngine()]); + } catch (error) { + runApp(_StartupFailed(error: error)); + return; + } + + runApp(const FunctionCallingApp()); +} + +/// Shown in place of the app when `FlutterGemma.initialize` throws, so a +/// failure before the first frame is a sentence instead of a blank window. +class _StartupFailed extends StatelessWidget { + const _StartupFailed({required this.error}); + + final Object error; + + @override + Widget build(BuildContext context) { + return MaterialApp( + title: 'Gemma Function Calling', + home: Scaffold( + body: Center( + child: Padding( + padding: const EdgeInsets.all(24), + child: Text( + 'flutter_gemma could not start.\n$error', + textAlign: TextAlign.center, + ), + ), + ), + ), + ); + } +} + +class FunctionCallingApp extends StatelessWidget { + const FunctionCallingApp({super.key}); + + @override + Widget build(BuildContext context) { + return MaterialApp( + title: 'Gemma Function Calling', + theme: ThemeData(colorSchemeSeed: Colors.indigo), + home: const ModelGate(model: _model), + ); + } +} + +/// Asks, on every cold start, whether the model is already installed. +/// +/// `install()` is idempotent, so the bytes are only ever fetched once. What a +/// drifted id costs you is this gate: it answers "no" forever, so the app +/// shows the download screen on every launch, the "download" there finishes +/// instantly, and you land straight back here. Delete the model with the chat's +/// delete button and relaunch to watch this branch flip back. +class ModelGate extends StatefulWidget { + const ModelGate({super.key, required this.model}); + + final ModelChoice model; + + @override + State createState() => _ModelGateState(); +} + +class _ModelGateState extends State { + late Future _installed = _check(); + + /// Installed is not the same as active. `getActiveModel` opens whichever + /// model was installed LAST, and this codelab's steps install two different + /// ones into a single application identity — so a run that finds the file + /// already here still has to say which model it means. `install()` is + /// idempotent: on a file already on disk it downloads nothing and just + /// records this model as the current one. + Future _check() async { + if (!await FlutterGemma.isModelInstalled(widget.model.fileName)) { + return false; + } + await FlutterGemma.installModel( + modelType: widget.model.modelType, + fileType: ModelFileType.litertlm, + ).fromNetwork(widget.model.url).install(); + return true; + } + + @override + Widget build(BuildContext context) { + return FutureBuilder( + future: _installed, + builder: (context, snapshot) { + if (snapshot.connectionState != ConnectionState.done) { + return const Scaffold( + body: Center(child: CircularProgressIndicator()), + ); + } + if (snapshot.hasError) { + // A FutureBuilder that ignores `hasError` renders the download + // screen as if nothing had gone wrong. Say what failed instead. + return _GateError( + error: snapshot.error!, + onRetry: () => setState(() => _installed = _check()), + ); + } + if (snapshot.data ?? false) { + return ChatPage( + model: widget.model, + onModelRemoved: () => setState(() => _installed = _check()), + ); + } + return DownloadPage( + model: widget.model, + onInstalled: () => setState(() => _installed = _check()), + ); + }, + ); + } +} + +/// Shown when the gate's own check fails, rather than falling through to the +/// download screen as if the answer had been "no". +class _GateError extends StatelessWidget { + const _GateError({required this.error, required this.onRetry}); + + final Object error; + final VoidCallback onRetry; + + @override + Widget build(BuildContext context) { + return Scaffold( + body: Center( + child: Padding( + padding: const EdgeInsets.all(24), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Text('$error', textAlign: TextAlign.center), + const SizedBox(height: 12), + FilledButton(onPressed: onRetry, child: const Text('Try again')), + ], + ), + ), + ), + ); + } +} diff --git a/codelabs/function-calling-flutter-gemma/step_03_the_loop/lib/model.dart b/codelabs/function-calling-flutter-gemma/step_03_the_loop/lib/model.dart new file mode 100644 index 000000000..2cefb1425 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/lib/model.dart @@ -0,0 +1,54 @@ +import 'package:flutter_gemma/flutter_gemma.dart'; + +/// One model this app knows how to install. +/// +/// [fileName] doubles as the model's id: `FlutterGemma.isModelInstalled` takes +/// the file name the model was installed under, not a display name. +class ModelChoice { + const ModelChoice({ + required this.label, + required this.url, + required this.fileName, + required this.modelType, + required this.sizeLabel, + }); + + final String label; + final String url; + final String fileName; + + /// Which family's function-call format the SDK should read and write. + /// + /// This is not decoration. `ModelType.functionGemma` selects + /// `FunctionGemmaCallFormat`, which renders the tool declarations into a + /// developer turn and parses `call:name{…}` back out + /// again. Name a different family and the SDK writes a prompt these weights + /// were never trained on and looks for a call in a syntax they never emit — + /// so every turn comes back as plain text and nothing says why. + final ModelType modelType; + + final String sizeLabel; +} + +/// The one model this step ships. +/// +/// The repository is ungated, so nothing here needs a Hugging Face token and +/// no run needs `--dart-define`. +abstract final class Models { + /// A 270M model whose whole job is function calling. + /// + /// 284 MB — small enough to download while you read this page, and small + /// enough that it does very little else: ask it a general question and the + /// answer will be thin. That is the trade this step is making on purpose. + /// Calling a function is a narrow skill, and a model specialised for it can + /// be a fraction of the size of one that also has to hold a conversation. + static const functionGemma = ModelChoice( + label: 'FunctionGemma 270M', + url: + 'https://huggingface.co/sasha-denisov/function-gemma-270M-it/' + 'resolve/main/functiongemma-270M-it.litertlm', + fileName: 'functiongemma-270M-it.litertlm', + modelType: ModelType.functionGemma, + sizeLabel: '284 MB', + ); +} diff --git a/codelabs/function-calling-flutter-gemma/step_03_the_loop/lib/tools.dart b/codelabs/function-calling-flutter-gemma/step_03_the_loop/lib/tools.dart new file mode 100644 index 000000000..c37060c2e --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/lib/tools.dart @@ -0,0 +1,71 @@ +import 'package:flutter_gemma/flutter_gemma.dart'; + +/// The one function this app lets the model ask for. +/// +/// A [Tool] is a DECLARATION and nothing else — a name, a description the +/// model reads, and a JSON Schema for the arguments. It holds no code and it +/// cannot run: the SDK renders this into the prompt and parses a call back +/// out, and running the call is the app's job. [runMultiply] below is the half +/// that actually computes something, and `chat_page.dart` is where the two are +/// wired together. +/// +/// Multiplication, because the answer is checkable. Ask a 270M model for +/// 1234 × 5678 and it will produce a confident number of about the right +/// length; ask it to call this instead and the number is exact, offline, and +/// you can verify it on a pocket calculator. A weather tool would demonstrate +/// the same mechanism and prove nothing about the answer. +const multiplyTool = Tool( + name: 'multiply', + // The model reads this. It is the only thing telling it WHEN to call — so + // "use this instead of working it out yourself" is instruction, not prose. + description: + 'Multiply two numbers and return the exact product. Use this for any ' + 'multiplication instead of working it out yourself.', + parameters: { + 'type': 'object', + 'properties': { + 'a': {'type': 'number', 'description': 'The first number.'}, + 'b': {'type': 'number', 'description': 'The second number.'}, + }, + 'required': ['a', 'b'], + }, +); + +/// Runs [multiplyTool] and returns the map the model will be shown. +/// +/// Everything this function returns becomes the model's only knowledge of what +/// happened, so the keys are part of the interface: `result` is what it will +/// read back to the user, and `error` is what it will apologise about. +Map runMultiply(Map args) { + final a = asNumber(args['a']); + final b = asNumber(args['b']); + if (a == null || b == null) { + // Returned, not thrown. A model wrote these arguments and a model can + // write nonsense; an error map is a turn it can read and correct on the + // next one, while an exception ends the conversation and takes the + // committed call with it. + return { + 'error': + 'multiply needs two numbers. Got a=${args['a']}, b=${args['b']}.', + }; + } + final product = a * b; + // `12 * 13` arriving as doubles comes back as `156.0`, and the model has to + // read that number out loud. Say 156. + return { + 'result': product is double && product == product.truncateToDouble() + ? product.toInt() + : product, + }; +} + +/// Arguments arrive as whatever JSON the model produced. +/// +/// It is trained to emit tool-call arguments as strings, so `"12"` is the +/// common case and `12` or `12.0` are the others. All three are the same +/// number and the app should not care which one it got. +num? asNumber(Object? value) => switch (value) { + final num n => n, + final String s => num.tryParse(s.trim()), + _ => null, +}; diff --git a/codelabs/function-calling-flutter-gemma/step_03_the_loop/linux/.gitignore b/codelabs/function-calling-flutter-gemma/step_03_the_loop/linux/.gitignore new file mode 100644 index 000000000..d3896c984 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/linux/.gitignore @@ -0,0 +1 @@ +flutter/ephemeral diff --git a/codelabs/function-calling-flutter-gemma/step_03_the_loop/linux/CMakeLists.txt b/codelabs/function-calling-flutter-gemma/step_03_the_loop/linux/CMakeLists.txt new file mode 100644 index 000000000..f21ac7bae --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/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 "functioncalling") +# The unique GTK application identifier for this application. See: +# https://wiki.gnome.org/HowDoI/ChooseApplicationID +set(APPLICATION_ID "dev.fluttergemma.functioncalling") + +# 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/codelabs/function-calling-flutter-gemma/step_03_the_loop/linux/flutter/CMakeLists.txt b/codelabs/function-calling-flutter-gemma/step_03_the_loop/linux/flutter/CMakeLists.txt new file mode 100644 index 000000000..d5bd01648 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/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/codelabs/function-calling-flutter-gemma/step_03_the_loop/linux/flutter/generated_plugin_registrant.cc b/codelabs/function-calling-flutter-gemma/step_03_the_loop/linux/flutter/generated_plugin_registrant.cc new file mode 100644 index 000000000..198e9645a --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/linux/flutter/generated_plugin_registrant.cc @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + +#include + +void fl_register_plugins(FlPluginRegistry* registry) { + g_autoptr(FlPluginRegistrar) flutter_gemma_registrar = + fl_plugin_registry_get_registrar_for_plugin(registry, "FlutterGemmaPlugin"); + flutter_gemma_plugin_register_with_registrar(flutter_gemma_registrar); +} diff --git a/codelabs/function-calling-flutter-gemma/step_03_the_loop/linux/flutter/generated_plugin_registrant.h b/codelabs/function-calling-flutter-gemma/step_03_the_loop/linux/flutter/generated_plugin_registrant.h new file mode 100644 index 000000000..e0f0a47bc --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/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/codelabs/function-calling-flutter-gemma/step_03_the_loop/linux/flutter/generated_plugins.cmake b/codelabs/function-calling-flutter-gemma/step_03_the_loop/linux/flutter/generated_plugins.cmake new file mode 100644 index 000000000..3b0705d0f --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/linux/flutter/generated_plugins.cmake @@ -0,0 +1,25 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST + flutter_gemma +) + +list(APPEND FLUTTER_FFI_PLUGIN_LIST + jni +) + +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/codelabs/function-calling-flutter-gemma/step_03_the_loop/linux/runner/CMakeLists.txt b/codelabs/function-calling-flutter-gemma/step_03_the_loop/linux/runner/CMakeLists.txt new file mode 100644 index 000000000..e97dabc70 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/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/codelabs/function-calling-flutter-gemma/step_03_the_loop/linux/runner/main.cc b/codelabs/function-calling-flutter-gemma/step_03_the_loop/linux/runner/main.cc new file mode 100644 index 000000000..e7c5c5437 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/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/codelabs/function-calling-flutter-gemma/step_03_the_loop/linux/runner/my_application.cc b/codelabs/function-calling-flutter-gemma/step_03_the_loop/linux/runner/my_application.cc new file mode 100644 index 000000000..917c019cf --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/linux/runner/my_application.cc @@ -0,0 +1,148 @@ +#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, "Gemma Function Calling"); + 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, "Gemma Function Calling"); + } + + 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/codelabs/function-calling-flutter-gemma/step_03_the_loop/linux/runner/my_application.h b/codelabs/function-calling-flutter-gemma/step_03_the_loop/linux/runner/my_application.h new file mode 100644 index 000000000..db16367a7 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/linux/runner/my_application.h @@ -0,0 +1,21 @@ +#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/codelabs/function-calling-flutter-gemma/step_03_the_loop/macos/.gitignore b/codelabs/function-calling-flutter-gemma/step_03_the_loop/macos/.gitignore new file mode 100644 index 000000000..746adbb6b --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/macos/.gitignore @@ -0,0 +1,7 @@ +# Flutter-related +**/Flutter/ephemeral/ +**/Pods/ + +# Xcode-related +**/dgph +**/xcuserdata/ diff --git a/codelabs/function-calling-flutter-gemma/step_03_the_loop/macos/Flutter/Flutter-Debug.xcconfig b/codelabs/function-calling-flutter-gemma/step_03_the_loop/macos/Flutter/Flutter-Debug.xcconfig new file mode 100644 index 000000000..4b81f9b2d --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/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/codelabs/function-calling-flutter-gemma/step_03_the_loop/macos/Flutter/Flutter-Release.xcconfig b/codelabs/function-calling-flutter-gemma/step_03_the_loop/macos/Flutter/Flutter-Release.xcconfig new file mode 100644 index 000000000..5caa9d157 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/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/codelabs/function-calling-flutter-gemma/step_03_the_loop/macos/Flutter/GeneratedPluginRegistrant.swift b/codelabs/function-calling-flutter-gemma/step_03_the_loop/macos/Flutter/GeneratedPluginRegistrant.swift new file mode 100644 index 000000000..0be86a9b4 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/macos/Flutter/GeneratedPluginRegistrant.swift @@ -0,0 +1,18 @@ +// +// Generated file. Do not edit. +// + +import FlutterMacOS +import Foundation + +import connectivity_plus +import flutter_gemma +import large_file_handler +import shared_preferences_foundation + +func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { + ConnectivityPlusPlugin.register(with: registry.registrar(forPlugin: "ConnectivityPlusPlugin")) + FlutterGemmaPlugin.register(with: registry.registrar(forPlugin: "FlutterGemmaPlugin")) + LargeFileHandlerPlugin.register(with: registry.registrar(forPlugin: "LargeFileHandlerPlugin")) + SharedPreferencesPlugin.register(with: registry.registrar(forPlugin: "SharedPreferencesPlugin")) +} diff --git a/codelabs/function-calling-flutter-gemma/step_03_the_loop/macos/Podfile b/codelabs/function-calling-flutter-gemma/step_03_the_loop/macos/Podfile new file mode 100644 index 000000000..32aafe8bf --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/macos/Podfile @@ -0,0 +1,98 @@ +platform :osx, '12.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', '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 + + # flutter_gemma: stage the upstream Apple companion dylibs into the built + # .app. `hook/build.dart` deliberately skips them from Native Assets on macOS + # (#247 — Google ships them without `-Wl,-headerpad_max_install_names`, so the + # JIT bundling path cannot rewrite their install_name), which leaves this + # build phase to stage them. + # + # The phase only LOCATES and RUNS a script; the staging logic itself lives in + # flutter_gemma_litertlm and is delivered next to the dylibs it stages. That + # is deliberate: this block is frozen into your Xcode project, and a copy of + # the logic frozen there cannot be fixed by upgrading the package. + installer.aggregate_targets.each do |aggregate_target| + aggregate_target.user_targets.each do |user_target| + phase_name = '[flutter_gemma] Setup LiteRT-LM macOS' + + # Only the app target embeds the Frameworks/ this phase patches. + # RunnerTests inherits Runner's framework search paths and has no + # Contents/Frameworks of its own — having the phase there creates a + # cross-target dependency on Runner's framework output that Xcode reports + # as "Cycle inside Flutter Assemble" (#300). Remove any stale copy from + # non-app targets and skip them. + unless user_target.name == 'Runner' + user_target.build_phases + .select { |p| p.respond_to?(:name) && p.name == phase_name } + .each { |p| user_target.build_phases.delete(p) } + next + end + + existing = user_target.shell_script_build_phases.find { |p| p.name == phase_name } + phase = existing || user_target.new_shell_script_build_phase(phase_name) + # The embedded LiteRtLm binary is an INPUT so the phase re-runs whenever + # Flutter's always-out-of-date `embed` phase re-copies the raw, unpatched + # binary over the patched one. Without it Xcode caches the phase after the + # first build and the second incremental build ships an unpatched + # LiteRtLm that fails dlopen at runtime (#368). + phase.input_paths = [ + '$(BUILT_PRODUCTS_DIR)/$(PRODUCT_NAME).app/Contents/Frameworks/LiteRtLm.framework/Versions/A/LiteRtLm', + ] + # A declared output lets Xcode order the phase in its dependency graph + # instead of treating it as "runs every build with no outputs" — the other + # half of the cycle warning (#300). The script touches this file. + phase.output_paths = ['$(DERIVED_FILE_DIR)/flutter_gemma_litertlm_macos.stamp'] + phase.shell_script = <<~SHELL + set -e + STAGER="${HOME}/Library/Caches/flutter_gemma/native/macos_arm64/stage_macos_companions.sh" + if [ ! -f "${STAGER}" ]; then + echo "[flutter_gemma] ERROR: ${STAGER} not found." >&2 + echo " flutter_gemma_litertlm 1.6.2+ installs it there from its build hook." >&2 + echo " Upgrade the package, then: flutter clean && flutter pub get" >&2 + exit 1 + fi + sh "${STAGER}" "${BUILT_PRODUCTS_DIR}/${PRODUCT_NAME}.app/Contents/Frameworks" + mkdir -p "$(dirname "${SCRIPT_OUTPUT_FILE_0}")" + touch "${SCRIPT_OUTPUT_FILE_0}" + SHELL + end + end +end diff --git a/codelabs/function-calling-flutter-gemma/step_03_the_loop/macos/Runner.xcodeproj/project.pbxproj b/codelabs/function-calling-flutter-gemma/step_03_the_loop/macos/Runner.xcodeproj/project.pbxproj new file mode 100644 index 000000000..8c78df2ee --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/macos/Runner.xcodeproj/project.pbxproj @@ -0,0 +1,729 @@ +// !$*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 */; }; + 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */ = {isa = PBXBuildFile; productRef = 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */; }; +/* 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 /* Gemma Function Calling.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "Gemma Function Calling.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 = ""; }; + 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */ = {isa = PBXFileReference; lastKnownFileType = wrapper; name = FlutterGeneratedPluginSwiftPackage; path = ephemeral/Packages/FlutterGeneratedPluginSwiftPackage; 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 = ( + 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */, + ); + 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 /* Gemma Function Calling.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 = ( + 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */, + 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; + packageProductDependencies = ( + 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */, + ); + productName = Runner; + productReference = 33CC10ED2044A3C60003C045 /* Gemma Function Calling.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; + packageReferences = ( + 781AD8BC2B33823900A9FFBB /* XCLocalSwiftPackageReference "Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage" */, + ); + 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 = dev.fluttergemma.functioncalling.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/$(PRODUCT_NAME).app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/$(PRODUCT_NAME)"; + }; + 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 = dev.fluttergemma.functioncalling.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/$(PRODUCT_NAME).app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/$(PRODUCT_NAME)"; + }; + 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 = dev.fluttergemma.functioncalling.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/$(PRODUCT_NAME).app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/$(PRODUCT_NAME)"; + }; + 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 = 12.0; + 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 = 12.0; + 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 = 12.0; + 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 */ + +/* Begin XCLocalSwiftPackageReference section */ + 781AD8BC2B33823900A9FFBB /* XCLocalSwiftPackageReference "Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage" */ = { + isa = XCLocalSwiftPackageReference; + relativePath = Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage; + }; +/* End XCLocalSwiftPackageReference section */ + +/* Begin XCSwiftPackageProductDependency section */ + 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */ = { + isa = XCSwiftPackageProductDependency; + productName = FlutterGeneratedPluginSwiftPackage; + }; +/* End XCSwiftPackageProductDependency section */ + }; + rootObject = 33CC10E52044A3C60003C045 /* Project object */; +} diff --git a/codelabs/function-calling-flutter-gemma/step_03_the_loop/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/codelabs/function-calling-flutter-gemma/step_03_the_loop/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 000000000..18d981003 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/codelabs/function-calling-flutter-gemma/step_03_the_loop/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/codelabs/function-calling-flutter-gemma/step_03_the_loop/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme new file mode 100644 index 000000000..822174206 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/codelabs/function-calling-flutter-gemma/step_03_the_loop/macos/Runner.xcworkspace/contents.xcworkspacedata b/codelabs/function-calling-flutter-gemma/step_03_the_loop/macos/Runner.xcworkspace/contents.xcworkspacedata new file mode 100644 index 000000000..21a3cc14c --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/macos/Runner.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,10 @@ + + + + + + + diff --git a/codelabs/function-calling-flutter-gemma/step_03_the_loop/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/codelabs/function-calling-flutter-gemma/step_03_the_loop/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 000000000..18d981003 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/codelabs/function-calling-flutter-gemma/step_03_the_loop/macos/Runner/AppDelegate.swift b/codelabs/function-calling-flutter-gemma/step_03_the_loop/macos/Runner/AppDelegate.swift new file mode 100644 index 000000000..b3c176141 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/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/codelabs/function-calling-flutter-gemma/step_03_the_loop/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json b/codelabs/function-calling-flutter-gemma/step_03_the_loop/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 000000000..a2ec33f19 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/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/codelabs/function-calling-flutter-gemma/step_03_the_loop/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png b/codelabs/function-calling-flutter-gemma/step_03_the_loop/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png new file mode 100644 index 000000000..82b6f9d9a Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_03_the_loop/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_03_the_loop/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png b/codelabs/function-calling-flutter-gemma/step_03_the_loop/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png new file mode 100644 index 000000000..13b35eba5 Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_03_the_loop/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_03_the_loop/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png b/codelabs/function-calling-flutter-gemma/step_03_the_loop/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png new file mode 100644 index 000000000..0a3f5fa40 Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_03_the_loop/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_03_the_loop/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png b/codelabs/function-calling-flutter-gemma/step_03_the_loop/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png new file mode 100644 index 000000000..bdb57226d Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_03_the_loop/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_03_the_loop/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png b/codelabs/function-calling-flutter-gemma/step_03_the_loop/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png new file mode 100644 index 000000000..f083318e0 Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_03_the_loop/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_03_the_loop/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png b/codelabs/function-calling-flutter-gemma/step_03_the_loop/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png new file mode 100644 index 000000000..326c0e72c Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_03_the_loop/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_03_the_loop/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png b/codelabs/function-calling-flutter-gemma/step_03_the_loop/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png new file mode 100644 index 000000000..2f1632cfd Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_03_the_loop/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_03_the_loop/macos/Runner/Base.lproj/MainMenu.xib b/codelabs/function-calling-flutter-gemma/step_03_the_loop/macos/Runner/Base.lproj/MainMenu.xib new file mode 100644 index 000000000..80e867a4e --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/macos/Runner/Base.lproj/MainMenu.xib @@ -0,0 +1,343 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/codelabs/function-calling-flutter-gemma/step_03_the_loop/macos/Runner/Configs/AppInfo.xcconfig b/codelabs/function-calling-flutter-gemma/step_03_the_loop/macos/Runner/Configs/AppInfo.xcconfig new file mode 100644 index 000000000..0fcdf0410 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/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 = Gemma Function Calling + +// The application's bundle identifier +PRODUCT_BUNDLE_IDENTIFIER = dev.fluttergemma.functioncalling + +// The copyright displayed in application information +PRODUCT_COPYRIGHT = Copyright © 2026 dev.fluttergemma. All rights reserved. diff --git a/codelabs/function-calling-flutter-gemma/step_03_the_loop/macos/Runner/Configs/Debug.xcconfig b/codelabs/function-calling-flutter-gemma/step_03_the_loop/macos/Runner/Configs/Debug.xcconfig new file mode 100644 index 000000000..36b0fd946 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/macos/Runner/Configs/Debug.xcconfig @@ -0,0 +1,2 @@ +#include "../../Flutter/Flutter-Debug.xcconfig" +#include "Warnings.xcconfig" diff --git a/codelabs/function-calling-flutter-gemma/step_03_the_loop/macos/Runner/Configs/Release.xcconfig b/codelabs/function-calling-flutter-gemma/step_03_the_loop/macos/Runner/Configs/Release.xcconfig new file mode 100644 index 000000000..dff4f4956 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/macos/Runner/Configs/Release.xcconfig @@ -0,0 +1,2 @@ +#include "../../Flutter/Flutter-Release.xcconfig" +#include "Warnings.xcconfig" diff --git a/codelabs/function-calling-flutter-gemma/step_03_the_loop/macos/Runner/Configs/Warnings.xcconfig b/codelabs/function-calling-flutter-gemma/step_03_the_loop/macos/Runner/Configs/Warnings.xcconfig new file mode 100644 index 000000000..42bcbf478 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/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/codelabs/function-calling-flutter-gemma/step_03_the_loop/macos/Runner/DebugProfile.entitlements b/codelabs/function-calling-flutter-gemma/step_03_the_loop/macos/Runner/DebugProfile.entitlements new file mode 100644 index 000000000..8eb23d1c4 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/macos/Runner/DebugProfile.entitlements @@ -0,0 +1,16 @@ + + + + + com.apple.security.app-sandbox + + com.apple.security.cs.allow-jit + + com.apple.security.cs.disable-library-validation + + com.apple.security.network.client + + com.apple.security.network.server + + + diff --git a/codelabs/function-calling-flutter-gemma/step_03_the_loop/macos/Runner/Info.plist b/codelabs/function-calling-flutter-gemma/step_03_the_loop/macos/Runner/Info.plist new file mode 100644 index 000000000..4789daa6a --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/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/codelabs/function-calling-flutter-gemma/step_03_the_loop/macos/Runner/MainFlutterWindow.swift b/codelabs/function-calling-flutter-gemma/step_03_the_loop/macos/Runner/MainFlutterWindow.swift new file mode 100644 index 000000000..3cc05eb23 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/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/codelabs/function-calling-flutter-gemma/step_03_the_loop/macos/Runner/Release.entitlements b/codelabs/function-calling-flutter-gemma/step_03_the_loop/macos/Runner/Release.entitlements new file mode 100644 index 000000000..d7c971d31 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/macos/Runner/Release.entitlements @@ -0,0 +1,12 @@ + + + + + com.apple.security.app-sandbox + + com.apple.security.cs.disable-library-validation + + com.apple.security.network.client + + + diff --git a/codelabs/function-calling-flutter-gemma/step_03_the_loop/macos/RunnerTests/RunnerTests.swift b/codelabs/function-calling-flutter-gemma/step_03_the_loop/macos/RunnerTests/RunnerTests.swift new file mode 100644 index 000000000..61f3bd1fc --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/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/codelabs/function-calling-flutter-gemma/step_03_the_loop/pubspec.yaml b/codelabs/function-calling-flutter-gemma/step_03_the_loop/pubspec.yaml new file mode 100644 index 000000000..324dd18bb --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/pubspec.yaml @@ -0,0 +1,97 @@ +name: gemma_quickstart +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.12.0 + +# 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 + + # The following adds the Cupertino Icons font to your application. + # Use with the CupertinoIcons class for iOS style icons. + cupertino_icons: ^1.0.8 + + # The engine-agnostic core: registry, install/runtime API, chat. + flutter_gemma: ^1.7.1 + # The .litertlm inference engine. Engines are opt-in — core + # registers none, so this package must be added explicitly. + flutter_gemma_litertlm: ^1.6.2 + +dev_dependencies: + flutter_test: + sdk: flutter + integration_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: ^6.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/codelabs/function-calling-flutter-gemma/step_03_the_loop/test/widget_test.dart b/codelabs/function-calling-flutter-gemma/step_03_the_loop/test/widget_test.dart new file mode 100644 index 000000000..5ef21261c --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/test/widget_test.dart @@ -0,0 +1,68 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:gemma_quickstart/download_page.dart'; +import 'package:gemma_quickstart/model.dart'; +import 'package:gemma_quickstart/tools.dart'; + +void main() { + // `isModelInstalled` is keyed by file name. `install()` skips bytes it + // already has, so a name that drifts from its URL does not re-download — it + // strands the app on a download screen the gate is never satisfied by. + test('the model id matches the last segment of its URL', () { + const model = Models.functionGemma; + expect(model.fileName, model.url.split('/').last, reason: model.label); + }); + + // The declaration is the model's only description of the function, so its + // shape is part of the app's behaviour and not a comment. A renamed + // parameter here is a call the app cannot answer. + test('the tool declares the two arguments the runner reads', () { + expect(multiplyTool.name, 'multiply'); + final properties = + multiplyTool.parameters['properties'] as Map; + expect(properties.keys, containsAll(['a', 'b'])); + expect(multiplyTool.parameters['required'], ['a', 'b']); + }); + + group('runMultiply answers whatever the model wrote', () { + // The model is trained to emit arguments as strings, so this is the + // ordinary case, not the exotic one. + test('strings', () { + expect(runMultiply({'a': '1234', 'b': '5678'}), {'result': 7006652}); + }); + + test('numbers', () { + expect(runMultiply({'a': 12, 'b': 13}), {'result': 156}); + }); + + // An integer product that arrives as doubles must not be read back to the + // user as "156.0". + test('doubles that are whole numbers come back whole', () { + expect(runMultiply({'a': 12.0, 'b': 13.0}), {'result': 156}); + }); + + test('a genuine fraction stays one', () { + expect(runMultiply({'a': 0.5, 'b': 3}), {'result': 1.5}); + }); + + // Returned, not thrown: the model has to be able to read this and try + // again, and an exception would end the turn instead. + test('nonsense is an error map, not an exception', () { + final answer = runMultiply({'a': 'twelve', 'b': 13}); + expect(answer.containsKey('error'), isTrue); + expect(answer.containsKey('result'), isFalse); + }); + }); + + testWidgets('the download screen offers the model before any plugin call', ( + tester, + ) async { + await tester.pumpWidget( + MaterialApp( + home: DownloadPage(model: Models.functionGemma, onInstalled: () {}), + ), + ); + expect(find.text('FunctionGemma 270M'), findsOneWidget); + expect(find.text('Download model'), findsOneWidget); + }); +} diff --git a/codelabs/function-calling-flutter-gemma/step_03_the_loop/web/favicon.png b/codelabs/function-calling-flutter-gemma/step_03_the_loop/web/favicon.png new file mode 100644 index 000000000..8aaa46ac1 Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_03_the_loop/web/favicon.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_03_the_loop/web/icons/Icon-192.png b/codelabs/function-calling-flutter-gemma/step_03_the_loop/web/icons/Icon-192.png new file mode 100644 index 000000000..b749bfef0 Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_03_the_loop/web/icons/Icon-192.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_03_the_loop/web/icons/Icon-512.png b/codelabs/function-calling-flutter-gemma/step_03_the_loop/web/icons/Icon-512.png new file mode 100644 index 000000000..88cfd48df Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_03_the_loop/web/icons/Icon-512.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_03_the_loop/web/icons/Icon-maskable-192.png b/codelabs/function-calling-flutter-gemma/step_03_the_loop/web/icons/Icon-maskable-192.png new file mode 100644 index 000000000..eb9b4d76e Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_03_the_loop/web/icons/Icon-maskable-192.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_03_the_loop/web/icons/Icon-maskable-512.png b/codelabs/function-calling-flutter-gemma/step_03_the_loop/web/icons/Icon-maskable-512.png new file mode 100644 index 000000000..d69c56691 Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_03_the_loop/web/icons/Icon-maskable-512.png differ diff --git a/codelabs/function-calling-flutter-gemma/step_03_the_loop/web/index.html b/codelabs/function-calling-flutter-gemma/step_03_the_loop/web/index.html new file mode 100644 index 000000000..4dc25043a --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/web/index.html @@ -0,0 +1,58 @@ + + + + + + + + + + + + + + + + + + + + Gemma Function Calling + + + + + + + + + + diff --git a/codelabs/function-calling-flutter-gemma/step_03_the_loop/web/manifest.json b/codelabs/function-calling-flutter-gemma/step_03_the_loop/web/manifest.json new file mode 100644 index 000000000..747e60366 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/web/manifest.json @@ -0,0 +1,35 @@ +{ + "name": "Gemma Function Calling", + "short_name": "Gemma Function Calling", + "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/codelabs/function-calling-flutter-gemma/step_03_the_loop/windows/.gitignore b/codelabs/function-calling-flutter-gemma/step_03_the_loop/windows/.gitignore new file mode 100644 index 000000000..d492d0d98 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/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/codelabs/function-calling-flutter-gemma/step_03_the_loop/windows/CMakeLists.txt b/codelabs/function-calling-flutter-gemma/step_03_the_loop/windows/CMakeLists.txt new file mode 100644 index 000000000..ed760319f --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/windows/CMakeLists.txt @@ -0,0 +1,108 @@ +# Project-level configuration. +cmake_minimum_required(VERSION 3.14) +project(functioncalling 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 "functioncalling") + +# 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/codelabs/function-calling-flutter-gemma/step_03_the_loop/windows/flutter/CMakeLists.txt b/codelabs/function-calling-flutter-gemma/step_03_the_loop/windows/flutter/CMakeLists.txt new file mode 100644 index 000000000..903f4899d --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/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/codelabs/function-calling-flutter-gemma/step_03_the_loop/windows/flutter/generated_plugin_registrant.cc b/codelabs/function-calling-flutter-gemma/step_03_the_loop/windows/flutter/generated_plugin_registrant.cc new file mode 100644 index 000000000..38c2332a8 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/windows/flutter/generated_plugin_registrant.cc @@ -0,0 +1,17 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + +#include +#include + +void RegisterPlugins(flutter::PluginRegistry* registry) { + ConnectivityPlusWindowsPluginRegisterWithRegistrar( + registry->GetRegistrarForPlugin("ConnectivityPlusWindowsPlugin")); + FlutterGemmaPluginRegisterWithRegistrar( + registry->GetRegistrarForPlugin("FlutterGemmaPlugin")); +} diff --git a/codelabs/function-calling-flutter-gemma/step_03_the_loop/windows/flutter/generated_plugin_registrant.h b/codelabs/function-calling-flutter-gemma/step_03_the_loop/windows/flutter/generated_plugin_registrant.h new file mode 100644 index 000000000..dc139d85a --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/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/codelabs/function-calling-flutter-gemma/step_03_the_loop/windows/flutter/generated_plugins.cmake b/codelabs/function-calling-flutter-gemma/step_03_the_loop/windows/flutter/generated_plugins.cmake new file mode 100644 index 000000000..8dcbac209 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/windows/flutter/generated_plugins.cmake @@ -0,0 +1,26 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST + connectivity_plus + flutter_gemma +) + +list(APPEND FLUTTER_FFI_PLUGIN_LIST + jni +) + +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/codelabs/function-calling-flutter-gemma/step_03_the_loop/windows/runner/CMakeLists.txt b/codelabs/function-calling-flutter-gemma/step_03_the_loop/windows/runner/CMakeLists.txt new file mode 100644 index 000000000..394917c05 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/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/codelabs/function-calling-flutter-gemma/step_03_the_loop/windows/runner/Runner.rc b/codelabs/function-calling-flutter-gemma/step_03_the_loop/windows/runner/Runner.rc new file mode 100644 index 000000000..967d1c9d1 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/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", "dev.fluttergemma" "\0" + VALUE "FileDescription", "Gemma Function Calling" "\0" + VALUE "FileVersion", VERSION_AS_STRING "\0" + VALUE "InternalName", "functioncalling" "\0" + VALUE "LegalCopyright", "Copyright (C) 2026 dev.fluttergemma. All rights reserved." "\0" + VALUE "OriginalFilename", "functioncalling.exe" "\0" + VALUE "ProductName", "Gemma Function Calling" "\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/codelabs/function-calling-flutter-gemma/step_03_the_loop/windows/runner/flutter_window.cpp b/codelabs/function-calling-flutter-gemma/step_03_the_loop/windows/runner/flutter_window.cpp new file mode 100644 index 000000000..955ee3038 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/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/codelabs/function-calling-flutter-gemma/step_03_the_loop/windows/runner/flutter_window.h b/codelabs/function-calling-flutter-gemma/step_03_the_loop/windows/runner/flutter_window.h new file mode 100644 index 000000000..6da0652f0 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/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/codelabs/function-calling-flutter-gemma/step_03_the_loop/windows/runner/main.cpp b/codelabs/function-calling-flutter-gemma/step_03_the_loop/windows/runner/main.cpp new file mode 100644 index 000000000..38dad4a50 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/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"Gemma Function Calling", 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/codelabs/function-calling-flutter-gemma/step_03_the_loop/windows/runner/resource.h b/codelabs/function-calling-flutter-gemma/step_03_the_loop/windows/runner/resource.h new file mode 100644 index 000000000..66a65d1e4 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/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/codelabs/function-calling-flutter-gemma/step_03_the_loop/windows/runner/resources/app_icon.ico b/codelabs/function-calling-flutter-gemma/step_03_the_loop/windows/runner/resources/app_icon.ico new file mode 100644 index 000000000..c04e20caf Binary files /dev/null and b/codelabs/function-calling-flutter-gemma/step_03_the_loop/windows/runner/resources/app_icon.ico differ diff --git a/codelabs/function-calling-flutter-gemma/step_03_the_loop/windows/runner/runner.exe.manifest b/codelabs/function-calling-flutter-gemma/step_03_the_loop/windows/runner/runner.exe.manifest new file mode 100644 index 000000000..153653e8d --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/windows/runner/runner.exe.manifest @@ -0,0 +1,14 @@ + + + + + PerMonitorV2 + + + + + + + + + diff --git a/codelabs/function-calling-flutter-gemma/step_03_the_loop/windows/runner/utils.cpp b/codelabs/function-calling-flutter-gemma/step_03_the_loop/windows/runner/utils.cpp new file mode 100644 index 000000000..3cb714665 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/windows/runner/utils.cpp @@ -0,0 +1,69 @@ +#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(); + } + // First, find the length of the string with a safe upper bound (CWE-126). + // UNICODE_STRING_MAX_CHARS (32767) is the maximum length of a UNICODE_STRING. + int input_length = static_cast(wcsnlen(utf16_string, UNICODE_STRING_MAX_CHARS)); + // Now use that bounded length to determine the required buffer size. + // When an explicit length is passed, WideCharToMultiByte does not include + // the null terminator in its returned size. + int target_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + input_length, nullptr, 0, nullptr, nullptr); + std::string utf8_string; + if (target_length == 0 || static_cast(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/codelabs/function-calling-flutter-gemma/step_03_the_loop/windows/runner/utils.h b/codelabs/function-calling-flutter-gemma/step_03_the_loop/windows/runner/utils.h new file mode 100644 index 000000000..3879d5475 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/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/codelabs/function-calling-flutter-gemma/step_03_the_loop/windows/runner/win32_window.cpp b/codelabs/function-calling-flutter-gemma/step_03_the_loop/windows/runner/win32_window.cpp new file mode 100644 index 000000000..60608d0fe --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/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/codelabs/function-calling-flutter-gemma/step_03_the_loop/windows/runner/win32_window.h b/codelabs/function-calling-flutter-gemma/step_03_the_loop/windows/runner/win32_window.h new file mode 100644 index 000000000..e901dde68 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_03_the_loop/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/codelabs/function-calling-flutter-gemma/step_04_finetune/README.md b/codelabs/function-calling-flutter-gemma/step_04_finetune/README.md new file mode 100644 index 000000000..4007eb778 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_04_finetune/README.md @@ -0,0 +1,103 @@ +# Step 4 — fine-tune the model on these tools + +Not a Flutter app. This directory holds the two inputs a +[litetune](https://github.com/DenisovAV/litetune) run needs, for the three +tools the rest of this codelab declares: + +```text +tools.json the three declarations, the same ones lib/tools.dart holds +raw.jsonl 72 prompt -> tool-call rows to train and score on +``` + +`tool/check_codelabs.sh` discovers step apps by their `pubspec.yaml`. There is +none here on purpose, so this directory is not analyzed, tested or built — it +is data and commands. + +## What you need + +**Access to the base model, requested before you start.** Three of the five +commands below name `google/functiongemma-270m-it`, and that repository is +gated with **manual** approval — an anonymous fetch of its `config.json` +returns `401`, and a person grants access rather than a checkbox, so it can +take hours or days. Request it on +[the model page](https://huggingface.co/google/functiongemma-270m-it), then +`hf auth login` (or export `HF_TOKEN`) once it is granted. Without it command 1 +fails on the tokenizer download and you never reach command 2. Nothing else in +this codelab needs a token: the `.litertlm` the app downloads comes from the +ungated `sasha-denisov/function-gemma-270M-it`. + +`pip install litetune` — **Linux or macOS**, Python 3.10–3.12. Python 3.13 +runs `prepare`, `tune` and `bundle` but not `convert` or `verify`, because the +export toolchain pins `numpy==2.0.2` and that stops publishing wheels after +3.12. Windows is untried. On Linux also `sudo apt-get install -y libvulkan1`, +or every invocation — `--help` included — dies in under a second. + +It runs on CPU, which is workable at 270M. The stage environments are cached +and they are large: `convert` pulls ~1.6 GB, `tune` 588 MB. `litetune env` +shows what is on disk and `litetune env --clean` removes it. + +This is alpha software, and its alpha is stated as *measured end to end on +`google/functiongemma-270m-it` and function calling* — which is exactly the +model and the task this codelab is on. The other scorer and the other base +models it supports are outside what has been measured. + +**You can skip this step.** The app in `complete/` works on the stock +FunctionGemma and on Gemma 4 without any of it. + +## The five commands + +Run them from this directory. Each is separate because each fails differently. + +```bash +# 1. Split, and reject rows that cannot be scored. Seconds. +litetune prepare --data raw.jsonl --output-dir data --context-length 1024 \ + --tokenizer google/functiongemma-270m-it + +# 2. Fine-tune. CPU is fine at this size. +litetune tune --model google/functiongemma-270m-it --data data/train.jsonl \ + --output-dir tuned --prompt-mode prerendered --method lora + +# 3. Convert, sweeping recipes rather than trusting a default. +litetune convert --model tuned/model --output-dir artifacts \ + --recipe dynamic_wi8_afp32 --recipe weight_only_wi8_afp32 + +# 4. Measure what the conversion cost, against the float twin. +# `convert` names the artifact; look the filename up rather than build it. +litetune verify --model artifacts/weight_only_wi8_afp32/.litertlm \ + --reference tuned/model --data data/heldout.jsonl \ + --json > manifest.json + +# 5. Package the artifact with what was measured about it. +litetune bundle --output-dir bundle \ + --model artifacts/weight_only_wi8_afp32/.litertlm \ + --declarations tools.json --prompt-mode prerendered \ + --base-model google/functiongemma-270m-it \ + --base-model-revision \ + --adapter tuned/adapter \ + --train-metrics tuned/metrics.json \ + --verify-manifest manifest.json +``` + +`--prompt-mode prerendered` because that is what this app does: `InferenceChat` +renders the declarations into the prompt itself for `ModelType.functionGemma`. +The value must be the **same** in `tune` and `bundle`; the wrong one produces a +fluent wrong answer rather than an error. + +`--recipe` has no default, and litetune's own line for why is worth keeping: +*"A sweep of one is not a comparison."* + +## Then open it in the app + +Command 3 above — not the codelab's Step 3 — already gives you a `.litertlm` +per recipe under `artifacts//`. +Run `complete/`, choose **Open a .litertlm from disk**, and paste the absolute +path. Nothing in `lib/` changes — it is a `.litertlm`, and the app opens it the +way it opens the two it downloads. + +## About these 72 rows + +They are enough to run all five commands end to end and get a file out. They +are not enough to move a quality number: litetune's own published figures come +from thousands of examples, and half of these are held out for scoring. Treat +the run as a rehearsal of the pipeline, and bring your own data when you want +a result. diff --git a/codelabs/function-calling-flutter-gemma/step_04_finetune/raw.jsonl b/codelabs/function-calling-flutter-gemma/step_04_finetune/raw.jsonl new file mode 100644 index 000000000..bde49abda --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_04_finetune/raw.jsonl @@ -0,0 +1,72 @@ +{"prompt": "tell me about this device", "target": {"name": "get_device_info", "args": {}}} +{"prompt": "check the clock for me", "target": {"name": "get_current_time", "args": {}}} +{"prompt": "tell me the current time", "target": {"name": "get_current_time", "args": {}}} +{"prompt": "report the platform", "target": {"name": "get_device_info", "args": {}}} +{"prompt": "what time is it on this device?", "target": {"name": "get_current_time", "args": {}}} +{"prompt": "work out 777 x 7 for me", "target": {"name": "multiply", "args": {"a": "777", "b": "7"}}} +{"prompt": "what is 12 times 13?", "target": {"name": "multiply", "args": {"a": "12", "b": "13"}}} +{"prompt": "128 multiplied by 256 is what?", "target": {"name": "multiply", "args": {"a": "128", "b": "256"}}} +{"prompt": "multiply 3 by 333", "target": {"name": "multiply", "args": {"a": "3", "b": "333"}}} +{"prompt": "I need the product of 60 and 60", "target": {"name": "multiply", "args": {"a": "60", "b": "60"}}} +{"prompt": "is this a debug build?", "target": {"name": "get_device_info", "args": {}}} +{"prompt": "am I on a phone or a desktop?", "target": {"name": "get_device_info", "args": {}}} +{"prompt": "clock, please", "target": {"name": "get_current_time", "args": {}}} +{"prompt": "what is today's date?", "target": {"name": "get_current_time", "args": {}}} +{"prompt": "do you know what time it is?", "target": {"name": "get_current_time", "args": {}}} +{"prompt": "what is 2048 times 8?", "target": {"name": "multiply", "args": {"a": "2048", "b": "8"}}} +{"prompt": "work out 23 x 45 for me", "target": {"name": "multiply", "args": {"a": "23", "b": "45"}}} +{"prompt": "what platform are you running on?", "target": {"name": "get_device_info", "args": {}}} +{"prompt": "current date and time please", "target": {"name": "get_current_time", "args": {}}} +{"prompt": "multiply 47 by 89", "target": {"name": "multiply", "args": {"a": "47", "b": "89"}}} +{"prompt": "compute 150 * 20", "target": {"name": "multiply", "args": {"a": "150", "b": "20"}}} +{"prompt": "is it morning or evening here?", "target": {"name": "get_current_time", "args": {}}} +{"prompt": "how much is 44 * 55?", "target": {"name": "multiply", "args": {"a": "44", "b": "55"}}} +{"prompt": "give me 19 times 21, exactly", "target": {"name": "multiply", "args": {"a": "19", "b": "21"}}} +{"prompt": "what time is it?", "target": {"name": "get_current_time", "args": {}}} +{"prompt": "what's the time right now?", "target": {"name": "get_current_time", "args": {}}} +{"prompt": "tell me the device info", "target": {"name": "get_device_info", "args": {}}} +{"prompt": "what is 640 times 480?", "target": {"name": "multiply", "args": {"a": "640", "b": "480"}}} +{"prompt": "quick, 13 times 17", "target": {"name": "multiply", "args": {"a": "13", "b": "17"}}} +{"prompt": "tell me today's date and the time", "target": {"name": "get_current_time", "args": {}}} +{"prompt": "is this Android or iOS?", "target": {"name": "get_device_info", "args": {}}} +{"prompt": "multiply 57 by 61", "target": {"name": "multiply", "args": {"a": "57", "b": "61"}}} +{"prompt": "identify this platform", "target": {"name": "get_device_info", "args": {}}} +{"prompt": "what are you running on right now?", "target": {"name": "get_device_info", "args": {}}} +{"prompt": "which system am I using?", "target": {"name": "get_device_info", "args": {}}} +{"prompt": "what's the host platform?", "target": {"name": "get_device_info", "args": {}}} +{"prompt": "compute 5 * 5000", "target": {"name": "multiply", "args": {"a": "5", "b": "5000"}}} +{"prompt": "compute 144 * 12", "target": {"name": "multiply", "args": {"a": "144", "b": "12"}}} +{"prompt": "where is this app running?", "target": {"name": "get_device_info", "args": {}}} +{"prompt": "what hardware is this?", "target": {"name": "get_device_info", "args": {}}} +{"prompt": "what's the time on this machine?", "target": {"name": "get_current_time", "args": {}}} +{"prompt": "I need the current timestamp", "target": {"name": "get_current_time", "args": {}}} +{"prompt": "can you multiply 36 and 25?", "target": {"name": "multiply", "args": {"a": "36", "b": "25"}}} +{"prompt": "what kind of build is this?", "target": {"name": "get_device_info", "args": {}}} +{"prompt": "what device am I on?", "target": {"name": "get_device_info", "args": {}}} +{"prompt": "what operating system is this?", "target": {"name": "get_device_info", "args": {}}} +{"prompt": "what time do you have?", "target": {"name": "get_current_time", "args": {}}} +{"prompt": "remind me what day it is", "target": {"name": "get_current_time", "args": {}}} +{"prompt": "what's the date today?", "target": {"name": "get_current_time", "args": {}}} +{"prompt": "I need the product of 1001 and 11", "target": {"name": "multiply", "args": {"a": "1001", "b": "11"}}} +{"prompt": "am I running this on the web?", "target": {"name": "get_device_info", "args": {}}} +{"prompt": "give me the local time", "target": {"name": "get_current_time", "args": {}}} +{"prompt": "which platform is this running on?", "target": {"name": "get_device_info", "args": {}}} +{"prompt": "work out 7 x 8 for me", "target": {"name": "multiply", "args": {"a": "7", "b": "8"}}} +{"prompt": "which OS is this app on?", "target": {"name": "get_device_info", "args": {}}} +{"prompt": "what day is it today?", "target": {"name": "get_current_time", "args": {}}} +{"prompt": "describe the device you're running on", "target": {"name": "get_device_info", "args": {}}} +{"prompt": "can you multiply 72 and 72?", "target": {"name": "multiply", "args": {"a": "72", "b": "72"}}} +{"prompt": "I need the product of 250 and 4", "target": {"name": "multiply", "args": {"a": "250", "b": "4"}}} +{"prompt": "101 multiplied by 101 is what?", "target": {"name": "multiply", "args": {"a": "101", "b": "101"}}} +{"prompt": "check what platform this is", "target": {"name": "get_device_info", "args": {}}} +{"prompt": "can you multiply 99 and 99?", "target": {"name": "multiply", "args": {"a": "99", "b": "99"}}} +{"prompt": "how much is 1234 * 5678?", "target": {"name": "multiply", "args": {"a": "1234", "b": "5678"}}} +{"prompt": "give me 8 times 125, exactly", "target": {"name": "multiply", "args": {"a": "8", "b": "125"}}} +{"prompt": "give me 16 times 64, exactly", "target": {"name": "multiply", "args": {"a": "16", "b": "64"}}} +{"prompt": "what is the time here?", "target": {"name": "get_current_time", "args": {}}} +{"prompt": "how much is 900 * 15?", "target": {"name": "multiply", "args": {"a": "900", "b": "15"}}} +{"prompt": "quick, 33 times 3", "target": {"name": "multiply", "args": {"a": "33", "b": "3"}}} +{"prompt": "365 multiplied by 24 is what?", "target": {"name": "multiply", "args": {"a": "365", "b": "24"}}} +{"prompt": "could you check the time?", "target": {"name": "get_current_time", "args": {}}} +{"prompt": "quick, 81 times 9", "target": {"name": "multiply", "args": {"a": "81", "b": "9"}}} +{"prompt": "how late is it?", "target": {"name": "get_current_time", "args": {}}} diff --git a/codelabs/function-calling-flutter-gemma/step_04_finetune/tools.json b/codelabs/function-calling-flutter-gemma/step_04_finetune/tools.json new file mode 100644 index 000000000..42988deb2 --- /dev/null +++ b/codelabs/function-calling-flutter-gemma/step_04_finetune/tools.json @@ -0,0 +1,30 @@ +[ + { + "name": "multiply", + "description": "Multiply two numbers and return the exact product. Use this for any multiplication instead of working it out yourself.", + "parameters": { + "type": "object", + "properties": { + "a": { "type": "number", "description": "The first number." }, + "b": { "type": "number", "description": "The second number." } + }, + "required": ["a", "b"] + } + }, + { + "name": "get_current_time", + "description": "Return the current local date and time on this device. Use this whenever the answer depends on what time it is now.", + "parameters": { + "type": "object", + "properties": {} + } + }, + { + "name": "get_device_info", + "description": "Return the platform this app is running on. Use this when asked about the device, the operating system, or where the app is running.", + "parameters": { + "type": "object", + "properties": {} + } + } +] diff --git a/tool/check_codelabs.sh b/tool/check_codelabs.sh index 04ac02bbf..f2a55ce7d 100755 --- a/tool/check_codelabs.sh +++ b/tool/check_codelabs.sh @@ -91,6 +91,12 @@ fi # One source can feed several starters — Getting Started's finished app is where # both of the codelabs that continue it begin — so this is a list of pairs, not # a map, and a new row is all a new continuation needs. +# +# It is a list of the codelabs that DO continue another, not of all of them. A +# starter is free to be its own app: function-calling's is Step 2 without the +# tools, on the 284 MB model that codelab is actually about, because inheriting +# Getting Started's finished app meant downloading a licence-gated half-gigabyte +# model that the next step then replaced and never opened again. MIRRORS=( "codelabs/getting-started-flutter-gemma/complete|codelabs/inference-engines-flutter-gemma/step_01_starter" "codelabs/getting-started-flutter-gemma/complete|codelabs/multimodal-flutter-gemma/step_01_starter" diff --git a/website/codelabs/function-calling-flutter-gemma/index.md b/website/codelabs/function-calling-flutter-gemma/index.md new file mode 100644 index 000000000..539c2f499 --- /dev/null +++ b/website/codelabs/function-calling-flutter-gemma/index.md @@ -0,0 +1,1051 @@ +author: Sasha Denisov +summary: Function Calling with On-Device Models in Flutter +id: function-calling-flutter-gemma +categories: flutter, ai, gemma, function-calling +environments: android, ios, macos, windows, linux, web +status: Published + +# Function Calling with On-Device Models in Flutter + +## Overview +Duration: 3 + +### What you'll build + +A chat app taught to hand work to your own Dart functions — and then, at the +end, taught to run on a model you fine-tuned yourself. + +It begins the way the other codelabs here begin — download a model, stream a +reply — but on the model this one is about. Three models, in fact, and the +order is the argument. The starter chats with **FunctionGemma 270M**: 284 MB, +ungated, and a model whose entire job is calling functions, so Step 2 has it +running your Dart before you have finished reading the page. Step 4 fine-tunes +that same 270M model on the three tools this codelab declares and produces a +`.litertlm` you open from disk. Step 5 pays **2.59 GB** for **Gemma 4 E2B**, +for the thing a 270M model cannot do at all: reason out loud before it chooses +which function to call. It also declares its tools by a different route, which +is where `toolChoice` stops behaving the way its three names suggest. + +That is the idea worth taking away: + +**A tool is a declaration plus a function, and the model never runs anything.** +It can only ask. Your app decides what `multiply` means, runs it, and sends +back a map — and that map is the model's entire knowledge of what happened. +Nothing about the weights changes, nothing is downloaded, and the model has no +way to reach your code except by asking for it by name. + +Which makes the second idea the one that actually bites. **Function calling is +not a request, it is a loop.** The model answers, or it asks; if it asks you +run something and answer *it*, and then it generates again — and it may ask +again. A turn is not one generation, it is however many the model needs, and +something has to decide when that stops. Step 2 writes that loop by hand so you +can see every exit it has. Step 3 deletes it and calls the one the SDK ships, +which has three exits the hand-written version did not. + +And the third: what a call is *committed* to. The moment the SDK hands you a +`FunctionCallResponse`, that call is already in the chat's history. Leave it +without a reply — because the user cancelled, because your tool threw, because +the stream errored — and the next message on that chat is poisoned: the model +re-issues the call, or answers nothing. Every exit path has to answer every +call. That is the rule the loop in Step 3 exists to keep. + +### What you'll learn + +* what a `Tool` declaration is, what it is not, and why the description is the + only thing telling the model *when* to call +* how a call arrives — `FunctionCallResponse` on the same stream as the text — + and how a result goes back, as `Message.toolResponse` +* how to drive the loop by hand, and then how to hand it to + `generateChatResponseWithTools` with `maxToolTurns` as the stop condition +* why every committed call must be answered on every exit path, including the + ones you did not plan for +* what `toolChoice` actually changes — and, on both models here, what it does + not: neither can be forced to call, for two different reasons +* how to fine-tune a 270M model on your own tools with **litetune**, convert it + to `.litertlm`, and measure what the conversion cost +* that a model you tuned loads through the same API as one you downloaded — + not one line of Dart changes + +### What you'll need + +* Flutter 3.44 or newer, and any one of Flutter's six platforms to run on: an + Android device or emulator, an iOS device or simulator, an Apple-silicon Mac, + a Windows or Linux desktop, or Chrome. `step_01_starter/` is a whole app, not + a diff against another codelab — clone the repo and run it +* **No Hugging Face token to run the app**, in any step. The two repositories + it downloads from — `sasha-denisov/function-gemma-270M-it` and + `litert-community/gemma-4-E2B-it-litert-lm` — are ungated, so every + `flutter run` here is a plain `flutter run` with no `--dart-define` +* Room for **284 MB** — one download, shared by Steps 1, 2 and 3 — and for + **2.59 GB** more in Step 5, plus the memory to open the larger one, roughly + 6 GB of RAM. A 4 GB phone is killed by the OS rather than told no +* Step 4 is optional and costs CPU time instead of megabytes: **Linux or + macOS**, Python 3.10–3.12, and about 2.2 GB of cached Python environments. + It is the one part of this codelab that *does* need a Hugging Face token, + because the base checkpoint it fine-tunes is gated and the approval is + manual — **request access before you start it**, see that step's own + prerequisites. Skip it and the app works on the stock models + +### Get the code + +```bash +git clone --depth 1 https://github.com/DenisovAV/flutter_gemma.git +cd flutter_gemma/codelabs/function-calling-flutter-gemma +ls +``` + +```text +step_01_starter/ a plain chat on FunctionGemma — no tools yet +step_02_one_tool/ after Step 2 — one tool, the loop written out +step_03_the_loop/ after Step 3 — the same tools, the SDK's loop +step_04_finetune/ NOT an app: the data and commands for a litetune run +complete/ after Step 5 — three tools, toolChoice, thinking +``` + +`step_04_finetune` has no `pubspec.yaml` on purpose. Its output is a model, not +code. + +## Step 1: What a tool call actually is +Duration: 6 + +### Run the starter + +Open `step_01_starter` and run it. It is the same shape of app the other +codelabs here start from — download a `.litertlm`, stream the reply, in text — +on the model this one is about: **FunctionGemma 270M**, 284 MB, from an ungated +repository, so there is no token to get and no `--dart-define` to remember. + +Nothing in it knows about tools yet, and that is the point of starting here: +everything Step 2 adds is visible as a diff against this. + +One thing in `main.dart` is worth seeing before you go on — the call that runs +before the first frame is guarded: + +```dart + try { + await FlutterGemma.initialize(inferenceEngines: [LiteRtLmEngine()]); + } catch (error) { + runApp(_StartupFailed(error: error)); + return; + } +``` + +That is not ceremony. This is the earliest thing in the app that can fail — +hot-restarting after adding a plugin throws `MissingPluginException` right here +— and an `await` before `runApp` that throws never reaches `runApp` at all. + +Now look at the call that opens the chat, because that is where this codelab's +change lands: + +```dart + final chat = await inference.createChat( + modelType: widget.model.modelType, + maxOutputTokens: 256, + ); +``` + +### Three things, and only one of them is code + +A tool the model can call is made of three parts, and it helps to name them +before any of them appear on screen. + +**The declaration** is a `Tool`: a name, a description, and a JSON Schema for +the arguments. It holds no code and it cannot run. The SDK renders it into the +prompt; the model reads it and nothing else. The description is not a comment — +it is the only thing that tells the model *when* this is the right function. + +**The call** is a `FunctionCallResponse`, and it arrives on the same stream as +the text. `generateChatResponseAsync` yields `ModelResponse`, which is a sealed +type: a `TextResponse` is a token of the answer, a `FunctionCallResponse` is +the model asking for `name(args)`. One turn can be either, or both. + +**The answer** is a `Message.toolResponse`, staged with `addQueryChunk` like +any other message. Until it reaches the session the model has not seen your +result — a tool is not a function the model called, it is a question it asked +and you replied to. + +### What the model cannot do + +It cannot run your code, it cannot see your code, and it cannot find out +whether the function exists. It writes a name and some arguments, and if that +name is one you never declared, you get a call for a function that is not +there. Answering that with an error map is the app working correctly; throwing +is the app losing the conversation. + +It also cannot be relied on for the thing this codelab uses as its example. Ask +a 270M model for 1234 × 5678 and you get a confident number of about the right +length. The point of the tool is not that the model is bad at arithmetic — it +is that you can check the answer without a network, without a service, and +without trusting anything. + +## Step 2: One tool, and the loop by hand +Duration: 11 + +### One field on the model you already have + +`step_02_one_tool` downloads nothing new. `main.dart`, `model.dart` and +`download_page.dart` are byte for byte the starter's, and everything this step +adds is a new `lib/tools.dart` and the chat page. Which makes one field in +`model.dart` worth reading before the tools arrive, because it is the field +that decides whether any of them work: + +```dart + /// A 270M model whose whole job is function calling. + /// + /// 284 MB — small enough to download while you read this page, and small + /// enough that it does very little else: ask it a general question and the + /// answer will be thin. That is the trade this step is making on purpose. + /// Calling a function is a narrow skill, and a model specialised for it can + /// be a fraction of the size of one that also has to hold a conversation. + static const functionGemma = ModelChoice( + label: 'FunctionGemma 270M', + url: + 'https://huggingface.co/sasha-denisov/function-gemma-270M-it/' + 'resolve/main/functiongemma-270M-it.litertlm', + fileName: 'functiongemma-270M-it.litertlm', + modelType: ModelType.functionGemma, + sizeLabel: '284 MB', + ); +``` + +`ModelType.functionGemma` is the line to pause on. It selects the format the +SDK writes *and* reads: the declarations go into a developer turn these weights +were trained on, and `call:multiply{…}` is parsed back +into a `FunctionCallResponse`. Name a different family and the SDK writes a +prompt the model never saw and waits for a syntax it never emits — every turn +comes back as plain text and nothing says why. + +### Declare the function + +A new file, `lib/tools.dart`: + +```dart +const multiplyTool = Tool( + name: 'multiply', + // The model reads this. It is the only thing telling it WHEN to call — so + // "use this instead of working it out yourself" is instruction, not prose. + description: + 'Multiply two numbers and return the exact product. Use this for any ' + 'multiplication instead of working it out yourself.', + parameters: { + 'type': 'object', + 'properties': { + 'a': {'type': 'number', 'description': 'The first number.'}, + 'b': {'type': 'number', 'description': 'The second number.'}, + }, + 'required': ['a', 'b'], + }, +); +``` + +Nothing there runs. The half that does is a plain Dart function: + +```dart +Map runMultiply(Map args) { + final a = asNumber(args['a']); + final b = asNumber(args['b']); + if (a == null || b == null) { + // Returned, not thrown. A model wrote these arguments and a model can + // write nonsense; an error map is a turn it can read and correct on the + // next one, while an exception ends the conversation and takes the + // committed call with it. + return { + 'error': + 'multiply needs two numbers. Got a=${args['a']}, b=${args['b']}.', + }; + } + final product = a * b; + // `12 * 13` arriving as doubles comes back as `156.0`, and the model has to + // read that number out loud. Say 156. + return { + 'result': product is double && product == product.truncateToDouble() + ? product.toInt() + : product, + }; +} +``` + +Two details there earn their lines. The arguments are whatever JSON the model +produced — FunctionGemma is trained to emit them as strings, so `"12"` is the +ordinary case and `12` and `12.0` are the others: + +```dart +num? asNumber(Object? value) => switch (value) { + final num n => n, + final String s => num.tryParse(s.trim()), + _ => null, +}; +``` + +And a bad call is *answered*, not thrown. Everything `runMultiply` returns +becomes the model's only knowledge of what happened; an exception instead ends +the turn and leaves a call in the history that nothing replied to. + +### Open a session that has tools + +Two arguments on `createChat`: + +```dart + final chat = await inference.createChat( + // Which family's call syntax the SDK writes and reads. With + // `ModelType.functionGemma` it renders the declarations into a + // developer turn these weights were trained on, and parses + // `call:multiply{…}` back into the + // `FunctionCallResponse` the loop below waits for. + modelType: widget.model.modelType, + // The declarations. This is the whole of "the model can call your + // code": a list of names, descriptions and argument schemas. + tools: const [multiplyTool], + // And the switch that turns the machinery on. `tools` without this is + // the quiet failure worth knowing about: `InferenceChat` logs + // "Model does not support function calls, but tools were provided. + // Tools will be ignored", never renders the declarations, and the + // model answers every question out of its own head — fluently, and + // with arithmetic it made up. + supportsFunctionCalls: true, + maxOutputTokens: 256, + ); +``` + +Note what the call *above* it does not take. If you came from the multimodal +codelab you will be looking for the second place to set the flag — the trap +where `supportImage` has to go on `getActiveModel` as well or native fails the +turn. There is no second place here: + +```dart + final inference = await FlutterGemma.getActiveModel( + maxTokens: 1024, + preferredBackend: PreferredBackend.cpu, + ); +``` + +`getActiveModel` builds the engine, and nothing about the engine changes when +you declare a function. Tools belong to the session. + +The two arguments it *does* take are worth a moment. `maxTokens: 1024` is what +this checkpoint is built for. The CPU backend is a workaround for **this file**, +and the distinction matters more than the workaround does. + +The `.litertlm` you just downloaded was converted before litetune began setting +`prefer_activation_type=fp32`. Without that key the GPU path answers every +prompt with `` repeated to the token limit — measured on Android and on +macOS Metal alike, with no exception, no warning, and a chat that looks alive +while it returns filler. On CPU the same weights ask for `multiply` correctly. + +So this is not "FunctionGemma needs a CPU", and it is not a platform bug. It is +one published artifact carrying a conversion setting that predates the fix. Step +4 converts the model again with a current litetune, and that artifact scores the +same on GPU as on CPU and runs about 1.5× faster — which is a fair summary of +what the fine-tuning step buys you even before you change a single training +row. + +What changes with tools is not the number but what has to fit under it: the +declarations are rendered into the prompt once and stay in the history for the +rest of the conversation, and every call and every tool response is another +turn inside the same 1024 — so a tool-calling chat runs out of room sooner than +a plain one does. + +### The loop, written out + +This is the part worth reading once. One message, three questions asked in +order: + +```dart + await chat.addQueryChunk(Message.text(text: text, isUser: true)); + + // ROUND ONE. The model either answers, or asks for the function. + final calls = await _generate(chat); + if (calls.isEmpty) return; // a plain answer — nothing to run + + // The app runs it. This half is never the SDK's: a tool is an action in + // your program, and only your program knows what `multiply` means. + for (final call in calls) { + final result = _run(call); + if (mounted) { + setState(() { + _turns + ..add(_Turn(_describeCall(call), kind: _TurnKind.toolCall)) + ..add(_Turn(jsonEncode(result), kind: _TurnKind.toolResult)); + }); + } + // Handing the answer back is a MESSAGE, not a return value. Until this + // reaches the session the model has not seen the number at all. + await chat.addQueryChunk( + Message.toolResponse(toolName: call.name, response: result), + ); + } + + // ROUND TWO. Same session, same history — now with the result in it. + final again = await _generate(chat); + if (again.isEmpty) return; +``` + +`_generate` is one generation. The text and the calls arrive on the same +stream, so it collects both: + +```dart + await for (final chunk in chat.generateChatResponseAsync()) { + switch (chunk) { + case TextResponse(:final token): + // Each TextResponse carries only the NEW text, not the whole reply + // so far — append, never replace. + buffer.write(token); + // Guarded rather than returned: a call this stream has already + // yielded is committed to the chat's history and still has to be + // answered, so the loop keeps draining even with no screen to paint. + if (mounted) { + setState( + () => + _turns[at] = _Turn(buffer.toString(), kind: _TurnKind.model), + ); + } + case FunctionCallResponse(): + pending.add(chunk); + case ParallelFunctionCallResponse(:final calls): + // One turn, several calls. FunctionGemma with a single declared tool + // will rarely do this, but the case exists and dropping it would + // leave committed calls unanswered. + pending.addAll(calls); + case ThinkingResponse(): + // Filtered out upstream unless the chat was opened with + // `isThinking: true` — `complete` does exactly that. Here the branch + // exists so the switch stays exhaustive. + break; + } + } +``` + +The switch is exhaustive over the sealed `ModelResponse` on purpose. Write it +as `if (chunk is TextResponse)` and a case the SDK adds later becomes silence +in your app rather than a compile error. + +### The rule this loop is already keeping + +Round two can come back with *another* call. This app runs one round and stops +— but it still answers what it will not run: + +```dart + // The model asked for another call. Every call the stream yielded is + // ALREADY in the chat's history, and a call left without a response + // poisons the next turn on this chat — the model re-issues it, or + // answers nothing at all. So the ones this step will not run still get + // an answer, and it says what happened. +``` + +That is the invariant to carry into Step 3. A `FunctionCallResponse` is +committed to the persistent history *at the moment it is yielded* — before your +code has seen it — so every call needs a reply on every path out, not only the +happy one. + +### Run it + +Run `step_02_one_tool` and ask *what is 1234 times 5678?* The transcript shows +four lines: your question, `multiply(a: 1234, b: 5678)`, `{"result":7006652}`, +and the model reading that number back. Check it on a calculator — that is the +point of choosing arithmetic. + +Then ask it something with no tool in it, like *hello*. One round, no calls, +and a thin little answer: this is a 270M model, and conversation is not what it +is for. + +## Step 3: Hand the loop to the SDK +Duration: 8 + +Everything in Step 2's `_send` past `addQueryChunk` is the same in every +tool-calling app ever written, and it has more edges than it looks. So the SDK +ships it: + +```dart + await for (final chunk in chat.generateChatResponseWithTools( + // Run the function. Returning the map is what feeds the model; the + // SDK wraps it in `Message.toolResponse` and stages it before the + // next generation. + onToolCall: _onToolCall, + maxToolTurns: _maxToolTurns, + // Called once, if the loop runs out of turns with calls still coming. + // Without it the reply is quietly empty or half-written and nothing + // says the cap is why. + onMaxToolTurns: () => hitCap = true, + )) { +``` + +The whole of your half is now the callback: + +```dart + Future> _onToolCall(FunctionCallResponse call) async { + final result = _run(call); +``` + +Staging your message is still yours. The loop drives generation; it does not +send your turn for you, exactly as `generateChatResponseAsync` does not: + +```dart + await chat.addQueryChunk(Message.text(text: text, isUser: true)); +``` + +### The stop condition + +```dart +const _maxToolTurns = 4; +``` + +The loop ends when a generation comes back with no calls in it — which is a +promise about the model, not about the code. A model that keeps asking would +run until the context window filled, so `maxToolTurns` is the cap, and hitting +it is reported rather than swallowed: + +```dart + if (hitCap && mounted) { + setState( + () => _notice = + 'The model was still asking for tools after $_maxToolTurns ' + 'turns, so the loop stopped. The answer above may be missing ' + 'or cut short.', + ); + } +``` + +A cap below 1 throws a `RangeError`, deliberately. Zero turns would answer the +message you just staged with nothing at all and close the stream, which on +screen is indistinguishable from a model that had nothing to say — so the SDK +refuses instead of producing a silent no-op. + +### What you got that you did not write + +The happy path in Step 2 was correct. Three others were not there at all, and +each of them is a committed call that would have been left dangling: + +* **the turn was cancelled** — the loop answers every collected call with + `{'status': 'cancelled'}` before returning, so the history is balanced and + the tools' side effects never run +* **your tool threw** — the failed call is answered with `{'error': …}`, the + siblings in that turn are answered as not run, and the exception is + *rethrown* so you still see it +* **the generation stream errored mid-turn** — the calls it had already yielded + are answered before the original error is rethrown + +All three balance the history before they return, and that is what leaves the +chat usable for the next message — with one exception the SDK states rather +than hides: if the session is already too broken to accept the balancing feed +itself, it logs that the history may be left unbalanced and that the recovery +is to recreate the session. All three would have taken another twenty lines in +`_send`, and you would only have found out you needed them from a conversation +that started answering nothing. + +### Run it + +Run `step_03_the_loop` and ask for something that chains: *12 times 12, then +that times 3*. Whether a 270M model plans two calls or stops after one is the +model's decision, not the loop's — a single call is what was measured here — and +either way the transcript shows each generation writing underneath the work it +was given, because the reply bubble is re-anchored every time a tool runs. If +it stops after one, that is the checkpoint's limit: the loop keeps going for as +long as calls keep coming, up to `_maxToolTurns`. + +## Step 4: Fine-tune the model on your own tools +Duration: 14 + +This step is optional, it does not touch `lib/`, and its output is a file. + +### Before you start: request access to the base model + +Three of the five commands below name `google/functiongemma-270m-it` — as the +tokenizer, as the model to tune, and as the base to record in the bundle. That +repository is **gated, and the approval is manual**: an anonymous fetch of its +`config.json` returns `401`, and access is granted by a person rather than by +accepting a checkbox, so it can take hours or days. + +So do this part first, not when you reach command 1: + +1. Open [the model page](https://huggingface.co/google/functiongemma-270m-it) + and request access. +2. When it is granted, `hf auth login` (or export `HF_TOKEN`). + +Without it `prepare` fails on the tokenizer download and you never reach +`tune`. This is the only place in the codelab that needs a token — the +`.litertlm` the app itself downloads comes from the ungated +`sasha-denisov/function-gemma-270M-it`, and no step of the app asks you to log +in. + +`step_04_finetune/` is not a Flutter app — it has no `pubspec.yaml`, so the +codelab gate does not analyze or build it. What it holds is the two inputs a +[litetune](https://github.com/DenisovAV/litetune) run needs, for the three +tools this codelab declares. + +### What litetune is + +It takes a Hugging Face checkpoint through LoRA fine-tuning, merges, exports to +`.litertlm`, and bundles the result with metadata — five commands, because each +stage fails differently and a single `run` would hide which one you are in. + +**This is alpha software**, and its own statement of what has been measured is +worth quoting: *measured end to end on `google/functiongemma-270m-it` and +function calling only*. That is precisely the model and the task you have been +running since Step 2 — so this codelab is inside the one path the tool has +actually been measured on. Its other scorer and its other base models are not. + +```bash +pip install litetune +``` + +**Linux or macOS**, Python 3.10–3.12. Python 3.13 runs `prepare`, `tune` and +`bundle` but not `convert` or `verify`: the export toolchain pins +`numpy==2.0.2`, and that stops publishing wheels after 3.12. Windows is +untried. On Linux you also need `libvulkan1` — `litert-lm` `dlopen()`s a +Vulkan-linked library even for the CPU backend, and without it every +invocation, `--help` included, dies in under a second: + +```bash +sudo apt-get install -y libvulkan1 # Debian/Ubuntu +``` + +It runs on CPU, which is workable at 270M. Each stage builds and caches its own +environment, and they are not small: `convert` pulls about 1.6 GB and `tune` +588 MB. `litetune env` shows what is on disk, `litetune env --clean` removes +it. Colab works out of the box. + +### Your data declares the task + +One JSON object per line, and **the shape of the target is how you say what +kind of task this is**. An object with a `name` is a tool call: + +```json +{"prompt": "set an alarm for 7", "target": {"name": "set_alarm", "args": {"hour": "7"}}} +``` + +A bare string is the answer itself, and that is `exact-text` rather than +function calling. Two shapes rather than a target plus a `--target-kind`, +because those two could disagree and a shape cannot disagree with itself. You +match it with `--scorer tool-call` at `verify`. + +`step_04_finetune/raw.jsonl` is 72 rows in that shape, for `multiply`, +`get_current_time` and `get_device_info` — the three tools `complete/` +declares: + +```json +{"prompt": "how much is 1234 * 5678?", "target": {"name": "multiply", "args": {"a": "1234", "b": "5678"}}} +``` + +Seventy-two rows are enough to run all five commands end to end and get a file +out. They are not enough to move a quality number: litetune's own published +figures come from thousands of examples, and `prepare` holds half of any file +back for scoring. Treat this run as a rehearsal of the pipeline and bring your +own data when you want a result. + +### The five commands + +Run them from `step_04_finetune/`. + +```bash +# 1. Split, and reject rows that cannot be scored. Seconds. +litetune prepare --data raw.jsonl --output-dir data --context-length 1024 \ + --tokenizer google/functiongemma-270m-it + +# 2. Fine-tune. CPU is fine at this size. +litetune tune --model google/functiongemma-270m-it --data data/train.jsonl \ + --output-dir tuned --prompt-mode prerendered --method lora + +# 3. Convert, sweeping recipes rather than trusting a default. +litetune convert --model tuned/model --output-dir artifacts \ + --recipe dynamic_wi8_afp32 --recipe weight_only_wi8_afp32 + +# 4. Measure what the conversion cost, against the float twin. +# `convert` names the artifact; look the filename up rather than build it. +litetune verify --model artifacts/weight_only_wi8_afp32/.litertlm \ + --reference tuned/model --data data/heldout.jsonl \ + --json > manifest.json + +# 5. Package the artifact with what was measured about it. +litetune bundle --output-dir bundle \ + --model artifacts/weight_only_wi8_afp32/.litertlm \ + --declarations tools.json --prompt-mode prerendered \ + --base-model google/functiongemma-270m-it \ + --base-model-revision \ + --adapter tuned/adapter \ + --train-metrics tuned/metrics.json \ + --verify-manifest manifest.json +``` + +Four of those flags decide something, and it is worth knowing which. + +**`--prompt-mode prerendered`** because that is what this app does. For +`ModelType.functionGemma`, `InferenceChat` renders the declarations into the +prompt itself — you read the code that does it in Step 2 — so the runtime must +not template them again. The value has to be the **same** in `tune` and +`bundle`, and the wrong one produces a fluent wrong answer rather than an +error. + +**`prepare` splits by content hash**, into `train.jsonl` and `heldout.jsonl`, +and rejects rows it cannot score. The held-out half is never trained on: +scoring a model on rows it was fitted to measures memorisation, not whether it +answers new inputs. Re-running `prepare` puts the same rows on the same side. + +**`--reference` is the float twin** — the same weights before conversion. That +is what makes the difference between the two sides the *conversion cost*, +rather than a mixture of that and whatever training did. Point it at an untuned +base instead and both numbers come back unavailable, because one measurement +cannot separate two effects. + +**`--recipe` has no default**, and litetune's own line for why is the right one +to keep: *"A sweep of one is not a comparison."* Two of its four recipes have +been measured (`dynamic_wi8_afp32`, `weight_only_wi8_afp32`) and two have not. +The two artifacts a sweep produces are 0.04% apart in bytes; nothing in file +size, exit code or logs separates them, and running both against held-out data +is the only thing that does. + +Command 3 in that list — not this codelab's Step 3 — already gives you +something shippable: one `.litertlm` per recipe under `artifacts//`. +Commands 4 and 5 are what let you say anything about it. + +### Then open it in the app + +Here is the punchline, and it is a small one on purpose. Run `complete/`, +choose **Open a .litertlm from disk**, paste the absolute path that `convert` +printed, and the app runs your model. + +Not one line of Dart changes. The `.litertlm` you produced is a `.litertlm`, +and the only thing that differs is where the bytes are: + +```dart + /// Points an install at wherever this model's bytes are. + /// + /// The two branches are the whole difference between a model you downloaded + /// and a model you tuned: `fromNetwork` fetches the file, `fromFile` + /// registers one that is already here. Everything after this line — the + /// session, the tools, the loop — cannot tell them apart. + InferenceInstallationBuilder locate(InferenceInstallationBuilder builder) => + path != null ? builder.fromFile(path!) : builder.fromNetwork(url!); +``` + +`fromFile` does not copy. It checks the file exists, registers the path, and +marks it protected — so `getModelPath` later hands back your own +`artifacts/` directory, and moving or deleting the file takes the model with +it. It is also why the delete button in `complete/` is safe on a tuned model: +`uninstallModel` skips the file for a `FileSource` install and only forgets the +metadata. The app never owned that file. + +On the web there is no path to give — the browser arm of `fromFile` registers a +URL, not a file — so `complete/` says so instead of offering a text field that +cannot work. + +**If you skip this step**, nothing downstream breaks. `complete/` ships two +models it can download and works on either. + +## Step 5: Three tools, toolChoice, and thinking +Duration: 12 + +`complete/` is the finished app: a model list, three tools, and two session +settings you can change while it runs. + +### Three tools cost the loop nothing + +```dart +/// Everything the model is told it can call. +const toolbox = [multiplyTool, clockTool, deviceTool]; +``` + +The loop did not change to accept them, because it dispatches by name: + +```dart +Map runTool(FunctionCallResponse call) { + final runner = toolRunners[call.name]; + if (runner == null) { + return {'error': 'This app has no tool named "${call.name}".'}; + } + return runner(call.args); +} +``` + +Two collections, and the reason they are two rather than a `switch`: + +```dart +const toolRunners = { + 'multiply': runMultiply, + 'get_current_time': runClock, + 'get_device_info': runDeviceInfo, +}; +``` + +A declaration with no runner is a call the app answers with an error forever +and the model never finds out why; a runner with no declaration is code the +model is never told about. Two collections can be compared, and +`test/widget_test.dart` does: + +```dart + test('every declared tool has a runner, and no runner is undeclared', () { + expect( + toolbox.map((t) => t.name).toSet(), + toolRunners.keys.toSet(), + reason: 'toolbox and toolRunners must name the same tools', + ); + }); +``` + +The other two tools are the device clock and the platform name, for the same +reason `multiply` was arithmetic: you can check both by eye, and neither needs +a network. A tool with no arguments still declares `parameters`, which is worth +knowing — + +```dart +const clockTool = Tool( + name: 'get_current_time', + description: + 'Return the current local date and time on this device. Use this ' + 'whenever the answer depends on what time it is now.', + parameters: {'type': 'object', 'properties': {}}, +); +``` + +— because FunctionGemma's rendered declaration gates the whole `parameters` +block on that map. Drop it and the model reads a declaration that was cut off. + +### toolChoice, and the models that cannot obey it + +`ToolChoice` has three values, and what each one is worth depends on **who +renders the declarations** for the model you picked: + +```dart + // Whether the model may, must, or must not call — and how much of that + // lands depends on who renders the declarations. On FunctionGemma the + // SDK renders them into the prompt, so `none` leaves them out and the + // model never learns the tools exist. On Gemma 4 the runtime renders + // them from `tools_json`, which `createChat` passes whatever you + // choose here — so `none` cannot take them back out. What it does + // switch off there is the SDK's suppression of tool-call JSON, which + // is why a call made under `none` can arrive as raw JSON in the bubble. + toolChoice: _toolChoice, +``` + +Switch to `none` on **FunctionGemma** and ask the multiplication question +again: the declarations are gone from the prompt, you get the model's own +arithmetic, and that is the demonstration. + +On **Gemma 4** the same switch is weaker than its name. Its declarations are +carried by the session — `createChat` forwards `tools` to `createSession` +without consulting `toolChoice` — so `none` cannot unsay them. All it does +there is turn off the SDK's swallowing of a tool-call turn, so if the model +calls anyway you see the raw `{"role":"assistant","tool_calls":[…]}` in the +reply bubble instead of prose. Worth trying once, because it is the clearest +possible look at what the passthrough format actually puts on the wire. + +Switch to `required` and **neither** model obeys it. The app says so rather +than leaving you to wonder: + +```dart + _notice = + _toolChoice == ToolChoice.required && + !widget.model.supportsRequiredToolChoice + ? '${widget.model.label} cannot be forced to call a tool — nothing ' + 'in the prompt it is given can say "you must", so `required` ' + 'behaves as "auto".' + : null; +``` + +That is not a bug in either model, and the two reasons are different. +FunctionGemma's prompt format has no way to express "you must call a function", +and honouring `required` would mean inventing tokens it was never trained on — +so `InferenceChat` logs a warning and behaves as `auto`. Gemma 4 never reaches +that code: the only "you must" text the SDK owns lives on the Dart-injection +path, which passthrough models skip by design, and the `tools_json` handed to +the runtime carries no `tool_choice` field at all. So there `required` is +silently `auto` — not even a warning. + +Which is why the answer is recorded per checkpoint rather than assumed from +size. Today it is `false` for both, and the bigger model is not the exception: + +```dart + /// Can this model be *forced* to call a tool? + /// + /// `ToolChoice.required` needs a way to say "you must call a function" in + /// the prompt the model actually reads, and neither of these has one. + /// FunctionGemma's format cannot express it, so the SDK logs a warning and + /// behaves as `auto`. Gemma 4's declarations go to the runtime as + /// `tools_json`, which carries no `tool_choice` — so `required` is `auto` + /// there too, without even the warning. Reasonable behaviour on the SDK's + /// part, and very confusing to watch if the app does not say so. + final bool supportsRequiredToolChoice; +``` + +### Thinking mode, and what the 2.59 GB buys + +Gemma 4 E2B can reason before it chooses. FunctionGemma cannot — 270M +parameters specialised for one skill, and reasoning is not it. One flag: + +```dart + // Reason first, then answer. On weights with no thinking training this + // buys nothing, which is why the switch is disabled for those. + isThinking: _thinking, +``` + +With it on, the stream carries a third kind of chunk: + +```dart + case ThinkingResponse(:final content): + // These reach the stream only because the chat was opened with + // `isThinking: true`; with it false the SDK drops them before this + // loop ever sees one. + _thought.write(content); + if (mounted) setState(_paintThinking); +``` + +`isThinking: false` is not a display choice — the SDK filters `ThinkingResponse` +out of the stream entirely, so an app that ignores the case sees nothing either +way. And the reasoning goes *above* the answer, because that is the order it +happened in: + +```dart + void _paintThinking() { + if (_thinkAt < 0) { + _turns.insert(_replyAt, const _Turn('', kind: _TurnKind.thinking)); + _thinkAt = _replyAt; + _replyAt += 1; + } + _turns[_thinkAt] = _Turn(_thought.toString(), kind: _TurnKind.thinking); + } +``` + +Thinking is generated text and comes out of the same budget as the answer, +which is why the session asks for more room when it is on: + +```dart + maxOutputTokens: _thinking ? 512 : 256, +``` + +### Both settings belong to the session + +Neither `toolChoice` nor `isThinking` can be changed on a live chat. One +decides whether the declarations are rendered into the prompt; the other +switches on a generation channel. Both are settled when the session is created, +so changing either closes the chat and opens another — and the transcript goes +with it: + +```dart + /// Rebuilds the session because a session setting changed. + /// + /// There is no way to change `toolChoice` or `isThinking` on a live chat: + /// both are decided when the session is created — one renders the + /// declarations into the prompt, the other switches on a generation channel + /// — so the honest thing is to close this one and open another. The + /// transcript goes with it, because the new session's history is empty and a + /// transcript that survived would be describing a conversation the model can + /// no longer remember. +``` + +### Three models, one container + +`complete/` opens with a list rather than a single constant, because by now +there are three things it can run: two downloads and whatever came out of Step +4. All three share one application identity, so `install()` being idempotent is +not enough — the gate has to say which model it *means*: + +```dart + Future _check() async { + if (!await FlutterGemma.isModelInstalled(widget.model.fileName)) { + return false; + } + await widget.model + .locate( + FlutterGemma.installModel( + modelType: widget.model.modelType, + fileType: ModelFileType.litertlm, + ), + ) + .install(); + return true; + } +``` + +A model you added from disk turns up in that list again on the next launch, +without the app storing anything of its own — `listInstalledModels` returns the +ids, and `getModelPath` turns one back into where the file actually is: + +```dart + Future> _findYourOwn() async { + final shipped = {for (final m in Models.downloadable) m.fileName}; + final installed = await FlutterGemma.listInstalledModels(); + final yours = []; + for (final id in installed) { + if (shipped.contains(id)) continue; + yours.add(ModelChoice.fromDisk(await FlutterGemma.getModelPath(id))); + } + return yours; + } +``` + +One simplification stated out loud: a model opened from disk is assumed to be a +fine-tuned FunctionGemma, because that is what Step 4 produces and nothing on +disk records which family a `.litertlm` belongs to. Tune a different base and +`ModelChoice.fromDisk` is the line to change. + +### Where this runs + +| | Android | iOS device | iOS Simulator | macOS | Windows | Linux | Web | +|---|---|---|---|---|---|---|---| +| Function calling | yes | yes | CPU only | yes | yes | yes | **no** (Gemma 4) | +| Thinking (Gemma 4) | yes | yes | CPU only | yes | yes | yes | see below | +| Open a file from disk | yes | yes | yes | yes | yes | yes | **no** | + +**The web** builds and runs, and text chat works. Function calling on **Gemma +4** does not, and this is known from the source rather than merely untried: the +browser `.litertlm` runtime does not override `createChat`, so it inherits the +base implementation, whose session factory never passes `tools:` on. Gemma 4's +declarations travel *with the session*, so on web they never arrive — the model +is told nothing about your functions and answers 1234 × 5678 out of its own +head. FunctionGemma's declarations are rendered into the prompt by +`InferenceChat` instead, so they are not lost the same way, but nothing in this +codelab was run on web against either model, so treat that half as unverified. +Thinking is unverified for the same reason: the browser runtime types its +`extra_context` as opaque JSON and its thinking channel has never been +confirmed end to end. The 2.59 GB model is in any case not a browser download, +and the from-disk path is genuinely absent: `fromFile` in a browser registers a +URL, because a browser has no path to give. + +**The iOS Simulator** runs CPU-only — Metal's simulator implementation caps a +single allocation at 256 MB, below Gemma 4's weights. FunctionGemma at 284 MB +is comfortable there; Gemma 4 will crawl if it loads at all, and hardware is +the answer. + +### Try it end to end + +`complete/` ships an integration test that downloads Gemma 4, opens one chat +with all three declarations, and asks a question the model cannot answer on its +own. It needs a device and a 2.59 GB download, so it is not part of CI: + +```bash +cd codelabs/function-calling-flutter-gemma/complete +flutter test integration_test/function_calling_test.dart -d +``` + +What it asserts is worth reading, because "the reply is not empty" would not +have caught anything: + +```dart + // Ground truth, taken from the call the model actually made rather than + // from what it was asked: `isNotEmpty` on the reply would not tell a model + // that used the tool from one that invented a plausible number and ignored + // it. Whatever arguments it chose, the product in the reply must be the + // one THIS app computed for them. +``` + +## What's next +Duration: 2 + +A declaration, a function, and a loop that knows when to stop — plus a model +you tuned yourself, if you spent the CPU time. + +* **On-device RAG** gives the model documents instead of functions: embed your + own text, search it, and ground the answer +* **`flutter_gemma_agent`** builds on exactly this loop — skills written as + Markdown, JavaScript or native intents, driven by the same + function-calling machinery +* **Multimodal** ([Vision and Audio on Device](/codelabs/multimodal-flutter-gemma)) + is the other thing a session flag switches on, and the codelab where the flag + really does have to go in two places + +### Reference + +* [flutter_gemma on pub.dev](https://pub.dev/packages/flutter_gemma) — the full + platform support matrix and the model table +* [litetune](https://github.com/DenisovAV/litetune) — the fine-tuning pipeline + Step 4 uses, including what it has and has not measured +* [Source and this codelab's code](https://github.com/DenisovAV/flutter_gemma) diff --git a/website/lib/codelabs/codelabs_page.dart b/website/lib/codelabs/codelabs_page.dart index 235f83e58..4f4000ead 100644 --- a/website/lib/codelabs/codelabs_page.dart +++ b/website/lib/codelabs/codelabs_page.dart @@ -94,11 +94,14 @@ class CodelabsPage extends StatelessComponent { title: 'Function Calling with On-Device Models in Flutter', blurb: 'Declare Dart functions the model can call, drive the call/response ' - 'loop, and watch it reason first with thinking mode.', - duration: '45 min', + 'loop by hand and then hand it to the SDK, fine-tune a 270M model on ' + 'your own tools, and watch a bigger one reason first with thinking ' + 'mode.', + duration: '56 min', level: 'Intermediate', - tags: ['function calling', 'tools', 'thinking mode'], + tags: ['function calling', 'tools', 'fine-tuning', 'thinking mode'], accent: Brand.green, + href: '/codelabs/function-calling-flutter-gemma', ), _Codelab( title: 'On-Device RAG in Flutter: Embeddings and Vector Search',