text
stringlengths
6
13.6M
id
stringlengths
13
176
metadata
dict
__index_level_0__
int64
0
1.69k
/* * Copyright 2019 The Chromium Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ package io.flutter.samples; import com.google.common.collect.Lists; import org.junit.Test; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; public class FlutterSampleNotificationProviderTest { @Test public void testContainsDartdocFlutterSample() { assertTrue(FlutterSampleNotificationProvider.containsDartdocFlutterSample( Lists.newArrayList("/// {@tool dartpad ...}"))); assertTrue(FlutterSampleNotificationProvider.containsDartdocFlutterSample( Lists.newArrayList("/// {@tool dartpad ...}"))); assertTrue(FlutterSampleNotificationProvider.containsDartdocFlutterSample( Lists.newArrayList("/// {@tool dartpad --template=stateless_widget_material}"))); assertTrue(FlutterSampleNotificationProvider.containsDartdocFlutterSample( Lists.newArrayList("/// {@tool --template=stateless_widget_material dartpad}"))); assertFalse(FlutterSampleNotificationProvider.containsDartdocFlutterSample( Lists.newArrayList("/// {tool dartpad ...}"))); assertFalse(FlutterSampleNotificationProvider.containsDartdocFlutterSample( Lists.newArrayList("/// {@tool dartpad ..."))); } }
flutter-intellij/flutter-idea/testSrc/unit/io/flutter/samples/FlutterSampleNotificationProviderTest.java/0
{ "file_path": "flutter-intellij/flutter-idea/testSrc/unit/io/flutter/samples/FlutterSampleNotificationProviderTest.java", "repo_id": "flutter-intellij", "token_count": 430 }
469
/* * Copyright 2021 The Chromium Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ package io.flutter.utils; import org.junit.Test; import java.awt.*; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class IconPreviewGeneratorTest { @Test @SuppressWarnings("ResultOfMethodCallIgnored") public void generateCupertino() throws IOException { final String fontPath = "testData/utils/CupertinoIcons.ttf"; final String propertiesPath = "testData/utils/cupertino.properties"; final Path tempDir = Files.createTempDirectory("preview"); final String outputPath = tempDir.toAbsolutePath().toString(); File preview = new File(outputPath); assertEquals(0, preview.list().length); IconPreviewGenerator ipg = new IconPreviewGenerator(fontPath, 16, 16, Color.black); ipg.batchConvert(outputPath, propertiesPath, ""); assertTrue(preview.exists()); assertTrue(preview.isDirectory()); final String[] list = preview.list(); assertEquals(1233, list.length); boolean found = false; // The list is not sorted and there's no need to sort it. // We just want to verify that a specific file exists. for (String each : list) { if (each.equals("add.png")) { found = true; break; } } assertTrue(found); for (File each : preview.listFiles()) { each.delete(); } preview.delete(); } }
flutter-intellij/flutter-idea/testSrc/unit/io/flutter/utils/IconPreviewGeneratorTest.java/0
{ "file_path": "flutter-intellij/flutter-idea/testSrc/unit/io/flutter/utils/IconPreviewGeneratorTest.java", "repo_id": "flutter-intellij", "token_count": 558 }
470
/* * Copyright (c) 2015, the Dart project authors. * * Licensed under the Eclipse Public License v1.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.eclipse.org/legal/epl-v10.html * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.dartlang.vm.service.element; // This file is generated by the script: pkg/vm_service/tool/generate.dart in dart-lang/sdk. import com.google.gson.JsonElement; import com.google.gson.JsonObject; /** * A {@link Breakpoint} describes a debugger breakpoint. */ @SuppressWarnings({"WeakerAccess", "unused"}) public class Breakpoint extends Obj { public Breakpoint(JsonObject json) { super(json); } /** * A number identifying this breakpoint to the user. */ public int getBreakpointNumber() { return getAsInt("breakpointNumber"); } /** * Is this breakpoint enabled? */ public boolean getEnabled() { return getAsBoolean("enabled"); } /** * Is this a breakpoint that was added synthetically as part of a step OverAsyncSuspension resume * command? * * Can return <code>null</code>. */ public boolean getIsSyntheticAsyncContinuation() { return getAsBoolean("isSyntheticAsyncContinuation"); } /** * SourceLocation when breakpoint is resolved, UnresolvedSourceLocation when a breakpoint is not * resolved. * * @return one of <code>SourceLocation</code> or <code>UnresolvedSourceLocation</code> */ public Object getLocation() { final JsonElement elem = json.get("location"); if (elem == null) return null; if (elem.isJsonObject()) { final JsonObject o = (JsonObject) elem; if (o.get("type").getAsString().equals("SourceLocation")) return new SourceLocation(o); if (o.get("type").getAsString().equals("UnresolvedSourceLocation")) return new UnresolvedSourceLocation(o); } return null; } /** * Has this breakpoint been assigned to a specific program location? */ public boolean getResolved() { return getAsBoolean("resolved"); } }
flutter-intellij/flutter-idea/third_party/vmServiceDrivers/org/dartlang/vm/service/element/Breakpoint.java/0
{ "file_path": "flutter-intellij/flutter-idea/third_party/vmServiceDrivers/org/dartlang/vm/service/element/Breakpoint.java", "repo_id": "flutter-intellij", "token_count": 740 }
471
package org.dartlang.vm.service.element; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonNull; import com.google.gson.JsonObject; import java.util.ArrayList; import java.util.List; /** * Superclass for all observatory elements. */ public class Element { protected final JsonObject json; public Element(JsonObject json) { this.json = json; } /** * A utility method to handle null values and JsonNull values. */ String getAsString(String name) { final JsonElement element = json.get(name); return (element == null || element == JsonNull.INSTANCE) ? null : element.getAsString(); } /** * A utility method to handle null values and JsonNull values. */ int getAsInt(String name) { final JsonElement element = json.get(name); return (element == null || element == JsonNull.INSTANCE) ? -1 : element.getAsInt(); } /** * A utility method to handle null values and JsonNull values. */ boolean getAsBoolean(String name) { final JsonElement element = json.get(name); return (element == null || element == JsonNull.INSTANCE) ? false : element.getAsBoolean(); } /** * Return the underlying JSON backing this element. */ public JsonObject getJson() { return json; } /** * Return a specific JSON member as a list of integers. */ List<Integer> getListInt(String memberName) { return jsonArrayToListInt(json.getAsJsonArray(memberName)); } /** * Return a specific JSON member as a list of strings. */ List<String> getListString(String memberName) { return jsonArrayToListString(json.getAsJsonArray(memberName)); } /** * Return a specific JSON member as a list of list of integers. */ List<List<Integer>> getListListInt(String memberName) { JsonArray array = json.getAsJsonArray(memberName); if (array == null) { return null; } int size = array.size(); List<List<Integer>> result = new ArrayList<>(); for (int index = 0; index < size; ++index) { result.add(jsonArrayToListInt(array.get(index).getAsJsonArray())); } return result; } private List<Integer> jsonArrayToListInt(JsonArray array) { int size = array.size(); List<Integer> result = new ArrayList<>(); for (int index = 0; index < size; ++index) { result.add(array.get(index).getAsInt()); } return result; } private List<String> jsonArrayToListString(JsonArray array) { int size = array.size(); List<String> result = new ArrayList<>(); for (int index = 0; index < size; ++index) { final JsonElement elem = array.get(index); result.add(elem == JsonNull.INSTANCE ? null : elem.getAsString()); } return result; } }
flutter-intellij/flutter-idea/third_party/vmServiceDrivers/org/dartlang/vm/service/element/Element.java/0
{ "file_path": "flutter-intellij/flutter-idea/third_party/vmServiceDrivers/org/dartlang/vm/service/element/Element.java", "repo_id": "flutter-intellij", "token_count": 960 }
472
/* * Copyright (c) 2015, the Dart project authors. * * Licensed under the Eclipse Public License v1.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.eclipse.org/legal/epl-v10.html * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.dartlang.vm.service.internal; import com.google.gson.JsonObject; import org.dartlang.vm.service.logging.Logging; /** * A {@link RequestSink} that reports with an error to each request. */ public class ErrorRequestSink implements RequestSink, VmServiceConst { /** * The {@link ResponseSink} to send error responses to. */ private final ResponseSink responseSink; private final String code; private final String message; public ErrorRequestSink(ResponseSink responseSink, String code, String message) { if (responseSink == null || code == null || message == null) { throw new IllegalArgumentException("Unexpected null argument: " + responseSink + " " + code + " " + message); } this.responseSink = responseSink; this.code = code; this.message = message; } @Override public void add(JsonObject request) { String id = request.getAsJsonPrimitive(ID).getAsString(); try { // TODO(danrubel) is this the correct format for an error response? JsonObject error = new JsonObject(); error.addProperty(CODE, code); error.addProperty(MESSAGE, message); JsonObject response = new JsonObject(); response.addProperty(ID, id); response.add(ERROR, error); responseSink.add(response); } catch (Throwable e) { Logging.getLogger().logError(e.getMessage(), e); } } @Override public void close() { } }
flutter-intellij/flutter-idea/third_party/vmServiceDrivers/org/dartlang/vm/service/internal/ErrorRequestSink.java/0
{ "file_path": "flutter-intellij/flutter-idea/third_party/vmServiceDrivers/org/dartlang/vm/service/internal/ErrorRequestSink.java", "repo_id": "flutter-intellij", "token_count": 653 }
473
/* * Copyright 2021 The Chromium Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ package io.flutter.utils; import static com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil.getChildren; import static com.intellij.openapi.util.text.StringUtil.isNotEmpty; import static java.util.Objects.requireNonNull; import com.android.tools.idea.gradle.dsl.model.BuildModelContext; import com.android.tools.idea.gradle.dsl.parser.elements.GradleDslElement; import com.android.tools.idea.gradle.dsl.parser.elements.GradleDslExpression; import com.android.tools.idea.gradle.dsl.parser.elements.GradleDslExpressionList; import com.android.tools.idea.gradle.dsl.parser.elements.GradleDslLiteral; import com.android.tools.idea.gradle.dsl.parser.files.GradleSettingsFile; import com.android.tools.idea.gradle.project.sync.GradleSyncState; import com.android.tools.idea.gradle.util.GradleProjectSystemUtil; import com.intellij.lang.java.JavaParserDefinition; import com.intellij.lexer.Lexer; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.externalSystem.model.DataNode; import com.intellij.openapi.externalSystem.model.ExternalProjectInfo; import com.intellij.openapi.externalSystem.model.ProjectKeys; import com.intellij.openapi.externalSystem.model.project.ModuleData; import com.intellij.openapi.externalSystem.model.project.ProjectData; import com.intellij.openapi.externalSystem.model.task.TaskData; import com.intellij.openapi.externalSystem.service.project.ProjectDataManager; import com.intellij.openapi.module.Module; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectType; import com.intellij.openapi.project.ProjectTypeService; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.io.FileUtilRt; import com.intellij.openapi.vfs.CharsetToolkit; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.pom.java.LanguageLevel; import com.intellij.psi.JavaTokenType; import com.intellij.psi.PsiElement; import com.intellij.psi.tree.java.IKeywordElementType; import com.intellij.util.ReflectionUtil; import com.intellij.util.WaitFor; import com.intellij.util.concurrency.AppExecutorUtil; import com.intellij.util.containers.MultiMap; import com.intellij.util.containers.WeakList; import com.jetbrains.lang.dart.sdk.DartSdkLibUtil; import io.flutter.FlutterUtils; import io.flutter.android.GradleSyncProvider; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.plugins.gradle.settings.GradleProjectSettings; import org.jetbrains.plugins.gradle.settings.GradleSettings; import org.jetbrains.plugins.gradle.util.GradleConstants; import java.io.*; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.nio.charset.StandardCharsets; import java.util.*; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Consumer; import java.util.stream.Stream; import static com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil.getChildren; import static com.intellij.openapi.util.text.StringUtil.isNotEmpty; import static java.util.Objects.requireNonNull; /* Add-to-app notes: - The Flutter module must be added to the Android app via manual editing as in the add-to-app docs, or by using the tool in Android Studio that generates a module and does the editing. - The Flutter module may be in a directory nested under the Android app or it may be in a different location entirely. IntelliJ supports both, and is moving toward the latter. - Enabling co-editing means converting the Flutter module to a Gradle module and adding it to the Android app as a sub-project. o If the parent of the Flutter module root directory is the Android app root directory, add "include ':flutterModule'" to the parent settings.gradle; otherwise something like what add-to-app does to define the :flutter module is needed. o Create a simple build.gradle in the Flutter module root directory. o Add Android-Gradle and Android facets to the Idea module of the Flutter module. */ public class GradleUtils { private static final String FLUTTER_PROJECT_NAME = ":" + AndroidUtils.FLUTTER_MODULE_NAME + ":"; private static final String FLUTTER_TASK_PREFIX = "compileFlutterBuild"; private static final WeakList<Project> COEDIT_TRANSFORMED_PROJECTS = new WeakList<>(); private static final int GRADLE_SYNC_TIMEOUT = 5 * 60 * 1000; // 5 minutes in millis. public static void addGradleListeners(@NotNull Project project) { if (!FlutterUtils.isAndroidStudio()) { // We're not supporting Gradle integration with IntelliJ currently, so these are disabled for now. // TODO(messick): Support Gradle in IntelliJ for add-to-app. //GradleSyncState.subscribe(project, new GradleSyncListener() { // @Override // public void syncSucceeded(@NotNull Project project) { // checkDartSupport(project); // if (isCoeditTransformedProject(project)) { // return; // } // enableCoeditIfAddToAppDetected(project); // } //}); //GradleBuildState.subscribe(project, new GradleBuildListener.Adapter() { // @Override // public void buildFinished(@NotNull BuildStatus status, @Nullable BuildContext context) { // checkDartSupport(project); // if (isCoeditTransformedProject(project)) { // return; // } // if (status == BuildStatus.SUCCESS && context != null && context.getGradleTasks().contains(":flutter:generateDebugSources")) { // enableCoeditIfAddToAppDetected(project); // } // } //}); } } public static void scheduleGradleSync(@NotNull Project project) { GradleSyncProvider provider = GradleSyncProvider.EP_NAME.getExtensionList().get(0); provider.scheduleSync(project); } public static void enableCoeditIfAddToAppDetected(@NotNull Project project) { if (isCoeditTransformedProject(project)) { return; } // After a Gradle sync has finished we check the tasks that were run to see if any belong to Flutter. Map<ProjectData, MultiMap<String, String>> tasks = getTasksMap(project); @NotNull String projectName = project.getName(); for (ProjectData projectData : tasks.keySet()) { MultiMap<String, String> map = tasks.get(projectData); Collection<String> col = map.get(FLUTTER_PROJECT_NAME); if (col.isEmpty()) { col = map.get(""); // Android Studio uses this. } if (!col.isEmpty()) { if (col.parallelStream().anyMatch((x) -> x.startsWith(FLUTTER_TASK_PREFIX))) { ApplicationManager.getApplication().invokeLater(() -> enableCoEditing(project)); } } } } private static void runAfterSyncFinishes(@NotNull Project project, @NotNull Consumer<Project> runnable) { new WaitFor(GRADLE_SYNC_TIMEOUT, () -> runnable.accept(project)) { @Override public boolean condition() { return !GradleSyncState.getInstance(project).isSyncInProgress(); } }; } public static void checkDartSupport(@NotNull Project project) { runAfterSyncFinishes(project, (p) -> { // Gradle sync-finished events are triggered before new modules have been committed. Once the condition // is met we still have to wait for a short while. AppExecutorUtil.getAppScheduledExecutorService().schedule(() -> { Stream<Module> modules = Arrays.stream(FlutterModuleUtils.getModules(p)).filter(FlutterModuleUtils::declaresFlutter); modules.forEach((module) -> { if (!DartSdkLibUtil.isDartSdkEnabled(module)) { new EnableDartSupportForModule(module).run(); } }); }, 1, TimeUnit.SECONDS); }); } private static boolean isVanillaAddToApp(@NotNull Project project, @Nullable VirtualFile file, @NotNull String name) { if (file == null) { return false; } VirtualFile dir = file.getParent(); if (dir.findChild(".ios") == null) { dir = dir.getParent(); } if (dir.getName().equals(".android")) { dir = dir.getParent(); } if (dir.findChild(".ios") == null && dir.findChild("ios") == null) { return false; } if (doesBuildFileExist(dir)) { return true; } GradleSettingsFile parsedSettings = parseSettings(project); if (parsedSettings == null) { return false; } // Check settings for "include :name". return findInclude(requireNonNull(parsedSettings), name) == null; } private static boolean doesBuildFileExist(VirtualFile dir) { return new File(dir.getPath(), SdkConstants.FN_BUILD_GRADLE).exists(); } @Nullable private static GradleSettingsFile parseSettings(Project project) { // Get the PSI for settings.gradle. In IntelliJ it is just this, but Android Studio uses a VirtualFile. //GradleSettingsFile parsedSettings = // BuildModelContext.create(project).getOrCreateSettingsFile(project); // We need to use reflection to create the expression so this code can be compiled (and run) in all the // code bases that are currently supported. boolean isAndroidStudio = FlutterUtils.isAndroidStudio(); VirtualFile projectDir = requireNonNull(FlutterUtils.getProjectRoot(project)); Object param = isAndroidStudio ? projectDir.findChild(SdkConstants.FN_SETTINGS_GRADLE) : project; if (param == null) { return null; } Method method = ReflectionUtil.getMethod(BuildModelContext.class, "getOrCreateSettingsFile", isAndroidStudio ? VirtualFile.class : Project.class); if (method == null) { return null; } try { return (GradleSettingsFile)method.invoke(makeBuildModelContext(project), param); } catch (InvocationTargetException | IllegalAccessException e) { return null; } } @SuppressWarnings("rawtypes") private static BuildModelContext makeBuildModelContext(Project project) { // return BuildModelContext.create(project); Method method = ReflectionUtil.getDeclaredMethod(BuildModelContext.class, "create", Project.class); if (method != null) { try { return (BuildModelContext)method.invoke(null, project); } catch (IllegalAccessException | InvocationTargetException e) { throw new RuntimeException(e); } } // If we get here we're using the 4.1 API. // return BuildModelContext.create(project, new AndroidLocationProvider()); Class locationProviderClass = AndroidLocationProvider.class.getInterfaces()[0]; // Class.forName("com.android.tools.idea.gradle.dsl.model.BuildModelContext.ResolvedConfigurationFileLocationProvider"); // does not work in the debugger. That's why we get it from the interfaces of AndroidLocationProvider. method = ReflectionUtil.getDeclaredMethod(BuildModelContext.class, "create", Project.class, locationProviderClass); assert method != null; try { return (BuildModelContext)method.invoke(null, project, new AndroidLocationProvider()); } catch (IllegalAccessException | InvocationTargetException e) { throw new RuntimeException(e); } } // The project is an Android project that contains a Flutter module. private static void enableCoEditing(@NotNull Project project) { Module module = FlutterUtils.findFlutterGradleModule(project); if (module == null) return; VirtualFile root = FlutterUtils.locateModuleRoot(module); if (root == null) return; VirtualFile androidDir = root.getParent(); VirtualFile flutterModuleDir = androidDir.getParent(); String flutterModuleName = flutterModuleDir.getName(); if (!isVanillaAddToApp(project, androidDir, flutterModuleName)) return; new CoEditHelper(project, flutterModuleDir).enable(); } private static void addCoeditTransformedProject(@NotNull Project project) { if (!project.isDisposed()) { COEDIT_TRANSFORMED_PROJECTS.add(project); } } private static boolean isCoeditTransformedProject(@NotNull Project project) { if (project.isDisposed()) { return true; } Iterator<Project> iter = COEDIT_TRANSFORMED_PROJECTS.iterator(); //noinspection WhileLoopReplaceableByForEach while (iter.hasNext()) { // See WeakList.iterator(). Project p = iter.next(); if (project.equals(p) && !p.isDisposed()) { return true; } } return false; } // Copied from org.jetbrains.plugins.gradle.execution.GradleRunAnythingProvider. @NotNull @SuppressWarnings("DuplicatedCode") private static Map<ProjectData, MultiMap<String, String>> getTasksMap(Project project) { Map<ProjectData, MultiMap<String, String>> tasks = new LinkedHashMap<>(); for (GradleProjectSettings setting : GradleSettings.getInstance(project).getLinkedProjectsSettings()) { final ExternalProjectInfo projectData = ProjectDataManager.getInstance().getExternalProjectData(project, GradleConstants.SYSTEM_ID, setting.getExternalProjectPath()); if (projectData == null || projectData.getExternalProjectStructure() == null) continue; MultiMap<String, String> projectTasks = MultiMap.createOrderedSet(); for (DataNode<ModuleData> moduleDataNode : getChildren(projectData.getExternalProjectStructure(), ProjectKeys.MODULE)) { String gradlePath; String moduleId = moduleDataNode.getData().getId(); if (moduleId.charAt(0) != ':') { int colonIndex = moduleId.indexOf(':'); gradlePath = colonIndex > 0 ? moduleId.substring(colonIndex) : ":"; } else { gradlePath = moduleId; } for (DataNode<TaskData> node : getChildren(moduleDataNode, ProjectKeys.TASK)) { TaskData taskData = node.getData(); String taskName = taskData.getName(); if (isNotEmpty(taskName)) { String taskPathPrefix = ":".equals(gradlePath) || taskName.startsWith(gradlePath) ? "" : (gradlePath + ':'); projectTasks.putValue(taskPathPrefix, taskName); } } } tasks.put(projectData.getExternalProjectStructure().getData(), projectTasks); } return tasks; } @Nullable private static PsiElement findInclude(GradleSettingsFile parsedSettings, String name) { Map<String, GradleDslElement> elements = parsedSettings.getPropertyElements(); GradleDslElement includes = elements.get("include"); if (includes == null) { return null; } for (GradleDslElement include : includes.getChildren()) { if (include instanceof GradleDslExpressionList) { for (GradleDslExpression expr : ((GradleDslExpressionList)include).getExpressions()) { if (expr instanceof GradleDslLiteral) { PsiElement lit = expr.getExpression(); if (matchesName(lit, name)) { return lit; } } } } if (include instanceof GradleDslLiteral) { PsiElement expr = ((GradleDslLiteral)include).getExpression(); if (matchesName(expr, name)) { return expr; } } } return null; } private static boolean matchesName(PsiElement expr, String name) { if (expr == null) return false; String text = expr.getText(); return name.equals(text.substring(2, text.length() - 1)); } private static class CoEditHelper { // TODO(messick) Rewrite this to use ProjectBuildModel. See FlutterModuleImporter for an example. @NotNull private final Project project; @NotNull private VirtualFile flutterModuleDir; @NotNull private final File flutterModuleRoot; @NotNull private final String flutterModuleName; private boolean hasIncludeFlutterModuleStatement; private boolean buildFileIsValid; private boolean inSameDir; private VirtualFile buildFile; private VirtualFile settingsFile; private VirtualFile projectRoot; private String pathToModule; private AtomicBoolean errorDuringOperation = new AtomicBoolean(false); private CoEditHelper(@NotNull Project project, @NotNull VirtualFile flutterModuleDir) { this.project = project; this.flutterModuleDir = flutterModuleDir; this.flutterModuleRoot = new File(flutterModuleDir.getPath()); this.flutterModuleName = flutterModuleDir.getName(); } private void enable() { // Look for "include ':flutterModuleName'". If not found, add it and create build.gradle in the Flutter module. Then sync. if (verifyEligibility()) { makeBuildFile(); if (errorDuringOperation.get()) return; addIncludeStatement(); if (errorDuringOperation.get()) return; addCoeditTransformedProject(project); // We may have multiple Gradle sync listeners. Write the files to disk synchronously so we won't edit them twice. projectRoot.refresh(false, true); if (!projectRoot.equals(flutterModuleDir.getParent())) { flutterModuleDir.refresh(false, true); } AppExecutorUtil.getAppExecutorService().execute(() -> scheduleGradleSyncAfterSyncFinishes(project)); } } private static void scheduleGradleSyncAfterSyncFinishes(@NotNull Project project) { runAfterSyncFinishes(project, (p) -> scheduleGradleSync((project))); } private boolean verifyEligibility() { projectRoot = FlutterUtils.getProjectRoot(project); requireNonNull(projectRoot); settingsFile = projectRoot.findChild(SdkConstants.FN_SETTINGS_GRADLE); if (settingsFile == null) { return false; } GradleSettingsFile parsedSettings = parseSettings(project); if (parsedSettings == null) { return false; } PsiElement includeFlutterModuleStmt = findInclude(parsedSettings, flutterModuleName); hasIncludeFlutterModuleStatement = includeFlutterModuleStmt != null; buildFile = GradleProjectSystemUtil.getGradleBuildFile(flutterModuleRoot); buildFileIsValid = buildFile != null && doesBuildFileExist(flutterModuleDir) && buildFile.getLength() > 0; return !(hasIncludeFlutterModuleStatement && buildFileIsValid); } private void makeBuildFile() { if (buildFileIsValid) { return; } createBuildFile(); if (errorDuringOperation.get()) return; writeBuildFile(); } private void createBuildFile() { ApplicationManager.getApplication().runWriteAction(() -> { try { buildFile = flutterModuleDir.findOrCreateChildData(this, SdkConstants.FN_BUILD_GRADLE); } catch (IOException e) { cleanupAfterError(); } }); } private void writeBuildFile() { ApplicationManager.getApplication().runWriteAction(() -> { try (OutputStream out = new BufferedOutputStream(buildFile.getOutputStream(this))) { out.write("buildscript {}".getBytes(StandardCharsets.UTF_8)); } catch (IOException ex) { cleanupAfterError(); } }); } private void addIncludeStatement() { if (hasIncludeFlutterModuleStatement) { return; } String originalContent = readSettingsFile(); if (errorDuringOperation.get()) return; String newContent = addStatements(originalContent); //if (errorDuringOperation.get()) return; writeSettingsFile(newContent, originalContent); } private String readSettingsFile() { inSameDir = flutterModuleDir.getParent().equals(projectRoot); pathToModule = FileUtilRt.getRelativePath(new File(projectRoot.getPath()), flutterModuleRoot); try { requireNonNull(pathToModule); requireNonNull(settingsFile); @SuppressWarnings({"IOResourceOpenedButNotSafelyClosed", "resource"}) BufferedInputStream str = new BufferedInputStream(settingsFile.getInputStream()); return FileUtil.loadTextAndClose(new InputStreamReader(str, CharsetToolkit.UTF8_CHARSET)); } catch (NullPointerException | IOException e) { cleanupAfterError(); } return ""; } public String addStatements(String originalContent) { StringBuilder content = new StringBuilder(); content.append(originalContent); content.append('\n'); content.append("include ':"); content.append(flutterModuleName); content.append("'\n"); // project(':flutter').projectDir = new File('pathToModule') if (!inSameDir) { content.append("project(':"); content.append(flutterModuleName); content.append("').projectDir = new File('"); content.append(FileUtil.normalize(pathToModule)); content.append("')\n"); } return content.toString(); } private void writeSettingsFile(String newContent, String originalContent) { ApplicationManager.getApplication().runWriteAction(() -> { try (OutputStream out = new BufferedOutputStream(settingsFile.getOutputStream(this))) { out.write(newContent.getBytes(StandardCharsets.UTF_8)); } catch (IOException ex) { cleanupAfterError(); try (OutputStream out = new BufferedOutputStream(settingsFile.getOutputStream(this))) { out.write(originalContent.getBytes(StandardCharsets.UTF_8)); } catch (IOException ignored) { } } }); } private void cleanupAfterError() { errorDuringOperation.set(true); addCoeditTransformedProject(project); try { if (buildFile != null) { buildFile.delete(this); } } catch (IOException ignored) { } } } } class SdkConstants { /** * An SDK Project's build.gradle file */ public static final String FN_BUILD_GRADLE = "build.gradle"; /** * An SDK Project's settings.gradle file */ public static final String FN_SETTINGS_GRADLE = "settings.gradle"; }
flutter-intellij/flutter-studio/src/io/flutter/utils/GradleUtils.java/0
{ "file_path": "flutter-intellij/flutter-studio/src/io/flutter/utils/GradleUtils.java", "repo_id": "flutter-intellij", "token_count": 7925 }
474
/* * Copyright 2017 The Chromium Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ package io.flutter.tests.gui; import static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.assertEquals; import com.android.tools.idea.tests.gui.framework.FlutterGuiTestRule; import com.android.tools.idea.tests.gui.framework.fixture.EditorFixture; import com.android.tools.idea.tests.gui.framework.fixture.newProjectWizard.FlutterProjectStepFixture; import com.android.tools.idea.tests.gui.framework.fixture.newProjectWizard.FlutterSettingsStepFixture; import com.android.tools.idea.tests.gui.framework.fixture.newProjectWizard.NewFlutterProjectWizardFixture; import io.flutter.module.FlutterProjectType; import io.flutter.tests.util.WizardUtils; import org.fest.swing.exception.WaitTimedOutError; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; /** * As long as the wizard is working properly the error checks * in FlutterProjectCreator will never be triggered. That leaves * quite a few lines untested. It currently has 79% coverage. * <p> * The "Install SDK" button of FlutterProjectStep is not tested. * It has 86% coverage currently, and most of the untested code * is part of the installer implementation. * <p> * If flakey tests are found try adjusting these settings: * Settings festSettings = myGuiTest.robot().settings(); * festSettings.delayBetweenEvents(50); // 30 * festSettings.eventPostingDelay(150); // 100 */ @RunWith(NewModuleTest.GuiTestRemoteRunner.class)//@RunWith(GuiTestSuiteRunner.class) public class NewProjectTest { @Rule public final FlutterGuiTestRule myGuiTest = new FlutterGuiTestRule(); @Test public void createNewProjectWithDefaults() { NewFlutterProjectWizardFixture wizard = myGuiTest.welcomeFrame().createNewProject(); try { wizard.clickNext().clickNext().clickFinish(); myGuiTest.waitForBackgroundTasks(); myGuiTest.ideFrame().waitForProjectSyncToFinish(); } catch (Exception ex) { // If this happens to be the first test run in a suite then there will be no SDK and it times out. assertThat(ex.getClass()).isAssignableTo(WaitTimedOutError.class); assertThat(ex.getMessage()).isEqualTo("Timed out waiting for matching JButton"); wizard.clickCancel(); } } @Test public void createNewApplicationWithDefaults() { WizardUtils.createNewApplication(myGuiTest); EditorFixture editor = myGuiTest.ideFrame().getEditor(); editor.waitUntilErrorAnalysisFinishes(); String expected = "import 'package:flutter/material.dart';\n" + "\n" + "void main() => runApp(MyApp());\n"; assertEquals(expected, editor.getCurrentFileContents().substring(0, expected.length())); } @Test public void createNewModuleWithDefaults() { WizardUtils.createNewModule(myGuiTest); EditorFixture editor = myGuiTest.ideFrame().getEditor(); editor.waitUntilErrorAnalysisFinishes(); String expected = "import 'package:flutter/material.dart';\n" + "\n" + "void main() => runApp(MyApp());\n"; assertEquals(expected, editor.getCurrentFileContents().substring(0, expected.length())); } @Test public void createNewPackageWithDefaults() { WizardUtils.createNewPackage(myGuiTest); EditorFixture editor = myGuiTest.ideFrame().getEditor(); editor.waitUntilErrorAnalysisFinishes(); String expected = "# flutterpackage\n" + "\n" + "A new Flutter package.\n" + "\n" + "## Getting Started\n" + "\n" + "This project is a starting point for a Dart\n" + "[package]"; assertEquals(expected, editor.getCurrentFileContents().substring(0, expected.length())); } @Test public void createNewPluginWithDefaults() { WizardUtils.createNewPlugin(myGuiTest); EditorFixture editor = myGuiTest.ideFrame().getEditor(); editor.waitUntilErrorAnalysisFinishes(); String expected = "import 'dart:async';\n" + "\n" + "import 'package:flutter/services.dart';\n" + "\n" + "class Flutterplugin"; assertEquals(expected, editor.getCurrentFileContents().substring(0, expected.length())); } @Test public void checkPersistentState() { FlutterProjectType type = FlutterProjectType.APP; WizardUtils.createNewProject(myGuiTest, type, "super_tron", "A super fancy tron", "com.google.super_tron", true, true); EditorFixture editor = myGuiTest.ideFrame().getEditor(); editor.waitUntilErrorAnalysisFinishes(); myGuiTest.ideFrame().invokeMenuPath("File", "New", "New Flutter Project..."); NewFlutterProjectWizardFixture wizard = myGuiTest.ideFrame().findNewProjectWizard(); wizard.chooseProjectType("Flutter Application").clickNext(); FlutterProjectStepFixture projectStep = wizard.getFlutterProjectStep(type); assertThat(projectStep.getProjectName()).isEqualTo("flutter_app"); // Not persisting assertThat(projectStep.getSdkPath()).isNotEmpty(); // Persisting assertThat(projectStep.getProjectLocation()).endsWith("checkPersistentState"); // Not persisting assertThat(projectStep.getDescription()).isEqualTo("A new Flutter application."); // Not persisting wizard.clickNext(); FlutterSettingsStepFixture settingsStep = wizard.getFlutterSettingsStep(); assertThat(settingsStep.getPackageName()).isEqualTo("com.google.flutterapp"); // Partially persisting settingsStep.getKotlinFixture().requireSelected(); // Persisting settingsStep.getSwiftFixture().requireSelected(); // Persisting settingsStep.getKotlinFixture().setSelected(false); wizard.clickCancel(); myGuiTest.ideFrame().invokeMenuPath("File", "New", "New Flutter Project..."); wizard = myGuiTest.ideFrame().findNewProjectWizard(); wizard.chooseProjectType("Flutter Application").clickNext(); wizard.clickNext(); settingsStep = wizard.getFlutterSettingsStep(); settingsStep.getKotlinFixture().requireNotSelected(); // Persisting settingsStep.getSwiftFixture().requireSelected(); // Independent of Kotlin wizard.clickCancel(); myGuiTest.ideFrame().invokeMenuPath("File", "New", "New Flutter Project..."); wizard = myGuiTest.ideFrame().findNewProjectWizard(); wizard.chooseProjectType("Flutter Application").clickNext(); projectStep = wizard.getFlutterProjectStep(type); projectStep.enterProjectLocation("/"); assertThat(projectStep.getErrorMessage()).contains("location"); wizard.clickCancel(); } }
flutter-intellij/flutter-studio/testSrc/io/flutter/tests/gui/NewProjectTest.java/0
{ "file_path": "flutter-intellij/flutter-studio/testSrc/io/flutter/tests/gui/NewProjectTest.java", "repo_id": "flutter-intellij", "token_count": 2183 }
475
<!-- Defines IDEA IDE-specific contributions and implementations. --> <idea-plugin> <extensions defaultExtensionNs="com.intellij"> <editorNotificationProvider implementation="io.flutter.inspections.IncompatibleDartPluginNotificationProvider"/> </extensions> </idea-plugin>
flutter-intellij/resources/META-INF/idea-contribs.xml/0
{ "file_path": "flutter-intellij/resources/META-INF/idea-contribs.xml", "repo_id": "flutter-intellij", "token_count": 80 }
476
# Generated file - do not edit. # suppress inspection "UnusedProperty" for whole file amber.primary=ffffc107 amber[50]=fffff8e1 amber[100]=ffffecb3 amber[200]=ffffe082 amber[300]=ffffd54f amber[400]=ffffca28 amber[500]=ffffc107 amber[600]=ffffb300 amber[700]=ffffa000 amber[800]=ffff8f00 amber[900]=ffff6f00 amberAccent.primary=ffffd740 amberAccent[100]=ffffe57f amberAccent[200]=ffffd740 amberAccent[400]=ffffc400 amberAccent[700]=ffffab00 black=ff000000 black12=1f000000 black26=42000000 black38=61000000 black45=73000000 black54=8a000000 black87=dd000000 blue.primary=ff2196f3 blue[50]=ffe3f2fd blue[100]=ffbbdefb blue[200]=ff90caf9 blue[300]=ff64b5f6 blue[400]=ff42a5f5 blue[500]=ff2196f3 blue[600]=ff1e88e5 blue[700]=ff1976d2 blue[800]=ff1565c0 blue[900]=ff0d47a1 blueAccent.primary=ff448aff blueAccent[100]=ff82b1ff blueAccent[200]=ff448aff blueAccent[400]=ff2979ff blueAccent[700]=ff2962ff blueGrey.primary=ff607d8b blueGrey[50]=ffeceff1 blueGrey[100]=ffcfd8dc blueGrey[200]=ffb0bec5 blueGrey[300]=ff90a4ae blueGrey[400]=ff78909c blueGrey[500]=ff607d8b blueGrey[600]=ff546e7a blueGrey[700]=ff455a64 blueGrey[800]=ff37474f blueGrey[900]=ff263238 brown.primary=ff795548 brown[50]=ffefebe9 brown[100]=ffd7ccc8 brown[200]=ffbcaaa4 brown[300]=ffa1887f brown[400]=ff8d6e63 brown[500]=ff795548 brown[600]=ff6d4c41 brown[700]=ff5d4037 brown[800]=ff4e342e brown[900]=ff3e2723 cyan.primary=ff00bcd4 cyan[50]=ffe0f7fa cyan[100]=ffb2ebf2 cyan[200]=ff80deea cyan[300]=ff4dd0e1 cyan[400]=ff26c6da cyan[500]=ff00bcd4 cyan[600]=ff00acc1 cyan[700]=ff0097a7 cyan[800]=ff00838f cyan[900]=ff006064 cyanAccent.primary=ff18ffff cyanAccent[100]=ff84ffff cyanAccent[200]=ff18ffff cyanAccent[400]=ff00e5ff cyanAccent[700]=ff00b8d4 deepOrange.primary=ffff5722 deepOrange[50]=fffbe9e7 deepOrange[100]=ffffccbc deepOrange[200]=ffffab91 deepOrange[300]=ffff8a65 deepOrange[400]=ffff7043 deepOrange[500]=ffff5722 deepOrange[600]=fff4511e deepOrange[700]=ffe64a19 deepOrange[800]=ffd84315 deepOrange[900]=ffbf360c deepOrangeAccent.primary=ffff6e40 deepOrangeAccent[100]=ffff9e80 deepOrangeAccent[200]=ffff6e40 deepOrangeAccent[400]=ffff3d00 deepOrangeAccent[700]=ffdd2c00 deepPurple.primary=ff673ab7 deepPurple[50]=ffede7f6 deepPurple[100]=ffd1c4e9 deepPurple[200]=ffb39ddb deepPurple[300]=ff9575cd deepPurple[400]=ff7e57c2 deepPurple[500]=ff673ab7 deepPurple[600]=ff5e35b1 deepPurple[700]=ff512da8 deepPurple[800]=ff4527a0 deepPurple[900]=ff311b92 deepPurpleAccent.primary=ff7c4dff deepPurpleAccent[100]=ffb388ff deepPurpleAccent[200]=ff7c4dff deepPurpleAccent[400]=ff651fff deepPurpleAccent[700]=ff6200ea green.primary=ff4caf50 green[50]=ffe8f5e9 green[100]=ffc8e6c9 green[200]=ffa5d6a7 green[300]=ff81c784 green[400]=ff66bb6a green[500]=ff4caf50 green[600]=ff43a047 green[700]=ff388e3c green[800]=ff2e7d32 green[900]=ff1b5e20 greenAccent.primary=ff69f0ae greenAccent[100]=ffb9f6ca greenAccent[200]=ff69f0ae greenAccent[400]=ff00e676 greenAccent[700]=ff00c853 grey.primary=ff9e9e9e grey[50]=fffafafa grey[100]=fff5f5f5 grey[200]=ffeeeeee grey[300]=ffe0e0e0 grey[350]=ffd6d6d6 grey[400]=ffbdbdbd grey[500]=ff9e9e9e grey[600]=ff757575 grey[700]=ff616161 grey[800]=ff424242 grey[850]=ff303030 grey[900]=ff212121 indigo.primary=ff3f51b5 indigo[50]=ffe8eaf6 indigo[100]=ffc5cae9 indigo[200]=ff9fa8da indigo[300]=ff7986cb indigo[400]=ff5c6bc0 indigo[500]=ff3f51b5 indigo[600]=ff3949ab indigo[700]=ff303f9f indigo[800]=ff283593 indigo[900]=ff1a237e indigoAccent.primary=ff536dfe indigoAccent[100]=ff8c9eff indigoAccent[200]=ff536dfe indigoAccent[400]=ff3d5afe indigoAccent[700]=ff304ffe lightBlue.primary=ff03a9f4 lightBlue[50]=ffe1f5fe lightBlue[100]=ffb3e5fc lightBlue[200]=ff81d4fa lightBlue[300]=ff4fc3f7 lightBlue[400]=ff29b6f6 lightBlue[500]=ff03a9f4 lightBlue[600]=ff039be5 lightBlue[700]=ff0288d1 lightBlue[800]=ff0277bd lightBlue[900]=ff01579b lightBlueAccent.primary=ff40c4ff lightBlueAccent[100]=ff80d8ff lightBlueAccent[200]=ff40c4ff lightBlueAccent[400]=ff00b0ff lightBlueAccent[700]=ff0091ea lightGreen.primary=ff8bc34a lightGreen[50]=fff1f8e9 lightGreen[100]=ffdcedc8 lightGreen[200]=ffc5e1a5 lightGreen[300]=ffaed581 lightGreen[400]=ff9ccc65 lightGreen[500]=ff8bc34a lightGreen[600]=ff7cb342 lightGreen[700]=ff689f38 lightGreen[800]=ff558b2f lightGreen[900]=ff33691e lightGreenAccent.primary=ffb2ff59 lightGreenAccent[100]=ffccff90 lightGreenAccent[200]=ffb2ff59 lightGreenAccent[400]=ff76ff03 lightGreenAccent[700]=ff64dd17 lime.primary=ffcddc39 lime[50]=fff9fbe7 lime[100]=fff0f4c3 lime[200]=ffe6ee9c lime[300]=ffdce775 lime[400]=ffd4e157 lime[500]=ffcddc39 lime[600]=ffc0ca33 lime[700]=ffafb42b lime[800]=ff9e9d24 lime[900]=ff827717 limeAccent.primary=ffeeff41 limeAccent[100]=fff4ff81 limeAccent[200]=ffeeff41 limeAccent[400]=ffc6ff00 limeAccent[700]=ffaeea00 orange.primary=ffff9800 orange[50]=fffff3e0 orange[100]=ffffe0b2 orange[200]=ffffcc80 orange[300]=ffffb74d orange[400]=ffffa726 orange[500]=ffff9800 orange[600]=fffb8c00 orange[700]=fff57c00 orange[800]=ffef6c00 orange[900]=ffe65100 orangeAccent.primary=ffffab40 orangeAccent[100]=ffffd180 orangeAccent[200]=ffffab40 orangeAccent[400]=ffff9100 orangeAccent[700]=ffff6d00 pink.primary=ffe91e63 pink[50]=fffce4ec pink[100]=fff8bbd0 pink[200]=fff48fb1 pink[300]=fff06292 pink[400]=ffec407a pink[500]=ffe91e63 pink[600]=ffd81b60 pink[700]=ffc2185b pink[800]=ffad1457 pink[900]=ff880e4f pinkAccent.primary=ffff4081 pinkAccent[100]=ffff80ab pinkAccent[200]=ffff4081 pinkAccent[400]=fff50057 pinkAccent[700]=ffc51162 purple.primary=ff9c27b0 purple[50]=fff3e5f5 purple[100]=ffe1bee7 purple[200]=ffce93d8 purple[300]=ffba68c8 purple[400]=ffab47bc purple[500]=ff9c27b0 purple[600]=ff8e24aa purple[700]=ff7b1fa2 purple[800]=ff6a1b9a purple[900]=ff4a148c purpleAccent.primary=ffe040fb purpleAccent[100]=ffea80fc purpleAccent[200]=ffe040fb purpleAccent[400]=ffd500f9 purpleAccent[700]=ffaa00ff red.primary=fff44336 red[50]=ffffebee red[100]=ffffcdd2 red[200]=ffef9a9a red[300]=ffe57373 red[400]=ffef5350 red[500]=fff44336 red[600]=ffe53935 red[700]=ffd32f2f red[800]=ffc62828 red[900]=ffb71c1c redAccent.primary=ffff5252 redAccent[100]=ffff8a80 redAccent[200]=ffff5252 redAccent[400]=ffff1744 redAccent[700]=ffd50000 teal.primary=ff009688 teal[50]=ffe0f2f1 teal[100]=ffb2dfdb teal[200]=ff80cbc4 teal[300]=ff4db6ac teal[400]=ff26a69a teal[500]=ff009688 teal[600]=ff00897b teal[700]=ff00796b teal[800]=ff00695c teal[900]=ff004d40 tealAccent.primary=ff64ffda tealAccent[100]=ffa7ffeb tealAccent[200]=ff64ffda tealAccent[400]=ff1de9b6 tealAccent[700]=ff00bfa5 transparent=00000000 white=ffffffff white10=1affffff white12=1fffffff white24=3dffffff white30=4dffffff white38=62ffffff white54=8affffff white60=99ffffff white70=b3ffffff yellow.primary=ffffeb3b yellow[50]=fffffde7 yellow[100]=fffff9c4 yellow[200]=fffff59d yellow[300]=fffff176 yellow[400]=ffffee58 yellow[500]=ffffeb3b yellow[600]=fffdd835 yellow[700]=fffbc02d yellow[800]=fff9a825 yellow[900]=fff57f17 yellowAccent.primary=ffffff00 yellowAccent[100]=ffffff8d yellowAccent[200]=ffffff00 yellowAccent[400]=ffffea00 yellowAccent[700]=ffffd600
flutter-intellij/resources/flutter/colors/material.properties/0
{ "file_path": "flutter-intellij/resources/flutter/colors/material.properties", "repo_id": "flutter-intellij", "token_count": 3222 }
477
<toolSet name="External Tools"> <tool name="Provision" showInMainMenu="false" showInEditor="false" showInProject="false" showInSearchPopup="false" disabled="false" useConsole="true" showConsoleOnStdOut="false" showConsoleOnStdErr="false" synchronizeAfterRun="true"> <exec> <option name="COMMAND" value="/bin/bash" /> <option name="PARAMETERS" value="bin/plugin test -s" /> <option name="WORKING_DIRECTORY" value="$ProjectFileDir$" /> </exec> </tool> </toolSet>
flutter-intellij/resources/intellij/External Tools.xml/0
{ "file_path": "flutter-intellij/resources/intellij/External Tools.xml", "repo_id": "flutter-intellij", "token_count": 175 }
478
#!/bin/sh # # Copyright © 2015-2021 the original authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ############################################################################## # # Gradle start up script for POSIX generated by Gradle. # # Important for running: # # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is # noncompliant, but you have some other compliant shell such as ksh or # bash, then to run this script, type that shell name before the whole # command line, like: # # ksh Gradle # # Busybox and similar reduced shells will NOT work, because this script # requires all of these POSIX shell features: # * functions; # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», # «${var#prefix}», «${var%suffix}», and «$( cmd )»; # * compound commands having a testable exit status, especially «case»; # * various built-in commands including «command», «set», and «ulimit». # # Important for patching: # # (2) This script targets any POSIX shell, so it avoids extensions provided # by Bash, Ksh, etc; in particular arrays are avoided. # # The "traditional" practice of packing multiple parameters into a # space-separated string is a well documented source of bugs and security # problems, so this is (mostly) avoided, by progressively accumulating # options in "$@", and eventually passing that to Java. # # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; # see the in-line comments for details. # # There are tweaks for specific operating systems such as AIX, CygWin, # Darwin, MinGW, and NonStop. # # (3) This script is generated from the Groovy template # https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt # within the Gradle project. # # You can find Gradle at https://github.com/gradle/gradle/. # ############################################################################## # Attempt to set APP_HOME # Resolve links: $0 may be a link app_path=$0 # Need this for daisy-chained symlinks. while APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path [ -h "$app_path" ] do ls=$( ls -ld "$app_path" ) link=${ls#*' -> '} case $link in #( /*) app_path=$link ;; #( *) app_path=$APP_HOME$link ;; esac done APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit APP_NAME="Gradle" APP_BASE_NAME=${0##*/} # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD=maximum warn () { echo "$*" } >&2 die () { echo echo "$*" echo exit 1 } >&2 # OS specific support (must be 'true' or 'false'). cygwin=false msys=false darwin=false nonstop=false case "$( uname )" in #( CYGWIN* ) cygwin=true ;; #( Darwin* ) darwin=true ;; #( MSYS* | MINGW* ) msys=true ;; #( NONSTOP* ) nonstop=true ;; esac CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar # Determine the Java command to use to start the JVM. if [ -n "$JAVA_HOME" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then # IBM's JDK on AIX uses strange locations for the executables JAVACMD=$JAVA_HOME/jre/sh/java else JAVACMD=$JAVA_HOME/bin/java fi if [ ! -x "$JAVACMD" ] ; then die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi else JAVACMD=java which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi # Increase the maximum file descriptors if we can. if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then case $MAX_FD in #( max*) MAX_FD=$( ulimit -H -n ) || warn "Could not query maximum file descriptor limit" esac case $MAX_FD in #( '' | soft) :;; #( *) ulimit -n "$MAX_FD" || warn "Could not set maximum file descriptor limit to $MAX_FD" esac fi # Collect all arguments for the java command, stacking in reverse order: # * args from the command line # * the main class name # * -classpath # * -D...appname settings # * --module-path (only if needed) # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. # For Cygwin or MSYS, switch paths to Windows format before running java if "$cygwin" || "$msys" ; then APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) JAVACMD=$( cygpath --unix "$JAVACMD" ) # Now convert the arguments - kludge to limit ourselves to /bin/sh for arg do if case $arg in #( -*) false ;; # don't mess with options #( /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath [ -e "$t" ] ;; #( *) false ;; esac then arg=$( cygpath --path --ignore --mixed "$arg" ) fi # Roll the args list around exactly as many times as the number of # args, so each arg winds up back in the position where it started, but # possibly modified. # # NB: a `for` loop captures its iteration list before it begins, so # changing the positional parameters here affects neither the number of # iterations, nor the values presented in `arg`. shift # remove old arg set -- "$@" "$arg" # push replacement arg done fi # Collect all arguments for the java command; # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of # shell script including quotes and variable substitutions, so put them in # double quotes to make sure that they get re-expanded; and # * put everything else in single quotes, so that it's not re-expanded. set -- \ "-Dorg.gradle.appname=$APP_BASE_NAME" \ -classpath "$CLASSPATH" \ org.gradle.wrapper.GradleWrapperMain \ "$@" # Stop when "xargs" is not available. if ! command -v xargs >/dev/null 2>&1 then die "xargs is not available" fi # Use "xargs" to parse quoted args. # # With -n1 it outputs one arg per line, with the quotes and backslashes removed. # # In Bash we could simply go: # # readarray ARGS < <( xargs -n1 <<<"$var" ) && # set -- "${ARGS[@]}" "$@" # # but POSIX shell has neither arrays nor command substitution, so instead we # post-process each arg (as a line of input to sed) to backslash-escape any # character that might be a shell metacharacter, then use eval to reverse # that process (while maintaining the separation between arguments), and wrap # the whole thing up as a single "set" statement. # # This will of course break if any of these variables contains a newline or # an unmatched quote. # eval "set -- $( printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | xargs -n1 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | tr '\n' ' ' )" '"$@"' exec "$JAVACMD" "$@"
flutter-intellij/third_party/gradlew/0
{ "file_path": "flutter-intellij/third_party/gradlew", "repo_id": "flutter-intellij", "token_count": 3204 }
479
include: package:lints/recommended.yaml linter: rules: - directives_ordering - unawaited_futures
flutter-intellij/tool/plugin/analysis_options.yaml/0
{ "file_path": "flutter-intellij/tool/plugin/analysis_options.yaml", "repo_id": "flutter-intellij", "token_count": 41 }
480
## Flutter SDK dependency versions The files in this directory specifies pinned versions of various dependencies of the flutter SDK. The `bin/internal/engine.version` file controls which version of the Flutter engine to use. The file contains the commit hash of a commit in the <https://github.com/flutter/engine> repository. That hash must have successfully been compiled on <https://build.chromium.org/p/client.flutter/> and had its artifacts (the binaries that run on Android and iOS, the compiler, etc) successfully uploaded to Google Cloud Storage. The `/bin/internal/engine.merge_method` file controls how we merge a pull request created by the engine auto-roller. If it's `squash`, there's only one commit for a pull request no matter how many engine commits there are inside that pull request. If it's `rebase`, the number of commits in the framework is equal to the number of engine commits in the pull request. The latter method makes it easier to detect regressions but costs more test resources. The `bin/internal/flutter_packages.version` file specifies the version of the `flutter/packages` repository to be used for testing. The `flutter/packages` repository isn't an upstream dependency of `flutter/flutter`; it is only used as part of the test suite for verification, and the pinned version here makes sure that tests are deterministic at each `flutter/flutter` commit.
flutter/bin/internal/README.md/0
{ "file_path": "flutter/bin/internal/README.md", "repo_id": "flutter", "token_count": 346 }
481
#!/usr/bin/env bash # Copyright 2014 The Flutter Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # ---------------------------------- NOTE ---------------------------------- # # # Please keep the logic in this file consistent with the logic in the # `shared.bat` script in the same directory to ensure that Flutter & Dart continue # to work across all platforms! # # -------------------------------------------------------------------------- # set -e # Needed because if it is set, cd may print the path it changed to. unset CDPATH function pub_upgrade_with_retry { local total_tries="10" local remaining_tries=$((total_tries - 1)) while [[ "$remaining_tries" -gt 0 ]]; do (cd "$FLUTTER_TOOLS_DIR" && "$DART" pub upgrade --suppress-analytics) && break >&2 echo "Error: Unable to 'pub upgrade' flutter tool. Retrying in five seconds... ($remaining_tries tries left)" remaining_tries=$((remaining_tries - 1)) sleep 5 done if [[ "$remaining_tries" == 0 ]]; then >&2 echo "Command 'pub upgrade' still failed after $total_tries tries, giving up." return 1 fi return 0 } # Trap function for removing any remaining lock file at exit. function _rmlock () { [ -n "$FLUTTER_UPGRADE_LOCK" ] && rm -rf "$FLUTTER_UPGRADE_LOCK" } # Determines which lock method to use, based on what is available on the system. # Returns a non-zero value if the lock was not acquired, zero if acquired. function _lock () { if hash flock 2>/dev/null; then flock --nonblock --exclusive 7 2>/dev/null elif hash shlock 2>/dev/null; then shlock -f "$1" -p $$ else mkdir "$1" 2>/dev/null fi } # Waits for an update lock to be acquired. # # To ensure that we don't simultaneously update Dart in multiple parallel # instances, we try to obtain an exclusive lock on this file descriptor (and # thus this script's source file) while we are updating Dart and compiling the # script. To do this, we try to use the command line program "flock", which is # available on many Unix-like platforms, in particular on most Linux # distributions. You give it a file descriptor, and it locks the corresponding # file, having inherited the file descriptor from the shell. # # Complicating matters, there are two major scenarios where this will not # work. # # The first is if the platform doesn't have "flock", for example on macOS. There # is not a direct equivalent, so on platforms that don't have flock, we fall # back to using trying to use the shlock command, and if that doesn't exist, # then we use mkdir as an atomic operation to create a lock directory. If mkdir # is able to create the directory, then the lock is acquired. To determine if we # have "flock" or "shlock" available, we use the "hash" shell built-in. # # The second complication is on network file shares. On NFS, to obtain an # exclusive lock you need a file descriptor that is open for writing. Thus, we # ignore errors from flock by redirecting all output to /dev/null, since users # will typically not care about errors from flock and are more likely to be # confused by them than helped. The "shlock" method doesn't work for network # shares, since it is PID-based. The "mkdir" method does work over NFS # implementations that support atomic directory creation (which is most of # them). The "schlock" and "flock" commands are more reliable than the mkdir # method, however, or we would use mkdir in all cases. # # The upgrade_flutter function calling _wait_for_lock is executed in a subshell # with a redirect that pipes the source of this script into file descriptor 7. # A flock lock is released when this subshell exits and file descriptor 7 is # closed. The mkdir lock is released via an exit trap from the subshell that # deletes the lock directory. function _wait_for_lock () { FLUTTER_UPGRADE_LOCK="$FLUTTER_ROOT/bin/cache/.upgrade_lock" local waiting_message_displayed while ! _lock "$FLUTTER_UPGRADE_LOCK"; do if [[ -z $waiting_message_displayed ]]; then # Print with a return so that if the Dart code also prints this message # when it does its own lock, the message won't appear twice. Be sure that # the clearing printf below has the same number of space characters. printf "Waiting for another flutter command to release the startup lock...\r" >&2; waiting_message_displayed="true" fi sleep .1; done if [[ $waiting_message_displayed == "true" ]]; then # Clear the waiting message so it doesn't overlap any following text. printf " \r" >&2; fi unset waiting_message_displayed # If the lock file is acquired, make sure that it is removed on exit. trap _rmlock INT TERM EXIT } # This function is always run in a subshell. Running the function in a subshell # is required to make sure any lock directory is cleaned up by the exit trap in # _wait_for_lock. function upgrade_flutter () ( mkdir -p "$FLUTTER_ROOT/bin/cache" local revision="$(cd "$FLUTTER_ROOT"; git rev-parse HEAD)" local compilekey="$revision:$FLUTTER_TOOL_ARGS" # Invalidate cache if: # * SNAPSHOT_PATH is not a file, or # * STAMP_PATH is not a file, or # * STAMP_PATH is an empty file, or # * Contents of STAMP_PATH is not what we are going to compile, or # * pubspec.yaml last modified after pubspec.lock if [[ ! -f "$SNAPSHOT_PATH" || \ ! -s "$STAMP_PATH" || \ "$(cat "$STAMP_PATH")" != "$compilekey" || \ "$FLUTTER_TOOLS_DIR/pubspec.yaml" -nt "$FLUTTER_TOOLS_DIR/pubspec.lock" ]]; then # Waits for the update lock to be acquired. Placing this check inside the # conditional allows the majority of flutter/dart installations to bypass # the lock entirely, but as a result this required a second verification that # the SDK is up to date. _wait_for_lock # A different shell process might have updated the tool/SDK. if [[ -f "$SNAPSHOT_PATH" && -s "$STAMP_PATH" && "$(cat "$STAMP_PATH")" == "$compilekey" && "$FLUTTER_TOOLS_DIR/pubspec.yaml" -ot "$FLUTTER_TOOLS_DIR/pubspec.lock" ]]; then exit $? fi # Fetch Dart... rm -f "$FLUTTER_ROOT/version" rm -f "$FLUTTER_ROOT/bin/cache/flutter.version.json" touch "$FLUTTER_ROOT/bin/cache/.dartignore" "$FLUTTER_ROOT/bin/internal/update_dart_sdk.sh" if [[ "$BIN_NAME" == 'dart' ]]; then # Don't try to build tool return fi >&2 echo Building flutter tool... # Prepare packages... if [[ "$CI" == "true" || "$BOT" == "true" || "$CONTINUOUS_INTEGRATION" == "true" || "$CHROME_HEADLESS" == "1" ]]; then PUB_ENVIRONMENT="$PUB_ENVIRONMENT:flutter_bot" else export PUB_SUMMARY_ONLY=1 fi export PUB_ENVIRONMENT="$PUB_ENVIRONMENT:flutter_install" pub_upgrade_with_retry # Move the old snapshot - we can't just overwrite it as the VM might currently have it # memory mapped (e.g. on flutter upgrade). For downloading a new dart sdk the folder is moved, # so we take the same approach of moving the file here. SNAPSHOT_PATH_OLD="$SNAPSHOT_PATH.old" if [ -f "$SNAPSHOT_PATH" ]; then mv "$SNAPSHOT_PATH" "$SNAPSHOT_PATH_OLD" fi # Compile... "$DART" --verbosity=error --disable-dart-dev $FLUTTER_TOOL_ARGS --snapshot="$SNAPSHOT_PATH" --snapshot-kind="app-jit" --packages="$FLUTTER_TOOLS_DIR/.dart_tool/package_config.json" --no-enable-mirrors "$SCRIPT_PATH" > /dev/null echo "$compilekey" > "$STAMP_PATH" # Delete any temporary snapshot path. if [ -f "$SNAPSHOT_PATH_OLD" ]; then rm -f "$SNAPSHOT_PATH_OLD" fi fi # The exit here is extraneous since the function is run in a subshell, but # this serves as documentation that running the function in a subshell is # required to make sure any lock directory created by mkdir is cleaned up. exit $? ) # This function is intended to be executed by entrypoints (e.g. `//bin/flutter` # and `//bin/dart`). PROG_NAME and BIN_DIR should already be set by those # entrypoints. function shared::execute() { export FLUTTER_ROOT="$(cd "${BIN_DIR}/.." ; pwd -P)" # If present, run the bootstrap script first BOOTSTRAP_PATH="$FLUTTER_ROOT/bin/internal/bootstrap.sh" if [ -f "$BOOTSTRAP_PATH" ]; then source "$BOOTSTRAP_PATH" fi FLUTTER_TOOLS_DIR="$FLUTTER_ROOT/packages/flutter_tools" SNAPSHOT_PATH="$FLUTTER_ROOT/bin/cache/flutter_tools.snapshot" STAMP_PATH="$FLUTTER_ROOT/bin/cache/flutter_tools.stamp" SCRIPT_PATH="$FLUTTER_TOOLS_DIR/bin/flutter_tools.dart" DART_SDK_PATH="$FLUTTER_ROOT/bin/cache/dart-sdk" DART="$DART_SDK_PATH/bin/dart" # If running over git-bash, overrides the default UNIX executables with win32 # executables case "$(uname -s)" in MINGW* | MSYS* ) DART="$DART.exe" ;; esac # Test if running as superuser – but don't warn if running within Docker or CI. if [[ "$EUID" == "0" && ! -f /.dockerenv && "$CI" != "true" && "$BOT" != "true" && "$CONTINUOUS_INTEGRATION" != "true" ]]; then >&2 echo " Woah! You appear to be trying to run flutter as root." >&2 echo " We strongly recommend running the flutter tool without superuser privileges." >&2 echo " /" >&2 echo "📎" fi # Test if Git is available on the Host if ! hash git 2>/dev/null; then >&2 echo "Error: Unable to find git in your PATH." exit 1 fi # Test if the flutter directory is a git clone (otherwise git rev-parse HEAD # would fail) if [[ ! -e "$FLUTTER_ROOT/.git" ]]; then >&2 echo "Error: The Flutter directory is not a clone of the GitHub project." >&2 echo " The flutter tool requires Git in order to operate properly;" >&2 echo " to install Flutter, see the instructions at:" >&2 echo " https://flutter.dev/get-started" exit 1 fi BIN_NAME="$(basename "$PROG_NAME")" # File descriptor 7 is prepared here so that we can use it with # flock(1) in _lock() (see above). # # We use number 7 because it's a luckier number than 3; luck is # important when making locks work reliably. Also because that way # if anyone is redirecting other file descriptors there's less # chance of a conflict. # # In any case, the file we redirect into this file descriptor is # this very source file you are reading right now, because that's # the only file we can truly guarantee exists, since we're running # it. We don't use PROG_NAME because otherwise if you run `dart` and # `flutter` simultaneously they'll end up using different lock files # and will corrupt each others' downloads. # # SHARED_NAME itself is prepared by the caller script. upgrade_flutter 7< "$SHARED_NAME" case "$BIN_NAME" in flutter*) # FLUTTER_TOOL_ARGS aren't quoted below, because it is meant to be # considered as separate space-separated args. exec "$DART" --disable-dart-dev --packages="$FLUTTER_TOOLS_DIR/.dart_tool/package_config.json" $FLUTTER_TOOL_ARGS "$SNAPSHOT_PATH" "$@" ;; dart*) exec "$DART" "$@" ;; *) >&2 echo "Error! Executable name $BIN_NAME not recognized!" exit 1 ;; esac }
flutter/bin/internal/shared.sh/0
{ "file_path": "flutter/bin/internal/shared.sh", "repo_id": "flutter", "token_count": 3852 }
482
#include "Generated.xcconfig"
flutter/dev/a11y_assessments/ios/Flutter/Debug.xcconfig/0
{ "file_path": "flutter/dev/a11y_assessments/ios/Flutter/Debug.xcconfig", "repo_id": "flutter", "token_count": 12 }
483
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'use_cases.dart'; class TextFieldUseCase extends UseCase { @override String get name => 'TextField'; @override String get route => '/text-field'; @override Widget build(BuildContext context) => const _MainWidget(); } class _MainWidget extends StatelessWidget { const _MainWidget(); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( backgroundColor: Theme.of(context).colorScheme.inversePrimary, title: const Text('TextField'), ), body: ListView( children: <Widget>[ const TextField( key: Key('enabled text field'), decoration: InputDecoration( labelText: 'Email', suffixText: '@gmail.com', hintText: 'Enter your email', ), ), TextField( key: const Key('disabled text field'), decoration: const InputDecoration( labelText: 'Email', suffixText: '@gmail.com', hintText: 'Enter your email', ), enabled: false, controller: TextEditingController(text: 'xyz'), ), ], ), ); } }
flutter/dev/a11y_assessments/lib/use_cases/text_field.dart/0
{ "file_path": "flutter/dev/a11y_assessments/lib/use_cases/text_field.dart", "repo_id": "flutter", "token_count": 608 }
484
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:a11y_assessments/use_cases/text_button.dart'; import 'package:flutter_test/flutter_test.dart'; import 'test_utils.dart'; void main() { testWidgets('text button can run', (WidgetTester tester) async { await pumpsUseCase(tester, TextButtonUseCase()); expect(find.text('Text button'), findsOneWidget); expect(find.text('Text button disabled'), findsOneWidget); }); }
flutter/dev/a11y_assessments/test/text_button_test.dart/0
{ "file_path": "flutter/dev/a11y_assessments/test/text_button_test.dart", "repo_id": "flutter", "token_count": 179 }
485
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'common.dart'; import 'src/animated_advanced_blend.dart'; import 'src/animated_blur_backdrop_filter.dart'; import 'src/animated_complex_image_filtered.dart'; import 'src/animated_complex_opacity.dart'; import 'src/animated_image.dart'; import 'src/animated_placeholder.dart'; import 'src/animation_with_microtasks.dart'; import 'src/backdrop_filter.dart'; import 'src/clipper_cache.dart'; import 'src/color_filter_and_fade.dart'; import 'src/color_filter_cache.dart'; import 'src/color_filter_with_unstable_child.dart'; import 'src/cubic_bezier.dart'; import 'src/cull_opacity.dart'; import 'src/draw_atlas.dart'; import 'src/draw_points.dart'; import 'src/draw_vertices.dart'; import 'src/filtered_child_animation.dart'; import 'src/fullscreen_textfield.dart'; import 'src/gradient_perf.dart'; import 'src/heavy_grid_view.dart'; import 'src/large_image_changer.dart'; import 'src/large_images.dart'; import 'src/list_text_layout.dart'; import 'src/multi_widget_construction.dart'; import 'src/opacity_peephole.dart'; import 'src/path_tessellation.dart'; import 'src/picture_cache.dart'; import 'src/picture_cache_complexity_scoring.dart'; import 'src/post_backdrop_filter.dart'; import 'src/raster_cache_use_memory.dart'; import 'src/shader_mask_cache.dart'; import 'src/simple_animation.dart'; import 'src/simple_scroll.dart'; import 'src/sliders.dart'; import 'src/stack_size.dart'; import 'src/text.dart'; import 'src/very_long_picture_scrolling.dart'; const String kMacrobenchmarks = 'Macrobenchmarks'; void main() => runApp(const MacrobenchmarksApp()); class MacrobenchmarksApp extends StatelessWidget { const MacrobenchmarksApp({super.key, this.initialRoute = '/'}); @override Widget build(BuildContext context) { return MaterialApp( title: kMacrobenchmarks, initialRoute: initialRoute, routes: <String, WidgetBuilder>{ '/': (BuildContext context) => const HomePage(), kCullOpacityRouteName: (BuildContext context) => const CullOpacityPage(), kCubicBezierRouteName: (BuildContext context) => const CubicBezierPage(), kBackdropFilterRouteName: (BuildContext context) => const BackdropFilterPage(), kPostBackdropFilterRouteName: (BuildContext context) => const PostBackdropFilterPage(), kSimpleAnimationRouteName: (BuildContext context) => const SimpleAnimationPage(), kPictureCacheRouteName: (BuildContext context) => const PictureCachePage(), kPictureCacheComplexityScoringRouteName: (BuildContext context) => const PictureCacheComplexityScoringPage(), kLargeImageChangerRouteName: (BuildContext context) => const LargeImageChangerPage(), kLargeImagesRouteName: (BuildContext context) => const LargeImagesPage(), kTextRouteName: (BuildContext context) => const TextPage(), kPathTessellationRouteName: (BuildContext context) => const PathTessellationPage(), kFullscreenTextRouteName: (BuildContext context) => const TextFieldPage(), kAnimatedPlaceholderRouteName: (BuildContext context) => const AnimatedPlaceholderPage(), kClipperCacheRouteName: (BuildContext context) => const ClipperCachePage(), kColorFilterAndFadeRouteName: (BuildContext context) => const ColorFilterAndFadePage(), kColorFilterCacheRouteName: (BuildContext context) => const ColorFilterCachePage(), kColorFilterWithUnstableChildName: (BuildContext context) => const ColorFilterWithUnstableChildPage(), kFadingChildAnimationRouteName: (BuildContext context) => const FilteredChildAnimationPage(FilterType.opacity), kImageFilteredTransformAnimationRouteName: (BuildContext context) => const FilteredChildAnimationPage(FilterType.rotateFilter), kMultiWidgetConstructionRouteName: (BuildContext context) => const MultiWidgetConstructTable(10, 20), kHeavyGridViewRouteName: (BuildContext context) => const HeavyGridViewPage(), kRasterCacheUseMemory: (BuildContext context) => const RasterCacheUseMemory(), kShaderMaskCacheRouteName: (BuildContext context) => const ShaderMaskCachePage(), kSimpleScrollRouteName: (BuildContext context) => const SimpleScroll(), kStackSizeRouteName: (BuildContext context) => const StackSizePage(), kAnimationWithMicrotasksRouteName: (BuildContext context) => const AnimationWithMicrotasks(), kAnimatedImageRouteName: (BuildContext context) => const AnimatedImagePage(), kOpacityPeepholeRouteName: (BuildContext context) => const OpacityPeepholePage(), ...opacityPeepholeRoutes, kGradientPerfRouteName: (BuildContext context) => const GradientPerfHomePage(), ...gradientPerfRoutes, kAnimatedComplexOpacityPerfRouteName: (BuildContext context) => const AnimatedComplexOpacity(), kListTextLayoutRouteName: (BuildContext context) => const ColumnOfText(), kAnimatedComplexImageFilteredPerfRouteName: (BuildContext context) => const AnimatedComplexImageFiltered(), kAnimatedBlurBackdropFilter: (BuildContext context) => const AnimatedBlurBackdropFilter(), kSlidersRouteName: (BuildContext context) => const SlidersPage(), kDrawPointsPageRougeName: (BuildContext context) => const DrawPointsPage(), kDrawVerticesPageRouteName: (BuildContext context) => const DrawVerticesPage(), kDrawAtlasPageRouteName: (BuildContext context) => const DrawAtlasPage(), kAnimatedAdvancedBlend: (BuildContext context) => const AnimatedAdvancedBlend(), kVeryLongPictureScrollingRouteName: (BuildContext context) => const VeryLongPictureScrollingPerf(), }, ); } final String initialRoute; } class HomePage extends StatelessWidget { const HomePage({super.key}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text(kMacrobenchmarks)), body: ListView( key: const Key(kScrollableName), children: <Widget>[ ElevatedButton( key: const Key(kCullOpacityRouteName), child: const Text('Cull opacity'), onPressed: () { Navigator.pushNamed(context, kCullOpacityRouteName); }, ), ElevatedButton( key: const Key(kCubicBezierRouteName), child: const Text('Cubic Bezier'), onPressed: () { Navigator.pushNamed(context, kCubicBezierRouteName); }, ), ElevatedButton( key: const Key(kBackdropFilterRouteName), child: const Text('Backdrop Filter'), onPressed: () { Navigator.pushNamed(context, kBackdropFilterRouteName); }, ), ElevatedButton( key: const Key(kPostBackdropFilterRouteName), child: const Text('Post Backdrop Filter'), onPressed: () { Navigator.pushNamed(context, kPostBackdropFilterRouteName); }, ), ElevatedButton( key: const Key(kSimpleAnimationRouteName), child: const Text('Simple Animation'), onPressed: () { Navigator.pushNamed(context, kSimpleAnimationRouteName); }, ), ElevatedButton( key: const Key(kPictureCacheRouteName), child: const Text('Picture Cache'), onPressed: () { Navigator.pushNamed(context, kPictureCacheRouteName); }, ), ElevatedButton( key: const Key(kPictureCacheComplexityScoringRouteName), child: const Text('Picture Cache Complexity Scoring'), onPressed: () { Navigator.pushNamed(context, kPictureCacheComplexityScoringRouteName); }, ), ElevatedButton( key: const Key(kLargeImagesRouteName), child: const Text('Large Images'), onPressed: () { Navigator.pushNamed(context, kLargeImagesRouteName); }, ), ElevatedButton( key: const Key(kPathTessellationRouteName), child: const Text('Path Tessellation'), onPressed: () { Navigator.pushNamed(context, kPathTessellationRouteName); }, ), ElevatedButton( key: const Key(kTextRouteName), child: const Text('Text'), onPressed: () { Navigator.pushNamed(context, kTextRouteName); }, ), ElevatedButton( key: const Key(kFullscreenTextRouteName), child: const Text('Fullscreen Text'), onPressed: () { Navigator.pushNamed(context, kFullscreenTextRouteName); }, ), ElevatedButton( key: const Key(kAnimatedPlaceholderRouteName), child: const Text('Animated Placeholder'), onPressed: () { Navigator.pushNamed(context, kAnimatedPlaceholderRouteName); }, ), ElevatedButton( key: const Key(kClipperCacheRouteName), child: const Text('Clipper Cache'), onPressed: () { Navigator.pushNamed(context, kClipperCacheRouteName); }, ), ElevatedButton( key: const Key(kColorFilterAndFadeRouteName), child: const Text('Color Filter and Fade'), onPressed: () { Navigator.pushNamed(context, kColorFilterAndFadeRouteName); }, ), ElevatedButton( key: const Key(kColorFilterCacheRouteName), child: const Text('Color Filter Cache'), onPressed: () { Navigator.pushNamed(context, kColorFilterCacheRouteName); }, ), ElevatedButton( key: const Key(kColorFilterWithUnstableChildName), child: const Text('Color Filter with Unstable Child'), onPressed: () { Navigator.pushNamed(context, kColorFilterWithUnstableChildName); }, ), ElevatedButton( key: const Key(kRasterCacheUseMemory), child: const Text('RasterCache Use Memory'), onPressed: () { Navigator.pushNamed(context, kRasterCacheUseMemory); }, ), ElevatedButton( key: const Key(kShaderMaskCacheRouteName), child: const Text('Shader Mask Cache'), onPressed: () { Navigator.pushNamed(context, kShaderMaskCacheRouteName); }, ), ElevatedButton( key: const Key(kFadingChildAnimationRouteName), child: const Text('Fading Child Animation'), onPressed: () { Navigator.pushNamed(context, kFadingChildAnimationRouteName); }, ), ElevatedButton( key: const Key(kImageFilteredTransformAnimationRouteName), child: const Text('ImageFiltered Transform Animation'), onPressed: () { Navigator.pushNamed(context, kImageFilteredTransformAnimationRouteName); }, ), ElevatedButton( key: const Key(kMultiWidgetConstructionRouteName), child: const Text('Widget Construction and Destruction'), onPressed: () { Navigator.pushNamed(context, kMultiWidgetConstructionRouteName); }, ), ElevatedButton( key: const Key(kHeavyGridViewRouteName), child: const Text('Heavy Grid View'), onPressed: () { Navigator.pushNamed(context, kHeavyGridViewRouteName); }, ), ElevatedButton( key: const Key(kLargeImageChangerRouteName), child: const Text('Large Image Changer'), onPressed: () { Navigator.pushNamed(context, kLargeImageChangerRouteName); }, ), ElevatedButton( key: const Key(kStackSizeRouteName), child: const Text('Stack Size'), onPressed: () { Navigator.pushNamed(context, kStackSizeRouteName); }, ), ElevatedButton( key: const Key(kAnimationWithMicrotasksRouteName), child: const Text('Animation With Microtasks'), onPressed: () { Navigator.pushNamed(context, kAnimationWithMicrotasksRouteName); }, ), ElevatedButton( key: const Key(kAnimatedImageRouteName), child: const Text('Animated Image'), onPressed: () { Navigator.pushNamed(context, kAnimatedImageRouteName); }, ), ElevatedButton( key: const Key(kOpacityPeepholeRouteName), child: const Text('Opacity Peephole tests'), onPressed: () { Navigator.pushNamed(context, kOpacityPeepholeRouteName); }, ), ElevatedButton( key: const Key(kGradientPerfRouteName), child: const Text('Gradient performance tests'), onPressed: () { Navigator.pushNamed(context, kGradientPerfRouteName); }, ), ElevatedButton( key: const Key(kAnimatedComplexOpacityPerfRouteName), child: const Text('Animated complex opacity perf'), onPressed: () { Navigator.pushNamed(context, kAnimatedComplexOpacityPerfRouteName); }, ), ElevatedButton( key: const Key(kAnimatedComplexImageFilteredPerfRouteName), child: const Text('Animated complex image filtered perf'), onPressed: () { Navigator.pushNamed(context, kAnimatedComplexImageFilteredPerfRouteName); }, ), ElevatedButton( key: const Key(kListTextLayoutRouteName), child: const Text('A list with lots of text'), onPressed: () { Navigator.pushNamed(context, kListTextLayoutRouteName); }, ), ElevatedButton( key: const Key(kAnimatedBlurBackdropFilter), child: const Text('An animating backdrop filter'), onPressed: () { Navigator.pushNamed(context, kAnimatedBlurBackdropFilter); }, ), ElevatedButton( key: const Key(kSlidersRouteName), child: const Text('Sliders'), onPressed: () { Navigator.pushNamed(context, kSlidersRouteName); }, ), ElevatedButton( key: const Key(kDrawPointsPageRougeName), child: const Text('Draw Points'), onPressed: () { Navigator.pushNamed(context, kDrawPointsPageRougeName); }, ), ElevatedButton( key: const Key(kDrawVerticesPageRouteName), child: const Text('Draw Vertices'), onPressed: () { Navigator.pushNamed(context, kDrawVerticesPageRouteName); }, ), ElevatedButton( key: const Key(kDrawAtlasPageRouteName), child: const Text('Draw Atlas'), onPressed: () { Navigator.pushNamed(context, kDrawAtlasPageRouteName); }, ), ElevatedButton( key: const Key(kAnimatedAdvancedBlend), child: const Text('Animated Advanced Blend'), onPressed: () { Navigator.pushNamed(context, kAnimatedAdvancedBlend); }, ), ElevatedButton( key: const Key(kVeryLongPictureScrollingRouteName), child: const Text('Very Long Picture Scrolling'), onPressed: () { Navigator.pushNamed(context, kVeryLongPictureScrollingRouteName); }, ), ], ), ); } }
flutter/dev/benchmarks/macrobenchmarks/lib/main.dart/0
{ "file_path": "flutter/dev/benchmarks/macrobenchmarks/lib/main.dart", "repo_id": "flutter", "token_count": 7162 }
486
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:typed_data'; import 'dart:ui'; import 'package:flutter/material.dart'; class DrawPointsPage extends StatefulWidget { const DrawPointsPage({super.key}); @override State<DrawPointsPage> createState() => _DrawPointsPageState(); } class _DrawPointsPageState extends State<DrawPointsPage> with SingleTickerProviderStateMixin { late final AnimationController controller; double tick = 0.0; @override void initState() { super.initState(); controller = AnimationController(vsync: this, duration: const Duration(hours: 1)); controller.addListener(() { setState(() { tick += 1; }); }); controller.forward(from: 0); } @override void dispose() { controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return CustomPaint( size: const Size(500, 500), painter: PointsPainter(tick), child: Container(), ); } } class PointsPainter extends CustomPainter { PointsPainter(this.tick); final double tick; final Float32List data = Float32List(8000); static const List<Color> kColors = <Color>[ Colors.red, Colors.blue, Colors.green, Colors.yellow, Colors.orange, Colors.purple, Colors.pink, Colors.deepPurple, ]; @override void paint(Canvas canvas, Size size) { if (size.width == 0) { return; } canvas.drawPaint(Paint()..color = Colors.white); for (int i = 0; i < 8; i++) { final double x = ((size.width / (i + 1)) + tick) % size.width; for (int j = 0; j < data.length; j += 2) { data[j] = x; data[j + 1] = (size.height / (j + 1)) + 200; } final Paint paint = Paint() ..color = kColors[i] ..strokeWidth = 5 ..strokeCap = StrokeCap.round ..style = PaintingStyle.stroke; canvas.drawRawPoints(PointMode.points, data, paint); } } @override bool shouldRepaint(covariant CustomPainter oldDelegate) { return true; } }
flutter/dev/benchmarks/macrobenchmarks/lib/src/draw_points.dart/0
{ "file_path": "flutter/dev/benchmarks/macrobenchmarks/lib/src/draw_points.dart", "repo_id": "flutter", "token_count": 827 }
487
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'package:flutter/material.dart'; import 'picture_cache.dart'; class ShaderMaskCachePage extends StatefulWidget { const ShaderMaskCachePage({super.key}); @override State<ShaderMaskCachePage> createState() => _ShaderMaskCachePageState(); } class _ShaderMaskCachePageState extends State<ShaderMaskCachePage> with TickerProviderStateMixin { final ScrollController _controller = ScrollController(); @override void initState() { super.initState(); _controller.addListener(() { if (_controller.offset < 10) { _controller.animateTo(100, duration: const Duration(milliseconds: 1000), curve: Curves.ease); } else if (_controller.offset > 90) { _controller.animateTo(0, duration: const Duration(milliseconds: 1000), curve: Curves.ease); } }); Timer(const Duration(milliseconds: 500), () { _controller.animateTo(100, duration: const Duration(milliseconds: 1000), curve: Curves.ease); }); } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.lightBlue, body: ListView( controller: _controller, children: <Widget>[ const SizedBox(height: 100), buildShaderMask(0), const SizedBox(height: 10), buildShaderMask(1), const SizedBox(height: 1000), ], ), ); } Widget buildShaderMask(int index) { return ShaderMask( shaderCallback: (Rect bounds) { return const RadialGradient( center: Alignment.topLeft, radius: 1.0, colors: <Color>[Colors.yellow, Colors.red], tileMode: TileMode.mirror, ).createShader(bounds); }, child: Container( clipBehavior: Clip.antiAlias, decoration: const BoxDecoration(boxShadow: <BoxShadow>[ BoxShadow( color: Colors.white, blurRadius: 5.0, ), ]), child: ListItem(index: index), ), ); } @override void dispose() { _controller.dispose(); super.dispose(); } }
flutter/dev/benchmarks/macrobenchmarks/lib/src/shader_mask_cache.dart/0
{ "file_path": "flutter/dev/benchmarks/macrobenchmarks/lib/src/shader_mask_cache.dart", "repo_id": "flutter", "token_count": 907 }
488
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:js_interop'; import 'dart:typed_data'; import 'dart:ui' as ui; import 'package:web/web.dart' as web; import 'recorder.dart'; // Measures the performance of image decoding. // // The benchmark measures the decoding latency and not impact on jank. It // cannot distinguish between blocking and non-blocking decoding. It naively // measures the total time it takes to decode image frames. For example, the // WASM codecs execute on the main thread and block the UI, leading to jank, // but the browser's WebCodecs API is asynchronous running on a separate thread // and does not jank. However, the benchmark result may be the same. // // This benchmark does not support the HTML renderer because the HTML renderer // cannot decode image frames (it always returns 1 dummy frame, even for // animated images). class BenchImageDecoding extends RawRecorder { BenchImageDecoding() : super( name: benchmarkName, useCustomWarmUp: true, ); static const String benchmarkName = 'bench_image_decoding'; // These test images are taken from https://github.com/flutter/flutter_gallery_assets/tree/master/lib/splash_effects static const List<String> _imageUrls = <String>[ 'assets/packages/flutter_gallery_assets/splash_effects/splash_effect_1.gif', 'assets/packages/flutter_gallery_assets/splash_effects/splash_effect_2.gif', 'assets/packages/flutter_gallery_assets/splash_effects/splash_effect_3.gif', ]; final List<Uint8List> _imageData = <Uint8List>[]; @override Future<void> setUpAll() async { if (_imageData.isNotEmpty) { return; } for (final String imageUrl in _imageUrls) { final Future<JSAny?> fetchFuture = web.window.fetch(imageUrl.toJS).toDart; final web.Response image = (await fetchFuture)! as web.Response; final Future<JSAny?> imageFuture = image.arrayBuffer().toDart; final JSArrayBuffer imageBuffer = (await imageFuture)! as JSArrayBuffer; _imageData.add(imageBuffer.toDart.asUint8List()); } } // The number of samples recorded so far. int _sampleCount = 0; // The number of samples used for warm-up. static const int _warmUpSampleCount = 5; // The number of samples used to measure performance after the warm-up. static const int _measuredSampleCount = 20; @override Future<void> body(Profile profile) async { await profile.recordAsync('recordImageDecode', () async { final List<Future<void>> allDecodes = <Future<void>>[ for (final Uint8List data in _imageData) _decodeImage(data), ]; await Future.wait(allDecodes); }, reported: true); _sampleCount += 1; if (_sampleCount == _warmUpSampleCount) { profile.stopWarmingUp(); } if (_sampleCount >= _warmUpSampleCount + _measuredSampleCount) { profile.stopBenchmark(); } } } Future<void> _decodeImage(Uint8List data) async { final ui.Codec codec = await ui.instantiateImageCodec(data); const int decodeFrameCount = 5; if (codec.frameCount < decodeFrameCount) { throw Exception( 'Test image contains too few frames for this benchmark (${codec.frameCount}). ' 'Choose a test image with at least $decodeFrameCount frames.' ); } for (int i = 0; i < decodeFrameCount; i++) { (await codec.getNextFrame()).image.dispose(); } codec.dispose(); }
flutter/dev/benchmarks/macrobenchmarks/lib/src/web/bench_image_decoding.dart/0
{ "file_path": "flutter/dev/benchmarks/macrobenchmarks/lib/src/web/bench_image_decoding.dart", "repo_id": "flutter", "token_count": 1153 }
489
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'dart:js_interop'; import 'dart:math' as math; import 'dart:ui'; import 'dart:ui_web' as ui_web; import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/scheduler.dart'; import 'package:flutter/services.dart'; import 'package:flutter/widgets.dart'; import 'package:meta/meta.dart'; import 'package:web/web.dart' as web; /// The default number of samples from warm-up iterations. /// /// This value is used when [Profile.useCustomWarmUp] is set to false. /// /// The benchmark is warmed up prior to measuring to allow JIT and caches to settle. const int _kDefaultWarmUpSampleCount = 200; /// The default number of samples collected to compute benchmark statistics. /// /// This value is used when [Profile.useCustomWarmUp] is set to false. const int _kDefaultMeasuredSampleCount = 100; /// The default total number of samples collected by a benchmark. /// /// This value is used when [Profile.useCustomWarmUp] is set to false. const int kDefaultTotalSampleCount = _kDefaultWarmUpSampleCount + _kDefaultMeasuredSampleCount; /// A benchmark metric that includes frame-related computations prior to /// submitting layer and picture operations to the underlying renderer, such as /// HTML and CanvasKit. During this phase we compute transforms, clips, and /// other information needed for rendering. const String kProfilePrerollFrame = 'preroll_frame'; /// A benchmark metric that includes submitting layer and picture information /// to the renderer. const String kProfileApplyFrame = 'apply_frame'; /// Measures the amount of time [action] takes. /// /// See also: /// /// * [timeAsyncAction], which measures the time of asynchronous work. Duration timeAction(VoidCallback action) { final Stopwatch stopwatch = Stopwatch()..start(); action(); stopwatch.stop(); return stopwatch.elapsed; } /// Measures the amount of time the future returned by [action] takes to complete. /// /// See also: /// /// * [timeAction], which measures the time of synchronous work. Future<Duration> timeAsyncAction(AsyncCallback action) async { final Stopwatch stopwatch = Stopwatch()..start(); await action(); stopwatch.stop(); return stopwatch.elapsed; } /// A function that performs asynchronous work. typedef AsyncVoidCallback = Future<void> Function(); /// An [AsyncVoidCallback] that doesn't do anything. /// /// This is used just so we don't have to deal with null all over the place. Future<void> _dummyAsyncVoidCallback() async {} /// Runs the benchmark using the given [recorder]. /// /// Notifies about "set up" and "tear down" events via the [setUpAllDidRun] /// and [tearDownAllWillRun] callbacks. @sealed class Runner { /// Creates a runner for the [recorder]. Runner({ required this.recorder, this.setUpAllDidRun = _dummyAsyncVoidCallback, this.tearDownAllWillRun = _dummyAsyncVoidCallback, }); /// The recorder that will run and record the benchmark. final Recorder recorder; /// Called immediately after [Recorder.setUpAll] future is resolved. /// /// This is useful, for example, to kick off a profiler or a tracer such that /// the "set up" computations are not included in the metrics. final AsyncVoidCallback setUpAllDidRun; /// Called just before calling [Recorder.tearDownAll]. /// /// This is useful, for example, to stop a profiler or a tracer such that /// the "tear down" computations are not included in the metrics. final AsyncVoidCallback tearDownAllWillRun; /// Runs the benchmark and reports the results. Future<Profile> run() async { await recorder.setUpAll(); await setUpAllDidRun(); final Profile profile = await recorder.run(); await tearDownAllWillRun(); await recorder.tearDownAll(); return profile; } } /// Base class for benchmark recorders. /// /// Each benchmark recorder has a [name] and a [run] method at a minimum. abstract class Recorder { Recorder._(this.name, this.isTracingEnabled); /// Whether this recorder requires tracing using Chrome's DevTools Protocol's /// "Tracing" API. final bool isTracingEnabled; /// The name of the benchmark. /// /// The results displayed in the Flutter Dashboard will use this name as a /// prefix. final String name; /// Returns the recorded profile. /// /// This value is only available while the benchmark is running. Profile? get profile; /// Whether the benchmark should continue running. /// /// Returns `false` if the benchmark collected enough data and it's time to /// stop. bool shouldContinue() => profile?.shouldContinue() ?? true; /// Called once before all runs of this benchmark recorder. /// /// This is useful for doing one-time setup work that's needed for the /// benchmark. Future<void> setUpAll() async {} /// The implementation of the benchmark that will produce a [Profile]. Future<Profile> run(); /// Called once after all runs of this benchmark recorder. /// /// This is useful for doing one-time clean up work after the benchmark is /// complete. Future<void> tearDownAll() async {} } /// A recorder for benchmarking raw execution of Dart code. /// /// This is useful for benchmarks that don't need frames or widgets. /// /// Example: /// /// ``` /// class BenchForLoop extends RawRecorder { /// BenchForLoop() : super(name: benchmarkName); /// /// static const String benchmarkName = 'for_loop'; /// /// @override /// void body(Profile profile) { /// profile.record('loop', () { /// double x = 0; /// for (int i = 0; i < 10000000; i++) { /// x *= 1.5; /// } /// }); /// } /// } /// ``` abstract class RawRecorder extends Recorder { RawRecorder({required String name, bool useCustomWarmUp = false}) : _useCustomWarmUp = useCustomWarmUp, super._(name, false); /// Whether to delimit warm-up frames in a custom way. final bool _useCustomWarmUp; /// The body of the benchmark. /// /// This is the part that records measurements of the benchmark. FutureOr<void> body(Profile profile); @override Profile? get profile => _profile; Profile? _profile; @override @nonVirtual Future<Profile> run() async { _profile = Profile(name: name, useCustomWarmUp: _useCustomWarmUp); do { await Future<void>.delayed(Duration.zero); final FutureOr<void> result = body(_profile!); if (result is Future) { await result; } } while (shouldContinue()); return _profile!; } } /// A recorder for benchmarking interactions with the engine without the /// framework by directly exercising [SceneBuilder]. /// /// To implement a benchmark, extend this class and implement [onDrawFrame]. /// /// Example: /// /// ``` /// class BenchDrawCircle extends SceneBuilderRecorder { /// BenchDrawCircle() : super(name: benchmarkName); /// /// static const String benchmarkName = 'draw_circle'; /// /// @override /// void onDrawFrame(SceneBuilder sceneBuilder) { /// final PictureRecorder pictureRecorder = PictureRecorder(); /// final Canvas canvas = Canvas(pictureRecorder); /// final Paint paint = Paint()..color = const Color.fromARGB(255, 255, 0, 0); /// final Size windowSize = window.physicalSize; /// canvas.drawCircle(windowSize.center(Offset.zero), 50.0, paint); /// final Picture picture = pictureRecorder.endRecording(); /// sceneBuilder.addPicture(picture); /// } /// } /// ``` abstract class SceneBuilderRecorder extends Recorder { SceneBuilderRecorder({required String name}) : super._(name, true); @override Profile? get profile => _profile; Profile? _profile; /// Called from [dart:ui.PlatformDispatcher.onBeginFrame]. @mustCallSuper void onBeginFrame() {} /// Called on every frame. /// /// An implementation should exercise the [sceneBuilder] to build a frame. /// However, it must not call [SceneBuilder.build] or /// [dart:ui.FlutterView.render]. Instead the benchmark harness will call them /// and time them appropriately. void onDrawFrame(SceneBuilder sceneBuilder); @override Future<Profile> run() { final Completer<Profile> profileCompleter = Completer<Profile>(); _profile = Profile(name: name); PlatformDispatcher.instance.onBeginFrame = (_) { try { startMeasureFrame(profile!); onBeginFrame(); } catch (error, stackTrace) { profileCompleter.completeError(error, stackTrace); rethrow; } }; PlatformDispatcher.instance.onDrawFrame = () { try { _profile!.record('drawFrameDuration', () { final SceneBuilder sceneBuilder = SceneBuilder(); onDrawFrame(sceneBuilder); _profile!.record('sceneBuildDuration', () { final Scene scene = sceneBuilder.build(); _profile!.record('windowRenderDuration', () { view.render(scene); }, reported: false); }, reported: false); }, reported: true); endMeasureFrame(); if (shouldContinue()) { PlatformDispatcher.instance.scheduleFrame(); } else { profileCompleter.complete(_profile!); } } catch (error, stackTrace) { profileCompleter.completeError(error, stackTrace); rethrow; } }; PlatformDispatcher.instance.scheduleFrame(); return profileCompleter.future; } FlutterView get view { assert(PlatformDispatcher.instance.implicitView != null, 'This benchmark requires the embedder to provide an implicit view.'); return PlatformDispatcher.instance.implicitView!; } } /// A recorder for benchmarking interactions with the framework by creating /// widgets. /// /// To implement a benchmark, extend this class and implement [createWidget]. /// /// Example: /// /// ``` /// class BenchListView extends WidgetRecorder { /// BenchListView() : super(name: benchmarkName); /// /// static const String benchmarkName = 'bench_list_view'; /// /// @override /// Widget createWidget() { /// return Directionality( /// textDirection: TextDirection.ltr, /// child: _TestListViewWidget(), /// ); /// } /// } /// /// class _TestListViewWidget extends StatefulWidget { /// @override /// State<StatefulWidget> createState() { /// return _TestListViewWidgetState(); /// } /// } /// /// class _TestListViewWidgetState extends State<_TestListViewWidget> { /// ScrollController scrollController; /// /// @override /// void initState() { /// super.initState(); /// scrollController = ScrollController(); /// Timer.run(() async { /// bool forward = true; /// while (true) { /// await scrollController.animateTo( /// forward ? 300 : 0, /// curve: Curves.linear, /// duration: const Duration(seconds: 1), /// ); /// forward = !forward; /// } /// }); /// } /// /// @override /// Widget build(BuildContext context) { /// return ListView.builder( /// controller: scrollController, /// itemCount: 10000, /// itemBuilder: (BuildContext context, int index) { /// return Text('Item #$index'); /// }, /// ); /// } /// } /// ``` abstract class WidgetRecorder extends Recorder implements FrameRecorder { WidgetRecorder({ required String name, this.useCustomWarmUp = false, }) : super._(name, true); /// Creates a widget to be benchmarked. /// /// The widget must create its own animation to drive the benchmark. The /// animation should continue indefinitely. The benchmark harness will stop /// pumping frames automatically. Widget createWidget(); final List<VoidCallback> _didStopCallbacks = <VoidCallback>[]; @override void registerDidStop(VoidCallback cb) { _didStopCallbacks.add(cb); } @override Profile? profile; Completer<void>? _runCompleter; /// Whether to delimit warm-up frames in a custom way. final bool useCustomWarmUp; late Stopwatch _drawFrameStopwatch; @override @mustCallSuper void frameWillDraw() { startMeasureFrame(profile!); _drawFrameStopwatch = Stopwatch()..start(); } @override @mustCallSuper void frameDidDraw() { endMeasureFrame(); profile!.addDataPoint('drawFrameDuration', _drawFrameStopwatch.elapsed, reported: true); if (shouldContinue()) { PlatformDispatcher.instance.scheduleFrame(); } else { for (final VoidCallback fn in _didStopCallbacks) { fn(); } _runCompleter!.complete(); } } @override void _onError(Object error, StackTrace? stackTrace) { _runCompleter!.completeError(error, stackTrace); } late final _RecordingWidgetsBinding _binding; @override @mustCallSuper Future<void> setUpAll() async { _binding = _RecordingWidgetsBinding.ensureInitialized(); } @override Future<Profile> run() async { _runCompleter = Completer<void>(); final Profile localProfile = profile = Profile(name: name, useCustomWarmUp: useCustomWarmUp); final Widget widget = createWidget(); registerEngineBenchmarkValueListener(kProfilePrerollFrame, (num value) { localProfile.addDataPoint( kProfilePrerollFrame, Duration(microseconds: value.toInt()), reported: false, ); }); registerEngineBenchmarkValueListener(kProfileApplyFrame, (num value) { localProfile.addDataPoint( kProfileApplyFrame, Duration(microseconds: value.toInt()), reported: false, ); }); _binding._beginRecording(this, widget); try { await _runCompleter!.future; return localProfile; } finally { stopListeningToEngineBenchmarkValues(kProfilePrerollFrame); stopListeningToEngineBenchmarkValues(kProfileApplyFrame); _runCompleter = null; profile = null; } } } /// A recorder for measuring the performance of building a widget from scratch /// starting from an empty frame. /// /// The recorder will call [createWidget] and render it, then it will pump /// another frame that clears the screen. It repeats this process, measuring the /// performance of frames that render the widget and ignoring the frames that /// clear the screen. abstract class WidgetBuildRecorder extends Recorder implements FrameRecorder { WidgetBuildRecorder({required String name}) : super._(name, true); /// Creates a widget to be benchmarked. /// /// The widget is not expected to animate as we only care about construction /// of the widget. If you are interested in benchmarking an animation, /// consider using [WidgetRecorder]. Widget createWidget(); final List<VoidCallback> _didStopCallbacks = <VoidCallback>[]; @override void registerDidStop(VoidCallback cb) { _didStopCallbacks.add(cb); } @override Profile? profile; Completer<void>? _runCompleter; late Stopwatch _drawFrameStopwatch; /// Whether in this frame we should call [createWidget] and render it. /// /// If false, then this frame will clear the screen. bool showWidget = true; /// The state that hosts the widget under test. late _WidgetBuildRecorderHostState _hostState; Widget? _getWidgetForFrame() { if (showWidget) { return createWidget(); } else { return null; } } late final _RecordingWidgetsBinding _binding; @override @mustCallSuper Future<void> setUpAll() async { _binding = _RecordingWidgetsBinding.ensureInitialized(); } @override @mustCallSuper void frameWillDraw() { if (showWidget) { startMeasureFrame(profile!); _drawFrameStopwatch = Stopwatch()..start(); } } @override @mustCallSuper void frameDidDraw() { // Only record frames that show the widget. if (showWidget) { endMeasureFrame(); profile!.addDataPoint('drawFrameDuration', _drawFrameStopwatch.elapsed, reported: true); } if (shouldContinue()) { showWidget = !showWidget; _hostState._setStateTrampoline(); } else { for (final VoidCallback fn in _didStopCallbacks) { fn(); } _runCompleter!.complete(); } } @override void _onError(Object error, StackTrace? stackTrace) { _runCompleter!.completeError(error, stackTrace); } @override Future<Profile> run() async { _runCompleter = Completer<void>(); final Profile localProfile = profile = Profile(name: name); _binding._beginRecording(this, _WidgetBuildRecorderHost(this)); try { await _runCompleter!.future; return localProfile; } finally { _runCompleter = null; profile = null; } } } /// Hosts widgets created by [WidgetBuildRecorder]. class _WidgetBuildRecorderHost extends StatefulWidget { const _WidgetBuildRecorderHost(this.recorder); final WidgetBuildRecorder recorder; @override State<StatefulWidget> createState() => _WidgetBuildRecorderHostState(); } class _WidgetBuildRecorderHostState extends State<_WidgetBuildRecorderHost> { @override void initState() { super.initState(); widget.recorder._hostState = this; } // This is just to bypass the @protected on setState. void _setStateTrampoline() { setState(() {}); } @override Widget build(BuildContext context) { return SizedBox.expand( child: widget.recorder._getWidgetForFrame(), ); } } /// Series of time recordings indexed in time order. /// /// A timeseries is expected to contain at least one warm-up frame added by /// calling [add] with `isWarmUpValue` set to true, followed by at least one /// measured value added by calling [add] with `isWarmUpValue` set to false. class Timeseries { /// Creates an empty timeseries. /// /// The [name] is a unique name of this timeseries. If [isReported] is true /// this timeseries is reported to the benchmark dashboard. Timeseries(this.name, this.isReported); /// The label of this timeseries used for debugging and result inspection. final String name; /// Whether this timeseries is reported to the benchmark dashboard. /// /// If `true` a new benchmark card is created for the timeseries and is /// visible on the dashboard. /// /// If `false` the data is stored but it does not show up on the dashboard. /// Use unreported metrics for metrics that are useful for manual inspection /// but that are too fine-grained to be useful for tracking on the dashboard. final bool isReported; /// The number of samples ignored as warm-up frames. int _warmUpSampleCount = 0; /// List of all the values that have been recorded. /// /// This list has no limit. final List<double> _allValues = <double>[]; /// The total amount of data collected, including ones that were dropped /// because of the sample size limit. int get count => _allValues.length; /// Extracts useful statistics out of this timeseries. /// /// See [TimeseriesStats] for more details. TimeseriesStats computeStats() { // Assertions do not use the `assert` keyword because benchmarks run in // profile mode, where asserts are tree-shaken out. if (_warmUpSampleCount == 0) { throw StateError( 'The benchmark did not warm-up. Use at least one sample to warm-up ' 'the benchmark to reduce noise.'); } if (_warmUpSampleCount >= count) { throw StateError( 'The benchmark did not report any measured samples. Add at least one ' 'sample after warm-up is done. There were $_warmUpSampleCount warm-up ' 'samples, and no measured samples in this timeseries.' ); } // The first few values we simply discard and never look at. They're from the warm-up phase. final List<double> warmUpValues = _allValues.sublist(0, _warmUpSampleCount); // Values we analyze. final List<double> candidateValues = _allValues.sublist(_warmUpSampleCount); // The average that includes outliers. final double dirtyAverage = _computeAverage(name, candidateValues); // The standard deviation that includes outliers. final double dirtyStandardDeviation = _computeStandardDeviationForPopulation(name, candidateValues); // Any value that's higher than this is considered an outlier. // Two standard deviations captures 95% of a normal distribution. final double outlierCutOff = dirtyAverage + dirtyStandardDeviation * 2; // Candidates with outliers removed. final Iterable<double> cleanValues = candidateValues.where((double value) => value <= outlierCutOff); // Outlier candidates. final Iterable<double> outliers = candidateValues.where((double value) => value > outlierCutOff); // Final statistics. final double cleanAverage = _computeAverage(name, cleanValues); final double standardDeviation = _computeStandardDeviationForPopulation(name, cleanValues); final double noise = cleanAverage > 0.0 ? standardDeviation / cleanAverage : 0.0; // Compute outlier average. If there are no outliers the outlier average is // the same as clean value average. In other words, in a perfect benchmark // with no noise the difference between average and outlier average is zero, // which the best possible outcome. Noise produces a positive difference // between the two. final double outlierAverage = outliers.isNotEmpty ? _computeAverage(name, outliers) : cleanAverage; final List<AnnotatedSample> annotatedValues = <AnnotatedSample>[ for (final double warmUpValue in warmUpValues) AnnotatedSample( magnitude: warmUpValue, isOutlier: warmUpValue > outlierCutOff, isWarmUpValue: true, ), for (final double candidate in candidateValues) AnnotatedSample( magnitude: candidate, isOutlier: candidate > outlierCutOff, isWarmUpValue: false, ), ]; return TimeseriesStats( name: name, average: cleanAverage, outlierCutOff: outlierCutOff, outlierAverage: outlierAverage, standardDeviation: standardDeviation, noise: noise, cleanSampleCount: cleanValues.length, outlierSampleCount: outliers.length, samples: annotatedValues, ); } // Whether the timeseries is in the warm-up phase. bool _isWarmingUp = true; /// Adds a value to this timeseries. void add(double value, {required bool isWarmUpValue}) { if (value < 0.0) { throw StateError( 'Timeseries $name: negative metric values are not supported. Got: $value', ); } if (isWarmUpValue) { if (!_isWarmingUp) { throw StateError( 'A warm-up value was added to the timeseries after the warm-up phase finished.' ); } _warmUpSampleCount += 1; } else if (_isWarmingUp) { _isWarmingUp = false; } _allValues.add(value); } } /// Various statistics about a [Timeseries]. /// /// See the docs on the individual fields for more details. @sealed class TimeseriesStats { const TimeseriesStats({ required this.name, required this.average, required this.outlierCutOff, required this.outlierAverage, required this.standardDeviation, required this.noise, required this.cleanSampleCount, required this.outlierSampleCount, required this.samples, }); /// The label used to refer to the corresponding timeseries. final String name; /// The average value of the measured samples without outliers. final double average; /// The standard deviation in the measured samples without outliers. final double standardDeviation; /// The noise as a multiple of the [average] value takes from clean samples. /// /// This value can be multiplied by 100.0 to get noise as a percentage of /// the average. /// /// If [average] is zero, treats the result as perfect score, returns zero. final double noise; /// The maximum value a sample can have without being considered an outlier. /// /// See [Timeseries.computeStats] for details on how this value is computed. final double outlierCutOff; /// The average of outlier samples. /// /// This value can be used to judge how badly we jank, when we jank. /// /// Another useful metrics is the difference between [outlierAverage] and /// [average]. The smaller the value the more predictable is the performance /// of the corresponding benchmark. final double outlierAverage; /// The number of measured samples after outlier are removed. final int cleanSampleCount; /// The number of outliers. final int outlierSampleCount; /// All collected samples, annotated with statistical information. /// /// See [AnnotatedSample] for more details. final List<AnnotatedSample> samples; /// Outlier average divided by clean average. /// /// This is a measure of performance consistency. The higher this number the /// worse is jank when it happens. Smaller is better, with 1.0 being the /// perfect score. If [average] is zero, this value defaults to 1.0. double get outlierRatio => average > 0.0 ? outlierAverage / average : 1.0; // this can only happen in perfect benchmark that reports only zeros @override String toString() { final StringBuffer buffer = StringBuffer(); buffer.writeln( '$name: (samples: $cleanSampleCount clean/$outlierSampleCount ' 'outliers/${cleanSampleCount + outlierSampleCount} ' 'measured/${samples.length} total)'); buffer.writeln(' | average: $average μs'); buffer.writeln(' | outlier average: $outlierAverage μs'); buffer.writeln(' | outlier/clean ratio: ${outlierRatio}x'); buffer.writeln(' | noise: ${_ratioToPercent(noise)}'); return buffer.toString(); } } /// Annotates a single measurement with statistical information. @sealed class AnnotatedSample { const AnnotatedSample({ required this.magnitude, required this.isOutlier, required this.isWarmUpValue, }); /// The non-negative raw result of the measurement. final double magnitude; /// Whether this sample was considered an outlier. final bool isOutlier; /// Whether this sample was taken during the warm-up phase. /// /// If this value is `true`, this sample does not participate in /// statistical computations. However, the sample would still be /// shown in the visualization of results so that the benchmark /// can be inspected manually to make sure there's a predictable /// warm-up regression slope. final bool isWarmUpValue; } /// Base class for a profile collected from running a benchmark. class Profile { /// Creates an empty profile that can be populated with benchmark samples /// using [record], [recordAsync], and [addDataPoint] methods. /// /// The [name] is the unique name of this profile that distinguishes is from /// other profiles. Typically, the name will describe the benchmark. /// /// If [useCustomWarmUp] is true the benchmark will continue running until /// [stopBenchmark] is called. Otherwise, the benchmark collects the /// [kDefaultTotalSampleCount] samples and stops automatically. Profile({required this.name, this.useCustomWarmUp = false}); /// The name of the benchmark that produced this profile. final String name; /// Whether to delimit warm-up frames in a custom way. final bool useCustomWarmUp; /// True if the benchmark is currently measuring warm-up frames. bool get isWarmingUp => _isWarmingUp; bool _isWarmingUp = true; /// True if the benchmark is currently running. bool get isRunning => _isRunning; bool _isRunning = true; /// Stops the warm-up phase. /// /// After calling this method, subsequent calls to [record], [recordAsync], /// and [addDataPoint] will record measured data samples. /// /// Call this method only once for each profile and only when [isWarmingUp] /// is true. void stopWarmingUp() { if (!_isWarmingUp) { throw StateError('Warm-up already stopped.'); } else { _isWarmingUp = false; } } /// Stops the benchmark. /// /// Call this method only once for each profile and only when [isWarmingUp] /// is false (i.e. after calling [stopWarmingUp]). void stopBenchmark() { if (_isWarmingUp) { throw StateError( 'Warm-up has not finished yet. Benchmark should only be stopped after ' 'it recorded at least one sample after the warm-up.' ); } else if (scoreData.isEmpty) { throw StateError( 'The benchmark did not collect any data.' ); } else { _isRunning = false; } } /// This data will be used to display cards in the Flutter Dashboard. final Map<String, Timeseries> scoreData = <String, Timeseries>{}; /// This data isn't displayed anywhere. It's stored for completeness purposes. final Map<String, dynamic> extraData = <String, dynamic>{}; /// Invokes [callback] and records the duration of its execution under [key]. /// /// See also: /// /// * [recordAsync], which records asynchronous work. Duration record(String key, VoidCallback callback, { required bool reported }) { final Duration duration = timeAction(callback); addDataPoint(key, duration, reported: reported); return duration; } /// Invokes [callback] and records the amount of time the returned future takes. /// /// See also: /// /// * [record], which records synchronous work. Future<Duration> recordAsync(String key, AsyncCallback callback, { required bool reported }) async { final Duration duration = await timeAsyncAction(callback); addDataPoint(key, duration, reported: reported); return duration; } /// Adds a timed sample to the timeseries corresponding to [key]. /// /// Set [reported] to `true` to report the timeseries to the dashboard UI. /// /// Set [reported] to `false` to store the data, but not show it on the /// dashboard UI. void addDataPoint(String key, Duration duration, { required bool reported }) { scoreData.putIfAbsent( key, () => Timeseries(key, reported), ).add(duration.inMicroseconds.toDouble(), isWarmUpValue: isWarmingUp); if (!useCustomWarmUp) { // The stopWarmingUp and stopBenchmark will not be called. Use the // auto-stopping logic. _autoUpdateBenchmarkPhase(); } } /// A convenience wrapper over [addDataPoint] for adding [AggregatedTimedBlock] /// to the profile. /// /// Uses [AggregatedTimedBlock.name] as the name of the data point, and /// [AggregatedTimedBlock.duration] as the duration. void addTimedBlock(AggregatedTimedBlock timedBlock, { required bool reported }) { addDataPoint(timedBlock.name, Duration(microseconds: timedBlock.duration.toInt()), reported: reported); } /// Checks the samples collected so far and sets the appropriate benchmark phase. /// /// If enough warm-up samples have been collected, stops the warm-up phase and /// begins the measuring phase. /// /// If enough total samples have been collected, stops the benchmark. void _autoUpdateBenchmarkPhase() { if (useCustomWarmUp) { StateError( 'Must not call _autoUpdateBenchmarkPhase if custom warm-up is used. ' 'Call `stopWarmingUp` and `stopBenchmark` instead.' ); } if (_isWarmingUp) { final bool doesHaveEnoughWarmUpSamples = scoreData.keys .every((String key) => scoreData[key]!.count >= _kDefaultWarmUpSampleCount); if (doesHaveEnoughWarmUpSamples) { stopWarmingUp(); } } else if (_isRunning) { final bool doesHaveEnoughTotalSamples = scoreData.keys .every((String key) => scoreData[key]!.count >= kDefaultTotalSampleCount); if (doesHaveEnoughTotalSamples) { stopBenchmark(); } } } /// Decides whether the data collected so far is sufficient to stop, or /// whether the benchmark should continue collecting more data. /// /// The signals used are sample size, noise, and duration. /// /// If any of the timeseries doesn't satisfy the noise requirements, this /// method will return true (asking the benchmark to continue collecting /// data). bool shouldContinue() { // If there are no `Timeseries` in the `scoreData`, then we haven't // recorded anything yet. Don't stop. if (scoreData.isEmpty) { return true; } return isRunning; } /// Returns a JSON representation of the profile that will be sent to the /// server. Map<String, dynamic> toJson() { final List<String> scoreKeys = <String>[]; final Map<String, dynamic> json = <String, dynamic>{ 'name': name, 'scoreKeys': scoreKeys, }; for (final String key in scoreData.keys) { final Timeseries timeseries = scoreData[key]!; if (timeseries.isReported) { scoreKeys.add('$key.average'); // Report `outlierRatio` rather than `outlierAverage`, because // the absolute value of outliers is less interesting than the // ratio. scoreKeys.add('$key.outlierRatio'); } final TimeseriesStats stats = timeseries.computeStats(); json['$key.average'] = stats.average; json['$key.outlierAverage'] = stats.outlierAverage; json['$key.outlierRatio'] = stats.outlierRatio; json['$key.noise'] = stats.noise; } json.addAll(extraData); return json; } @override String toString() { final StringBuffer buffer = StringBuffer(); buffer.writeln('name: $name'); for (final String key in scoreData.keys) { final Timeseries timeseries = scoreData[key]!; final TimeseriesStats stats = timeseries.computeStats(); buffer.writeln(stats.toString()); } for (final String key in extraData.keys) { final dynamic value = extraData[key]; if (value is List) { buffer.writeln('$key:'); for (final dynamic item in value) { buffer.writeln(' - $item'); } } else { buffer.writeln('$key: $value'); } } return buffer.toString(); } } /// Computes the arithmetic mean (or average) of given [values]. double _computeAverage(String label, Iterable<double> values) { if (values.isEmpty) { throw StateError('$label: attempted to compute an average of an empty value list.'); } final double sum = values.reduce((double a, double b) => a + b); return sum / values.length; } /// Computes population standard deviation. /// /// Unlike sample standard deviation, which divides by N - 1, this divides by N. /// /// See also: /// /// * <https://en.wikipedia.org/wiki/Standard_deviation> double _computeStandardDeviationForPopulation(String label, Iterable<double> population) { if (population.isEmpty) { throw StateError('$label: attempted to compute the standard deviation of empty population.'); } final double mean = _computeAverage(label, population); final double sumOfSquaredDeltas = population.fold<double>( 0.0, (double previous, double value) => previous += math.pow(value - mean, 2), ); return math.sqrt(sumOfSquaredDeltas / population.length); } String _ratioToPercent(double value) { return '${(value * 100).toStringAsFixed(2)}%'; } /// Implemented by recorders that use [_RecordingWidgetsBinding] to receive /// frame life-cycle calls. abstract class FrameRecorder { /// Add a callback that will be called by the recorder when it stops recording. void registerDidStop(VoidCallback cb); /// Called just before calling [SchedulerBinding.handleDrawFrame]. void frameWillDraw(); /// Called immediately after calling [SchedulerBinding.handleDrawFrame]. void frameDidDraw(); /// Reports an error. /// /// The implementation is expected to halt benchmark execution as soon as possible. void _onError(Object error, StackTrace? stackTrace); } /// A variant of [WidgetsBinding] that collaborates with a [Recorder] to decide /// when to stop pumping frames. /// /// A normal [WidgetsBinding] typically always pumps frames whenever a widget /// instructs it to do so by calling [scheduleFrame] (transitively via /// `setState`). This binding will stop pumping new frames as soon as benchmark /// parameters are satisfactory (e.g. when the metric noise levels become low /// enough). class _RecordingWidgetsBinding extends BindingBase with GestureBinding, SchedulerBinding, ServicesBinding, PaintingBinding, SemanticsBinding, RendererBinding, WidgetsBinding { @override void initInstances() { super.initInstances(); _instance = this; } /// The singleton instance of this object. /// /// Provides access to the features exposed by this class. The binding must /// be initialized before using this getter; this is typically done by calling /// [_RecordingWidgetsBinding.ensureInitialized]. static _RecordingWidgetsBinding get instance => BindingBase.checkInstance(_instance); static _RecordingWidgetsBinding? _instance; /// Returns an instance of the [_RecordingWidgetsBinding], creating and /// initializing it if necessary. /// /// See also: /// /// * [WidgetsFlutterBinding.ensureInitialized], the equivalent in the widgets framework. static _RecordingWidgetsBinding ensureInitialized() { if (_instance == null) { _RecordingWidgetsBinding(); } return instance; } FrameRecorder? _recorder; bool _hasErrored = false; /// To short-circuit all frame lifecycle methods when the benchmark has /// stopped collecting data. bool _benchmarkStopped = false; void _beginRecording(FrameRecorder recorder, Widget widget) { if (_recorder != null) { throw Exception( 'Cannot call _RecordingWidgetsBinding._beginRecording more than once', ); } final FlutterExceptionHandler? originalOnError = FlutterError.onError; recorder.registerDidStop(() { _benchmarkStopped = true; }); // Fail hard and fast on errors. Benchmarks should not have any errors. FlutterError.onError = (FlutterErrorDetails details) { _haltBenchmarkWithError(details.exception, details.stack); originalOnError?.call(details); }; _recorder = recorder; runApp(widget); } void _haltBenchmarkWithError(Object error, StackTrace? stackTrace) { if (_hasErrored) { return; } _recorder?._onError(error, stackTrace); _hasErrored = true; } @override void handleBeginFrame(Duration? rawTimeStamp) { // Don't keep on truckin' if there's an error or the benchmark has stopped. if (_hasErrored || _benchmarkStopped) { return; } try { super.handleBeginFrame(rawTimeStamp); } catch (error, stackTrace) { _haltBenchmarkWithError(error, stackTrace); rethrow; } } @override void scheduleFrame() { // Don't keep on truckin' if there's an error or the benchmark has stopped. if (_hasErrored || _benchmarkStopped) { return; } super.scheduleFrame(); } @override void handleDrawFrame() { // Don't keep on truckin' if there's an error or the benchmark has stopped. if (_hasErrored || _benchmarkStopped) { return; } try { _recorder?.frameWillDraw(); super.handleDrawFrame(); _recorder?.frameDidDraw(); } catch (error, stackTrace) { _haltBenchmarkWithError(error, stackTrace); rethrow; } } } int _currentFrameNumber = 1; /// If [_calledStartMeasureFrame] is true, we have called [startMeasureFrame] /// but have not its pairing [endMeasureFrame] yet. /// /// This flag ensures that [startMeasureFrame] and [endMeasureFrame] are always /// called in pairs, with [startMeasureFrame] followed by [endMeasureFrame]. bool _calledStartMeasureFrame = false; /// Whether we are recording a measured frame. /// /// This flag ensures that we always stop measuring a frame if we /// have started one. Because we want to skip warm-up frames, this flag /// is necessary. bool _isMeasuringFrame = false; /// Adds a marker indication the beginning of frame rendering. /// /// This adds an event to the performance trace used to find measured frames in /// Chrome tracing data. The tracing data contains all frames, but some /// benchmarks are only interested in a subset of frames. For example, /// [WidgetBuildRecorder] only measures frames that build widgets, and ignores /// frames that clear the screen. /// /// Warm-up frames are not measured. If [profile.isWarmingUp] is true, /// this function does nothing. void startMeasureFrame(Profile profile) { if (_calledStartMeasureFrame) { throw Exception('`startMeasureFrame` called twice in a row.'); } _calledStartMeasureFrame = true; if (!profile.isWarmingUp) { // Tell the browser to mark the beginning of the frame. web.window.performance.mark('measured_frame_start#$_currentFrameNumber'); _isMeasuringFrame = true; } } /// Signals the end of a measured frame. /// /// See [startMeasureFrame] for details on what this instrumentation is used /// for. /// /// Warm-up frames are not measured. If [profile.isWarmingUp] was true /// when the corresponding [startMeasureFrame] was called, /// this function does nothing. void endMeasureFrame() { if (!_calledStartMeasureFrame) { throw Exception('`startMeasureFrame` has not been called before calling `endMeasureFrame`'); } _calledStartMeasureFrame = false; if (_isMeasuringFrame) { // Tell the browser to mark the end of the frame, and measure the duration. web.window.performance.mark('measured_frame_end#$_currentFrameNumber'); web.window.performance.measure( 'measured_frame', 'measured_frame_start#$_currentFrameNumber'.toJS, 'measured_frame_end#$_currentFrameNumber', ); // Increment the current frame number. _currentFrameNumber += 1; _isMeasuringFrame = false; } } /// A function that receives a benchmark value from the framework. typedef EngineBenchmarkValueListener = void Function(num value); // Maps from a value label name to a listener. final Map<String, EngineBenchmarkValueListener> _engineBenchmarkListeners = <String, EngineBenchmarkValueListener>{}; /// Registers a [listener] for engine benchmark values labeled by [name]. /// /// If another listener is already registered, overrides it. void registerEngineBenchmarkValueListener(String name, EngineBenchmarkValueListener listener) { if (_engineBenchmarkListeners.containsKey(name)) { throw StateError( 'A listener for "$name" is already registered.\n' 'Call `stopListeningToEngineBenchmarkValues` to unregister the previous ' 'listener before registering a new one.' ); } if (_engineBenchmarkListeners.isEmpty) { // The first listener is being registered. Register the global listener. ui_web.benchmarkValueCallback = _dispatchEngineBenchmarkValue; } _engineBenchmarkListeners[name] = listener; } /// Stops listening to engine benchmark values under labeled by [name]. void stopListeningToEngineBenchmarkValues(String name) { _engineBenchmarkListeners.remove(name); if (_engineBenchmarkListeners.isEmpty) { // The last listener unregistered. Remove the global listener. ui_web.benchmarkValueCallback = null; } } // Dispatches a benchmark value reported by the engine to the relevant listener. // // If there are no listeners registered for [name], ignores the value. void _dispatchEngineBenchmarkValue(String name, double value) { final EngineBenchmarkValueListener? listener = _engineBenchmarkListeners[name]; if (listener != null) { listener(value); } }
flutter/dev/benchmarks/macrobenchmarks/lib/src/web/recorder.dart/0
{ "file_path": "flutter/dev/benchmarks/macrobenchmarks/lib/src/web/recorder.dart", "repo_id": "flutter", "token_count": 13840 }
490
#include "../../Flutter/Flutter-Release.xcconfig" #include "Warnings.xcconfig"
flutter/dev/benchmarks/macrobenchmarks/macos/Runner/Configs/Release.xcconfig/0
{ "file_path": "flutter/dev/benchmarks/macrobenchmarks/macos/Runner/Configs/Release.xcconfig", "repo_id": "flutter", "token_count": 32 }
491
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:ui'; import '../common.dart'; const int _kNumIters = 10000; void main() { assert(false, "Don't run benchmarks in debug mode! Use 'flutter run --release'."); final Stopwatch watch = Stopwatch(); print('RRect contains benchmark...'); watch.start(); for (int i = 0; i < _kNumIters; i += 1) { final RRect outer = RRect.fromLTRBR(10, 10, 20, 20, const Radius.circular(2.0)); outer.contains(const Offset(15, 15)); } watch.stop(); final BenchmarkResultPrinter printer = BenchmarkResultPrinter(); printer.addResult( description: 'RRect contains', value: watch.elapsedMicroseconds / _kNumIters, unit: 'µs per iteration', name: 'rrect_contains_iteration', ); printer.printToStdout(); }
flutter/dev/benchmarks/microbenchmarks/lib/geometry/rrect_contains_bench.dart/0
{ "file_path": "flutter/dev/benchmarks/microbenchmarks/lib/geometry/rrect_contains_bench.dart", "repo_id": "flutter", "token_count": 308 }
492
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. include ':app' rootProject.name = "Multiple Flutters" setBinding(new Binding([gradle: this])) // new evaluate(new File( // new settingsDir.parentFile, // new './module/.android/include_flutter.groovy' // new ))
flutter/dev/benchmarks/multiple_flutters/android/settings.gradle/0
{ "file_path": "flutter/dev/benchmarks/multiple_flutters/android/settings.gradle", "repo_id": "flutter", "token_count": 275 }
493
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>CADisableMinimumFrameDurationOnPhone</key> <true/> <key>CFBundleDevelopmentRegion</key> <string>$(DEVELOPMENT_LANGUAGE)</string> <key>CFBundleExecutable</key> <string>$(EXECUTABLE_NAME)</string> <key>CFBundleIdentifier</key> <string>com.yourcompany.platformViewsLayout</string> <key>CFBundleInfoDictionaryVersion</key> <string>6.0</string> <key>CFBundleName</key> <string>complex_layout</string> <key>CFBundlePackageType</key> <string>APPL</string> <key>CFBundleShortVersionString</key> <string>1.0</string> <key>CFBundleSignature</key> <string>????</string> <key>CFBundleVersion</key> <string>1</string> <key>GADApplicationIdentifier</key> <string>ca-app-pub-3940256099942544~1458002511</string> <key>LSRequiresIPhoneOS</key> <true/> <key>UIApplicationSupportsIndirectInputEvents</key> <true/> <key>UILaunchStoryboardName</key> <string>LaunchScreen</string> <key>UIMainStoryboardFile</key> <string>Main</string> <key>UISupportedInterfaceOrientations</key> <array> <string>UIInterfaceOrientationPortrait</string> <string>UIInterfaceOrientationLandscapeLeft</string> <string>UIInterfaceOrientationLandscapeRight</string> </array> <key>UISupportedInterfaceOrientations~ipad</key> <array> <string>UIInterfaceOrientationPortrait</string> <string>UIInterfaceOrientationPortraitUpsideDown</string> <string>UIInterfaceOrientationLandscapeLeft</string> <string>UIInterfaceOrientationLandscapeRight</string> </array> <key>io.flutter.embedded_views_preview</key> <true/> <key>io.flutter.metal_preview</key> <true/> </dict> </plist>
flutter/dev/benchmarks/platform_views_layout/ios/Runner/Info.plist/0
{ "file_path": "flutter/dev/benchmarks/platform_views_layout/ios/Runner/Info.plist", "repo_id": "flutter", "token_count": 691 }
494
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package dev.benchmarks.platform_views_layout_hybrid_composition; import android.content.Context; import android.graphics.Color; import android.view.View; import android.widget.TextView; import io.flutter.plugin.platform.PlatformView; public class DummyPlatformView implements PlatformView { private final TextView textView; @SuppressWarnings("unchecked") DummyPlatformView(final Context context, int id) { textView = new TextView(context); textView.setTextSize(72); textView.setBackgroundColor(Color.rgb(255, 255, 255)); textView.setText("DummyPlatformView"); } @Override public View getView() { return textView; } @Override public void dispose() {} }
flutter/dev/benchmarks/platform_views_layout_hybrid_composition/android/app/src/main/java/dev/bechmarks/platform_views_layout/DummyPlatformView.java/0
{ "file_path": "flutter/dev/benchmarks/platform_views_layout_hybrid_composition/android/app/src/main/java/dev/bechmarks/platform_views_layout/DummyPlatformView.java", "repo_id": "flutter", "token_count": 298 }
495
# Options used by the localizations tool ## `arb-dir` sets the input directory. The output directory will match ## the input directory if the output directory is not set. arb-dir: lib/i18n ## `header-file` is the file that contains a custom ## header for each of the generated files. header-file: header.txt ## `output-class` is the name of the localizations class your ## Flutter application will use. The file will need to be ## imported throughout your application. output-class: StockStrings ## `output-localization-file` is the name of the generated file. output-localization-file: stock_strings.dart ## `template-arb-file` describes the template arb file that the tool ## will use to check and validate the remaining arb files when ## generating Flutter's localization files. synthetic-package: false template-arb-file: stocks_en.arb ## setting `nullable-getter` to false generates a non-nullable ## StockStrings getter. This removes the need for adding null checks ## in the Flutter application itself. nullable-getter: false
flutter/dev/benchmarks/test_apps/stocks/l10n.yaml/0
{ "file_path": "flutter/dev/benchmarks/test_apps/stocks/l10n.yaml", "repo_id": "flutter", "token_count": 270 }
496
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'stock_arrow.dart'; import 'stock_data.dart'; class _StockSymbolView extends StatelessWidget { const _StockSymbolView({ required this.stock, required this.arrow, }); final Stock stock; final Widget arrow; @override Widget build(BuildContext context) { final String lastSale = '\$${stock.lastSale.toStringAsFixed(2)}'; String changeInPrice = '${stock.percentChange.toStringAsFixed(2)}%'; if (stock.percentChange > 0) { changeInPrice = '+$changeInPrice'; } final TextStyle headings = Theme.of(context).textTheme.bodyLarge!; return Container( padding: const EdgeInsets.all(20.0), child: Column( mainAxisSize: MainAxisSize.min, children: <Widget>[ Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ Text( stock.symbol, key: ValueKey<String>('${stock.symbol}_symbol_name'), style: Theme.of(context).textTheme.displaySmall, ), arrow, ], ), Text('Last Sale', style: headings), Text('$lastSale ($changeInPrice)'), Container( height: 8.0 ), Text('Market Cap', style: headings), Text(stock.marketCap), Container( height: 8.0 ), RichText( text: TextSpan( style: DefaultTextStyle.of(context).style.merge(const TextStyle(fontSize: 8.0)), text: 'Prices may be delayed by ', children: const <TextSpan>[ TextSpan(text: 'several', style: TextStyle(fontStyle: FontStyle.italic)), TextSpan(text: ' years.'), ], ), ), ], ), ); } } class StockSymbolPage extends StatelessWidget { const StockSymbolPage({ super.key, required this.symbol, required this.stocks, }); final String symbol; final StockData stocks; @override Widget build(BuildContext context) { return AnimatedBuilder( animation: stocks, builder: (BuildContext context, Widget? child) { final Stock? stock = stocks[symbol]; return Scaffold( appBar: AppBar( title: Text(stock?.name ?? symbol), ), body: SingleChildScrollView( child: Container( margin: const EdgeInsets.all(20.0), child: Card( child: AnimatedCrossFade( duration: const Duration(milliseconds: 300), firstChild: const Padding( padding: EdgeInsets.all(20.0), child: Center(child: CircularProgressIndicator()), ), secondChild: stock != null ? _StockSymbolView( stock: stock, arrow: Hero( tag: stock, child: StockArrow(percentChange: stock.percentChange), ), ) : Padding( padding: const EdgeInsets.all(20.0), child: Center(child: Text('$symbol not found')), ), crossFadeState: stock == null && stocks.loading ? CrossFadeState.showFirst : CrossFadeState.showSecond, ), ), ), ), ); }, ); } } class StockSymbolBottomSheet extends StatelessWidget { const StockSymbolBottomSheet({ super.key, required this.stock, }); final Stock stock; @override Widget build(BuildContext context) { return Container( padding: const EdgeInsets.all(10.0), decoration: const BoxDecoration( border: Border(top: BorderSide(color: Colors.black26)) ), child: _StockSymbolView( stock: stock, arrow: StockArrow(percentChange: stock.percentChange), ), ); } }
flutter/dev/benchmarks/test_apps/stocks/lib/stock_symbol_viewer.dart/0
{ "file_path": "flutter/dev/benchmarks/test_apps/stocks/lib/stock_symbol_viewer.dart", "repo_id": "flutter", "token_count": 2029 }
497
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'dart:io' as io; import 'package:flutter_devicelab/framework/browser.dart'; import 'package:shelf/shelf.dart'; import 'package:shelf/shelf_io.dart' as shelf_io; import 'package:shelf_static/shelf_static.dart'; /// Runs Chrome, opens the given `appUrl`, and returns the result reported by the /// app. /// /// The app is served from the `appDirectory`. Typically, the app is built /// using `flutter build web` and served from `build/web`. /// /// The launched app is expected to report the result by sending an HTTP POST /// request to "/test-result" containing result data as plain text body of the /// request. This function has no opinion about what that string contains. Future<String> evalTestAppInChrome({ required String appUrl, required String appDirectory, int serverPort = 8080, int browserDebugPort = 8081, }) async { io.HttpServer? server; Chrome? chrome; try { final Completer<String> resultCompleter = Completer<String>(); server = await io.HttpServer.bind('localhost', serverPort); final Cascade cascade = Cascade() .add((Request request) async { if (request.requestedUri.path.endsWith('/test-result')) { resultCompleter.complete(await request.readAsString()); return Response.ok('Test results received'); } return Response.notFound(''); }) .add(createStaticHandler(appDirectory)); shelf_io.serveRequests(server, cascade.handler); final io.Directory userDataDirectory = io.Directory.systemTemp.createTempSync('flutter_chrome_user_data.'); chrome = await Chrome.launch(ChromeOptions( headless: true, debugPort: browserDebugPort, url: appUrl, userDataDirectory: userDataDirectory.path, windowHeight: 500, windowWidth: 500, ), onError: resultCompleter.completeError); return await resultCompleter.future; } finally { chrome?.stop(); await server?.close(); } } typedef ServerRequestListener = void Function(Request); class AppServer { AppServer._(this._server, this.chrome, this.onChromeError); static Future<AppServer> start({ required String appUrl, required String appDirectory, required String cacheControl, int serverPort = 8080, int browserDebugPort = 8081, bool headless = true, List<Handler>? additionalRequestHandlers, }) async { io.HttpServer server; Chrome chrome; server = await io.HttpServer.bind('localhost', serverPort); final Handler staticHandler = createStaticHandler(appDirectory, defaultDocument: 'index.html'); Cascade cascade = Cascade(); if (additionalRequestHandlers != null) { for (final Handler handler in additionalRequestHandlers) { cascade = cascade.add(handler); } } cascade = cascade.add((Request request) async { final Response response = await staticHandler(request); return response.change(headers: <String, Object>{ 'cache-control': cacheControl, }); }); shelf_io.serveRequests(server, cascade.handler); final io.Directory userDataDirectory = io.Directory.systemTemp.createTempSync('flutter_chrome_user_data.'); final Completer<String> chromeErrorCompleter = Completer<String>(); chrome = await Chrome.launch(ChromeOptions( headless: headless, debugPort: browserDebugPort, url: appUrl, userDataDirectory: userDataDirectory.path, ), onError: chromeErrorCompleter.complete); return AppServer._(server, chrome, chromeErrorCompleter.future); } final Future<String> onChromeError; final io.HttpServer _server; final Chrome chrome; Future<void> stop() async { chrome.stop(); await _server.close(); } }
flutter/dev/bots/browser.dart/0
{ "file_path": "flutter/dev/bots/browser.dart", "repo_id": "flutter", "token_count": 1283 }
498
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:core' hide print; import 'dart:io' hide exit; import 'package:path/path.dart' as path; import 'package:shelf/shelf.dart'; import 'browser.dart'; import 'run_command.dart'; import 'test/common.dart'; import 'utils.dart'; final String _bat = Platform.isWindows ? '.bat' : ''; final String _flutterRoot = path.dirname(path.dirname(path.dirname(path.fromUri(Platform.script)))); final String _flutter = path.join(_flutterRoot, 'bin', 'flutter$_bat'); final String _testAppDirectory = path.join(_flutterRoot, 'dev', 'integration_tests', 'web'); final String _testAppWebDirectory = path.join(_testAppDirectory, 'web'); final String _appBuildDirectory = path.join(_testAppDirectory, 'build', 'web'); final String _target = path.join('lib', 'service_worker_test.dart'); final String _targetWithCachedResources = path.join('lib', 'service_worker_test_cached_resources.dart'); final String _targetWithBlockedServiceWorkers = path.join('lib', 'service_worker_test_blocked_service_workers.dart'); final String _targetPath = path.join(_testAppDirectory, _target); enum ServiceWorkerTestType { // Mocks how FF disables service workers. blockedServiceWorkers, // Drops the main.dart.js directly on the page. withoutFlutterJs, // Uses the standard, promise-based, flutterJS initialization. withFlutterJs, // Uses the shorthand engineInitializer.autoStart(); withFlutterJsShort, // Uses onEntrypointLoaded callback instead of returned promise. withFlutterJsEntrypointLoadedEvent, // Same as withFlutterJsEntrypointLoadedEvent, but with TrustedTypes enabled. withFlutterJsTrustedTypesOn, // Same as withFlutterJsEntrypointLoadedEvent, but with nonce required. withFlutterJsNonceOn, // Uses custom serviceWorkerVersion. withFlutterJsCustomServiceWorkerVersion, // Entrypoint generated by `flutter create`. generatedEntrypoint, } // Run a web service worker test as a standalone Dart program. Future<void> main() async { // When updating this list, also update `dev/bots/test.dart`. This `main()` // function is only here for convenience. Adding tests here will not add them // to LUCI. await runWebServiceWorkerTest(headless: false, testType: ServiceWorkerTestType.withoutFlutterJs); await runWebServiceWorkerTest(headless: false, testType: ServiceWorkerTestType.withFlutterJs); await runWebServiceWorkerTest(headless: false, testType: ServiceWorkerTestType.withFlutterJsShort); await runWebServiceWorkerTest(headless: false, testType: ServiceWorkerTestType.withFlutterJsEntrypointLoadedEvent); await runWebServiceWorkerTest(headless: false, testType: ServiceWorkerTestType.withFlutterJsTrustedTypesOn); await runWebServiceWorkerTest(headless: false, testType: ServiceWorkerTestType.withFlutterJsNonceOn); await runWebServiceWorkerTestWithCachingResources(headless: false, testType: ServiceWorkerTestType.withoutFlutterJs); await runWebServiceWorkerTestWithCachingResources(headless: false, testType: ServiceWorkerTestType.withFlutterJs); await runWebServiceWorkerTestWithCachingResources(headless: false, testType: ServiceWorkerTestType.withFlutterJsShort); await runWebServiceWorkerTestWithCachingResources(headless: false, testType: ServiceWorkerTestType.withFlutterJsEntrypointLoadedEvent); await runWebServiceWorkerTestWithCachingResources(headless: false, testType: ServiceWorkerTestType.withFlutterJsTrustedTypesOn); await runWebServiceWorkerTestWithGeneratedEntrypoint(headless: false); await runWebServiceWorkerTestWithBlockedServiceWorkers(headless: false); await runWebServiceWorkerTestWithCustomServiceWorkerVersion(headless: false); if (hasError) { reportErrorsAndExit('${bold}One or more tests failed.$reset'); } reportSuccessAndExit('${bold}Tests successful.$reset'); } // Regression test for https://github.com/flutter/flutter/issues/109093. // // Tests the entrypoint that's generated by `flutter create`. Future<void> runWebServiceWorkerTestWithGeneratedEntrypoint({ required bool headless, }) async { await _generateEntrypoint(); await runWebServiceWorkerTestWithCachingResources(headless: headless, testType: ServiceWorkerTestType.generatedEntrypoint); } Future<void> _generateEntrypoint() async { final Directory tempDirectory = Directory.systemTemp.createTempSync('flutter_web_generated_entrypoint.'); await runCommand( _flutter, <String>[ 'create', 'generated_entrypoint_test' ], workingDirectory: tempDirectory.path, ); final File generatedEntrypoint = File(path.join(tempDirectory.path, 'generated_entrypoint_test', 'web', 'index.html')); final String generatedEntrypointCode = generatedEntrypoint.readAsStringSync(); final File testEntrypoint = File(path.join( _testAppWebDirectory, _testTypeToIndexFile(ServiceWorkerTestType.generatedEntrypoint), )); testEntrypoint.writeAsStringSync(generatedEntrypointCode); tempDirectory.deleteSync(recursive: true); } Future<void> _setAppVersion(int version) async { final File targetFile = File(_targetPath); await targetFile.writeAsString( (await targetFile.readAsString()).replaceFirst( RegExp(r'CLOSE\?version=\d+'), 'CLOSE?version=$version', ) ); } String _testTypeToIndexFile(ServiceWorkerTestType type) { return switch (type) { ServiceWorkerTestType.blockedServiceWorkers => 'index_with_blocked_service_workers.html', ServiceWorkerTestType.withFlutterJs => 'index_with_flutterjs.html', ServiceWorkerTestType.withoutFlutterJs => 'index_without_flutterjs.html', ServiceWorkerTestType.withFlutterJsShort => 'index_with_flutterjs_short.html', ServiceWorkerTestType.withFlutterJsEntrypointLoadedEvent => 'index_with_flutterjs_entrypoint_loaded.html', ServiceWorkerTestType.withFlutterJsTrustedTypesOn => 'index_with_flutterjs_el_tt_on.html', ServiceWorkerTestType.withFlutterJsNonceOn => 'index_with_flutterjs_el_nonce.html', ServiceWorkerTestType.withFlutterJsCustomServiceWorkerVersion => 'index_with_flutterjs_custom_sw_version.html', ServiceWorkerTestType.generatedEntrypoint => 'generated_entrypoint.html', }; } Future<void> _rebuildApp({ required int version, required ServiceWorkerTestType testType, required String target }) async { await _setAppVersion(version); await runCommand( _flutter, <String>[ 'clean' ], workingDirectory: _testAppDirectory, ); await runCommand( 'cp', <String>[ _testTypeToIndexFile(testType), 'index.html', ], workingDirectory: _testAppWebDirectory, ); await runCommand( _flutter, <String>['build', 'web', '--web-resources-cdn', '--profile', '-t', target], workingDirectory: _testAppDirectory, environment: <String, String>{ 'FLUTTER_WEB': 'true', }, ); } void _expectRequestCounts( Map<String, int> expectedCounts, Map<String, int> requestedPathCounts, ) { expect(requestedPathCounts, expectedCounts); requestedPathCounts.clear(); } Future<void> _waitForAppToLoad( Map<String, int> waitForCounts, Map<String, int> requestedPathCounts, AppServer? server ) async { print('Waiting for app to load $waitForCounts'); await Future.any(<Future<Object?>>[ () async { int tries = 1; while (!waitForCounts.entries.every((MapEntry<String, int> entry) => (requestedPathCounts[entry.key] ?? 0) >= entry.value)) { if (tries++ % 20 == 0) { print('Still waiting. Requested so far: $requestedPathCounts'); } await Future<void>.delayed(const Duration(milliseconds: 100)); } }(), server!.onChromeError.then((String error) { throw Exception('Chrome error: $error'); }), ]); } /// A drop-in replacement for `package:test` expect that can run outside the /// test zone. void expect(Object? actual, Object? expected) { final Matcher matcher = wrapMatcher(expected); // matchState needs to be of type <Object?, Object?>, see https://github.com/flutter/flutter/issues/99522 final Map<Object?, Object?> matchState = <Object?, Object?>{}; if (matcher.matches(actual, matchState)) { return; } final StringDescription mismatchDescription = StringDescription(); matcher.describeMismatch(actual, mismatchDescription, matchState, true); throw TestFailure(mismatchDescription.toString()); } Future<void> runWebServiceWorkerTest({ required bool headless, required ServiceWorkerTestType testType, }) async { final Map<String, int> requestedPathCounts = <String, int>{}; void expectRequestCounts(Map<String, int> expectedCounts) => _expectRequestCounts(expectedCounts, requestedPathCounts); AppServer? server; Future<void> waitForAppToLoad(Map<String, int> waitForCounts) async => _waitForAppToLoad(waitForCounts, requestedPathCounts, server); String? reportedVersion; Future<void> startAppServer({ required String cacheControl, }) async { final int serverPort = await findAvailablePortAndPossiblyCauseFlakyTests(); final int browserDebugPort = await findAvailablePortAndPossiblyCauseFlakyTests(); server = await AppServer.start( headless: headless, cacheControl: cacheControl, // TODO(yjbanov): use a better port disambiguation strategy than trying // to guess what ports other tests use. appUrl: 'http://localhost:$serverPort/index.html', serverPort: serverPort, browserDebugPort: browserDebugPort, appDirectory: _appBuildDirectory, additionalRequestHandlers: <Handler>[ (Request request) { final String requestedPath = request.url.path; requestedPathCounts.putIfAbsent(requestedPath, () => 0); requestedPathCounts[requestedPath] = requestedPathCounts[requestedPath]! + 1; if (requestedPath == 'CLOSE') { reportedVersion = request.url.queryParameters['version']; return Response.ok('OK'); } return Response.notFound(''); }, ], ); } // Preserve old index.html as index_og.html so we can restore it later for other tests await runCommand( 'mv', <String>[ 'index.html', 'index_og.html', ], workingDirectory: _testAppWebDirectory, ); final bool shouldExpectFlutterJs = testType != ServiceWorkerTestType.withoutFlutterJs; print('BEGIN runWebServiceWorkerTest(headless: $headless, testType: $testType)'); try { ///// // Attempt to load a different version of the service worker! ///// await _rebuildApp(version: 1, testType: testType, target: _target); print('Call update() on the current web worker'); await startAppServer(cacheControl: 'max-age=0'); await waitForAppToLoad(<String, int> { if (shouldExpectFlutterJs) 'flutter.js': 1, 'CLOSE': 1, }); expect(reportedVersion, '1'); reportedVersion = null; await server!.chrome.reloadPage(ignoreCache: true); await waitForAppToLoad(<String, int> { if (shouldExpectFlutterJs) 'flutter.js': 2, 'CLOSE': 2, }); expect(reportedVersion, '1'); reportedVersion = null; await _rebuildApp(version: 2, testType: testType, target: _target); await server!.chrome.reloadPage(ignoreCache: true); await waitForAppToLoad(<String, int>{ if (shouldExpectFlutterJs) 'flutter.js': 3, 'CLOSE': 3, }); expect(reportedVersion, '2'); reportedVersion = null; requestedPathCounts.clear(); await server!.stop(); ////////////////////////////////////////////////////// // Caching server ////////////////////////////////////////////////////// await _rebuildApp(version: 1, testType: testType, target: _target); print('With cache: test first page load'); await startAppServer(cacheControl: 'max-age=3600'); await waitForAppToLoad(<String, int>{ 'CLOSE': 1, 'flutter_service_worker.js': 1, }); expectRequestCounts(<String, int>{ // Even though the server is caching index.html is downloaded twice, // once by the initial page load, and once by the service worker. // Other resources are loaded once only by the service worker. 'index.html': 2, if (shouldExpectFlutterJs) 'flutter.js': 1, 'main.dart.js': 1, 'flutter_service_worker.js': 1, 'flutter_bootstrap.js': 1, 'assets/FontManifest.json': 1, 'assets/AssetManifest.bin.json': 1, 'assets/fonts/MaterialIcons-Regular.otf': 1, 'CLOSE': 1, // In headless mode Chrome does not load 'manifest.json' and 'favicon.png'. if (!headless) ...<String, int>{ 'manifest.json': 1, 'favicon.png': 1, }, }); expect(reportedVersion, '1'); reportedVersion = null; print('With cache: test page reload'); await server!.chrome.reloadPage(); await waitForAppToLoad(<String, int>{ 'CLOSE': 1, 'flutter_service_worker.js': 1, }); expectRequestCounts(<String, int>{ 'flutter_service_worker.js': 1, 'CLOSE': 1, }); expect(reportedVersion, '1'); reportedVersion = null; print('With cache: test page reload after rebuild'); await _rebuildApp(version: 2, testType: testType, target: _target); // Since we're caching, we need to ignore cache when reloading the page. await server!.chrome.reloadPage(ignoreCache: true); await waitForAppToLoad(<String, int>{ 'CLOSE': 1, 'flutter_service_worker.js': 2, }); expectRequestCounts(<String, int>{ 'index.html': 2, if (shouldExpectFlutterJs) 'flutter.js': 1, 'flutter_service_worker.js': 2, 'flutter_bootstrap.js': 1, 'main.dart.js': 1, 'assets/AssetManifest.bin.json': 1, 'assets/FontManifest.json': 1, 'CLOSE': 1, if (!headless) 'favicon.png': 1, }); expect(reportedVersion, '2'); reportedVersion = null; await server!.stop(); ////////////////////////////////////////////////////// // Non-caching server ////////////////////////////////////////////////////// print('No cache: test first page load'); await _rebuildApp(version: 3, testType: testType, target: _target); await startAppServer(cacheControl: 'max-age=0'); await waitForAppToLoad(<String, int>{ 'CLOSE': 1, 'flutter_service_worker.js': 1, }); expectRequestCounts(<String, int>{ 'index.html': 2, if (shouldExpectFlutterJs) 'flutter.js': 1, 'main.dart.js': 1, 'assets/FontManifest.json': 1, 'flutter_service_worker.js': 1, 'flutter_bootstrap.js': 1, 'assets/AssetManifest.bin.json': 1, 'assets/fonts/MaterialIcons-Regular.otf': 1, 'CLOSE': 1, // In headless mode Chrome does not load 'manifest.json' and 'favicon.png'. if (!headless) ...<String, int>{ 'manifest.json': 1, 'favicon.png': 1, }, }); expect(reportedVersion, '3'); reportedVersion = null; print('No cache: test page reload'); await server!.chrome.reloadPage(); await waitForAppToLoad(<String, int>{ 'CLOSE': 1, if (shouldExpectFlutterJs) 'flutter.js': 1, 'flutter_service_worker.js': 1, }); expectRequestCounts(<String, int>{ if (shouldExpectFlutterJs) 'flutter.js': 1, 'flutter_service_worker.js': 1, 'CLOSE': 1, if (!headless) 'manifest.json': 1, }); expect(reportedVersion, '3'); reportedVersion = null; print('No cache: test page reload after rebuild'); await _rebuildApp(version: 4, testType: testType, target: _target); // TODO(yjbanov): when running Chrome with DevTools protocol, for some // reason a hard refresh is still required. This works without a hard // refresh when running Chrome manually as normal. At the time of writing // this test I wasn't able to figure out what's wrong with the way we run // Chrome from tests. await server!.chrome.reloadPage(ignoreCache: true); await waitForAppToLoad(<String, int>{ 'CLOSE': 1, 'flutter_service_worker.js': 1, }); expectRequestCounts(<String, int>{ 'index.html': 2, if (shouldExpectFlutterJs) 'flutter.js': 1, 'flutter_service_worker.js': 2, 'flutter_bootstrap.js': 1, 'main.dart.js': 1, 'assets/AssetManifest.bin.json': 1, 'assets/FontManifest.json': 1, 'CLOSE': 1, if (!headless) ...<String, int>{ 'manifest.json': 1, 'favicon.png': 1, }, }); expect(reportedVersion, '4'); reportedVersion = null; } finally { await runCommand( 'mv', <String>[ 'index_og.html', 'index.html', ], workingDirectory: _testAppWebDirectory, ); await _setAppVersion(1); await server?.stop(); } print('END runWebServiceWorkerTest(headless: $headless, testType: $testType)'); } Future<void> runWebServiceWorkerTestWithCachingResources({ required bool headless, required ServiceWorkerTestType testType }) async { final Map<String, int> requestedPathCounts = <String, int>{}; void expectRequestCounts(Map<String, int> expectedCounts) => _expectRequestCounts(expectedCounts, requestedPathCounts); AppServer? server; Future<void> waitForAppToLoad(Map<String, int> waitForCounts) async => _waitForAppToLoad(waitForCounts, requestedPathCounts, server); Future<void> startAppServer({ required String cacheControl, }) async { final int serverPort = await findAvailablePortAndPossiblyCauseFlakyTests(); final int browserDebugPort = await findAvailablePortAndPossiblyCauseFlakyTests(); server = await AppServer.start( headless: headless, cacheControl: cacheControl, // TODO(yjbanov): use a better port disambiguation strategy than trying // to guess what ports other tests use. appUrl: 'http://localhost:$serverPort/index.html', serverPort: serverPort, browserDebugPort: browserDebugPort, appDirectory: _appBuildDirectory, additionalRequestHandlers: <Handler>[ (Request request) { final String requestedPath = request.url.path; requestedPathCounts.putIfAbsent(requestedPath, () => 0); requestedPathCounts[requestedPath] = requestedPathCounts[requestedPath]! + 1; if (requestedPath == 'assets/fonts/MaterialIcons-Regular.otf') { return Response.internalServerError(); } return Response.notFound(''); }, ], ); } // Preserve old index.html as index_og.html so we can restore it later for other tests await runCommand( 'mv', <String>[ 'index.html', 'index_og.html', ], workingDirectory: _testAppWebDirectory, ); final bool usesFlutterBootstrapJs = testType == ServiceWorkerTestType.generatedEntrypoint; final bool shouldExpectFlutterJs = !usesFlutterBootstrapJs && testType != ServiceWorkerTestType.withoutFlutterJs; print('BEGIN runWebServiceWorkerTestWithCachingResources(headless: $headless, testType: $testType)'); try { ////////////////////////////////////////////////////// // Caching server ////////////////////////////////////////////////////// await _rebuildApp(version: 1, testType: testType, target: _targetWithCachedResources); print('With cache: test first page load'); await startAppServer(cacheControl: 'max-age=3600'); await waitForAppToLoad(<String, int>{ 'assets/fonts/MaterialIcons-Regular.otf': 1, 'flutter_service_worker.js': 1, }); expectRequestCounts(<String, int>{ // Even though the server is caching index.html is downloaded twice, // once by the initial page load, and once by the service worker. // Other resources are loaded once only by the service worker. 'index.html': 2, if (shouldExpectFlutterJs) 'flutter.js': 1, 'main.dart.js': 1, 'flutter_service_worker.js': 1, 'flutter_bootstrap.js': usesFlutterBootstrapJs ? 2 : 1, 'assets/FontManifest.json': 1, 'assets/AssetManifest.bin.json': 1, 'assets/fonts/MaterialIcons-Regular.otf': 1, // In headless mode Chrome does not load 'manifest.json' and 'favicon.png'. if (!headless) ...<String, int>{ 'manifest.json': 1, 'favicon.png': 1, }, }); print('With cache: test first page reload'); await server!.chrome.reloadPage(); await waitForAppToLoad(<String, int>{ 'assets/fonts/MaterialIcons-Regular.otf': 1, 'flutter_service_worker.js': 1, }); expectRequestCounts(<String, int>{ 'assets/fonts/MaterialIcons-Regular.otf': 1, 'flutter_service_worker.js': 1, }); print('With cache: test second page reload'); await server!.chrome.reloadPage(); await waitForAppToLoad(<String, int>{ 'assets/fonts/MaterialIcons-Regular.otf': 1, 'flutter_service_worker.js': 1, }); expectRequestCounts(<String, int>{ 'assets/fonts/MaterialIcons-Regular.otf': 1, 'flutter_service_worker.js': 1, }); print('With cache: test third page reload'); await server!.chrome.reloadPage(); await waitForAppToLoad(<String, int>{ 'assets/fonts/MaterialIcons-Regular.otf': 1, 'flutter_service_worker.js': 1, }); expectRequestCounts(<String, int>{ 'assets/fonts/MaterialIcons-Regular.otf': 1, 'flutter_service_worker.js': 1, }); print('With cache: test page reload after rebuild'); await _rebuildApp(version: 1, testType: testType, target: _targetWithCachedResources); // Since we're caching, we need to ignore cache when reloading the page. await server!.chrome.reloadPage(ignoreCache: true); await waitForAppToLoad(<String, int>{ 'assets/fonts/MaterialIcons-Regular.otf': 1, 'flutter_service_worker.js': 1, }); expectRequestCounts(<String, int>{ 'index.html': 2, if (shouldExpectFlutterJs) 'flutter.js': 1, 'main.dart.js': 1, 'flutter_service_worker.js': 2, 'flutter_bootstrap.js': usesFlutterBootstrapJs ? 2 : 1, 'assets/FontManifest.json': 1, 'assets/AssetManifest.bin.json': 1, 'assets/fonts/MaterialIcons-Regular.otf': 1, // In headless mode Chrome does not load 'manifest.json' and 'favicon.png'. if (!headless) ...<String, int>{ 'favicon.png': 1, }, }); } finally { await runCommand( 'mv', <String>[ 'index_og.html', 'index.html', ], workingDirectory: _testAppWebDirectory, ); await server?.stop(); } print('END runWebServiceWorkerTestWithCachingResources(headless: $headless, testType: $testType)'); } Future<void> runWebServiceWorkerTestWithBlockedServiceWorkers({ required bool headless }) async { final Map<String, int> requestedPathCounts = <String, int>{}; void expectRequestCounts(Map<String, int> expectedCounts) => _expectRequestCounts(expectedCounts, requestedPathCounts); AppServer? server; Future<void> waitForAppToLoad(Map<String, int> waitForCounts) async => _waitForAppToLoad(waitForCounts, requestedPathCounts, server); Future<void> startAppServer({ required String cacheControl, }) async { final int serverPort = await findAvailablePortAndPossiblyCauseFlakyTests(); final int browserDebugPort = await findAvailablePortAndPossiblyCauseFlakyTests(); server = await AppServer.start( headless: headless, cacheControl: cacheControl, // TODO(yjbanov): use a better port disambiguation strategy than trying // to guess what ports other tests use. appUrl: 'http://localhost:$serverPort/index.html', serverPort: serverPort, browserDebugPort: browserDebugPort, appDirectory: _appBuildDirectory, additionalRequestHandlers: <Handler>[ (Request request) { final String requestedPath = request.url.path; requestedPathCounts.putIfAbsent(requestedPath, () => 0); requestedPathCounts[requestedPath] = requestedPathCounts[requestedPath]! + 1; if (requestedPath == 'CLOSE') { return Response.ok('OK'); } return Response.notFound(''); }, ], ); } // Preserve old index.html as index_og.html so we can restore it later for other tests await runCommand( 'mv', <String>[ 'index.html', 'index_og.html', ], workingDirectory: _testAppWebDirectory, ); print('BEGIN runWebServiceWorkerTestWithBlockedServiceWorkers(headless: $headless)'); try { await _rebuildApp(version: 1, testType: ServiceWorkerTestType.blockedServiceWorkers, target: _targetWithBlockedServiceWorkers); print('Ensure app starts (when service workers are blocked)'); await startAppServer(cacheControl: 'max-age=3600'); await waitForAppToLoad(<String, int>{ 'CLOSE': 1, }); expectRequestCounts(<String, int>{ 'index.html': 1, 'flutter.js': 1, 'main.dart.js': 1, 'assets/FontManifest.json': 1, 'assets/fonts/MaterialIcons-Regular.otf': 1, 'CLOSE': 1, // In headless mode Chrome does not load 'manifest.json' and 'favicon.png'. if (!headless) ...<String, int>{ 'manifest.json': 1, 'favicon.png': 1, }, }); } finally { await runCommand( 'mv', <String>[ 'index_og.html', 'index.html', ], workingDirectory: _testAppWebDirectory, ); await server?.stop(); } print('END runWebServiceWorkerTestWithBlockedServiceWorkers(headless: $headless)'); } /// Regression test for https://github.com/flutter/flutter/issues/130212. Future<void> runWebServiceWorkerTestWithCustomServiceWorkerVersion({ required bool headless, }) async { final Map<String, int> requestedPathCounts = <String, int>{}; void expectRequestCounts(Map<String, int> expectedCounts) => _expectRequestCounts(expectedCounts, requestedPathCounts); AppServer? server; Future<void> waitForAppToLoad(Map<String, int> waitForCounts) async => _waitForAppToLoad(waitForCounts, requestedPathCounts, server); Future<void> startAppServer({ required String cacheControl, }) async { final int serverPort = await findAvailablePortAndPossiblyCauseFlakyTests(); final int browserDebugPort = await findAvailablePortAndPossiblyCauseFlakyTests(); server = await AppServer.start( headless: headless, cacheControl: cacheControl, // TODO(yjbanov): use a better port disambiguation strategy than trying // to guess what ports other tests use. appUrl: 'http://localhost:$serverPort/index.html', serverPort: serverPort, browserDebugPort: browserDebugPort, appDirectory: _appBuildDirectory, additionalRequestHandlers: <Handler>[ (Request request) { final String requestedPath = request.url.path; requestedPathCounts.putIfAbsent(requestedPath, () => 0); requestedPathCounts[requestedPath] = requestedPathCounts[requestedPath]! + 1; if (requestedPath == 'CLOSE') { return Response.ok('OK'); } return Response.notFound(''); }, ], ); } // Preserve old index.html as index_og.html so we can restore it later for other tests await runCommand( 'mv', <String>[ 'index.html', 'index_og.html', ], workingDirectory: _testAppWebDirectory, ); print('BEGIN runWebServiceWorkerTestWithCustomServiceWorkerVersion(headless: $headless)'); try { await _rebuildApp(version: 1, testType: ServiceWorkerTestType.withFlutterJsCustomServiceWorkerVersion, target: _target); print('Test page load'); await startAppServer(cacheControl: 'max-age=0'); await waitForAppToLoad(<String, int>{ 'CLOSE': 1, 'flutter_service_worker.js': 1, 'assets/fonts/MaterialIcons-Regular.otf': 1, }); expectRequestCounts(<String, int>{ 'index.html': 2, 'flutter.js': 1, 'main.dart.js': 1, 'CLOSE': 1, 'flutter_service_worker.js': 1, 'flutter_bootstrap.js': 1, 'assets/FontManifest.json': 1, 'assets/AssetManifest.bin.json': 1, 'assets/fonts/MaterialIcons-Regular.otf': 1, // In headless mode Chrome does not load 'manifest.json' and 'favicon.png'. if (!headless) ...<String, int>{ 'manifest.json': 1, 'favicon.png': 1, }, }); print('Test page reload, ensure service worker is not reloaded'); await server!.chrome.reloadPage(ignoreCache: true); await waitForAppToLoad(<String, int>{ 'CLOSE': 1, 'flutter.js': 1, }); expectRequestCounts(<String, int>{ 'index.html': 1, 'flutter.js': 1, 'main.dart.js': 1, 'assets/FontManifest.json': 1, 'assets/fonts/MaterialIcons-Regular.otf': 1, 'CLOSE': 1, // In headless mode Chrome does not load 'manifest.json' and 'favicon.png'. if (!headless) ...<String, int>{ 'manifest.json': 1, 'favicon.png': 1, }, }); print('Test page reload after rebuild, ensure service worker is not reloaded'); await _rebuildApp(version: 1, testType: ServiceWorkerTestType.withFlutterJsCustomServiceWorkerVersion, target: _target); await server!.chrome.reloadPage(ignoreCache: true); await waitForAppToLoad(<String, int>{ 'CLOSE': 1, 'flutter.js': 1, }); expectRequestCounts(<String, int>{ 'index.html': 1, 'flutter.js': 1, 'main.dart.js': 1, 'assets/FontManifest.json': 1, 'assets/fonts/MaterialIcons-Regular.otf': 1, 'CLOSE': 1, // In headless mode Chrome does not load 'manifest.json' and 'favicon.png'. if (!headless) ...<String, int>{ 'manifest.json': 1, 'favicon.png': 1, }, }); } finally { await runCommand( 'mv', <String>[ 'index_og.html', 'index.html', ], workingDirectory: _testAppWebDirectory, ); await server?.stop(); } print('END runWebServiceWorkerTestWithCustomServiceWorkerVersion(headless: $headless)'); }
flutter/dev/bots/service_worker_test.dart/0
{ "file_path": "flutter/dev/bots/service_worker_test.dart", "repo_id": "flutter", "token_count": 11589 }
499
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /// Sample Code /// /// Should not be tag-enforced, no analysis failures should be found. /// /// {@tool snippet} /// Sample invocations of [matchesGoldenFile]. /// /// ```dart /// await expectLater( /// find.text('Save'), /// matchesGoldenFile('save.png'), /// ); /// /// await expectLater( /// image, /// matchesGoldenFile('save.png'), /// ); /// /// await expectLater( /// imageFuture, /// matchesGoldenFile( /// 'save.png', /// version: 2, /// ), /// ); /// /// await expectLater( /// find.byType(MyWidget), /// matchesGoldenFile('goldens/myWidget.png'), /// ); /// ``` /// {@end-tool} /// String? foo; // Other comments // matchesGoldenFile('comment.png'); String literal = 'matchesGoldenFile()'; // flutter_ignore: golden_tag (see analyze.dart)
flutter/dev/bots/test/analyze-test-input/root/packages/foo/golden_doc.dart/0
{ "file_path": "flutter/dev/bots/test/analyze-test-input/root/packages/foo/golden_doc.dart", "repo_id": "flutter", "token_count": 306 }
500
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:io'; import 'package:path/path.dart' as path; import 'common.dart'; void main() { test('We are in a directory with a space in it', () async { // The Flutter SDK should be in a directory with a space in it, to make sure // our tools support that. final String? expectedName = Platform.environment['FLUTTER_SDK_PATH_WITH_SPACE']; expect(expectedName, 'flutter sdk'); expect(expectedName, contains(' ')); final List<String> parts = path.split(Directory.current.absolute.path); expect(parts.reversed.take(3), <String?>['bots', 'dev', expectedName]); }, skip: true); // https://github.com/flutter/flutter/issues/87285 }
flutter/dev/bots/test/sdk_directory_has_space_test.dart/0
{ "file_path": "flutter/dev/bots/test/sdk_directory_has_space_test.dart", "repo_id": "flutter", "token_count": 268 }
501
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:args/args.dart'; import 'package:args/command_runner.dart'; import 'package:file/file.dart'; import './git.dart'; import './globals.dart' show releaseCandidateBranchRegex; import './repository.dart'; import './stdio.dart'; import './version.dart'; const String kRemote = 'remote'; class CandidatesCommand extends Command<void> { CandidatesCommand({ required this.flutterRoot, required this.checkouts, }) : git = Git(checkouts.processManager), stdio = checkouts.stdio { argParser.addOption( kRemote, help: 'Which remote name to query for branches.', defaultsTo: 'upstream', ); } final Checkouts checkouts; final Directory flutterRoot; final Git git; final Stdio stdio; @override String get name => 'candidates'; @override String get description => 'List release candidates.'; @override Future<void> run() async { final ArgResults results = argResults!; await git.run( <String>['fetch', results[kRemote] as String], 'Fetch from remote ${results[kRemote]}', workingDirectory: flutterRoot.path, ); final FrameworkRepository framework = HostFrameworkRepository( checkouts: checkouts, name: 'framework-for-candidates', upstreamPath: flutterRoot.path, ); final Version currentVersion = await framework.flutterVersion(); stdio.printStatus('currentVersion = $currentVersion'); final List<String> branches = (await git.getOutput( <String>[ 'branch', '--no-color', '--remotes', '--list', '${results[kRemote]}/*', ], 'List all remote branches', workingDirectory: flutterRoot.path, )).split('\n'); // Pattern for extracting only the branch name via sub-group 1 final RegExp remotePattern = RegExp('${results[kRemote]}\\/(.*)'); for (final String branchName in branches) { final RegExpMatch? candidateMatch = releaseCandidateBranchRegex.firstMatch(branchName); if (candidateMatch == null) { continue; } final int currentX = currentVersion.x; final int currentY = currentVersion.y; final int currentZ = currentVersion.z; final int currentM = currentVersion.m ?? 0; final int x = int.parse(candidateMatch.group(1)!); final int y = int.parse(candidateMatch.group(2)!); final int m = int.parse(candidateMatch.group(3)!); final RegExpMatch? match = remotePattern.firstMatch(branchName); // If this is not the correct remote if (match == null) { continue; } if (x < currentVersion.x) { continue; } if (x == currentVersion.x && y < currentVersion.y) { continue; } if (x == currentX && y == currentY && currentZ == 0 && m <= currentM) { continue; } stdio.printStatus(match.group(1)!); } } }
flutter/dev/conductor/core/lib/src/candidates.dart/0
{ "file_path": "flutter/dev/conductor/core/lib/src/candidates.dart", "repo_id": "flutter", "token_count": 1133 }
502
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:args/args.dart'; import 'package:args/command_runner.dart'; import 'package:file/file.dart'; import 'package:fixnum/fixnum.dart'; import 'package:meta/meta.dart'; import 'package:platform/platform.dart'; import 'package:process/process.dart'; import 'context.dart'; import 'git.dart'; import 'globals.dart'; import 'proto/conductor_state.pb.dart' as pb; import 'proto/conductor_state.pbenum.dart'; import 'repository.dart'; import 'state.dart' as state_import; import 'stdio.dart'; import 'version.dart'; const String kCandidateOption = 'candidate-branch'; const String kDartRevisionOption = 'dart-revision'; const String kEngineUpstreamOption = 'engine-upstream'; const String kFrameworkMirrorOption = 'framework-mirror'; const String kFrameworkUpstreamOption = 'framework-upstream'; const String kEngineMirrorOption = 'engine-mirror'; const String kReleaseOption = 'release-channel'; const String kStateOption = 'state-file'; const String kVersionOverrideOption = 'version-override'; const String kGithubUsernameOption = 'github-username'; /// Command to print the status of the current Flutter release. /// /// This command has many required options which the user must provide /// via command line arguments (or optionally environment variables). /// /// This command is the one with the worst user experience (as the user has to /// carefully type out many different options into their terminal) and the one /// that would benefit the most from a GUI frontend. This command will /// optionally read its options from an environment variable to facilitate a workflow /// in which configuration is provided by editing a bash script that sets environment /// variables and then invokes the conductor tool. class StartCommand extends Command<void> { StartCommand({ required this.checkouts, required this.conductorVersion, }) : platform = checkouts.platform, processManager = checkouts.processManager, fileSystem = checkouts.fileSystem, stdio = checkouts.stdio { final String defaultPath = state_import.defaultStateFilePath(platform); argParser.addOption( kCandidateOption, help: 'The candidate branch the release will be based on.', ); argParser.addOption( kReleaseOption, help: 'The target release channel for the release.', allowed: kBaseReleaseChannels, ); argParser.addOption( kFrameworkUpstreamOption, defaultsTo: FrameworkRepository.defaultUpstream, help: 'Configurable Framework repo upstream remote. Primarily for testing.', hide: true, ); argParser.addOption( kEngineUpstreamOption, defaultsTo: EngineRepository.defaultUpstream, help: 'Configurable Engine repo upstream remote. Primarily for testing.', hide: true, ); argParser.addOption( kStateOption, defaultsTo: defaultPath, help: 'Path to persistent state file. Defaults to $defaultPath', ); argParser.addOption( kDartRevisionOption, help: 'New Dart revision to cherrypick.', ); argParser.addFlag( kForceFlag, abbr: 'f', help: 'Override all validations of the command line inputs.', ); argParser.addOption( kVersionOverrideOption, help: 'Explicitly set the desired version. This should only be used if ' 'the version computed by the tool is not correct.', ); argParser.addOption( kGithubUsernameOption, help: 'Github username', ); } final Checkouts checkouts; final String conductorVersion; final FileSystem fileSystem; final Platform platform; final ProcessManager processManager; final Stdio stdio; @override String get name => 'start'; @override String get description => 'Initialize a new Flutter release.'; @override Future<void> run() async { final ArgResults argumentResults = argResults!; if (!platform.isMacOS && !platform.isLinux) { throw ConductorException( 'Error! This tool is only supported on macOS and Linux', ); } final String frameworkUpstream = getValueFromEnvOrArgs( kFrameworkUpstreamOption, argumentResults, platform.environment, )!; final String githubUsername = getValueFromEnvOrArgs( kGithubUsernameOption, argumentResults, platform.environment, )!; final String frameworkMirror = '[email protected]:$githubUsername/flutter.git'; final String engineUpstream = getValueFromEnvOrArgs( kEngineUpstreamOption, argumentResults, platform.environment, )!; final String engineMirror = '[email protected]:$githubUsername/engine.git'; final String candidateBranch = getValueFromEnvOrArgs( kCandidateOption, argumentResults, platform.environment, )!; final String releaseChannel = getValueFromEnvOrArgs( kReleaseOption, argumentResults, platform.environment, )!; final String? dartRevision = getValueFromEnvOrArgs( kDartRevisionOption, argumentResults, platform.environment, allowNull: true, ); final bool force = getBoolFromEnvOrArgs( kForceFlag, argumentResults, platform.environment, ); final File stateFile = checkouts.fileSystem.file( getValueFromEnvOrArgs( kStateOption, argumentResults, platform.environment), ); final String? versionOverrideString = getValueFromEnvOrArgs( kVersionOverrideOption, argumentResults, platform.environment, allowNull: true, ); Version? versionOverride; if (versionOverrideString != null) { versionOverride = Version.fromString(versionOverrideString); } final StartContext context = StartContext( candidateBranch: candidateBranch, checkouts: checkouts, dartRevision: dartRevision, engineMirror: engineMirror, engineUpstream: engineUpstream, conductorVersion: conductorVersion, frameworkMirror: frameworkMirror, frameworkUpstream: frameworkUpstream, processManager: processManager, releaseChannel: releaseChannel, stateFile: stateFile, force: force, versionOverride: versionOverride, githubUsername: githubUsername, ); return context.run(); } } /// Context for starting a new release. /// /// This is a frontend-agnostic implementation. class StartContext extends Context { StartContext({ required this.candidateBranch, required this.dartRevision, required this.engineMirror, required this.engineUpstream, required this.frameworkMirror, required this.frameworkUpstream, required this.conductorVersion, required this.processManager, required this.releaseChannel, required this.githubUsername, required super.checkouts, required super.stateFile, this.force = false, this.versionOverride, }) : git = Git(processManager), engine = EngineRepository( checkouts, initialRef: 'upstream/$candidateBranch', upstreamRemote: Remote( name: RemoteName.upstream, url: engineUpstream, ), mirrorRemote: Remote( name: RemoteName.mirror, url: engineMirror, ), ), framework = FrameworkRepository( checkouts, initialRef: 'upstream/$candidateBranch', upstreamRemote: Remote( name: RemoteName.upstream, url: frameworkUpstream, ), mirrorRemote: Remote( name: RemoteName.mirror, url: frameworkMirror, ), ); final String candidateBranch; final String? dartRevision; final String engineMirror; final String engineUpstream; final String frameworkMirror; final String frameworkUpstream; final String conductorVersion; final Git git; final ProcessManager processManager; final String releaseChannel; final Version? versionOverride; final String githubUsername; /// If validations should be overridden. final bool force; final EngineRepository engine; final FrameworkRepository framework; /// Determine which part of the version to increment in the next release. /// /// If [atBranchPoint] is true, then this is a [ReleaseType.BETA_INITIAL]. @visibleForTesting ReleaseType computeReleaseType(Version lastVersion, bool atBranchPoint) { if (atBranchPoint) { return ReleaseType.BETA_INITIAL; } if (releaseChannel == 'stable') { if (lastVersion.type == VersionType.stable) { return ReleaseType.STABLE_HOTFIX; } else { return ReleaseType.STABLE_INITIAL; } } return ReleaseType.BETA_HOTFIX; } Future<void> run() async { if (stateFile.existsSync()) { throw ConductorException( 'Error! A persistent state file already found at ${stateFile.path}.\n\n' 'Run `conductor clean` to cancel a previous release.'); } if (!releaseCandidateBranchRegex.hasMatch(candidateBranch)) { throw ConductorException( 'Invalid release candidate branch "$candidateBranch". Text should ' 'match the regex pattern /${releaseCandidateBranchRegex.pattern}/.', ); } final Int64 unixDate = Int64(DateTime.now().millisecondsSinceEpoch); final pb.ConductorState state = pb.ConductorState(); state.releaseChannel = releaseChannel; state.createdDate = unixDate; state.lastUpdatedDate = unixDate; // Create a new branch so that we don't accidentally push to upstream // candidateBranch. final String workingBranchName = 'cherrypicks-$candidateBranch'; await engine.newBranch(workingBranchName); if (dartRevision != null && dartRevision!.isNotEmpty) { await engine.updateDartRevision(dartRevision!); await engine.commit('Update Dart SDK to $dartRevision', addFirst: true); } final String engineHead = await engine.reverseParse('HEAD'); state.engine = (pb.Repository.create() ..candidateBranch = candidateBranch ..workingBranch = workingBranchName ..startingGitHead = engineHead ..currentGitHead = engineHead ..checkoutPath = (await engine.checkoutDirectory).path ..upstream = (pb.Remote.create() ..name = 'upstream' ..url = engine.upstreamRemote.url ) ..mirror = (pb.Remote.create() ..name = 'mirror' ..url = engine.mirrorRemote!.url ) ); if (dartRevision != null && dartRevision!.isNotEmpty) { state.engine.dartRevision = dartRevision!; } await framework.newBranch(workingBranchName); // Get framework version final Version lastVersion = Version.fromString(await framework.getFullTag( framework.upstreamRemote.name, candidateBranch, exact: false, )); final String frameworkHead = await framework.reverseParse('HEAD'); final String branchPoint = await framework.branchPoint( '${framework.upstreamRemote.name}/$candidateBranch', '${framework.upstreamRemote.name}/${FrameworkRepository.defaultBranch}', ); final bool atBranchPoint = branchPoint == frameworkHead; final ReleaseType releaseType = computeReleaseType(lastVersion, atBranchPoint); state.releaseType = releaseType; try { lastVersion.ensureValid(candidateBranch, releaseType); } on ConductorException catch (e) { // Let the user know, but resume execution stdio.printError(e.message); } Version nextVersion; if (versionOverride != null) { nextVersion = versionOverride!; } else { nextVersion = calculateNextVersion(lastVersion, releaseType); nextVersion = await ensureBranchPointTagged( branchPoint: branchPoint, requestedVersion: nextVersion, framework: framework, ); } state.releaseVersion = nextVersion.toString(); state.framework = (pb.Repository.create() ..candidateBranch = candidateBranch ..workingBranch = workingBranchName ..startingGitHead = frameworkHead ..currentGitHead = frameworkHead ..checkoutPath = (await framework.checkoutDirectory).path ..upstream = (pb.Remote.create() ..name = 'upstream' ..url = framework.upstreamRemote.url ) ..mirror = (pb.Remote.create() ..name = 'mirror' ..url = framework.mirrorRemote!.url ) ); state.currentPhase = ReleasePhase.APPLY_ENGINE_CHERRYPICKS; state.conductorVersion = conductorVersion; stdio.printTrace('Writing state to file ${stateFile.path}...'); updateState(state, stdio.logs); stdio.printStatus(state_import.presentState(state)); } /// Determine this release's version number from the [lastVersion] and the [incrementLetter]. Version calculateNextVersion(Version lastVersion, ReleaseType releaseType) { late final Version nextVersion; switch (releaseType) { case ReleaseType.STABLE_INITIAL: nextVersion = Version( x: lastVersion.x, y: lastVersion.y, z: 0, type: VersionType.stable, ); case ReleaseType.STABLE_HOTFIX: nextVersion = Version.increment(lastVersion, 'z'); case ReleaseType.BETA_INITIAL: nextVersion = Version.fromCandidateBranch(candidateBranch); case ReleaseType.BETA_HOTFIX: nextVersion = Version.increment(lastVersion, 'n'); } return nextVersion; } /// Ensures the branch point [candidateBranch] and `master` has a version tag. /// /// This is necessary for version reporting for users on the `master` channel /// to be correct. Future<Version> ensureBranchPointTagged({ required Version requestedVersion, required String branchPoint, required FrameworkRepository framework, }) async { if (await framework.isCommitTagged(branchPoint)) { // The branch point is tagged, no work to be done return requestedVersion; } if (requestedVersion.n != 0) { stdio.printError( 'Tried to tag the branch point, however the target version is ' '$requestedVersion, which does not have n == 0!', ); return requestedVersion; } final bool response = await prompt( 'About to tag the release candidate branch branchpoint of $branchPoint ' 'as $requestedVersion and push it to ${framework.upstreamRemote.url}. ' 'Is this correct?', ); if (!response) { throw ConductorException('Aborting command.'); } stdio.printStatus( 'Applying the tag $requestedVersion at the branch point $branchPoint'); await framework.tag( branchPoint, requestedVersion.toString(), frameworkUpstream, ); final Version nextVersion = Version.increment(requestedVersion, 'n'); stdio.printStatus('The actual release will be version $nextVersion.'); return nextVersion; } }
flutter/dev/conductor/core/lib/src/start.dart/0
{ "file_path": "flutter/dev/conductor/core/lib/src/start.dart", "repo_id": "flutter", "token_count": 5343 }
503
@ECHO off REM Copyright 2014 The Flutter Authors. All rights reserved. REM Use of this source code is governed by a BSD-style license that can be REM found in the LICENSE file. REM This should match the ci.sh file in this directory. REM This is called from the LUCI recipes: REM https://flutter.googlesource.com/recipes/+/refs/heads/master/recipe_modules/adhoc_validation/resources/customer_testing.bat ECHO. ECHO Updating pub packages... CALL dart pub get CD ..\tools CALL dart pub get CD ..\customer_testing ECHO. ECHO Finding correct version of customer tests... CMD /S /C "IF EXIST "..\..\bin\cache\pkg\tests\" RMDIR /S /Q ..\..\bin\cache\pkg\tests" git clone https://github.com/flutter/tests.git ..\..\bin\cache\pkg\tests FOR /F "usebackq tokens=*" %%a IN (`dart --enable-asserts ..\tools\bin\find_commit.dart . master ..\..\bin\cache\pkg\tests main`) DO git -C ..\..\bin\cache\pkg\tests checkout %%a ECHO. ECHO Running tests... CD ..\..\bin\cache\pkg\tests CALL dart --enable-asserts ..\..\..\..\dev\customer_testing\run_tests.dart --verbose --skip-on-fetch-failure --skip-template registry/*.test
flutter/dev/customer_testing/ci.bat/0
{ "file_path": "flutter/dev/customer_testing/ci.bat", "repo_id": "flutter", "token_count": 386 }
504
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter_devicelab/framework/apk_utils.dart'; import 'package:flutter_devicelab/framework/framework.dart'; import 'package:flutter_devicelab/framework/task_result.dart'; import 'package:flutter_devicelab/framework/utils.dart'; import 'package:path/path.dart' as path; Future<void> main() async { await task(() async { try { bool foundApkProjectName = false; await runProjectTest((FlutterProject flutterProject) async { section('APK content for task assembleRelease with --obfuscate'); await inDirectory(flutterProject.rootPath, () async { await flutter('build', options: <String>[ 'apk', '--target-platform=android-arm', '--obfuscate', '--split-debug-info=foo/', '--verbose', ]); }); final String outputApkDirectory = path.join( flutterProject.rootPath, 'build/app/outputs/apk/release/app-release.apk', ); final Iterable<String> apkFiles = await getFilesInApk(outputApkDirectory); checkCollectionContains<String>(<String>[ ...flutterAssets, ...baseApkFiles, 'lib/armeabi-v7a/libapp.so', ], apkFiles); // Verify that an identifier from the Dart project code is not present // in the compiled binary. await inDirectory(flutterProject.rootPath, () async { await exec('unzip', <String>[outputApkDirectory]); checkFileExists(path.join(flutterProject.rootPath, 'lib/armeabi-v7a/libapp.so')); final String response = await eval( 'grep', <String>[flutterProject.name, 'lib/armeabi-v7a/libapp.so'], canFail: true, ); if (response.trim().contains('matches')) { foundApkProjectName = true; } }); }); bool foundAarProjectName = false; await runModuleProjectTest((FlutterModuleProject flutterProject) async { section('AAR content with --obfuscate'); await inDirectory(flutterProject.rootPath, () async { await flutter('build', options: <String>[ 'aar', '--target-platform=android-arm', '--obfuscate', '--split-debug-info=foo/', '--no-debug', '--no-profile', '--verbose', ]); }); final String outputAarDirectory = path.join( flutterProject.rootPath, 'build/host/outputs/repo/com/example/${flutterProject.name}/flutter_release/1.0/flutter_release-1.0.aar', ); final Iterable<String> aarFiles = await getFilesInAar(outputAarDirectory); checkCollectionContains<String>(<String>[ ...flutterAssets, 'jni/armeabi-v7a/libapp.so', ], aarFiles); // Verify that an identifier from the Dart project code is not present // in the compiled binary. await inDirectory(flutterProject.rootPath, () async { await exec('unzip', <String>[outputAarDirectory]); checkFileExists(path.join(flutterProject.rootPath, 'jni/armeabi-v7a/libapp.so')); final String response = await eval( 'grep', <String>[flutterProject.name, 'jni/armeabi-v7a/libapp.so'], canFail: true, ); if (response.trim().contains('matches')) { foundAarProjectName = true; } }); }); if (foundApkProjectName) { return TaskResult.failure('Found project name in obfuscated APK dart library'); } if (foundAarProjectName) { return TaskResult.failure('Found project name in obfuscated AAR dart library'); } return TaskResult.success(null); } on TaskResult catch (taskResult) { return taskResult; } catch (e) { return TaskResult.failure(e.toString()); } }); }
flutter/dev/devicelab/bin/tasks/android_obfuscate_test.dart/0
{ "file_path": "flutter/dev/devicelab/bin/tasks/android_obfuscate_test.dart", "repo_id": "flutter", "token_count": 1797 }
505
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:io'; import 'package:flutter_devicelab/framework/devices.dart'; import 'package:flutter_devicelab/framework/framework.dart'; import 'package:flutter_devicelab/framework/task_result.dart'; import 'package:flutter_devicelab/framework/utils.dart' as utils; import 'package:flutter_devicelab/tasks/perf_tests.dart' show ListStatistics; import 'package:path/path.dart' as path; const String _bundleName = 'dev.flutter.multipleflutters'; const String _activityName = 'MainActivity'; const int _numberOfIterations = 10; Future<void> _withApkInstall( String apkPath, String bundleName, Future<void> Function(AndroidDevice) body) async { final DeviceDiscovery devices = DeviceDiscovery(); final AndroidDevice device = await devices.workingDevice as AndroidDevice; await device.unlock(); try { // Force proper cleanup before trying to install app. If uninstall fails, // we log exception and proceed with running the test. await device.adb(<String>['uninstall', bundleName]); } on Exception catch (error) { print('adb uninstall failed with exception: $error. Will proceed with test run.'); } await device.adb(<String>['install', '-r', apkPath]); try { await body(device); } finally { await device.adb(<String>['uninstall', bundleName]); } } /// Since we don't check the gradle wrapper in with the android host project we /// yank the gradle wrapper from the module (which is added by the Flutter tool). void _copyGradleFromModule(String source, String destination) { print('copying gradle from module $source to $destination'); final String wrapperPath = path.join(source, '.android', 'gradlew'); final String windowsWrapperPath = path.join(source, '.android', 'gradlew.bat'); final String wrapperDestinationPath = path.join(destination, 'gradlew'); final String windowsWrapperDestinationPath = path.join(destination, 'gradlew.bat'); File(wrapperPath).copySync(wrapperDestinationPath); File(windowsWrapperPath).copySync(windowsWrapperDestinationPath); final Directory gradleDestinationDirectory = Directory(path.join(destination, 'gradle', 'wrapper')); if (!gradleDestinationDirectory.existsSync()) { gradleDestinationDirectory.createSync(recursive: true); } final String gradleDestinationPath = path.join(gradleDestinationDirectory.path, 'gradle-wrapper.jar'); final String gradlePath = path.join(source, '.android', 'gradle', 'wrapper', 'gradle-wrapper.jar'); File(gradlePath).copySync(gradleDestinationPath); } Future<TaskResult> _doTest() async { try { final String flutterDirectory = utils.flutterDirectory.path; final String multipleFluttersPath = path.join(flutterDirectory, 'dev', 'benchmarks', 'multiple_flutters'); final String modulePath = path.join(multipleFluttersPath, 'module'); final String androidPath = path.join(multipleFluttersPath, 'android'); final String gradlew = Platform.isWindows ? 'gradlew.bat' : 'gradlew'; final String gradlewExecutable = Platform.isWindows ? '.\\$gradlew' : './$gradlew'; await utils.flutter('precache', options: <String>['--android'], workingDirectory: modulePath); await utils.flutter('pub', options: <String>['get'], workingDirectory: modulePath); _copyGradleFromModule(modulePath, androidPath); await utils.eval(gradlewExecutable, <String>['assembleRelease'], workingDirectory: androidPath); final String apkPath = path.join(multipleFluttersPath, 'android', 'app', 'build', 'outputs', 'apk', 'release', 'app-release.apk'); TaskResult? result; await _withApkInstall(apkPath, _bundleName, (AndroidDevice device) async { final List<int> totalMemorySamples = <int>[]; for (int i = 0; i < _numberOfIterations; ++i) { await device.adb(<String>[ 'shell', 'am', 'start', '-n', '$_bundleName/$_bundleName.$_activityName', ]); await Future<void>.delayed(const Duration(seconds: 10)); final Map<String, dynamic> memoryStats = await device.getMemoryStats(_bundleName); final int totalMemory = memoryStats['total_kb'] as int; totalMemorySamples.add(totalMemory); await device.stop(_bundleName); } final ListStatistics totalMemoryStatistics = ListStatistics(totalMemorySamples); final Map<String, dynamic> results = <String, dynamic>{ ...totalMemoryStatistics.asMap('totalMemory'), }; result = TaskResult.success(results, benchmarkScoreKeys: results.keys.toList()); }); return result ?? TaskResult.failure('no results found'); } catch (ex) { return TaskResult.failure(ex.toString()); } } Future<void> main() async { await task(_doTest); }
flutter/dev/devicelab/bin/tasks/flutter_engine_group_performance.dart/0
{ "file_path": "flutter/dev/devicelab/bin/tasks/flutter_engine_group_performance.dart", "repo_id": "flutter", "token_count": 1668 }
506
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'dart:convert'; import 'dart:io'; import 'package:flutter_devicelab/framework/framework.dart'; import 'package:flutter_devicelab/framework/task_result.dart'; import 'package:flutter_devicelab/framework/utils.dart'; Future<void> main() async { await task(const NewGalleryChromeRunTest().run); } /// After the gallery loads, a duration of [durationToWaitForError] /// is waited, allowing any possible exceptions to be thrown. const Duration durationToWaitForError = Duration(seconds: 5); /// Flutter prints this string when an app is successfully loaded. /// Used to check when the app is successfully loaded. const String successfullyLoadedString = 'To hot restart'; /// Flutter prints this string when an exception is caught. /// Used to check if there are any exceptions. const String exceptionString = 'EXCEPTION CAUGHT'; /// Checks that the New Flutter Gallery runs successfully on Chrome. class NewGalleryChromeRunTest { const NewGalleryChromeRunTest(); /// Runs the test. Future<TaskResult> run() async { final TaskResult result = await inDirectory<TaskResult>('${flutterDirectory.path}/dev/integration_tests/new_gallery/', () async { await flutter('create', options: <String>[ '--platforms', 'web,android,ios', '--no-overwrite', '.' ]); await flutter('doctor'); await flutter('packages', options: <String>['get']); await flutter('build', options: <String>[ 'web', '-v', '--release', '--no-pub', ]); final List<String> options = <String>['-d', 'chrome', '--verbose', '--resident']; final Process process = await startFlutter( 'run', options: options, ); final Completer<void> stdoutDone = Completer<void>(); final Completer<void> stderrDone = Completer<void>(); bool success = true; process.stdout .transform<String>(utf8.decoder) .transform<String>(const LineSplitter()) .listen((String line) { if (line.contains(successfullyLoadedString)) { // Successfully started. Future<void>.delayed( durationToWaitForError, () {process.stdin.write('q');} ); } if (line.contains(exceptionString)) { success = false; } print('stdout: $line'); }, onDone: () { stdoutDone.complete(); }); process.stderr .transform<String>(utf8.decoder) .transform<String>(const LineSplitter()) .listen((String line) { print('stderr: $line'); }, onDone: () { stderrDone.complete(); }); await Future.wait<void>(<Future<void>>[ stdoutDone.future, stderrDone.future, ]); await process.exitCode; if (success) { return TaskResult.success(<String, dynamic>{}); } else { return TaskResult.failure('An exception was thrown.'); } }); return result; } }
flutter/dev/devicelab/bin/tasks/flutter_gallery_v2_chrome_run_test.dart/0
{ "file_path": "flutter/dev/devicelab/bin/tasks/flutter_gallery_v2_chrome_run_test.dart", "repo_id": "flutter", "token_count": 1249 }
507
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:io'; import 'package:meta/meta.dart'; import 'package:process/process.dart'; @immutable class RunningProcessInfo { const RunningProcessInfo(this.pid, this.commandLine, this.creationDate); final int pid; final String commandLine; final DateTime creationDate; @override bool operator ==(Object other) { return other is RunningProcessInfo && other.pid == pid && other.commandLine == commandLine && other.creationDate == creationDate; } Future<bool> terminate({required ProcessManager processManager}) async { // This returns true when the signal is sent, not when the process goes away. // See also https://github.com/dart-lang/sdk/issues/40759 (killPid should wait for process to be terminated). if (Platform.isWindows) { // TODO(ianh): Move Windows to killPid once we can. // - killPid on Windows has not-useful return code: https://github.com/dart-lang/sdk/issues/47675 final ProcessResult result = await processManager.run(<String>[ 'taskkill.exe', '/pid', '$pid', '/f', ]); return result.exitCode == 0; } return processManager.killPid(pid, ProcessSignal.sigkill); } @override int get hashCode => Object.hash(pid, commandLine, creationDate); @override String toString() { return 'RunningProcesses(pid: $pid, commandLine: $commandLine, creationDate: $creationDate)'; } } Future<Set<RunningProcessInfo>> getRunningProcesses({ String? processName, required ProcessManager processManager, }) { if (Platform.isWindows) { return windowsRunningProcesses(processName, processManager); } return posixRunningProcesses(processName, processManager); } @visibleForTesting Future<Set<RunningProcessInfo>> windowsRunningProcesses( String? processName, ProcessManager processManager, ) async { // PowerShell script to get the command line arguments and create time of a process. // See: https://docs.microsoft.com/en-us/windows/desktop/cimwin32prov/win32-process final String script = processName != null ? '"Get-CimInstance Win32_Process -Filter \\"name=\'$processName\'\\" | Select-Object ProcessId,CreationDate,CommandLine | Format-Table -AutoSize | Out-String -Width 4096"' : '"Get-CimInstance Win32_Process | Select-Object ProcessId,CreationDate,CommandLine | Format-Table -AutoSize | Out-String -Width 4096"'; // TODO(ianh): Unfortunately, there doesn't seem to be a good way to get // ProcessManager to run this. final ProcessResult result = await Process.run( 'powershell -command $script', <String>[], ); if (result.exitCode != 0) { print('Could not list processes!'); print(result.stderr); print(result.stdout); return <RunningProcessInfo>{}; } return processPowershellOutput(result.stdout as String).toSet(); } /// Parses the output of the PowerShell script from [windowsRunningProcesses]. /// /// E.g.: /// ProcessId CreationDate CommandLine /// --------- ------------ ----------- /// 2904 3/11/2019 11:01:54 AM "C:\Program Files\Android\Android Studio\jre\bin\java.exe" -Xmx1536M -Dfile.encoding=windows-1252 -Duser.country=US -Duser.language=en -Duser.variant -cp C:\Users\win1\.gradle\wrapper\dists\gradle-4.10.2-all\9fahxiiecdb76a5g3aw9oi8rv\gradle-4.10.2\lib\gradle-launcher-4.10.2.jar org.gradle.launcher.daemon.bootstrap.GradleDaemon 4.10.2 @visibleForTesting Iterable<RunningProcessInfo> processPowershellOutput(String output) sync* { const int processIdHeaderSize = 'ProcessId'.length; const int creationDateHeaderStart = processIdHeaderSize + 1; late int creationDateHeaderEnd; late int commandLineHeaderStart; bool inTableBody = false; for (final String line in output.split('\n')) { if (line.startsWith('ProcessId')) { commandLineHeaderStart = line.indexOf('CommandLine'); creationDateHeaderEnd = commandLineHeaderStart - 1; } if (line.startsWith('--------- ------------')) { inTableBody = true; continue; } if (!inTableBody || line.isEmpty) { continue; } if (line.length < commandLineHeaderStart) { continue; } // 3/11/2019 11:01:54 AM // 12/11/2019 11:01:54 AM String rawTime = line.substring( creationDateHeaderStart, creationDateHeaderEnd, ).trim(); if (rawTime[1] == '/') { rawTime = '0$rawTime'; } if (rawTime[4] == '/') { rawTime = '${rawTime.substring(0, 3)}0${rawTime.substring(3)}'; } final String year = rawTime.substring(6, 10); final String month = rawTime.substring(3, 5); final String day = rawTime.substring(0, 2); String time = rawTime.substring(11, 19); if (time[7] == ' ') { time = '0$time'.trim(); } if (rawTime.endsWith('PM')) { final int hours = int.parse(time.substring(0, 2)); time = '${hours + 12}${time.substring(2)}'; } final int pid = int.parse(line.substring(0, processIdHeaderSize).trim()); final DateTime creationDate = DateTime.parse('$year-$month-${day}T$time'); final String commandLine = line.substring(commandLineHeaderStart).trim(); yield RunningProcessInfo(pid, commandLine, creationDate); } } @visibleForTesting Future<Set<RunningProcessInfo>> posixRunningProcesses( String? processName, ProcessManager processManager, ) async { // Cirrus is missing this in Linux for some reason. if (!processManager.canRun('ps')) { print('Cannot list processes on this system: "ps" not available.'); return <RunningProcessInfo>{}; } final ProcessResult result = await processManager.run(<String>[ 'ps', '-eo', 'lstart,pid,command', ]); if (result.exitCode != 0) { print('Could not list processes!'); print(result.stderr); print(result.stdout); return <RunningProcessInfo>{}; } return processPsOutput(result.stdout as String, processName).toSet(); } /// Parses the output of the command in [posixRunningProcesses]. /// /// E.g.: /// /// STARTED PID COMMAND /// Sat Mar 9 20:12:47 2019 1 /sbin/launchd /// Sat Mar 9 20:13:00 2019 49 /usr/sbin/syslogd @visibleForTesting Iterable<RunningProcessInfo> processPsOutput( String output, String? processName, ) sync* { bool inTableBody = false; for (String line in output.split('\n')) { if (line.trim().startsWith('STARTED')) { inTableBody = true; continue; } if (!inTableBody || line.isEmpty) { continue; } if (processName != null && !line.contains(processName)) { continue; } if (line.length < 25) { continue; } // 'Sat Feb 16 02:29:55 2019' // 'Sat Mar 9 20:12:47 2019' const Map<String, String> months = <String, String>{ 'Jan': '01', 'Feb': '02', 'Mar': '03', 'Apr': '04', 'May': '05', 'Jun': '06', 'Jul': '07', 'Aug': '08', 'Sep': '09', 'Oct': '10', 'Nov': '11', 'Dec': '12', }; final String rawTime = line.substring(0, 24); final String year = rawTime.substring(20, 24); final String month = months[rawTime.substring(4, 7)]!; final String day = rawTime.substring(8, 10).replaceFirst(' ', '0'); final String time = rawTime.substring(11, 19); final DateTime creationDate = DateTime.parse('$year-$month-${day}T$time'); line = line.substring(24).trim(); final int nextSpace = line.indexOf(' '); final int pid = int.parse(line.substring(0, nextSpace)); final String commandLine = line.substring(nextSpace + 1); yield RunningProcessInfo(pid, commandLine, creationDate); } }
flutter/dev/devicelab/lib/framework/running_processes.dart/0
{ "file_path": "flutter/dev/devicelab/lib/framework/running_processes.dart", "repo_id": "flutter", "token_count": 2867 }
508
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import '../framework/devices.dart'; import '../framework/framework.dart'; import '../framework/talkback.dart'; import '../framework/task_result.dart'; import '../framework/utils.dart'; TaskFunction createChannelsIntegrationTest() { return IntegrationTest( '${flutterDirectory.path}/dev/integration_tests/channels', 'integration_test/main_test.dart', ).call; } TaskFunction createPlatformInteractionTest() { return DriverTest( '${flutterDirectory.path}/dev/integration_tests/platform_interaction', 'lib/main.dart', ).call; } TaskFunction createFlavorsTest({Map<String, String>? environment}) { return DriverTest( '${flutterDirectory.path}/dev/integration_tests/flavors', 'lib/main.dart', extraOptions: <String>['--flavor', 'paid'], environment: environment, ).call; } TaskFunction createIntegrationTestFlavorsTest({Map<String, String>? environment}) { return IntegrationTest( '${flutterDirectory.path}/dev/integration_tests/flavors', 'integration_test/integration_test.dart', extraOptions: <String>['--flavor', 'paid'], environment: environment, ).call; } TaskFunction createExternalTexturesFrameRateIntegrationTest() { return DriverTest( '${flutterDirectory.path}/dev/integration_tests/external_textures', 'lib/frame_rate_main.dart', ).call; } TaskFunction createPlatformChannelSampleTest({String? deviceIdOverride}) { return DriverTest( '${flutterDirectory.path}/examples/platform_channel', 'test_driver/button_tap.dart', deviceIdOverride: deviceIdOverride, ).call; } TaskFunction createPlatformChannelSwiftSampleTest() { return DriverTest( '${flutterDirectory.path}/examples/platform_channel_swift', 'test_driver/button_tap.dart', ).call; } TaskFunction createEmbeddedAndroidViewsIntegrationTest() { return DriverTest( '${flutterDirectory.path}/dev/integration_tests/android_views', 'lib/main.dart', ).call; } TaskFunction createHybridAndroidViewsIntegrationTest() { return DriverTest( '${flutterDirectory.path}/dev/integration_tests/hybrid_android_views', 'lib/main.dart', ).call; } TaskFunction createAndroidSemanticsIntegrationTest() { return IntegrationTest( '${flutterDirectory.path}/dev/integration_tests/android_semantics_testing', 'integration_test/main_test.dart', withTalkBack: true, ).call; } TaskFunction createIOSPlatformViewTests() { return DriverTest( '${flutterDirectory.path}/dev/integration_tests/ios_platform_view_tests', 'lib/main.dart', extraOptions: <String>[ '--dart-define=ENABLE_DRIVER_EXTENSION=true', ], ).call; } TaskFunction createEndToEndKeyboardTest() { return DriverTest( '${flutterDirectory.path}/dev/integration_tests/ui', 'lib/keyboard_resize.dart', ).call; } TaskFunction createEndToEndFrameNumberTest() { return DriverTest( '${flutterDirectory.path}/dev/integration_tests/ui', 'lib/frame_number.dart', ).call; } TaskFunction createEndToEndDriverTest({Map<String, String>? environment}) { return DriverTest( '${flutterDirectory.path}/dev/integration_tests/ui', 'lib/driver.dart', environment: environment, ).call; } TaskFunction createEndToEndScreenshotTest() { return DriverTest( '${flutterDirectory.path}/dev/integration_tests/ui', 'lib/screenshot.dart', ).call; } TaskFunction createEndToEndKeyboardTextfieldTest() { return DriverTest( '${flutterDirectory.path}/dev/integration_tests/ui', 'lib/keyboard_textfield.dart', ).call; } TaskFunction dartDefinesTask() { return DriverTest( '${flutterDirectory.path}/dev/integration_tests/ui', 'lib/defines.dart', extraOptions: <String>[ '--dart-define=test.valueA=Example,A', '--dart-define=test.valueB=Value', ], ).call; } TaskFunction createEndToEndIntegrationTest() { return IntegrationTest( '${flutterDirectory.path}/dev/integration_tests/ui', 'integration_test/integration_test.dart', ).call; } TaskFunction createSpellCheckIntegrationTest() { return IntegrationTest( '${flutterDirectory.path}/dev/integration_tests/spell_check', 'integration_test/integration_test.dart', ).call; } TaskFunction createWindowsStartupDriverTest({String? deviceIdOverride}) { return DriverTest( '${flutterDirectory.path}/dev/integration_tests/windows_startup_test', 'lib/main.dart', deviceIdOverride: deviceIdOverride, ).call; } TaskFunction createWideGamutTest() { return IntegrationTest( '${flutterDirectory.path}/dev/integration_tests/wide_gamut_test', 'integration_test/app_test.dart', createPlatforms: <String>['ios'], ).call; } class DriverTest { DriverTest( this.testDirectory, this.testTarget, { this.extraOptions = const <String>[], this.deviceIdOverride, this.environment, } ); final String testDirectory; final String testTarget; final List<String> extraOptions; final String? deviceIdOverride; final Map<String, String>? environment; Future<TaskResult> call() { return inDirectory<TaskResult>(testDirectory, () async { String deviceId; if (deviceIdOverride != null) { deviceId = deviceIdOverride!; } else { final Device device = await devices.workingDevice; await device.unlock(); deviceId = device.deviceId; } await flutter('packages', options: <String>['get']); final List<String> options = <String>[ '--no-android-gradle-daemon', '-v', '-t', testTarget, '-d', deviceId, ...extraOptions, ]; await flutter('drive', options: options, environment: environment); return TaskResult.success(null); }); } } class IntegrationTest { IntegrationTest( this.testDirectory, this.testTarget, { this.extraOptions = const <String>[], this.createPlatforms = const <String>[], this.withTalkBack = false, this.environment, } ); final String testDirectory; final String testTarget; final List<String> extraOptions; final List<String> createPlatforms; final bool withTalkBack; final Map<String, String>? environment; Future<TaskResult> call() { return inDirectory<TaskResult>(testDirectory, () async { final Device device = await devices.workingDevice; await device.unlock(); final String deviceId = device.deviceId; await flutter('packages', options: <String>['get']); if (createPlatforms.isNotEmpty) { await flutter('create', options: <String>[ '--platforms', createPlatforms.join(','), '--no-overwrite', '.' ]); } if (withTalkBack) { if (device is! AndroidDevice) { return TaskResult.failure('A test that enables TalkBack can only be run on Android devices'); } await enableTalkBack(); } final List<String> options = <String>[ '-v', '-d', deviceId, testTarget, ...extraOptions, ]; await flutter('test', options: options, environment: environment); if (withTalkBack) { await disableTalkBack(); } return TaskResult.success(null); }); } }
flutter/dev/devicelab/lib/tasks/integration_tests.dart/0
{ "file_path": "flutter/dev/devicelab/lib/tasks/integration_tests.dart", "repo_id": "flutter", "token_count": 2724 }
509
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:convert' show jsonDecode; // JSON Event samples taken from running an instrumented version of the // integration tests of this package that dumped all the data as captured. /// To test isBeginFrame. (Sampled from Chrome 89+) final Map<String, Object?> beginMainFrameJson_89plus = jsonDecode(''' { "args": { "frameTime": 2338687248768 }, "cat": "blink", "dur": 6836, "name": "WebFrameWidgetImpl::BeginMainFrame", "ph": "X", "pid": 1367081, "tdur": 393, "tid": 1, "ts": 2338687258440, "tts": 375499 } ''') as Map<String, Object?>; /// To test isUpdateAllLifecyclePhases. (Sampled from Chrome 89+) final Map<String, Object?> updateLifecycleJson_89plus = jsonDecode(''' { "args": {}, "cat": "blink", "dur": 103, "name": "WebFrameWidgetImpl::UpdateLifecycle", "ph": "X", "pid": 1367081, "tdur": 102, "tid": 1, "ts": 2338687265284, "tts": 375900 } ''') as Map<String, Object?>; /// To test isBeginMeasuredFrame. (Sampled from Chrome 89+) final Map<String, Object?> beginMeasuredFrameJson_89plus = jsonDecode(''' { "args": {}, "cat": "blink.user_timing", "id": "0xea2a8b45", "name": "measured_frame", "ph": "b", "pid": 1367081, "scope": "blink.user_timing", "tid": 1, "ts": 2338687265932 } ''') as Map<String, Object?>; /// To test isEndMeasuredFrame. (Sampled from Chrome 89+) final Map<String, Object?> endMeasuredFrameJson_89plus = jsonDecode(''' { "args": {}, "cat": "blink.user_timing", "id": "0xea2a8b45", "name": "measured_frame", "ph": "e", "pid": 1367081, "scope": "blink.user_timing", "tid": 1, "ts": 2338687440485 } ''') as Map<String, Object?>; /// An unrelated data frame to test negative cases. final Map<String, Object?> unrelatedPhXJson = jsonDecode(''' { "args": {}, "cat": "blink,rail", "dur": 2, "name": "PageAnimator::serviceScriptedAnimations", "ph": "X", "pid": 1367081, "tdur": 2, "tid": 1, "ts": 2338691143317, "tts": 1685405 } ''') as Map<String, Object?>; /// Another unrelated data frame to test negative cases. final Map<String, Object?> anotherUnrelatedJson = jsonDecode(''' { "args": { "sort_index": -1 }, "cat": "__metadata", "name": "thread_sort_index", "ph": "M", "pid": 1367081, "tid": 1, "ts": 2338692906482 } ''') as Map<String, Object?>;
flutter/dev/devicelab/test/framework/browser_test_json_samples.dart/0
{ "file_path": "flutter/dev/devicelab/test/framework/browser_test_json_samples.dart", "repo_id": "flutter", "token_count": 1111 }
510
window.ApiSurveyDocs = function(apiPages) { var url = window.location.href; var fragments = url.split('/'); if (fragments == null || fragments.length == 0) { return; } var classFragment = fragments[fragments.length -1]; if (classFragment == null) { return; } var apiDocClassFragments = classFragment.split('-'); if (apiDocClassFragments.length != 2) { return; } var apiDocClass = apiDocClassFragments[0]; if (url == null || apiPages.indexOf(apiDocClass) == -1) { return; } scriptElement = document.createElement('script'); scriptElement.setAttribute('src', 'https://www.google.com/insights/consumersurveys/async_survey?site=sygvgfetfwmwm7isniaym3m6f4'); document.head.appendChild(scriptElement); } scriptElement = document.createElement('script'); scriptElement.setAttribute('src', 'https://storage.googleapis.com/flutter-dashboard.appspot.com/api_survey/api_survey_docs.html'); document.head.appendChild(scriptElement);
flutter/dev/docs/assets/api_survey.js/0
{ "file_path": "flutter/dev/docs/assets/api_survey.js", "repo_id": "flutter", "token_count": 336 }
511
name: platform_integration environment: sdk: '>=3.2.0-0 <4.0.0'
flutter/dev/docs/platform_integration/pubspec.yaml/0
{ "file_path": "flutter/dev/docs/platform_integration/pubspec.yaml", "repo_id": "flutter", "token_count": 33 }
512
distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists distributionUrl=https\://services.gradle.org/distributions/gradle-REPLACEME-all.zip
flutter/dev/integration_tests/android_host_app_v2_embedding/gradle/wrapper/gradle-wrapper.properties/0
{ "file_path": "flutter/dev/integration_tests/android_host_app_v2_embedding/gradle/wrapper/gradle-wrapper.properties", "repo_id": "flutter", "token_count": 73 }
513
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'dart:io' show Platform; import 'dart:typed_data'; import 'package:flutter/material.dart'; import 'src/basic_messaging.dart'; import 'src/method_calls.dart'; import 'src/pair.dart'; import 'src/test_step.dart'; void main() { runApp(const TestApp()); } class TestApp extends StatefulWidget { const TestApp({super.key}); @override State<TestApp> createState() => _TestAppState(); } class _TestAppState extends State<TestApp> { static final dynamic anUnknownValue = DateTime.fromMillisecondsSinceEpoch(1520777802314); static final List<dynamic> aList = <dynamic>[ false, 0, 0.0, 'hello', <dynamic>[ <String, dynamic>{'key': 42}, ], ]; static final Map<String, dynamic> aMap = <String, dynamic>{ 'a': false, 'b': 0, 'c': 0.0, 'd': 'hello', 'e': <dynamic>[ <String, dynamic>{'key': 42}, ], }; static final Uint8List someUint8s = Uint8List.fromList(<int>[ 0xBA, 0x5E, 0xBA, 0x11, ]); static final Int32List someInt32s = Int32List.fromList(<int>[ -0x7fffffff - 1, 0, 0x7fffffff, ]); static final Int64List someInt64s = Int64List.fromList(<int>[ -0x7fffffffffffffff - 1, 0, 0x7fffffffffffffff, ]); static final Float32List someFloat32s = Float32List.fromList(<double>[ double.nan, double.negativeInfinity, -double.maxFinite, -double.minPositive, -0.0, 0.0, double.minPositive, double.maxFinite, double.infinity, ]); static final Float64List someFloat64s = Float64List.fromList(<double>[ double.nan, double.negativeInfinity, -double.maxFinite, -double.minPositive, -0.0, 0.0, double.minPositive, double.maxFinite, double.infinity, ]); static final dynamic aCompoundUnknownValue = <dynamic>[ anUnknownValue, Pair(anUnknownValue, aList), ]; static final List<TestStep> steps = <TestStep>[ () => methodCallJsonSuccessHandshake(null), () => methodCallJsonSuccessHandshake(true), () => methodCallJsonSuccessHandshake(7), () => methodCallJsonSuccessHandshake('world'), () => methodCallJsonSuccessHandshake(aList), () => methodCallJsonSuccessHandshake(aMap), () => methodCallJsonNotImplementedHandshake(), () => methodCallStandardSuccessHandshake(null), () => methodCallStandardSuccessHandshake(true), () => methodCallStandardSuccessHandshake(7), () => methodCallStandardSuccessHandshake('world'), () => methodCallStandardSuccessHandshake(aList), () => methodCallStandardSuccessHandshake(aMap), () => methodCallStandardSuccessHandshake(anUnknownValue), () => methodCallStandardSuccessHandshake(aCompoundUnknownValue), () => methodCallJsonErrorHandshake(null), () => methodCallJsonErrorHandshake('world'), () => methodCallStandardErrorHandshake(null), () => methodCallStandardErrorHandshake('world'), () => methodCallStandardNotImplementedHandshake(), () => basicBinaryHandshake(null), if (!Platform.isMacOS) // Note, it was decided that this will function differently on macOS. See // also: https://github.com/flutter/flutter/issues/110865. () => basicBinaryHandshake(ByteData(0)), () => basicBinaryHandshake(ByteData(4)..setUint32(0, 0x12345678)), () => basicStringHandshake('hello, world'), () => basicStringHandshake('hello \u263A \u{1f602} unicode'), if (!Platform.isMacOS) // Note, it was decided that this will function differently on macOS. See // also: https://github.com/flutter/flutter/issues/110865. () => basicStringHandshake(''), () => basicStringHandshake(null), () => basicJsonHandshake(null), () => basicJsonHandshake(true), () => basicJsonHandshake(false), () => basicJsonHandshake(0), () => basicJsonHandshake(-7), () => basicJsonHandshake(7), () => basicJsonHandshake(1 << 32), () => basicJsonHandshake(1 << 56), () => basicJsonHandshake(0.0), () => basicJsonHandshake(-7.0), () => basicJsonHandshake(7.0), () => basicJsonHandshake(''), () => basicJsonHandshake('hello, world'), () => basicJsonHandshake('hello, "world"'), () => basicJsonHandshake('hello \u263A \u{1f602} unicode'), () => basicJsonHandshake(<dynamic>[]), () => basicJsonHandshake(aList), () => basicJsonHandshake(<String, dynamic>{}), () => basicJsonHandshake(aMap), () => basicStandardHandshake(null), () => basicStandardHandshake(true), () => basicStandardHandshake(false), () => basicStandardHandshake(0), () => basicStandardHandshake(-7), () => basicStandardHandshake(7), () => basicStandardHandshake(1 << 32), () => basicStandardHandshake(1 << 64), () => basicStandardHandshake(1 << 128), () => basicStandardHandshake(0.0), () => basicStandardHandshake(-7.0), () => basicStandardHandshake(7.0), () => basicStandardHandshake(''), () => basicStandardHandshake('hello, world'), () => basicStandardHandshake('hello \u263A \u{1f602} unicode'), () => basicStandardHandshake(someUint8s), () => basicStandardHandshake(someInt32s), () => basicStandardHandshake(someInt64s), () => basicStandardHandshake(someFloat32s), () => basicStandardHandshake(someFloat64s), () => basicStandardHandshake(<dynamic>[]), () => basicStandardHandshake(aList), () => basicStandardHandshake(<String, dynamic>{}), () => basicStandardHandshake(<dynamic, dynamic>{7: true, false: -7}), () => basicStandardHandshake(aMap), () => basicStandardHandshake(anUnknownValue), () => basicStandardHandshake(aCompoundUnknownValue), () => basicBinaryMessageToUnknownChannel(), () => basicStringMessageToUnknownChannel(), () => basicJsonMessageToUnknownChannel(), () => basicStandardMessageToUnknownChannel(), if (Platform.isIOS || Platform.isAndroid || Platform.isMacOS) () => basicBackgroundStandardEcho(123), ]; Future<TestStepResult>? _result; int _step = 0; void _executeNextStep() { setState(() { if (_step < steps.length) { _result = steps[_step++](); } else { _result = Future<TestStepResult>.value(TestStepResult.complete); } }); } Widget _buildTestResultWidget( BuildContext context, AsyncSnapshot<TestStepResult> snapshot, ) { return TestStepResult.fromSnapshot(snapshot).asWidget(context); } @override Widget build(BuildContext context) { return MaterialApp( title: 'Channels Test', home: Scaffold( appBar: AppBar( title: const Text('Channels Test'), ), body: Padding( padding: const EdgeInsets.all(20.0), child: FutureBuilder<TestStepResult>( future: _result, builder: _buildTestResultWidget, ), ), floatingActionButton: FloatingActionButton( key: const ValueKey<String>('step'), onPressed: _executeNextStep, child: const Icon(Icons.navigate_next), ), ), ); } }
flutter/dev/integration_tests/channels/lib/main.dart/0
{ "file_path": "flutter/dev/integration_tests/channels/lib/main.dart", "repo_id": "flutter", "token_count": 2759 }
514
#!/usr/bin/env bash # Copyright 2014 The Flutter Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. mkdir customassets curl https://raw.githubusercontent.com/flutter/goldens/0fbd6c5d30ec714ffefd63b47910aee7debd2e7e/dev/integration_tests/assets_for_deferred_components_test/flutter_logo.png --output customassets/flutter_logo.png curl https://raw.githubusercontent.com/flutter/goldens/0fbd6c5d30ec714ffefd63b47910aee7debd2e7e/dev/integration_tests/assets_for_deferred_components_test/key.properties --output android/key.properties curl https://raw.githubusercontent.com/flutter/goldens/0fbd6c5d30ec714ffefd63b47910aee7debd2e7e/dev/integration_tests/assets_for_deferred_components_test/testing-keystore.jks --output android/testing-keystore.jks
flutter/dev/integration_tests/deferred_components_test/download_assets.sh/0
{ "file_path": "flutter/dev/integration_tests/deferred_components_test/download_assets.sh", "repo_id": "flutter", "token_count": 295 }
515
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #import "AppDelegate.h" #import "GeneratedPluginRegistrant.h" @implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { [GeneratedPluginRegistrant registerWithRegistry:self]; // Override point for customization after application launch. FlutterViewController* controller = (FlutterViewController*)self.window.rootViewController; FlutterMethodChannel* flavorChannel = [FlutterMethodChannel methodChannelWithName:@"flavor" binaryMessenger:controller]; [flavorChannel setMethodCallHandler:^(FlutterMethodCall *call, FlutterResult result) { NSString* flavor = (NSString*)[[NSBundle mainBundle].infoDictionary valueForKey:@"Flavor"]; result(flavor); }]; return [super application:application didFinishLaunchingWithOptions:launchOptions]; } @end
flutter/dev/integration_tests/flavors/ios/Runner/AppDelegate.m/0
{ "file_path": "flutter/dev/integration_tests/flavors/ios/Runner/AppDelegate.m", "repo_id": "flutter", "token_count": 281 }
516
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>CFBundleDevelopmentRegion</key> <string>$(DEVELOPMENT_LANGUAGE)</string> <key>CFBundleDisplayName</key> <string>$(PRODUCT_NAME)</string> <key>CFBundleExecutable</key> <string>$(EXECUTABLE_NAME)</string> <key>CFBundleIconFile</key> <string></string> <key>CFBundleIdentifier</key> <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string> <key>CFBundleInfoDictionaryVersion</key> <string>6.0</string> <key>CFBundleName</key> <string>$(PRODUCT_NAME)</string> <key>CFBundlePackageType</key> <string>APPL</string> <key>CFBundleShortVersionString</key> <string>$(FLUTTER_BUILD_NAME)</string> <key>CFBundleVersion</key> <string>$(FLUTTER_BUILD_NUMBER)</string> <key>LSMinimumSystemVersion</key> <string>$(MACOSX_DEPLOYMENT_TARGET)</string> <key>NSHumanReadableCopyright</key> <string>$(PRODUCT_COPYRIGHT)</string> <key>NSMainNibFile</key> <string>MainMenu</string> <key>NSPrincipalClass</key> <string>NSApplication</string> </dict> </plist>
flutter/dev/integration_tests/flavors/macos/Runner/Info.plist/0
{ "file_path": "flutter/dev/integration_tests/flavors/macos/Runner/Info.plist", "repo_id": "flutter", "token_count": 477 }
517
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/cupertino.dart'; import '../../gallery/demo.dart'; class CupertinoProgressIndicatorDemo extends StatelessWidget { const CupertinoProgressIndicatorDemo({super.key}); static const String routeName = '/cupertino/progress_indicator'; @override Widget build(BuildContext context) { return CupertinoPageScaffold( navigationBar: CupertinoNavigationBar( // We're specifying a back label here because the previous page is a // Material page. CupertinoPageRoutes could auto-populate these back // labels. previousPageTitle: 'Cupertino', middle: const Text('Activity Indicator'), trailing: CupertinoDemoDocumentationButton(routeName), ), child: const Center( child: CupertinoActivityIndicator(), ), ); } }
flutter/dev/integration_tests/flutter_gallery/lib/demo/cupertino/cupertino_activity_indicator_demo.dart/0
{ "file_path": "flutter/dev/integration_tests/flutter_gallery/lib/demo/cupertino/cupertino_activity_indicator_demo.dart", "repo_id": "flutter", "token_count": 333 }
518
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import '../../gallery/demo.dart'; class NavigationIconView { NavigationIconView({ required Widget icon, Widget? activeIcon, String? title, Color? color, required TickerProvider vsync, }) : _icon = icon, _color = color, _title = title, item = BottomNavigationBarItem( icon: icon, activeIcon: activeIcon, label: title, backgroundColor: color, ), controller = AnimationController( duration: kThemeAnimationDuration, vsync: vsync, ) { _animation = controller.drive(CurveTween( curve: const Interval(0.5, 1.0, curve: Curves.fastOutSlowIn), )); } final Widget _icon; final Color? _color; final String? _title; final BottomNavigationBarItem item; final AnimationController controller; late Animation<double> _animation; FadeTransition transition(BottomNavigationBarType type, BuildContext context) { Color? iconColor; switch (type) { case BottomNavigationBarType.shifting: iconColor = _color; case BottomNavigationBarType.fixed: final ThemeData theme = Theme.of(context); iconColor = switch (theme.brightness) { Brightness.light => theme.colorScheme.primary, Brightness.dark => theme.colorScheme.secondary, }; } return FadeTransition( opacity: _animation, child: SlideTransition( position: _animation.drive( Tween<Offset>( begin: const Offset(0.0, 0.02), // Slightly down. end: Offset.zero, ), ), child: IconTheme( data: IconThemeData( color: iconColor, size: 120.0, ), child: Semantics( label: 'Placeholder for $_title tab', child: _icon, ), ), ), ); } } class CustomIcon extends StatelessWidget { const CustomIcon({super.key}); @override Widget build(BuildContext context) { final IconThemeData iconTheme = IconTheme.of(context); return Container( margin: const EdgeInsets.all(4.0), width: iconTheme.size! - 8.0, height: iconTheme.size! - 8.0, color: iconTheme.color, ); } } class CustomInactiveIcon extends StatelessWidget { const CustomInactiveIcon({super.key}); @override Widget build(BuildContext context) { final IconThemeData iconTheme = IconTheme.of(context); return Container( margin: const EdgeInsets.all(4.0), width: iconTheme.size! - 8.0, height: iconTheme.size! - 8.0, decoration: BoxDecoration( border: Border.all(color: iconTheme.color!, width: 2.0), ), ); } } class BottomNavigationDemo extends StatefulWidget { const BottomNavigationDemo({super.key}); static const String routeName = '/material/bottom_navigation'; @override State<BottomNavigationDemo> createState() => _BottomNavigationDemoState(); } class _BottomNavigationDemoState extends State<BottomNavigationDemo> with TickerProviderStateMixin { int _currentIndex = 0; BottomNavigationBarType _type = BottomNavigationBarType.shifting; late List<NavigationIconView> _navigationViews; @override void initState() { super.initState(); _navigationViews = <NavigationIconView>[ NavigationIconView( icon: const Icon(Icons.access_alarm), title: 'Alarm', color: Colors.deepPurple, vsync: this, ), NavigationIconView( activeIcon: const CustomIcon(), icon: const CustomInactiveIcon(), title: 'Box', color: Colors.deepOrange, vsync: this, ), NavigationIconView( activeIcon: const Icon(Icons.cloud), icon: const Icon(Icons.cloud_queue), title: 'Cloud', color: Colors.teal, vsync: this, ), NavigationIconView( activeIcon: const Icon(Icons.favorite), icon: const Icon(Icons.favorite_border), title: 'Favorites', color: Colors.indigo, vsync: this, ), NavigationIconView( icon: const Icon(Icons.event_available), title: 'Event', color: Colors.pink, vsync: this, ), ]; _navigationViews[_currentIndex].controller.value = 1.0; } @override void dispose() { for (final NavigationIconView view in _navigationViews) { view.controller.dispose(); } super.dispose(); } Widget _buildTransitionsStack() { final List<FadeTransition> transitions = <FadeTransition>[ for (final NavigationIconView view in _navigationViews) view.transition(_type, context), ]; // We want to have the newly animating (fading in) views on top. transitions.sort((FadeTransition a, FadeTransition b) { final Animation<double> aAnimation = a.opacity; final Animation<double> bAnimation = b.opacity; final double aValue = aAnimation.value; final double bValue = bAnimation.value; return aValue.compareTo(bValue); }); return Stack(children: transitions); } @override Widget build(BuildContext context) { final BottomNavigationBar botNavBar = BottomNavigationBar( items: _navigationViews .map<BottomNavigationBarItem>((NavigationIconView navigationView) => navigationView.item) .toList(), currentIndex: _currentIndex, type: _type, onTap: (int index) { setState(() { _navigationViews[_currentIndex].controller.reverse(); _currentIndex = index; _navigationViews[_currentIndex].controller.forward(); }); }, ); return Scaffold( appBar: AppBar( title: const Text('Bottom navigation'), actions: <Widget>[ MaterialDemoDocumentationButton(BottomNavigationDemo.routeName), PopupMenuButton<BottomNavigationBarType>( onSelected: (BottomNavigationBarType value) { setState(() { _type = value; }); }, itemBuilder: (BuildContext context) => <PopupMenuItem<BottomNavigationBarType>>[ const PopupMenuItem<BottomNavigationBarType>( value: BottomNavigationBarType.fixed, child: Text('Fixed'), ), const PopupMenuItem<BottomNavigationBarType>( value: BottomNavigationBarType.shifting, child: Text('Shifting'), ), ], ), ], ), body: Center( child: _buildTransitionsStack(), ), bottomNavigationBar: botNavBar, ); } }
flutter/dev/integration_tests/flutter_gallery/lib/demo/material/bottom_navigation_demo.dart/0
{ "file_path": "flutter/dev/integration_tests/flutter_gallery/lib/demo/material/bottom_navigation_demo.dart", "repo_id": "flutter", "token_count": 2855 }
519
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. export 'backdrop_demo.dart'; export 'banner_demo.dart'; export 'bottom_app_bar_demo.dart'; export 'bottom_navigation_demo.dart'; export 'buttons_demo.dart'; export 'cards_demo.dart'; export 'chip_demo.dart'; export 'data_table_demo.dart'; export 'date_and_time_picker_demo.dart'; export 'dialog_demo.dart'; export 'drawer_demo.dart'; export 'elevation_demo.dart'; export 'expansion_panels_demo.dart'; export 'expansion_tile_list_demo.dart'; export 'grid_list_demo.dart'; export 'icons_demo.dart'; export 'leave_behind_demo.dart'; export 'list_demo.dart'; export 'menu_demo.dart'; export 'modal_bottom_sheet_demo.dart'; export 'overscroll_demo.dart'; export 'page_selector_demo.dart'; export 'persistent_bottom_sheet_demo.dart'; export 'progress_indicator_demo.dart'; export 'reorderable_list_demo.dart'; export 'scrollable_tabs_demo.dart'; export 'search_demo.dart'; export 'selection_controls_demo.dart'; export 'slider_demo.dart'; export 'snack_bar_demo.dart'; export 'tabs_demo.dart'; export 'tabs_fab_demo.dart'; export 'text_form_field_demo.dart'; export 'tooltip_demo.dart';
flutter/dev/integration_tests/flutter_gallery/lib/demo/material/material.dart/0
{ "file_path": "flutter/dev/integration_tests/flutter_gallery/lib/demo/material/material.dart", "repo_id": "flutter", "token_count": 494 }
520
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import '../../gallery/demo.dart'; const String _introText = 'Tooltips are short identifying messages that briefly appear in response to ' 'a long press. Tooltip messages are also used by services that make Flutter ' 'apps accessible, like screen readers.'; class TooltipDemo extends StatelessWidget { const TooltipDemo({super.key}); static const String routeName = '/material/tooltips'; @override Widget build(BuildContext context) { final ThemeData theme = Theme.of(context); return Scaffold( appBar: AppBar( title: const Text('Tooltips'), actions: <Widget>[MaterialDemoDocumentationButton(routeName)], ), body: Builder( builder: (BuildContext context) { return SafeArea( top: false, bottom: false, child: ListView( children: <Widget>[ Text(_introText, style: theme.textTheme.titleMedium), Row( children: <Widget>[ Text('Long press the ', style: theme.textTheme.titleMedium), Tooltip( message: 'call icon', child: Icon( Icons.call, size: 18.0, color: theme.iconTheme.color, ), ), Text(' icon.', style: theme.textTheme.titleMedium), ], ), Center( child: IconButton( iconSize: 48.0, icon: const Icon(Icons.call), color: theme.iconTheme.color, tooltip: 'Place a phone call', onPressed: () { ScaffoldMessenger.of(context).showSnackBar(const SnackBar( content: Text('That was an ordinary tap.'), )); }, ), ), ] .map<Widget>((Widget widget) { return Padding( padding: const EdgeInsets.only(top: 16.0, left: 16.0, right: 16.0), child: widget, ); }) .toList(), ), ); } ), ); } }
flutter/dev/integration_tests/flutter_gallery/lib/demo/material/tooltip_demo.dart/0
{ "file_path": "flutter/dev/integration_tests/flutter_gallery/lib/demo/material/tooltip_demo.dart", "repo_id": "flutter", "token_count": 1328 }
521
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import '../model/product.dart'; import 'product_card.dart'; class TwoProductCardColumn extends StatelessWidget { const TwoProductCardColumn({ super.key, required this.bottom, this.top, }); final Product? bottom, top; @override Widget build(BuildContext context) { return LayoutBuilder(builder: (BuildContext context, BoxConstraints constraints) { const double spacerHeight = 44.0; final double heightOfCards = (constraints.biggest.height - spacerHeight) / 2.0; final double availableHeightForImages = heightOfCards - ProductCard.kTextBoxHeight; // Ensure the cards take up the available space as long as the screen is // sufficiently tall, otherwise fallback on a constant aspect ratio. final double imageAspectRatio = availableHeightForImages >= 0.0 ? constraints.biggest.width / availableHeightForImages : 49.0 / 33.0; return ListView( physics: const ClampingScrollPhysics(), children: <Widget>[ Padding( padding: const EdgeInsetsDirectional.only(start: 28.0), child: top != null ? ProductCard( imageAspectRatio: imageAspectRatio, product: top, ) : SizedBox( height: heightOfCards > 0 ? heightOfCards : spacerHeight, ), ), const SizedBox(height: spacerHeight), Padding( padding: const EdgeInsetsDirectional.only(end: 28.0), child: ProductCard( imageAspectRatio: imageAspectRatio, product: bottom, ), ), ], ); }); } } class OneProductCardColumn extends StatelessWidget { const OneProductCardColumn({super.key, this.product}); final Product? product; @override Widget build(BuildContext context) { return ListView( physics: const ClampingScrollPhysics(), reverse: true, children: <Widget>[ const SizedBox( height: 40.0, ), ProductCard( product: product, ), ], ); } }
flutter/dev/integration_tests/flutter_gallery/lib/demo/shrine/supplemental/product_columns.dart/0
{ "file_path": "flutter/dev/integration_tests/flutter_gallery/lib/demo/shrine/supplemental/product_columns.dart", "repo_id": "flutter", "token_count": 974 }
522
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // This code is not runnable, it contains code snippets displayed in the Gallery. import 'package:flutter/material.dart'; class ButtonsDemo { void setState(VoidCallback callback) { } late BuildContext context; void buttons() { // START buttons_elevated // Create an elevated button. ElevatedButton( child: const Text('BUTTON TITLE'), onPressed: () { // Perform some action }, ); // Create a disabled button. // Buttons are disabled when onPressed isn't // specified or is null. const ElevatedButton( onPressed: null, child: Text('BUTTON TITLE'), ); // Create a button with an icon and a // title. ElevatedButton.icon( icon: const Icon(Icons.add, size: 18.0), label: const Text('BUTTON TITLE'), onPressed: () { // Perform some action }, ); // END // START buttons_outlined // Create an outlined button. OutlinedButton( child: const Text('BUTTON TITLE'), onPressed: () { // Perform some action }, ); // Create a disabled button. // Buttons are disabled when onPressed isn't // specified or is null. const OutlinedButton( onPressed: null, child: Text('BUTTON TITLE'), ); // Create a button with an icon and a // title. OutlinedButton.icon( icon: const Icon(Icons.add, size: 18.0), label: const Text('BUTTON TITLE'), onPressed: () { // Perform some action }, ); // END // START buttons_text // Create a text button. TextButton( child: const Text('BUTTON TITLE'), onPressed: () { // Perform some action }, ); // Create a disabled button. // Buttons are disabled when onPressed isn't // specified or is null. const TextButton( onPressed: null, child: Text('BUTTON TITLE'), ); // END // START buttons_dropdown // Member variable holding value. String? dropdownValue; // Dropdown button with string values. DropdownButton<String>( value: dropdownValue, onChanged: (String? newValue) { // null indicates the user didn't select a // new value. setState(() { if (newValue != null) { dropdownValue = newValue; } }); }, items: <String>['One', 'Two', 'Free', 'Four'] .map<DropdownMenuItem<String>>((String value) { return DropdownMenuItem<String>( value: value, child: Text(value)); }) .toList(), ); // END // START buttons_icon // Member variable holding toggle value. late bool value = true; // Toggleable icon button. IconButton( icon: const Icon(Icons.thumb_up), onPressed: () { setState(() => value = !value); }, color: value ? Theme.of(context).primaryColor : null, ); // END // START buttons_action // Floating action button in Scaffold. Scaffold( appBar: AppBar( title: const Text('Demo'), ), floatingActionButton: const FloatingActionButton( onPressed: null, child: Icon(Icons.add), ), ); // END } } class SelectionControls { void setState(VoidCallback callback) { } void selectionControls() { // START selectioncontrols_checkbox // Member variable holding the checkbox's value. bool? checkboxValue = false; // Create a checkbox. Checkbox( value: checkboxValue, onChanged: (bool? value) { setState(() { checkboxValue = value; }); }, ); // Create a tristate checkbox. Checkbox( tristate: true, value: checkboxValue, onChanged: (bool? value) { setState(() { checkboxValue = value; }); }, ); // Create a disabled checkbox. // Checkboxes are disabled when onChanged isn't // specified or null. const Checkbox(value: false, onChanged: null); // END // START selectioncontrols_radio // Member variable holding value. int? radioValue = 0; // Method setting value. void handleRadioValueChanged(int? value) { setState(() { radioValue = value; }); } // Creates a set of radio buttons. Row( children: <Widget>[ Radio<int>( value: 0, groupValue: radioValue, onChanged: handleRadioValueChanged, ), Radio<int>( value: 1, groupValue: radioValue, onChanged: handleRadioValueChanged, ), Radio<int>( value: 2, groupValue: radioValue, onChanged: handleRadioValueChanged, ), ], ); // Creates a disabled radio button. const Radio<int>( value: 0, groupValue: 0, onChanged: null, ); // END // START selectioncontrols_switch // Member variable holding value. bool switchValue = false; // Create a switch. Switch( value: switchValue, onChanged: (bool value) { setState(() { switchValue = value; } ); }); // Create a disabled switch. // Switches are disabled when onChanged isn't // specified or null. const Switch(value: false, onChanged: null); // END } } class GridLists { void gridlists() { // START gridlists // Creates a scrollable grid list with images // loaded from the web. GridView.count( crossAxisCount: 3, padding: const EdgeInsets.all(4.0), mainAxisSpacing: 4.0, crossAxisSpacing: 4.0, children: <String>[ 'https://example.com/image-0.jpg', 'https://example.com/image-1.jpg', 'https://example.com/image-2.jpg', '...', 'https://example.com/image-n.jpg', ].map<Widget>((String url) { return GridTile( footer: GridTileBar( title: Text(url), ), child: Image.network(url, fit: BoxFit.cover), ); }).toList(), ); // END } } class AnimatedImage { void animatedImage() { // START animated_image Image.network('https://example.com/animated-image.gif'); // END } }
flutter/dev/integration_tests/flutter_gallery/lib/gallery/example_code.dart/0
{ "file_path": "flutter/dev/integration_tests/flutter_gallery/lib/gallery/example_code.dart", "repo_id": "flutter", "token_count": 1957 }
523
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter_gallery/demo/calculator/logic.dart'; import 'package:test/test.dart' hide TypeMatcher, isInstanceOf; void main() { test('Test order of operations: 12 + 3 * 4 = 24', () { CalcExpression expression = CalcExpression.empty(); expression = expression.appendDigit(1)!; expression = expression.appendDigit(2)!; expression = expression.appendOperation(Operation.Addition)!; expression = expression.appendDigit(3)!; expression = expression.appendOperation(Operation.Multiplication)!; expression = expression.appendDigit(4)!; expression = expression.computeResult()!; expect(expression.state, equals(ExpressionState.Result)); expect(expression.toString(), equals('24')); }); test('Test floating point 0.1 + 0.2 = 0.3', () { CalcExpression expression = CalcExpression.empty(); expression = expression.appendDigit(0)!; expression = expression.appendPoint()!; expression = expression.appendDigit(1)!; expression = expression.appendOperation(Operation.Addition)!; expression = expression.appendDigit(0)!; expression = expression.appendPoint()!; expression = expression.appendDigit(2)!; expression = expression.computeResult()!; expect(expression.state, equals(ExpressionState.Result)); expect(expression.toString(), equals('0.3')); }); test('Test floating point 1.0/10.0 = 0.1', () { CalcExpression expression = CalcExpression.empty(); expression = expression.appendDigit(1)!; expression = expression.appendPoint()!; expression = expression.appendDigit(0)!; expression = expression.appendOperation(Operation.Division)!; expression = expression.appendDigit(1)!; expression = expression.appendDigit(0)!; expression = expression.appendPoint()!; expression = expression.appendDigit(0)!; expression = expression.computeResult()!; expect(expression.state, equals(ExpressionState.Result)); expect(expression.toString(), equals('0.1')); }); test('Test 1/0 = Infinity', () { CalcExpression expression = CalcExpression.empty(); expression = expression.appendDigit(1)!; expression = expression.appendOperation(Operation.Division)!; expression = expression.appendDigit(0)!; expression = expression.computeResult()!; expect(expression.state, equals(ExpressionState.Result)); expect(expression.toString(), equals('Infinity')); }); test('Test use result in next calculation: 1 + 1 = 2 + 1 = 3 + 1 = 4', () { CalcExpression expression = CalcExpression.empty(); expression = expression.appendDigit(1)!; expression = expression.appendOperation(Operation.Addition)!; expression = expression.appendDigit(1)!; expression = expression.computeResult()!; expression = expression.appendOperation(Operation.Addition)!; expression = expression.appendDigit(1)!; expression = expression.computeResult()!; expression = expression.appendOperation(Operation.Addition)!; expression = expression.appendDigit(1)!; expression = expression.computeResult()!; expect(expression.state, equals(ExpressionState.Result)); expect(expression.toString(), equals('4')); }); test('Test minus -3 - -2 = -1', () { CalcExpression expression = CalcExpression.empty(); expression = expression.appendMinus()!; expression = expression.appendDigit(3)!; expression = expression.appendMinus()!; expression = expression.appendMinus()!; expression = expression.appendDigit(2)!; expression = expression.computeResult()!; expect(expression.state, equals(ExpressionState.Result)); expect(expression.toString(), equals('-1')); }); }
flutter/dev/integration_tests/flutter_gallery/test/calculator/logic.dart/0
{ "file_path": "flutter/dev/integration_tests/flutter_gallery/test/calculator/logic.dart", "repo_id": "flutter", "token_count": 1201 }
524
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:math' as math; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter_gallery/gallery/app.dart' show GalleryApp; import 'package:flutter_gallery/gallery/demos.dart'; import 'package:flutter_test/flutter_test.dart'; // This title is visible on the home and demo category pages. It's // not visible when the demos are running. const String kGalleryTitle = 'Flutter gallery'; // All of the classes printed by debugDump etc, must have toString() // values approved by verityToStringOutput(). int toStringErrors = 0; // There are 3 places where the Gallery demos are traversed. // 1- In widget tests such as dev/integration_tests/flutter_gallery/test/smoke_test.dart // 2- In driver tests such as dev/integration_tests/flutter_gallery/test_driver/transitions_perf_test.dart // 3- In on-device instrumentation tests such as dev/integration_tests/flutter_gallery/test/live_smoketest.dart // // If you change navigation behavior in the Gallery or in the framework, make // sure all 3 are covered. void reportToStringError(String name, String route, int lineNumber, List<String> lines, String message) { // If you're on line 12, then it has index 11. // If you want 1 line before and 1 line after, then you want lines with index 10, 11, and 12. // That's (lineNumber-1)-margin .. (lineNumber-1)+margin, or lineNumber-(margin+1) .. lineNumber+(margin-1) const int margin = 5; final int firstLine = math.max(0, lineNumber - margin); final int lastLine = math.min(lines.length, lineNumber + margin); print('$name : $route : line $lineNumber of ${lines.length} : $message; nearby lines were:\n ${lines.sublist(firstLine, lastLine).join("\n ")}'); toStringErrors += 1; } void verifyToStringOutput(String name, String route, String testString) { int lineNumber = 0; final List<String> lines = testString.split('\n'); if (!testString.endsWith('\n')) { reportToStringError(name, route, lines.length, lines, 'does not end with a line feed'); } for (final String line in lines) { lineNumber += 1; if (line == '' && lineNumber != lines.length) { reportToStringError(name, route, lineNumber, lines, 'found empty line'); } else if (line.contains('Instance of ')) { reportToStringError(name, route, lineNumber, lines, 'found a class that does not have its own toString'); } else if (line.endsWith(' ')) { reportToStringError(name, route, lineNumber, lines, 'found a line with trailing whitespace'); } } } Future<void> smokeDemo(WidgetTester tester, GalleryDemo demo) async { // Don't use pumpUntilNoTransientCallbacks in this function, because some of // the smoketests have infinitely-running animations (e.g. the progress // indicators demo). await tester.tap(find.text(demo.title)); await tester.pump(); // Launch the demo. await tester.pump(const Duration(milliseconds: 400)); // Wait until the demo has opened. expect(find.text(kGalleryTitle), findsNothing); // Leave the demo on the screen briefly for manual testing. await tester.pump(const Duration(milliseconds: 400)); // Scroll the demo around a bit. await tester.flingFrom(const Offset(400.0, 300.0), const Offset(-100.0, 0.0), 500.0); await tester.flingFrom(const Offset(400.0, 300.0), const Offset(0.0, -100.0), 500.0); await tester.pump(); await tester.pump(const Duration(milliseconds: 50)); await tester.pump(const Duration(milliseconds: 200)); await tester.pump(const Duration(milliseconds: 400)); // Verify that the dumps are pretty. final String routeName = demo.routeName; verifyToStringOutput('debugDumpApp', routeName, WidgetsBinding.instance.rootElement!.toStringDeep()); verifyToStringOutput('debugDumpRenderTree', routeName, RendererBinding.instance.renderViews.single.toStringDeep()); verifyToStringOutput('debugDumpLayerTree', routeName, RendererBinding.instance.renderViews.single.debugLayer?.toStringDeep() ?? ''); verifyToStringOutput('debugDumpFocusTree', routeName, WidgetsBinding.instance.focusManager.toStringDeep()); // Scroll the demo around a bit more. await tester.flingFrom(const Offset(400.0, 300.0), const Offset(0.0, 400.0), 1000.0); await tester.pump(); await tester.pump(const Duration(milliseconds: 400)); await tester.flingFrom(const Offset(400.0, 300.0), const Offset(-200.0, 0.0), 500.0); await tester.pump(); await tester.pump(const Duration(milliseconds: 50)); await tester.pump(const Duration(milliseconds: 200)); await tester.pump(const Duration(milliseconds: 400)); await tester.flingFrom(const Offset(400.0, 300.0), const Offset(100.0, 0.0), 500.0); await tester.pump(); await tester.pump(const Duration(milliseconds: 400)); // Go back await tester.pageBack(); await tester.pumpAndSettle(); await tester.pump(); // Start the pop "back" operation. await tester.pump(); // Complete the willPop() Future. await tester.pump(const Duration(milliseconds: 400)); // Wait until it has finished. } Future<void> smokeOptionsPage(WidgetTester tester) async { final Finder showOptionsPageButton = find.byTooltip('Toggle options page'); // Show the options page await tester.tap(showOptionsPageButton); await tester.pumpAndSettle(); // Switch to the dark theme: first menu button, choose 'Dark' await tester.tap(find.byIcon(Icons.arrow_drop_down).first); await tester.pumpAndSettle(); await tester.tap(find.text('Dark')); await tester.pumpAndSettle(); // Switch back to system theme setting: first menu button, choose 'System Default' await tester.tap(find.byIcon(Icons.arrow_drop_down).first); await tester.pumpAndSettle(); await tester.tap(find.text('System Default').at(1), warnIfMissed: false); // https://github.com/flutter/flutter/issues/82908 await tester.pumpAndSettle(); // Switch text direction: first switch await tester.tap(find.byType(Switch).first); await tester.pumpAndSettle(); // Switch back to system text direction: first switch control again await tester.tap(find.byType(Switch).first); await tester.pumpAndSettle(); // Scroll the 'Send feedback' item into view await tester.drag(find.text('Theme'), const Offset(0.0, -1000.0)); await tester.pumpAndSettle(); await tester.tap(find.text('Send feedback')); await tester.pumpAndSettle(); // Close the options page expect(showOptionsPageButton, findsOneWidget); await tester.tap(showOptionsPageButton); await tester.pumpAndSettle(); } Future<void> smokeGallery(WidgetTester tester) async { bool sendFeedbackButtonPressed = false; await tester.pumpWidget( GalleryApp( testMode: true, onSendFeedback: () { sendFeedbackButtonPressed = true; // see smokeOptionsPage() }, ), ); await tester.pump(); // see https://github.com/flutter/flutter/issues/1865 await tester.pump(); // triggers a frame expect(find.text(kGalleryTitle), findsOneWidget); for (final GalleryDemoCategory category in kAllGalleryDemoCategories) { await Scrollable.ensureVisible(tester.element(find.text(category.name)), alignment: 0.5); await tester.tap(find.text(category.name)); await tester.pumpAndSettle(); for (final GalleryDemo demo in kGalleryCategoryToDemos[category]!) { await Scrollable.ensureVisible(tester.element(find.text(demo.title))); await smokeDemo(tester, demo); tester.binding.debugAssertNoTransientCallbacks('A transient callback was still active after running $demo'); } await tester.pageBack(); await tester.pumpAndSettle(); } expect(toStringErrors, 0); await smokeOptionsPage(tester); expect(sendFeedbackButtonPressed, true); } void main() { testWidgets( 'Flutter Gallery app smoke test', smokeGallery, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.macOS }), ); testWidgets('Flutter Gallery app smoke test with semantics', (WidgetTester tester) async { final SemanticsHandle handle = SemanticsBinding.instance.ensureSemantics(); await smokeGallery(tester); handle.dispose(); }); }
flutter/dev/integration_tests/flutter_gallery/test/smoke_test.dart/0
{ "file_path": "flutter/dev/integration_tests/flutter_gallery/test/smoke_test.dart", "repo_id": "flutter", "token_count": 2662 }
525
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // See //dev/devicelab/bin/tasks/flutter_gallery__memory_nav.dart import 'package:flutter/material.dart'; import 'package:flutter/scheduler.dart'; import 'package:flutter_gallery/gallery/app.dart' show GalleryApp; import 'package:flutter_test/flutter_test.dart'; Future<void> endOfAnimation() async { do { await SchedulerBinding.instance.endOfFrame; } while (SchedulerBinding.instance.hasScheduledFrame); } int iteration = 0; class LifecycleObserver extends WidgetsBindingObserver { @override void didChangeAppLifecycleState(AppLifecycleState state) { debugPrint('==== MEMORY BENCHMARK ==== $state ===='); debugPrint('This was lifecycle event number $iteration in this instance'); } } Future<void> main() async { runApp(const GalleryApp()); await endOfAnimation(); await Future<void>.delayed(const Duration(milliseconds: 50)); debugPrint('==== MEMORY BENCHMARK ==== READY ===='); WidgetsBinding.instance.addObserver(LifecycleObserver()); }
flutter/dev/integration_tests/flutter_gallery/test_memory/back_button.dart/0
{ "file_path": "flutter/dev/integration_tests/flutter_gallery/test_memory/back_button.dart", "repo_id": "flutter", "token_count": 367 }
526
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #import "AppDelegate.h" #import "MainViewController.h" @implementation GREYHostApplicationDistantObject (AppDelegate) - (NSNotificationCenter *)notificationCenter { return [NSNotificationCenter defaultCenter]; } @end @interface AppDelegate () @property(nonatomic, strong, readwrite) FlutterEngine* engine; @end @implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; MainViewController *mainViewController = [[MainViewController alloc] init]; UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:mainViewController]; navigationController.navigationBar.translucent = NO; self.engine = [[FlutterEngine alloc] initWithName:@"test" project:nil]; [self.engine runWithEntrypoint:nil]; self.window.rootViewController = navigationController; [self.window makeKeyAndVisible]; return YES; } @end
flutter/dev/integration_tests/ios_add2app_life_cycle/ios_add2app/AppDelegate.m/0
{ "file_path": "flutter/dev/integration_tests/ios_add2app_life_cycle/ios_add2app/AppDelegate.m", "repo_id": "flutter", "token_count": 347 }
527
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // ExtensionDelegate.swift // watch Extension // // Created by Georg Wechslberger on 08.04.20. // import WatchKit class ExtensionDelegate: NSObject, WKExtensionDelegate { func applicationDidFinishLaunching() { // Perform any final initialization of your application. } func applicationDidBecomeActive() { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillResignActive() { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, etc. } func handle(_ backgroundTasks: Set<WKRefreshBackgroundTask>) { // Sent when the system needs to launch the application in the background to process tasks. Tasks arrive in a set, so loop through and process each one. for task in backgroundTasks { // Use a switch statement to check the task type switch task { case let backgroundTask as WKApplicationRefreshBackgroundTask: // Be sure to complete the background task once you’re done. backgroundTask.setTaskCompletedWithSnapshot(false) case let snapshotTask as WKSnapshotRefreshBackgroundTask: // Snapshot tasks have a unique completion call, make sure to set your expiration date snapshotTask.setTaskCompleted(restoredDefaultState: true, estimatedSnapshotExpiration: Date.distantFuture, userInfo: nil) case let connectivityTask as WKWatchConnectivityRefreshBackgroundTask: // Be sure to complete the connectivity task once you’re done. connectivityTask.setTaskCompletedWithSnapshot(false) case let urlSessionTask as WKURLSessionRefreshBackgroundTask: // Be sure to complete the URL session task once you’re done. urlSessionTask.setTaskCompletedWithSnapshot(false) case let relevantShortcutTask as WKRelevantShortcutRefreshBackgroundTask: // Be sure to complete the relevant-shortcut task once you're done. relevantShortcutTask.setTaskCompletedWithSnapshot(false) case let intentDidRunTask as WKIntentDidRunRefreshBackgroundTask: // Be sure to complete the intent-did-run task once you're done. intentDidRunTask.setTaskCompletedWithSnapshot(false) default: // make sure to complete unhandled task types task.setTaskCompletedWithSnapshot(false) } } } }
flutter/dev/integration_tests/ios_app_with_extensions/ios/watch Extension/ExtensionDelegate.swift/0
{ "file_path": "flutter/dev/integration_tests/ios_app_with_extensions/ios/watch Extension/ExtensionDelegate.swift", "repo_id": "flutter", "token_count": 1055 }
528
<?xml version="1.0" encoding="UTF-8"?> <Workspace version = "1.0"> <FileRef location = "group:Host.xcodeproj"> </FileRef> <FileRef location = "group:Pods/Pods.xcodeproj"> </FileRef> </Workspace>
flutter/dev/integration_tests/ios_host_app/Host.xcworkspace/contents.xcworkspacedata/0
{ "file_path": "flutter/dev/integration_tests/ios_host_app/Host.xcworkspace/contents.xcworkspacedata", "repo_id": "flutter", "token_count": 103 }
529
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #import <UIKit/UIKit.h> @protocol NativeViewControllerDelegate /// Triggered when the increment button from the NativeViewController is tapped. -(void)didTapIncrementButton; @end @interface NativeViewController : UIViewController - (instancetype)initWithDelegate:(id<NativeViewControllerDelegate>)delegate NS_DESIGNATED_INITIALIZER; @property(nonatomic, weak) id<NativeViewControllerDelegate> delegate; -(void)didReceiveIncrement; @end
flutter/dev/integration_tests/ios_host_app/Host/NativeViewController.h/0
{ "file_path": "flutter/dev/integration_tests/ios_host_app/Host/NativeViewController.h", "repo_id": "flutter", "token_count": 182 }
530
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #import "ViewFactory.h" @interface PlatformView: NSObject<FlutterPlatformView> @property (strong, nonatomic) UIView *platformView; @end @implementation PlatformView - (instancetype)init { self = [super init]; if (self) { _platformView = [[UIView alloc] init]; _platformView.backgroundColor = [UIColor blueColor]; } return self; } - (UIView *)view { return self.platformView; } @end @implementation ViewFactory - (NSObject<FlutterPlatformView> *)createWithFrame:(CGRect)frame viewIdentifier:(int64_t)viewId arguments:(id)args { return [[PlatformView alloc] init]; } @end
flutter/dev/integration_tests/ios_platform_view_tests/ios/Runner/ViewFactory.m/0
{ "file_path": "flutter/dev/integration_tests/ios_platform_view_tests/ios/Runner/ViewFactory.m", "repo_id": "flutter", "token_count": 251 }
531
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import '../../gallery_localizations.dart'; // BEGIN cupertinoSearchTextFieldDemo class CupertinoSearchTextFieldDemo extends StatefulWidget { const CupertinoSearchTextFieldDemo({super.key}); @override State<CupertinoSearchTextFieldDemo> createState() => _CupertinoSearchTextFieldDemoState(); } class _CupertinoSearchTextFieldDemoState extends State<CupertinoSearchTextFieldDemo> { final List<String> platforms = <String>[ 'Android', 'iOS', 'Windows', 'Linux', 'MacOS', 'Web' ]; final TextEditingController _queryTextController = TextEditingController(); String _searchPlatform = ''; List<String> filteredPlatforms = <String>[]; @override void initState() { super.initState(); filteredPlatforms = platforms; _queryTextController.addListener(() { if (_queryTextController.text.isEmpty) { setState(() { _searchPlatform = ''; filteredPlatforms = platforms; }); } else { setState(() { _searchPlatform = _queryTextController.text; }); } }); } @override Widget build(BuildContext context) { final GalleryLocalizations localizations = GalleryLocalizations.of(context)!; return CupertinoPageScaffold( navigationBar: CupertinoNavigationBar( automaticallyImplyLeading: false, middle: Text(localizations.demoCupertinoSearchTextFieldTitle), ), child: SafeArea( child: Column( children: <Widget>[ CupertinoSearchTextField( controller: _queryTextController, restorationId: 'search_text_field', padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 12), decoration: const BoxDecoration( border: Border( bottom: BorderSide( width: 0, color: CupertinoColors.inactiveGray, ), ), ), placeholder: localizations.demoCupertinoSearchTextFieldPlaceholder, ), _buildPlatformList(), ], ), ), ); } Widget _buildPlatformList() { if (_searchPlatform.isNotEmpty) { final List<String> tempList = <String>[]; for (int i = 0; i < filteredPlatforms.length; i++) { if (filteredPlatforms[i] .toLowerCase() .contains(_searchPlatform.toLowerCase())) { tempList.add(filteredPlatforms[i]); } } filteredPlatforms = tempList; } return ListView.builder( itemCount: filteredPlatforms.length, shrinkWrap: true, itemBuilder: (BuildContext context, int index) { return ListTile(title: Text(filteredPlatforms[index])); }, ); } } // END
flutter/dev/integration_tests/new_gallery/lib/demos/cupertino/cupertino_search_text_field_demo.dart/0
{ "file_path": "flutter/dev/integration_tests/new_gallery/lib/demos/cupertino/cupertino_search_text_field_demo.dart", "repo_id": "flutter", "token_count": 1295 }
532
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import '../../gallery_localizations.dart'; // BEGIN tooltipDemo class TooltipDemo extends StatelessWidget { const TooltipDemo({super.key}); @override Widget build(BuildContext context) { final GalleryLocalizations localizations = GalleryLocalizations.of(context)!; return Scaffold( appBar: AppBar( automaticallyImplyLeading: false, title: Text(localizations.demoTooltipTitle), ), body: Center( child: Padding( padding: const EdgeInsets.all(8), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text( localizations.demoTooltipInstructions, textAlign: TextAlign.center, ), const SizedBox(height: 16), Tooltip( message: localizations.starterAppTooltipSearch, child: IconButton( color: Theme.of(context).colorScheme.primary, onPressed: () {}, icon: const Icon(Icons.search), ), ), ], ), ), ), ); } } // END
flutter/dev/integration_tests/new_gallery/lib/demos/material/tooltip_demo.dart/0
{ "file_path": "flutter/dev/integration_tests/new_gallery/lib/demos/material/tooltip_demo.dart", "repo_id": "flutter", "token_count": 644 }
533
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:collection'; import 'package:collection/collection.dart'; import 'package:flutter/material.dart'; import 'package:flutter_localized_locales/flutter_localized_locales.dart'; import 'package:url_launcher/url_launcher.dart'; import '../constants.dart'; import '../data/gallery_options.dart'; import '../gallery_localizations.dart'; import '../layout/adaptive.dart'; import 'about.dart' as about; import 'home.dart'; import 'settings_list_item.dart'; enum _ExpandableSetting { textScale, textDirection, locale, platform, theme, } class SettingsPage extends StatefulWidget { const SettingsPage({ super.key, required this.animationController, }); final AnimationController animationController; @override State<SettingsPage> createState() => _SettingsPageState(); } class _SettingsPageState extends State<SettingsPage> { _ExpandableSetting? _expandedSettingId; late Animation<double> _staggerSettingsItemsAnimation; void onTapSetting(_ExpandableSetting settingId) { setState(() { if (_expandedSettingId == settingId) { _expandedSettingId = null; } else { _expandedSettingId = settingId; } }); } void _closeSettingId(AnimationStatus status) { if (status == AnimationStatus.dismissed) { setState(() { _expandedSettingId = null; }); } } @override void initState() { super.initState(); // When closing settings, also shrink expanded setting. widget.animationController.addStatusListener(_closeSettingId); _staggerSettingsItemsAnimation = CurvedAnimation( parent: widget.animationController, curve: const Interval( 0.4, 1.0, curve: Curves.ease, ), ); } @override void dispose() { super.dispose(); widget.animationController.removeStatusListener(_closeSettingId); } /// Given a [Locale], returns a [DisplayOption] with its native name for a /// title and its name in the currently selected locale for a subtitle. If the /// native name can't be determined, it is omitted. If the locale can't be /// determined, the locale code is used. DisplayOption _getLocaleDisplayOption(BuildContext context, Locale? locale) { final String localeCode = locale.toString(); final String? localeName = LocaleNames.of(context)!.nameOf(localeCode); if (localeName != null) { final String? localeNativeName = LocaleNamesLocalizationsDelegate.nativeLocaleNames[localeCode]; return localeNativeName != null ? DisplayOption(localeNativeName, subtitle: localeName) : DisplayOption(localeName); } else { // gsw, fil, and es_419 aren't in flutter_localized_countries' dataset // so we handle them separately switch (localeCode) { case 'gsw': return DisplayOption('Schwiizertüütsch', subtitle: 'Swiss German'); case 'fil': return DisplayOption('Filipino', subtitle: 'Filipino'); case 'es_419': return DisplayOption( 'español (Latinoamérica)', subtitle: 'Spanish (Latin America)', ); } } return DisplayOption(localeCode); } /// Create a sorted — by native name – map of supported locales to their /// intended display string, with a system option as the first element. LinkedHashMap<Locale, DisplayOption> _getLocaleOptions() { final LinkedHashMap<Locale, DisplayOption> localeOptions = LinkedHashMap<Locale, DisplayOption>.of(<Locale, DisplayOption>{ systemLocaleOption: DisplayOption( GalleryLocalizations.of(context)!.settingsSystemDefault + (deviceLocale != null ? ' - ${_getLocaleDisplayOption(context, deviceLocale).title}' : ''), ), }); final List<Locale> supportedLocales = List<Locale>.from(GalleryLocalizations.supportedLocales); supportedLocales.removeWhere((Locale locale) => locale == deviceLocale); final List<MapEntry<Locale, DisplayOption>> displayLocales = Map<Locale, DisplayOption>.fromIterable( supportedLocales, value: (dynamic locale) => _getLocaleDisplayOption(context, locale as Locale?), ).entries.toList() ..sort((MapEntry<Locale, DisplayOption> l1, MapEntry<Locale, DisplayOption> l2) => compareAsciiUpperCase(l1.value.title, l2.value.title)); localeOptions.addAll(LinkedHashMap<Locale, DisplayOption>.fromEntries(displayLocales)); return localeOptions; } @override Widget build(BuildContext context) { final ColorScheme colorScheme = Theme.of(context).colorScheme; final GalleryOptions options = GalleryOptions.of(context); final bool isDesktop = isDisplayDesktop(context); final GalleryLocalizations localizations = GalleryLocalizations.of(context)!; final List<Widget> settingsListItems = <Widget>[ SettingsListItem<double?>( title: localizations.settingsTextScaling, selectedOption: options.textScaleFactor( context, useSentinel: true, ), optionsMap: LinkedHashMap<double?, DisplayOption>.of(<double?, DisplayOption>{ systemTextScaleFactorOption: DisplayOption( localizations.settingsSystemDefault, ), 0.8: DisplayOption( localizations.settingsTextScalingSmall, ), 1.0: DisplayOption( localizations.settingsTextScalingNormal, ), 2.0: DisplayOption( localizations.settingsTextScalingLarge, ), 3.0: DisplayOption( localizations.settingsTextScalingHuge, ), }), onOptionChanged: (double? newTextScale) => GalleryOptions.update( context, options.copyWith(textScaleFactor: newTextScale), ), onTapSetting: () => onTapSetting(_ExpandableSetting.textScale), isExpanded: _expandedSettingId == _ExpandableSetting.textScale, ), SettingsListItem<CustomTextDirection?>( title: localizations.settingsTextDirection, selectedOption: options.customTextDirection, optionsMap: LinkedHashMap<CustomTextDirection?, DisplayOption>.of(<CustomTextDirection?, DisplayOption>{ CustomTextDirection.localeBased: DisplayOption( localizations.settingsTextDirectionLocaleBased, ), CustomTextDirection.ltr: DisplayOption( localizations.settingsTextDirectionLTR, ), CustomTextDirection.rtl: DisplayOption( localizations.settingsTextDirectionRTL, ), }), onOptionChanged: (CustomTextDirection? newTextDirection) => GalleryOptions.update( context, options.copyWith(customTextDirection: newTextDirection), ), onTapSetting: () => onTapSetting(_ExpandableSetting.textDirection), isExpanded: _expandedSettingId == _ExpandableSetting.textDirection, ), SettingsListItem<Locale?>( title: localizations.settingsLocale, selectedOption: options.locale == deviceLocale ? systemLocaleOption : options.locale, optionsMap: _getLocaleOptions(), onOptionChanged: (Locale? newLocale) { if (newLocale == systemLocaleOption) { newLocale = deviceLocale; } GalleryOptions.update( context, options.copyWith(locale: newLocale), ); }, onTapSetting: () => onTapSetting(_ExpandableSetting.locale), isExpanded: _expandedSettingId == _ExpandableSetting.locale, ), SettingsListItem<TargetPlatform?>( title: localizations.settingsPlatformMechanics, selectedOption: options.platform, optionsMap: LinkedHashMap<TargetPlatform?, DisplayOption>.of(<TargetPlatform?, DisplayOption>{ TargetPlatform.android: DisplayOption('Android'), TargetPlatform.iOS: DisplayOption('iOS'), TargetPlatform.macOS: DisplayOption('macOS'), TargetPlatform.linux: DisplayOption('Linux'), TargetPlatform.windows: DisplayOption('Windows'), }), onOptionChanged: (TargetPlatform? newPlatform) => GalleryOptions.update( context, options.copyWith(platform: newPlatform), ), onTapSetting: () => onTapSetting(_ExpandableSetting.platform), isExpanded: _expandedSettingId == _ExpandableSetting.platform, ), SettingsListItem<ThemeMode?>( title: localizations.settingsTheme, selectedOption: options.themeMode, optionsMap: LinkedHashMap<ThemeMode?, DisplayOption>.of(<ThemeMode?, DisplayOption>{ ThemeMode.system: DisplayOption( localizations.settingsSystemDefault, ), ThemeMode.dark: DisplayOption( localizations.settingsDarkTheme, ), ThemeMode.light: DisplayOption( localizations.settingsLightTheme, ), }), onOptionChanged: (ThemeMode? newThemeMode) => GalleryOptions.update( context, options.copyWith(themeMode: newThemeMode), ), onTapSetting: () => onTapSetting(_ExpandableSetting.theme), isExpanded: _expandedSettingId == _ExpandableSetting.theme, ), ToggleSetting( text: GalleryLocalizations.of(context)!.settingsSlowMotion, value: options.timeDilation != 1.0, onChanged: (bool isOn) => GalleryOptions.update( context, options.copyWith(timeDilation: isOn ? 5.0 : 1.0), ), ), ]; return Material( color: colorScheme.secondaryContainer, child: Padding( padding: isDesktop ? EdgeInsets.zero : const EdgeInsets.only( bottom: galleryHeaderHeight, ), // Remove ListView top padding as it is already accounted for. child: MediaQuery.removePadding( removeTop: isDesktop, context: context, child: ListView( children: <Widget>[ if (isDesktop) const SizedBox(height: firstHeaderDesktopTopPadding), Padding( padding: const EdgeInsets.symmetric(horizontal: 32), child: ExcludeSemantics( child: Header( color: Theme.of(context).colorScheme.onSurface, text: localizations.settingsTitle, ), ), ), if (isDesktop) ...settingsListItems else ...<Widget>[ _AnimateSettingsListItems( animation: _staggerSettingsItemsAnimation, children: settingsListItems, ), const SizedBox(height: 16), Divider(thickness: 2, height: 0, color: colorScheme.outline), const SizedBox(height: 12), const SettingsAbout(), const SettingsFeedback(), const SizedBox(height: 12), Divider(thickness: 2, height: 0, color: colorScheme.outline), const SettingsAttribution(), ], ], ), ), ), ); } } class SettingsAbout extends StatelessWidget { const SettingsAbout({super.key}); @override Widget build(BuildContext context) { return _SettingsLink( title: GalleryLocalizations.of(context)!.settingsAbout, icon: Icons.info_outline, onTap: () { about.showAboutDialog(context: context); }, ); } } class SettingsFeedback extends StatelessWidget { const SettingsFeedback({super.key}); @override Widget build(BuildContext context) { return _SettingsLink( title: GalleryLocalizations.of(context)!.settingsFeedback, icon: Icons.feedback, onTap: () async { final Uri url = Uri.parse('https://github.com/flutter/gallery/issues/new/choose/'); if (await canLaunchUrl(url)) { await launchUrl(url); } }, ); } } class SettingsAttribution extends StatelessWidget { const SettingsAttribution({super.key}); @override Widget build(BuildContext context) { final bool isDesktop = isDisplayDesktop(context); final double verticalPadding = isDesktop ? 0.0 : 28.0; return MergeSemantics( child: Padding( padding: EdgeInsetsDirectional.only( start: isDesktop ? 24 : 32, end: isDesktop ? 0 : 32, top: verticalPadding, bottom: verticalPadding, ), child: SelectableText( GalleryLocalizations.of(context)!.settingsAttribution, style: Theme.of(context).textTheme.bodyLarge!.copyWith( fontSize: 12, color: Theme.of(context).colorScheme.onSecondary, ), textAlign: isDesktop ? TextAlign.end : TextAlign.start, ), ), ); } } class _SettingsLink extends StatelessWidget { const _SettingsLink({ required this.title, this.icon, this.onTap, }); final String title; final IconData? icon; final GestureTapCallback? onTap; @override Widget build(BuildContext context) { final TextTheme textTheme = Theme.of(context).textTheme; final ColorScheme colorScheme = Theme.of(context).colorScheme; final bool isDesktop = isDisplayDesktop(context); return InkWell( onTap: onTap, child: Padding( padding: EdgeInsets.symmetric( horizontal: isDesktop ? 24 : 32, ), child: Row( mainAxisSize: MainAxisSize.min, children: <Widget>[ Icon( icon, color: colorScheme.onSecondary.withOpacity(0.5), size: 24, ), Flexible( child: Padding( padding: const EdgeInsetsDirectional.only( start: 16, top: 12, bottom: 12, ), child: Text( title, style: textTheme.titleSmall!.apply( color: colorScheme.onSecondary, ), textAlign: isDesktop ? TextAlign.end : TextAlign.start, ), ), ), ], ), ), ); } } /// Animate the settings list items to stagger in from above. class _AnimateSettingsListItems extends StatelessWidget { const _AnimateSettingsListItems({ required this.animation, required this.children, }); final Animation<double> animation; final List<Widget> children; @override Widget build(BuildContext context) { const double dividingPadding = 4.0; final Tween<double> dividerTween = Tween<double>( begin: 0, end: dividingPadding, ); return Padding( padding: const EdgeInsets.symmetric(vertical: 16.0), child: Column( children: <Widget>[ for (final Widget child in children) AnimatedBuilder( animation: animation, builder: (BuildContext context, Widget? child) { return Padding( padding: EdgeInsets.only( top: dividerTween.animate(animation).value, ), child: child, ); }, child: child, ), ], ), ); } }
flutter/dev/integration_tests/new_gallery/lib/pages/settings.dart/0
{ "file_path": "flutter/dev/integration_tests/new_gallery/lib/pages/settings.dart", "repo_id": "flutter", "token_count": 6636 }
534
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import '../../../data/gallery_options.dart'; import '../../../gallery_localizations.dart'; import 'formatters.dart'; abstract class Destination { const Destination({ required this.id, required this.destination, required this.assetSemanticLabel, required this.imageAspectRatio, }); final int id; final String destination; final String assetSemanticLabel; final double imageAspectRatio; String get assetName; String subtitle(BuildContext context); String subtitleSemantics(BuildContext context) => subtitle(context); @override String toString() => '$destination (id=$id)'; } class FlyDestination extends Destination { const FlyDestination({ required super.id, required super.destination, required super.assetSemanticLabel, required this.stops, super.imageAspectRatio = 1, this.duration, }); final int stops; final Duration? duration; @override String get assetName => 'crane/destinations/fly_$id.jpg'; @override String subtitle(BuildContext context) { final String stopsText = GalleryLocalizations.of(context)!.craneFlyStops(stops); if (duration == null) { return stopsText; } else { final TextDirection? textDirection = GalleryOptions.of(context).resolvedTextDirection(); final String durationText = formattedDuration(context, duration!, abbreviated: true); return textDirection == TextDirection.ltr ? '$stopsText · $durationText' : '$durationText · $stopsText'; } } @override String subtitleSemantics(BuildContext context) { final String stopsText = GalleryLocalizations.of(context)!.craneFlyStops(stops); if (duration == null) { return stopsText; } else { final String durationText = formattedDuration(context, duration!, abbreviated: false); return '$stopsText, $durationText'; } } } class SleepDestination extends Destination { const SleepDestination({ required super.id, required super.destination, required super.assetSemanticLabel, required this.total, super.imageAspectRatio = 1, }); final int total; @override String get assetName => 'crane/destinations/sleep_$id.jpg'; @override String subtitle(BuildContext context) { return GalleryLocalizations.of(context)!.craneSleepProperties(total); } } class EatDestination extends Destination { const EatDestination({ required super.id, required super.destination, required super.assetSemanticLabel, required this.total, super.imageAspectRatio = 1, }); final int total; @override String get assetName => 'crane/destinations/eat_$id.jpg'; @override String subtitle(BuildContext context) { return GalleryLocalizations.of(context)!.craneEatRestaurants(total); } }
flutter/dev/integration_tests/new_gallery/lib/studies/crane/model/destination.dart/0
{ "file_path": "flutter/dev/integration_tests/new_gallery/lib/studies/crane/model/destination.dart", "repo_id": "flutter", "token_count": 990 }
535
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import '../../data/gallery_options.dart'; import '../../gallery_localizations.dart'; import '../../layout/adaptive.dart'; import '../../layout/text_scale.dart'; import 'tabs/accounts.dart'; import 'tabs/bills.dart'; import 'tabs/budgets.dart'; import 'tabs/overview.dart'; import 'tabs/settings.dart'; const int tabCount = 5; const int turnsToRotateRight = 1; const int turnsToRotateLeft = 3; class HomePage extends StatefulWidget { const HomePage({super.key}); @override State<HomePage> createState() => _HomePageState(); } class _HomePageState extends State<HomePage> with SingleTickerProviderStateMixin, RestorationMixin { late TabController _tabController; RestorableInt tabIndex = RestorableInt(0); @override String get restorationId => 'home_page'; @override void restoreState(RestorationBucket? oldBucket, bool initialRestore) { registerForRestoration(tabIndex, 'tab_index'); _tabController.index = tabIndex.value; } @override void initState() { super.initState(); _tabController = TabController(length: tabCount, vsync: this) ..addListener(() { // Set state to make sure that the [_RallyTab] widgets get updated when changing tabs. setState(() { tabIndex.value = _tabController.index; }); }); } @override void dispose() { _tabController.dispose(); tabIndex.dispose(); super.dispose(); } @override Widget build(BuildContext context) { final ThemeData theme = Theme.of(context); final bool isDesktop = isDisplayDesktop(context); Widget tabBarView; if (isDesktop) { final bool isTextDirectionRtl = GalleryOptions.of(context).resolvedTextDirection() == TextDirection.rtl; final int verticalRotation = isTextDirectionRtl ? turnsToRotateLeft : turnsToRotateRight; final int revertVerticalRotation = isTextDirectionRtl ? turnsToRotateRight : turnsToRotateLeft; tabBarView = Row( children: <Widget>[ Container( width: 150 + 50 * (cappedTextScale(context) - 1), alignment: Alignment.topCenter, padding: const EdgeInsets.symmetric(vertical: 32), child: Column( children: <Widget>[ const SizedBox(height: 24), ExcludeSemantics( child: SizedBox( height: 80, child: Image.asset( 'logo.png', package: 'rally_assets', ), ), ), const SizedBox(height: 24), // Rotate the tab bar, so the animation is vertical for desktops. RotatedBox( quarterTurns: verticalRotation, child: _RallyTabBar( tabs: _buildTabs( context: context, theme: theme, isVertical: true) .map( (Widget widget) { // Revert the rotation on the tabs. return RotatedBox( quarterTurns: revertVerticalRotation, child: widget, ); }, ).toList(), tabController: _tabController, ), ), ], ), ), Expanded( // Rotate the tab views so we can swipe up and down. child: RotatedBox( quarterTurns: verticalRotation, child: TabBarView( controller: _tabController, children: _buildTabViews().map( (Widget widget) { // Revert the rotation on the tab views. return RotatedBox( quarterTurns: revertVerticalRotation, child: widget, ); }, ).toList(), ), ), ), ], ); } else { tabBarView = Column( children: <Widget>[ _RallyTabBar( tabs: _buildTabs(context: context, theme: theme), tabController: _tabController, ), Expanded( child: TabBarView( controller: _tabController, children: _buildTabViews(), ), ), ], ); } return ApplyTextOptions( child: Scaffold( body: SafeArea( // For desktop layout we do not want to have SafeArea at the top and // bottom to display 100% height content on the accounts view. top: !isDesktop, bottom: !isDesktop, child: Theme( // This theme effectively removes the default visual touch // feedback for tapping a tab, which is replaced with a custom // animation. data: theme.copyWith( splashColor: Colors.transparent, highlightColor: Colors.transparent, ), child: FocusTraversalGroup( policy: OrderedTraversalPolicy(), child: tabBarView, ), ), ), ), ); } List<Widget> _buildTabs( {required BuildContext context, required ThemeData theme, bool isVertical = false}) { final GalleryLocalizations localizations = GalleryLocalizations.of(context)!; return <Widget>[ _RallyTab( theme: theme, iconData: Icons.pie_chart, title: localizations.rallyTitleOverview, tabIndex: 0, tabController: _tabController, isVertical: isVertical, ), _RallyTab( theme: theme, iconData: Icons.attach_money, title: localizations.rallyTitleAccounts, tabIndex: 1, tabController: _tabController, isVertical: isVertical, ), _RallyTab( theme: theme, iconData: Icons.money_off, title: localizations.rallyTitleBills, tabIndex: 2, tabController: _tabController, isVertical: isVertical, ), _RallyTab( theme: theme, iconData: Icons.table_chart, title: localizations.rallyTitleBudgets, tabIndex: 3, tabController: _tabController, isVertical: isVertical, ), _RallyTab( theme: theme, iconData: Icons.settings, title: localizations.rallyTitleSettings, tabIndex: 4, tabController: _tabController, isVertical: isVertical, ), ]; } List<Widget> _buildTabViews() { return const <Widget>[ OverviewView(), AccountsView(), BillsView(), BudgetsView(), SettingsView(), ]; } } class _RallyTabBar extends StatelessWidget { const _RallyTabBar({ required this.tabs, this.tabController, }); final List<Widget> tabs; final TabController? tabController; @override Widget build(BuildContext context) { return FocusTraversalOrder( order: const NumericFocusOrder(0), child: TabBar( // Setting isScrollable to true prevents the tabs from being // wrapped in [Expanded] widgets, which allows for more // flexible sizes and size animations among tabs. isScrollable: true, labelPadding: EdgeInsets.zero, tabs: tabs, controller: tabController, // This hides the tab indicator. indicatorColor: Colors.transparent, ), ); } } class _RallyTab extends StatefulWidget { _RallyTab({ required ThemeData theme, IconData? iconData, required String title, int? tabIndex, required TabController tabController, required this.isVertical, }) : titleText = Text(title, style: theme.textTheme.labelLarge), isExpanded = tabController.index == tabIndex, icon = Icon(iconData, semanticLabel: title); final Text titleText; final Icon icon; final bool isExpanded; final bool isVertical; @override _RallyTabState createState() => _RallyTabState(); } class _RallyTabState extends State<_RallyTab> with SingleTickerProviderStateMixin { late Animation<double> _titleSizeAnimation; late Animation<double> _titleFadeAnimation; late Animation<double> _iconFadeAnimation; late AnimationController _controller; @override void initState() { super.initState(); _controller = AnimationController( duration: const Duration(milliseconds: 200), vsync: this, ); _titleSizeAnimation = _controller.view; _titleFadeAnimation = _controller.drive(CurveTween(curve: Curves.easeOut)); _iconFadeAnimation = _controller.drive(Tween<double>(begin: 0.6, end: 1)); if (widget.isExpanded) { _controller.value = 1; } } @override void didUpdateWidget(_RallyTab oldWidget) { super.didUpdateWidget(oldWidget); if (widget.isExpanded) { _controller.forward(); } else { _controller.reverse(); } } @override Widget build(BuildContext context) { if (widget.isVertical) { return Column( children: <Widget>[ const SizedBox(height: 18), FadeTransition( opacity: _iconFadeAnimation, child: widget.icon, ), const SizedBox(height: 12), FadeTransition( opacity: _titleFadeAnimation, child: SizeTransition( axisAlignment: -1, sizeFactor: _titleSizeAnimation, child: Center(child: ExcludeSemantics(child: widget.titleText)), ), ), const SizedBox(height: 18), ], ); } // Calculate the width of each unexpanded tab by counting the number of // units and dividing it into the screen width. Each unexpanded tab is 1 // unit, and there is always 1 expanded tab which is 1 unit + any extra // space determined by the multiplier. final double width = MediaQuery.of(context).size.width; const int expandedTitleWidthMultiplier = 2; final double unitWidth = width / (tabCount + expandedTitleWidthMultiplier); return ConstrainedBox( constraints: const BoxConstraints(minHeight: 56), child: Row( children: <Widget>[ FadeTransition( opacity: _iconFadeAnimation, child: SizedBox( width: unitWidth, child: widget.icon, ), ), FadeTransition( opacity: _titleFadeAnimation, child: SizeTransition( axis: Axis.horizontal, axisAlignment: -1, sizeFactor: _titleSizeAnimation, child: SizedBox( width: unitWidth * expandedTitleWidthMultiplier, child: Center( child: ExcludeSemantics(child: widget.titleText), ), ), ), ), ], ), ); } @override void dispose() { _controller.dispose(); super.dispose(); } }
flutter/dev/integration_tests/new_gallery/lib/studies/rally/home.dart/0
{ "file_path": "flutter/dev/integration_tests/new_gallery/lib/studies/rally/home.dart", "repo_id": "flutter", "token_count": 5189 }
536
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import '../../layout/adaptive.dart'; import 'mail_card_preview.dart'; import 'model/email_model.dart'; import 'model/email_store.dart'; class MailboxBody extends StatelessWidget { const MailboxBody({super.key}); @override Widget build(BuildContext context) { final bool isDesktop = isDisplayDesktop(context); final bool isTablet = isDisplaySmallDesktop(context); final double startPadding = isTablet ? 60.0 : isDesktop ? 120.0 : 4.0; final double endPadding = isTablet ? 30.0 : isDesktop ? 60.0 : 4.0; return Consumer<EmailStore>( builder: (BuildContext context, EmailStore model, Widget? child) { final MailboxPageType destination = model.selectedMailboxPage; final String destinationString = destination .toString() .substring(destination.toString().indexOf('.') + 1); late List<Email> emails; switch (destination) { case MailboxPageType.inbox: { emails = model.inboxEmails; break; } case MailboxPageType.sent: { emails = model.outboxEmails; break; } case MailboxPageType.starred: { emails = model.starredEmails; break; } case MailboxPageType.trash: { emails = model.trashEmails; break; } case MailboxPageType.spam: { emails = model.spamEmails; break; } case MailboxPageType.drafts: { emails = model.draftEmails; break; } } return SafeArea( bottom: false, child: Row( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Expanded( child: emails.isEmpty ? Center(child: Text('Empty in $destinationString')) : ListView.separated( itemCount: emails.length, padding: EdgeInsetsDirectional.only( start: startPadding, end: endPadding, top: isDesktop ? 28 : 0, bottom: kToolbarHeight, ), primary: false, separatorBuilder: (BuildContext context, int index) => const SizedBox(height: 4), itemBuilder: (BuildContext context, int index) { final Email email = emails[index]; return MailPreviewCard( id: email.id, email: email, isStarred: model.isEmailStarred(email.id), onDelete: () => model.deleteEmail(email.id), onStar: () { final int emailId = email.id; if (model.isEmailStarred(emailId)) { model.unstarEmail(emailId); } else { model.starEmail(emailId); } }, onStarredMailbox: model.selectedMailboxPage == MailboxPageType.starred, ); }, ), ), if (isDesktop) ...<Widget>[ Padding( padding: const EdgeInsetsDirectional.only(top: 14), child: Row( children: <Widget>[ IconButton( key: const ValueKey<String>('ReplySearch'), icon: const Icon(Icons.search), onPressed: () { Provider.of<EmailStore>( context, listen: false, ).onSearchPage = true; }, ), SizedBox(width: isTablet ? 30 : 60), ], ), ), ] ], ), ); }, ); } }
flutter/dev/integration_tests/new_gallery/lib/studies/reply/mailbox_body.dart/0
{ "file_path": "flutter/dev/integration_tests/new_gallery/lib/studies/reply/mailbox_body.dart", "repo_id": "flutter", "token_count": 2786 }
537
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/widgets.dart'; import '../../../gallery_localizations.dart'; import 'product.dart'; class ProductsRepository { static List<Product> loadProducts(Category category) { final List<Product> allProducts = <Product>[ Product( category: categoryAccessories, id: 0, isFeatured: true, name: (BuildContext context) => GalleryLocalizations.of(context)!.shrineProductVagabondSack, price: 120, assetAspectRatio: 329 / 246, ), Product( category: categoryAccessories, id: 1, isFeatured: true, name: (BuildContext context) => GalleryLocalizations.of(context)!.shrineProductStellaSunglasses, price: 58, assetAspectRatio: 329 / 247, ), Product( category: categoryAccessories, id: 2, isFeatured: false, name: (BuildContext context) => GalleryLocalizations.of(context)!.shrineProductWhitneyBelt, price: 35, assetAspectRatio: 329 / 228, ), Product( category: categoryAccessories, id: 3, isFeatured: true, name: (BuildContext context) => GalleryLocalizations.of(context)!.shrineProductGardenStrand, price: 98, assetAspectRatio: 329 / 246, ), Product( category: categoryAccessories, id: 4, isFeatured: false, name: (BuildContext context) => GalleryLocalizations.of(context)!.shrineProductStrutEarrings, price: 34, assetAspectRatio: 329 / 246, ), Product( category: categoryAccessories, id: 5, isFeatured: false, name: (BuildContext context) => GalleryLocalizations.of(context)!.shrineProductVarsitySocks, price: 12, assetAspectRatio: 329 / 246, ), Product( category: categoryAccessories, id: 6, isFeatured: false, name: (BuildContext context) => GalleryLocalizations.of(context)!.shrineProductWeaveKeyring, price: 16, assetAspectRatio: 329 / 246, ), Product( category: categoryAccessories, id: 7, isFeatured: true, name: (BuildContext context) => GalleryLocalizations.of(context)!.shrineProductGatsbyHat, price: 40, assetAspectRatio: 329 / 246, ), Product( category: categoryAccessories, id: 8, isFeatured: true, name: (BuildContext context) => GalleryLocalizations.of(context)!.shrineProductShrugBag, price: 198, assetAspectRatio: 329 / 246, ), Product( category: categoryHome, id: 9, isFeatured: true, name: (BuildContext context) => GalleryLocalizations.of(context)!.shrineProductGiltDeskTrio, price: 58, assetAspectRatio: 329 / 246, ), Product( category: categoryHome, id: 10, isFeatured: false, name: (BuildContext context) => GalleryLocalizations.of(context)!.shrineProductCopperWireRack, price: 18, assetAspectRatio: 329 / 246, ), Product( category: categoryHome, id: 11, isFeatured: false, name: (BuildContext context) => GalleryLocalizations.of(context)!.shrineProductSootheCeramicSet, price: 28, assetAspectRatio: 329 / 247, ), Product( category: categoryHome, id: 12, isFeatured: false, name: (BuildContext context) => GalleryLocalizations.of(context)!.shrineProductHurrahsTeaSet, price: 34, assetAspectRatio: 329 / 213, ), Product( category: categoryHome, id: 13, isFeatured: true, name: (BuildContext context) => GalleryLocalizations.of(context)!.shrineProductBlueStoneMug, price: 18, assetAspectRatio: 329 / 246, ), Product( category: categoryHome, id: 14, isFeatured: true, name: (BuildContext context) => GalleryLocalizations.of(context)!.shrineProductRainwaterTray, price: 27, assetAspectRatio: 329 / 246, ), Product( category: categoryHome, id: 15, isFeatured: true, name: (BuildContext context) => GalleryLocalizations.of(context)!.shrineProductChambrayNapkins, price: 16, assetAspectRatio: 329 / 246, ), Product( category: categoryHome, id: 16, isFeatured: true, name: (BuildContext context) => GalleryLocalizations.of(context)!.shrineProductSucculentPlanters, price: 16, assetAspectRatio: 329 / 246, ), Product( category: categoryHome, id: 17, isFeatured: false, name: (BuildContext context) => GalleryLocalizations.of(context)!.shrineProductQuartetTable, price: 175, assetAspectRatio: 329 / 246, ), Product( category: categoryHome, id: 18, isFeatured: true, name: (BuildContext context) => GalleryLocalizations.of(context)!.shrineProductKitchenQuattro, price: 129, assetAspectRatio: 329 / 246, ), Product( category: categoryClothing, id: 19, isFeatured: false, name: (BuildContext context) => GalleryLocalizations.of(context)!.shrineProductClaySweater, price: 48, assetAspectRatio: 329 / 219, ), Product( category: categoryClothing, id: 20, isFeatured: false, name: (BuildContext context) => GalleryLocalizations.of(context)!.shrineProductSeaTunic, price: 45, assetAspectRatio: 329 / 221, ), Product( category: categoryClothing, id: 21, isFeatured: false, name: (BuildContext context) => GalleryLocalizations.of(context)!.shrineProductPlasterTunic, price: 38, assetAspectRatio: 220 / 329, ), Product( category: categoryClothing, id: 22, isFeatured: false, name: (BuildContext context) => GalleryLocalizations.of(context)!.shrineProductWhitePinstripeShirt, price: 70, assetAspectRatio: 219 / 329, ), Product( category: categoryClothing, id: 23, isFeatured: false, name: (BuildContext context) => GalleryLocalizations.of(context)!.shrineProductChambrayShirt, price: 70, assetAspectRatio: 329 / 221, ), Product( category: categoryClothing, id: 24, isFeatured: true, name: (BuildContext context) => GalleryLocalizations.of(context)!.shrineProductSeabreezeSweater, price: 60, assetAspectRatio: 220 / 329, ), Product( category: categoryClothing, id: 25, isFeatured: false, name: (BuildContext context) => GalleryLocalizations.of(context)!.shrineProductGentryJacket, price: 178, assetAspectRatio: 329 / 219, ), Product( category: categoryClothing, id: 26, isFeatured: false, name: (BuildContext context) => GalleryLocalizations.of(context)!.shrineProductNavyTrousers, price: 74, assetAspectRatio: 220 / 329, ), Product( category: categoryClothing, id: 27, isFeatured: true, name: (BuildContext context) => GalleryLocalizations.of(context)!.shrineProductWalterHenleyWhite, price: 38, assetAspectRatio: 219 / 329, ), Product( category: categoryClothing, id: 28, isFeatured: true, name: (BuildContext context) => GalleryLocalizations.of(context)!.shrineProductSurfAndPerfShirt, price: 48, assetAspectRatio: 329 / 219, ), Product( category: categoryClothing, id: 29, isFeatured: true, name: (BuildContext context) => GalleryLocalizations.of(context)!.shrineProductGingerScarf, price: 98, assetAspectRatio: 219 / 329, ), Product( category: categoryClothing, id: 30, isFeatured: true, name: (BuildContext context) => GalleryLocalizations.of(context)!.shrineProductRamonaCrossover, price: 68, assetAspectRatio: 220 / 329, ), Product( category: categoryClothing, id: 31, isFeatured: false, name: (BuildContext context) => GalleryLocalizations.of(context)!.shrineProductChambrayShirt, price: 38, assetAspectRatio: 329 / 223, ), Product( category: categoryClothing, id: 32, isFeatured: false, name: (BuildContext context) => GalleryLocalizations.of(context)!.shrineProductClassicWhiteCollar, price: 58, assetAspectRatio: 221 / 329, ), Product( category: categoryClothing, id: 33, isFeatured: true, name: (BuildContext context) => GalleryLocalizations.of(context)!.shrineProductCeriseScallopTee, price: 42, assetAspectRatio: 329 / 219, ), Product( category: categoryClothing, id: 34, isFeatured: false, name: (BuildContext context) => GalleryLocalizations.of(context)!.shrineProductShoulderRollsTee, price: 27, assetAspectRatio: 220 / 329, ), Product( category: categoryClothing, id: 35, isFeatured: false, name: (BuildContext context) => GalleryLocalizations.of(context)!.shrineProductGreySlouchTank, price: 24, assetAspectRatio: 222 / 329, ), Product( category: categoryClothing, id: 36, isFeatured: false, name: (BuildContext context) => GalleryLocalizations.of(context)!.shrineProductSunshirtDress, price: 58, assetAspectRatio: 219 / 329, ), Product( category: categoryClothing, id: 37, isFeatured: true, name: (BuildContext context) => GalleryLocalizations.of(context)!.shrineProductFineLinesTee, price: 58, assetAspectRatio: 219 / 329, ), ]; if (category == categoryAll) { return allProducts; } else { return allProducts.where((Product p) => p.category == category).toList(); } } }
flutter/dev/integration_tests/new_gallery/lib/studies/shrine/model/products_repository.dart/0
{ "file_path": "flutter/dev/integration_tests/new_gallery/lib/studies/shrine/model/products_repository.dart", "repo_id": "flutter", "token_count": 5109 }
538
package com.example.non_nullable import io.flutter.embedding.android.FlutterActivity class MainActivity : FlutterActivity()
flutter/dev/integration_tests/non_nullable/android/app/src/main/kotlin/com/example/non_nullable/MainActivity.kt/0
{ "file_path": "flutter/dev/integration_tests/non_nullable/android/app/src/main/kotlin/com/example/non_nullable/MainActivity.kt", "repo_id": "flutter", "token_count": 36 }
539
#include "Generated.xcconfig"
flutter/dev/integration_tests/platform_interaction/ios/Flutter/Debug.xcconfig/0
{ "file_path": "flutter/dev/integration_tests/platform_interaction/ios/Flutter/Debug.xcconfig", "repo_id": "flutter", "token_count": 12 }
540
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. plugins { id "com.android.application" id "kotlin-android" id "dev.flutter.flutter-gradle-plugin" } android { namespace "com.yourcompany.integration_ui" compileSdk flutter.compileSdkVersion compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } defaultConfig { minSdkVersion flutter.minSdkVersion targetSdkVersion flutter.targetSdkVersion versionCode 1 versionName "1.0" } 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.debug } } } flutter { source '../..' }
flutter/dev/integration_tests/ui/android/app/build.gradle/0
{ "file_path": "flutter/dev/integration_tests/ui/android/app/build.gradle", "repo_id": "flutter", "token_count": 377 }
541
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter_driver/flutter_driver.dart'; import 'package:test/test.dart' hide TypeMatcher, isInstanceOf; void main() { late FlutterDriver driver; setUpAll(() async { driver = await FlutterDriver.connect(); }); tearDownAll(() async { await driver.close(); }); test('check that we are painting in debugPaintSize mode', () async { expect(await driver.requestData('status'), 'log: paint debugPaintSize'); }, timeout: Timeout.none); }
flutter/dev/integration_tests/ui/test_driver/commands_debug_paint_test.dart/0
{ "file_path": "flutter/dev/integration_tests/ui/test_driver/commands_debug_paint_test.dart", "repo_id": "flutter", "token_count": 196 }
542
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:html' as html; import 'package:flutter/material.dart'; void main() => runApp(const MyApp()); class MyApp extends StatelessWidget { const MyApp({super.key}); // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Scroll Wheel Test', theme: ThemeData( primarySwatch: Colors.blue, fontFamily: 'RobotoMono', visualDensity: VisualDensity.adaptivePlatformDensity, ), home: const MyHomePage(title: 'Flutter Scroll Wheel Test'), ); } } class MyHomePage extends StatefulWidget { const MyHomePage({super.key, required this.title}); final String title; @override State createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title), ), body: ListView.builder( itemCount: 1000, itemBuilder: (BuildContext context, int index) => Padding( padding: const EdgeInsets.all(20), child: Container( height: 100, color: Colors.lightBlue, child: Center( child: Text('Item $index'), ), ), ), ), floatingActionButton: FloatingActionButton.extended( key: const Key('scroll-button'), onPressed: () { const int centerX = 100; //html.window.innerWidth ~/ 2; const int centerY = 100; //html.window.innerHeight ~/ 2; dispatchMouseWheelEvent(centerX, centerY, DeltaMode.kLine, 0, 1); dispatchMouseWheelEvent(centerX, centerY, DeltaMode.kLine, 0, 1); dispatchMouseWheelEvent(centerX, centerY, DeltaMode.kLine, 0, 1); dispatchMouseWheelEvent(centerX, centerY, DeltaMode.kLine, 0, 1); dispatchMouseWheelEvent(centerX, centerY, DeltaMode.kLine, 0, 1); }, label: const Text('Scroll'), icon: const Icon(Icons.thumb_up), ), ); } } abstract class DeltaMode { static const int kLine = 0x01; } void dispatchMouseWheelEvent(int mouseX, int mouseY, int deltaMode, double deltaX, double deltaY) { final html.EventTarget target = html.document.elementFromPoint(mouseX, mouseY)!; target.dispatchEvent(html.MouseEvent('mouseover', screenX: mouseX, screenY: mouseY, clientX: mouseX, clientY: mouseY, )); target.dispatchEvent(html.MouseEvent('mousemove', screenX: mouseX, screenY: mouseY, clientX: mouseX, clientY: mouseY, )); target.dispatchEvent(html.WheelEvent('wheel', screenX: mouseX, screenY: mouseY, clientX: mouseX, clientY: mouseY, deltaMode: deltaMode, deltaX : deltaX, deltaY : deltaY, )); }
flutter/dev/integration_tests/web_e2e_tests/lib/scroll_wheel_main.dart/0
{ "file_path": "flutter/dev/integration_tests/web_e2e_tests/lib/scroll_wheel_main.dart", "repo_id": "flutter", "token_count": 1188 }
543
# Windows start up test This test verifies that Flutter draws a frame before the Windows app is shown.
flutter/dev/integration_tests/windows_startup_test/README.md/0
{ "file_path": "flutter/dev/integration_tests/windows_startup_test/README.md", "repo_id": "flutter", "token_count": 24 }
544
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; class AnimatedIconsTestApp extends StatelessWidget { const AnimatedIconsTestApp({super.key}); @override Widget build(BuildContext context) { return const MaterialApp( title: 'Animated Icons Test', home: Scaffold( body: IconsList(), ), ); } } class IconsList extends StatelessWidget { const IconsList({super.key}); @override Widget build(BuildContext context) { return ListView( children: samples.map<IconSampleRow>((IconSample s) => IconSampleRow(s)).toList(), ); } } class IconSampleRow extends StatefulWidget { const IconSampleRow(this.sample, {super.key}); final IconSample sample; @override State createState() => IconSampleRowState(); } class IconSampleRowState extends State<IconSampleRow> with SingleTickerProviderStateMixin { late final AnimationController progress = AnimationController(vsync: this, duration: const Duration(milliseconds: 300)); @override Widget build(BuildContext context) { return ListTile( leading: InkWell( onTap: () { progress.forward(from: 0.0); }, child: AnimatedIcon( icon: widget.sample.icon, progress: progress, color: Colors.lightBlue, ), ), title: Text(widget.sample.description), subtitle: Slider( value: progress.value, onChanged: (double v) { progress.animateTo(v, duration: Duration.zero); }, ), ); } @override void initState() { super.initState(); progress.addListener(_handleChange); } @override void dispose() { progress.removeListener(_handleChange); super.dispose(); } void _handleChange() { setState(() {}); } } const List<IconSample> samples = <IconSample> [ IconSample(AnimatedIcons.arrow_menu, 'arrow_menu'), IconSample(AnimatedIcons.menu_arrow, 'menu_arrow'), IconSample(AnimatedIcons.close_menu, 'close_menu'), IconSample(AnimatedIcons.menu_close, 'menu_close'), IconSample(AnimatedIcons.home_menu, 'home_menu'), IconSample(AnimatedIcons.menu_home, 'menu_home'), IconSample(AnimatedIcons.play_pause, 'play_pause'), IconSample(AnimatedIcons.pause_play, 'pause_play'), IconSample(AnimatedIcons.list_view, 'list_view'), IconSample(AnimatedIcons.view_list, 'view_list'), IconSample(AnimatedIcons.add_event, 'add_event'), IconSample(AnimatedIcons.event_add, 'event_add'), IconSample(AnimatedIcons.ellipsis_search, 'ellipsis_search'), IconSample(AnimatedIcons.search_ellipsis, 'search_ellipsis'), ]; class IconSample { const IconSample(this.icon, this.description); final AnimatedIconData icon; final String description; } void main() => runApp(const AnimatedIconsTestApp());
flutter/dev/manual_tests/lib/animated_icons.dart/0
{ "file_path": "flutter/dev/manual_tests/lib/animated_icons.dart", "repo_id": "flutter", "token_count": 1014 }
545
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:io'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:manual_tests/card_collection.dart' as card_collection; import 'mock_image_http.dart'; void main() { testWidgets('Card Collection smoke test', (WidgetTester tester) async { HttpOverrides.runZoned<Future<void>>(() async { card_collection.main(); // builds the app and schedules a frame but doesn't trigger one await tester.pump(); // see https://github.com/flutter/flutter/issues/1865 await tester.pump(); // triggers a frame final Finder navigationMenu = find.byWidgetPredicate((Widget widget) { if (widget is Tooltip) { return widget.message == 'Open navigation menu'; } return false; }); expect(navigationMenu, findsOneWidget); await tester.tap(navigationMenu); await tester.pump(); // start opening menu await tester.pump(const Duration(seconds: 1)); // wait til it's really opened // smoke test for various checkboxes await tester.tap(find.text('Make card labels editable')); await tester.pump(); await tester.tap(find.text('Let the sun shine')); await tester.pump(); await tester.tap(find.text('Make card labels editable')); await tester.pump(); await tester.tap(find.text('Vary font sizes')); await tester.pump(); }, createHttpClient: createMockImageHttpClient); }); }
flutter/dev/manual_tests/test/card_collection_test.dart/0
{ "file_path": "flutter/dev/manual_tests/test/card_collection_test.dart", "repo_id": "flutter", "token_count": 577 }
546
# Dartdoc Samples and Snippets The [snippets] tool uses the files in the `skeletons` directory to inject code blocks generated from `{@tool dartpad}`, `{@tool sample}`, and `{@tool snippet}` sections found in doc comments into the API docs. [snippets]: https://github.com/flutter/assets-for-api-docs/tree/master/packages/snippets
flutter/dev/snippets/config/README.md/0
{ "file_path": "flutter/dev/snippets/config/README.md", "repo_id": "flutter", "token_count": 105 }
547
{ "version": "v0_206", "md.comp.bottom-app-bar.container.color": "surfaceContainer", "md.comp.bottom-app-bar.container.elevation": "md.sys.elevation.level2", "md.comp.bottom-app-bar.container.height": 80.0, "md.comp.bottom-app-bar.container.shape": "md.sys.shape.corner.none" }
flutter/dev/tools/gen_defaults/data/bottom_app_bar.json/0
{ "file_path": "flutter/dev/tools/gen_defaults/data/bottom_app_bar.json", "repo_id": "flutter", "token_count": 117 }
548
{ "version": "v0_206", "md.sys.color.background": "md.ref.palette.neutral98", "md.sys.color.error": "md.ref.palette.error40", "md.sys.color.error-container": "md.ref.palette.error90", "md.sys.color.inverse-on-surface": "md.ref.palette.neutral95", "md.sys.color.inverse-primary": "md.ref.palette.primary80", "md.sys.color.inverse-surface": "md.ref.palette.neutral20", "md.sys.color.on-background": "md.ref.palette.neutral10", "md.sys.color.on-error": "md.ref.palette.error100", "md.sys.color.on-error-container": "md.ref.palette.error10", "md.sys.color.on-primary": "md.ref.palette.primary100", "md.sys.color.on-primary-container": "md.ref.palette.primary10", "md.sys.color.on-primary-fixed": "md.ref.palette.primary10", "md.sys.color.on-primary-fixed-variant": "md.ref.palette.primary30", "md.sys.color.on-secondary": "md.ref.palette.secondary100", "md.sys.color.on-secondary-container": "md.ref.palette.secondary10", "md.sys.color.on-secondary-fixed": "md.ref.palette.secondary10", "md.sys.color.on-secondary-fixed-variant": "md.ref.palette.secondary30", "md.sys.color.on-surface": "md.ref.palette.neutral10", "md.sys.color.on-surface-variant": "md.ref.palette.neutral-variant30", "md.sys.color.on-tertiary": "md.ref.palette.tertiary100", "md.sys.color.on-tertiary-container": "md.ref.palette.tertiary10", "md.sys.color.on-tertiary-fixed": "md.ref.palette.tertiary10", "md.sys.color.on-tertiary-fixed-variant": "md.ref.palette.tertiary30", "md.sys.color.outline": "md.ref.palette.neutral-variant50", "md.sys.color.outline-variant": "md.ref.palette.neutral-variant80", "md.sys.color.primary": "md.ref.palette.primary40", "md.sys.color.primary-container": "md.ref.palette.primary90", "md.sys.color.primary-fixed": "md.ref.palette.primary90", "md.sys.color.primary-fixed-dim": "md.ref.palette.primary80", "md.sys.color.scrim": "md.ref.palette.neutral0", "md.sys.color.secondary": "md.ref.palette.secondary40", "md.sys.color.secondary-container": "md.ref.palette.secondary90", "md.sys.color.secondary-fixed": "md.ref.palette.secondary90", "md.sys.color.secondary-fixed-dim": "md.ref.palette.secondary80", "md.sys.color.shadow": "md.ref.palette.neutral0", "md.sys.color.surface": "md.ref.palette.neutral98", "md.sys.color.surface-bright": "md.ref.palette.neutral98", "md.sys.color.surface-container": "md.ref.palette.neutral94", "md.sys.color.surface-container-high": "md.ref.palette.neutral92", "md.sys.color.surface-container-highest": "md.ref.palette.neutral90", "md.sys.color.surface-container-low": "md.ref.palette.neutral96", "md.sys.color.surface-container-lowest": "md.ref.palette.neutral100", "md.sys.color.surface-dim": "md.ref.palette.neutral87", "md.sys.color.surface-tint": "primary", "md.sys.color.surface-variant": "md.ref.palette.neutral-variant90", "md.sys.color.tertiary": "md.ref.palette.tertiary40", "md.sys.color.tertiary-container": "md.ref.palette.tertiary90", "md.sys.color.tertiary-fixed": "md.ref.palette.tertiary90", "md.sys.color.tertiary-fixed-dim": "md.ref.palette.tertiary80" }
flutter/dev/tools/gen_defaults/data/color_light.json/0
{ "file_path": "flutter/dev/tools/gen_defaults/data/color_light.json", "repo_id": "flutter", "token_count": 1267 }
549
{ "version": "v0_206", "md.comp.list.divider.leading-space": 16.0, "md.comp.list.divider.trailing-space": 16.0, "md.comp.list.focus.indicator.color": "secondary", "md.comp.list.focus.indicator.outline.offset": "md.sys.state.focus-indicator.inner-offset", "md.comp.list.focus.indicator.thickness": "md.sys.state.focus-indicator.thickness", "md.comp.list.list-item.container.color": "surface", "md.comp.list.list-item.container.elevation": "md.sys.elevation.level0", "md.comp.list.list-item.container.shape": "md.sys.shape.corner.none", "md.comp.list.list-item.disabled.label-text.color": "onSurface", "md.comp.list.list-item.disabled.label-text.opacity": 0.38, "md.comp.list.list-item.disabled.leading-icon.color": "onSurface", "md.comp.list.list-item.disabled.leading-icon.opacity": 0.38, "md.comp.list.list-item.disabled.state-layer.color": "onSurface", "md.comp.list.list-item.disabled.state-layer.opacity": "md.sys.state.focus.state-layer-opacity", "md.comp.list.list-item.disabled.trailing-icon.color": "onSurface", "md.comp.list.list-item.disabled.trailing-icon.opacity": 0.38, "md.comp.list.list-item.dragged.container.elevation": "md.sys.elevation.level4", "md.comp.list.list-item.dragged.label-text.color": "onSurface", "md.comp.list.list-item.dragged.leading-icon.icon.color": "onSurfaceVariant", "md.comp.list.list-item.dragged.state-layer.color": "onSurface", "md.comp.list.list-item.dragged.state-layer.opacity": "md.sys.state.pressed.state-layer-opacity", "md.comp.list.list-item.dragged.trailing-icon.icon.color": "onSurfaceVariant", "md.comp.list.list-item.focus.label-text.color": "onSurface", "md.comp.list.list-item.focus.leading-icon.icon.color": "onSurfaceVariant", "md.comp.list.list-item.focus.state-layer.color": "onSurface", "md.comp.list.list-item.focus.state-layer.opacity": "md.sys.state.focus.state-layer-opacity", "md.comp.list.list-item.focus.trailing-icon.icon.color": "onSurfaceVariant", "md.comp.list.list-item.hover.label-text.color": "onSurface", "md.comp.list.list-item.hover.leading-icon.icon.color": "onSurfaceVariant", "md.comp.list.list-item.hover.state-layer.color": "onSurface", "md.comp.list.list-item.hover.state-layer.opacity": "md.sys.state.hover.state-layer-opacity", "md.comp.list.list-item.hover.trailing-icon.icon.color": "onSurfaceVariant", "md.comp.list.list-item.label-text.color": "onSurface", "md.comp.list.list-item.label-text.text-style": "bodyLarge", "md.comp.list.list-item.large.leading-video.height": 69.0, "md.comp.list.list-item.leading-avatar.color": "primaryContainer", "md.comp.list.list-item.leading-avatar-label.color": "onPrimaryContainer", "md.comp.list.list-item.leading-avatar-label.text-style": "titleMedium", "md.comp.list.list-item.leading-avatar.shape": "md.sys.shape.corner.full", "md.comp.list.list-item.leading-avatar.size": 40.0, "md.comp.list.list-item.leading-icon.color": "onSurfaceVariant", "md.comp.list.list-item.leading-icon.size": 24.0, "md.comp.list.list-item.leading-image.height": 56.0, "md.comp.list.list-item.leading-image.shape": "md.sys.shape.corner.none", "md.comp.list.list-item.leading-image.width": 56.0, "md.comp.list.list-item.leading-space": 16.0, "md.comp.list.list-item.leading-video.shape": "md.sys.shape.corner.none", "md.comp.list.list-item.leading-video.width": 100.0, "md.comp.list.list-item.one-line.container.height": 56.0, "md.comp.list.list-item.overline.color": "onSurfaceVariant", "md.comp.list.list-item.overline.text-style": "labelSmall", "md.comp.list.list-item.pressed.label-text.color": "onSurface", "md.comp.list.list-item.pressed.leading-icon.icon.color": "onSurfaceVariant", "md.comp.list.list-item.pressed.state-layer.color": "onSurface", "md.comp.list.list-item.pressed.state-layer.opacity": "md.sys.state.pressed.state-layer-opacity", "md.comp.list.list-item.pressed.trailing-icon.icon.color": "onSurfaceVariant", "md.comp.list.list-item.selected.trailing-icon.color": "primary", "md.comp.list.list-item.small.leading-video.height": 56.0, "md.comp.list.list-item.supporting-text.color": "onSurfaceVariant", "md.comp.list.list-item.supporting-text.text-style": "bodyMedium", "md.comp.list.list-item.three-line.container.height": 88.0, "md.comp.list.list-item.trailing-icon.color": "onSurfaceVariant", "md.comp.list.list-item.trailing-icon.size": 24.0, "md.comp.list.list-item.trailing-space": 16.0, "md.comp.list.list-item.trailing-supporting-text.color": "onSurfaceVariant", "md.comp.list.list-item.trailing-supporting-text.text-style": "labelSmall", "md.comp.list.list-item.two-line.container.height": 72.0, "md.comp.list.list-item.unselected.trailing-icon.color": "onSurface" }
flutter/dev/tools/gen_defaults/data/list.json/0
{ "file_path": "flutter/dev/tools/gen_defaults/data/list.json", "repo_id": "flutter", "token_count": 1886 }
550
{ "version": "v0_206", "md.comp.sheet.bottom.docked.container.color": "surfaceContainerLow", "md.comp.sheet.bottom.docked.container.shape": "md.sys.shape.corner.extra-large.top", "md.comp.sheet.bottom.docked.drag-handle.color": "onSurfaceVariant", "md.comp.sheet.bottom.docked.drag-handle.height": 4.0, "md.comp.sheet.bottom.docked.drag-handle.width": 32.0, "md.comp.sheet.bottom.docked.minimized.container.shape": "md.sys.shape.corner.none", "md.comp.sheet.bottom.docked.modal.container.elevation": "md.sys.elevation.level1", "md.comp.sheet.bottom.docked.standard.container.elevation": "md.sys.elevation.level1", "md.comp.sheet.bottom.focus.indicator.color": "secondary", "md.comp.sheet.bottom.focus.indicator.outline.offset": "md.sys.state.focus-indicator.outer-offset", "md.comp.sheet.bottom.focus.indicator.thickness": "md.sys.state.focus-indicator.thickness" }
flutter/dev/tools/gen_defaults/data/sheet_bottom.json/0
{ "file_path": "flutter/dev/tools/gen_defaults/data/sheet_bottom.json", "repo_id": "flutter", "token_count": 347 }
551
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'template.dart'; class BadgeTemplate extends TokenTemplate { const BadgeTemplate(super.blockName, super.fileName, super.tokens, { super.colorSchemePrefix = '_colors.', }); @override String generate() => ''' class _${blockName}DefaultsM3 extends BadgeThemeData { _${blockName}DefaultsM3(this.context) : super( smallSize: ${getToken("md.comp.badge.size")}, largeSize: ${getToken("md.comp.badge.large.size")}, padding: const EdgeInsets.symmetric(horizontal: 4), alignment: AlignmentDirectional.topEnd, ); final BuildContext context; late final ThemeData _theme = Theme.of(context); late final ColorScheme _colors = _theme.colorScheme; @override Color? get backgroundColor => ${color("md.comp.badge.color")}; @override Color? get textColor => ${color("md.comp.badge.large.label-text.color")}; @override TextStyle? get textStyle => ${textStyle("md.comp.badge.large.label-text")}; } '''; }
flutter/dev/tools/gen_defaults/lib/badge_template.dart/0
{ "file_path": "flutter/dev/tools/gen_defaults/lib/badge_template.dart", "repo_id": "flutter", "token_count": 370 }
552
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'template.dart'; class IconButtonTemplate extends TokenTemplate { const IconButtonTemplate(this.tokenGroup, super.blockName, super.fileName, super.tokens, { super.colorSchemePrefix = '_colors.', }); final String tokenGroup; String _backgroundColor() { switch (tokenGroup) { case 'md.comp.filled-icon-button': case 'md.comp.filled-tonal-icon-button': return ''' MaterialStateProperty.resolveWith((Set<MaterialState> states) { if (states.contains(MaterialState.disabled)) { return ${componentColor('$tokenGroup.disabled.container')}; } if (states.contains(MaterialState.selected)) { return ${componentColor('$tokenGroup.selected.container')}; } if (toggleable) { // toggleable but unselected case return ${componentColor('$tokenGroup.unselected.container')}; } return ${componentColor('$tokenGroup.container')}; })'''; case 'md.comp.outlined-icon-button': return ''' MaterialStateProperty.resolveWith((Set<MaterialState> states) { if (states.contains(MaterialState.disabled)) { if (states.contains(MaterialState.selected)) { return ${componentColor('$tokenGroup.disabled.selected.container')}; } return Colors.transparent; } if (states.contains(MaterialState.selected)) { return ${componentColor('$tokenGroup.selected.container')}; } return Colors.transparent; })'''; } return ''' const MaterialStatePropertyAll<Color?>(Colors.transparent)'''; } String _foregroundColor() { switch (tokenGroup) { case 'md.comp.filled-icon-button': case 'md.comp.filled-tonal-icon-button': return ''' MaterialStateProperty.resolveWith((Set<MaterialState> states) { if (states.contains(MaterialState.disabled)) { return ${componentColor('$tokenGroup.disabled.icon')}; } if (states.contains(MaterialState.selected)) { return ${componentColor('$tokenGroup.toggle.selected.icon')}; } if (toggleable) { // toggleable but unselected case return ${componentColor('$tokenGroup.toggle.unselected.icon')}; } return ${componentColor('$tokenGroup.icon')}; })'''; case 'md.comp.outlined-icon-button': case 'md.comp.icon-button': return ''' MaterialStateProperty.resolveWith((Set<MaterialState> states) { if (states.contains(MaterialState.disabled)) { return ${componentColor('$tokenGroup.disabled.icon')}; } if (states.contains(MaterialState.selected)) { return ${componentColor('$tokenGroup.selected.icon')}; } return ${componentColor('$tokenGroup.unselected.icon')}; })'''; } return ''' const MaterialStatePropertyAll<Color?>(Colors.transparent)'''; } String _overlayColor() { switch (tokenGroup) { case 'md.comp.filled-icon-button': case 'md.comp.filled-tonal-icon-button': return ''' MaterialStateProperty.resolveWith((Set<MaterialState> states) { if (states.contains(MaterialState.selected)) { if (states.contains(MaterialState.pressed)) { return ${componentColor('$tokenGroup.toggle.selected.pressed.state-layer')}.withOpacity(${opacity('$tokenGroup.pressed.state-layer.opacity')}); } if (states.contains(MaterialState.hovered)) { return ${componentColor('$tokenGroup.toggle.selected.hover.state-layer')}.withOpacity(${opacity('$tokenGroup.hover.state-layer.opacity')}); } if (states.contains(MaterialState.focused)) { return ${componentColor('$tokenGroup.toggle.selected.focus.state-layer')}.withOpacity(${opacity('$tokenGroup.focus.state-layer.opacity')}); } } if (toggleable) { // toggleable but unselected case if (states.contains(MaterialState.pressed)) { return ${componentColor('$tokenGroup.toggle.unselected.pressed.state-layer')}.withOpacity(${opacity('$tokenGroup.pressed.state-layer.opacity')}); } if (states.contains(MaterialState.hovered)) { return ${componentColor('$tokenGroup.toggle.unselected.hover.state-layer')}.withOpacity(${opacity('$tokenGroup.hover.state-layer.opacity')}); } if (states.contains(MaterialState.focused)) { return ${componentColor('$tokenGroup.toggle.unselected.focus.state-layer')}.withOpacity(${opacity('$tokenGroup.focus.state-layer.opacity')}); } } if (states.contains(MaterialState.pressed)) { return ${componentColor('$tokenGroup.pressed.state-layer')}; } if (states.contains(MaterialState.hovered)) { return ${componentColor('$tokenGroup.hover.state-layer')}; } if (states.contains(MaterialState.focused)) { return ${componentColor('$tokenGroup.focus.state-layer')}; } return Colors.transparent; })'''; case 'md.comp.outlined-icon-button': return ''' MaterialStateProperty.resolveWith((Set<MaterialState> states) { if (states.contains(MaterialState.selected)) { if (states.contains(MaterialState.pressed)) { return ${componentColor('$tokenGroup.selected.pressed.state-layer')}.withOpacity(${opacity('$tokenGroup.pressed.state-layer.opacity')}); } if (states.contains(MaterialState.hovered)) { return ${componentColor('$tokenGroup.selected.hover.state-layer')}.withOpacity(${opacity('$tokenGroup.hover.state-layer.opacity')}); } if (states.contains(MaterialState.focused)) { return ${componentColor('$tokenGroup.selected.focus.state-layer')}.withOpacity(${opacity('$tokenGroup.focus.state-layer.opacity')}); } } if (states.contains(MaterialState.pressed)) { return ${componentColor('$tokenGroup.unselected.pressed.state-layer')}.withOpacity(${opacity('$tokenGroup.pressed.state-layer.opacity')}); } if (states.contains(MaterialState.hovered)) { return ${componentColor('$tokenGroup.unselected.hover.state-layer')}.withOpacity(${opacity('$tokenGroup.hover.state-layer.opacity')}); } if (states.contains(MaterialState.focused)) { return ${componentColor('$tokenGroup.unselected.focus.state-layer')}.withOpacity(${opacity('$tokenGroup.focus.state-layer.opacity')}); } return Colors.transparent; })'''; case 'md.comp.icon-button': return ''' MaterialStateProperty.resolveWith((Set<MaterialState> states) { if (states.contains(MaterialState.selected)) { if (states.contains(MaterialState.pressed)) { return ${componentColor('$tokenGroup.selected.pressed.state-layer')}; } if (states.contains(MaterialState.hovered)) { return ${componentColor('$tokenGroup.selected.hover.state-layer')}; } if (states.contains(MaterialState.focused)) { return ${componentColor('$tokenGroup.selected.focus.state-layer')}; } } if (states.contains(MaterialState.pressed)) { return ${componentColor('$tokenGroup.unselected.pressed.state-layer')}; } if (states.contains(MaterialState.hovered)) { return ${componentColor('$tokenGroup.unselected.hover.state-layer')}; } if (states.contains(MaterialState.focused)) { return ${componentColor('$tokenGroup.unselected.focus.state-layer')}; } return Colors.transparent; })'''; } return ''' const MaterialStatePropertyAll<Color?>(Colors.transparent)'''; } String _minimumSize() { if (tokenAvailable('$tokenGroup.container.height') && tokenAvailable('$tokenGroup.container.width')) { return ''' const MaterialStatePropertyAll<Size>(Size(${getToken('$tokenGroup.container.width')}, ${getToken('$tokenGroup.container.height')}))'''; } else { return ''' const MaterialStatePropertyAll<Size>(Size(40.0, 40.0))'''; } } String _shape() { if (tokenAvailable('$tokenGroup.container.shape')) { return ''' const MaterialStatePropertyAll<OutlinedBorder>(${shape("$tokenGroup.container", "")})'''; } else { return ''' const MaterialStatePropertyAll<OutlinedBorder>(${shape("$tokenGroup.state-layer", "")})'''; } } String _side() { if (tokenAvailable('$tokenGroup.unselected.outline.color')) { return ''' MaterialStateProperty.resolveWith((Set<MaterialState> states) { if (states.contains(MaterialState.selected)) { return null; } else { if (states.contains(MaterialState.disabled)) { return BorderSide(color: ${componentColor('$tokenGroup.disabled.unselected.outline')}); } return BorderSide(color: ${componentColor('$tokenGroup.unselected.outline')}); } })'''; } return ''' null'''; } String _elevationColor(String token) { if (tokenAvailable(token)) { return 'MaterialStatePropertyAll<Color>(${color(token)})'; } else { return 'const MaterialStatePropertyAll<Color>(Colors.transparent)'; } } @override String generate() => ''' class _${blockName}DefaultsM3 extends ButtonStyle { _${blockName}DefaultsM3(this.context, this.toggleable) : super( animationDuration: kThemeChangeDuration, enableFeedback: true, alignment: Alignment.center, ); final BuildContext context; final bool toggleable; late final ColorScheme _colors = Theme.of(context).colorScheme; // No default text style @override MaterialStateProperty<Color?>? get backgroundColor =>${_backgroundColor()}; @override MaterialStateProperty<Color?>? get foregroundColor =>${_foregroundColor()}; @override MaterialStateProperty<Color?>? get overlayColor =>${_overlayColor()}; @override MaterialStateProperty<double>? get elevation => const MaterialStatePropertyAll<double>(0.0); @override MaterialStateProperty<Color>? get shadowColor => ${_elevationColor("$tokenGroup.container.shadow-color")}; @override MaterialStateProperty<Color>? get surfaceTintColor => ${_elevationColor("$tokenGroup.container.surface-tint-layer.color")}; @override MaterialStateProperty<EdgeInsetsGeometry>? get padding => const MaterialStatePropertyAll<EdgeInsetsGeometry>(EdgeInsets.all(8.0)); @override MaterialStateProperty<Size>? get minimumSize =>${_minimumSize()}; // No default fixedSize @override MaterialStateProperty<Size>? get maximumSize => const MaterialStatePropertyAll<Size>(Size.infinite); @override MaterialStateProperty<double>? get iconSize => const MaterialStatePropertyAll<double>(${getToken("$tokenGroup.icon.size")}); @override MaterialStateProperty<BorderSide?>? get side =>${_side()}; @override MaterialStateProperty<OutlinedBorder>? get shape =>${_shape()}; @override MaterialStateProperty<MouseCursor?>? get mouseCursor => MaterialStateProperty.resolveWith((Set<MaterialState> states) { if (states.contains(MaterialState.disabled)) { return SystemMouseCursors.basic; } return SystemMouseCursors.click; }); @override VisualDensity? get visualDensity => VisualDensity.standard; @override MaterialTapTargetSize? get tapTargetSize => Theme.of(context).materialTapTargetSize; @override InteractiveInkFeatureFactory? get splashFactory => Theme.of(context).splashFactory; } '''; }
flutter/dev/tools/gen_defaults/lib/icon_button_template.dart/0
{ "file_path": "flutter/dev/tools/gen_defaults/lib/icon_button_template.dart", "repo_id": "flutter", "token_count": 4253 }
553
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'template.dart'; class SnackbarTemplate extends TokenTemplate { const SnackbarTemplate( this.tokenGroup, super.blockName, super.fileName, super.tokens, { super.colorSchemePrefix = '_colors.' }); final String tokenGroup; @override String generate() => ''' class _${blockName}DefaultsM3 extends SnackBarThemeData { _${blockName}DefaultsM3(this.context); final BuildContext context; late final ThemeData _theme = Theme.of(context); late final ColorScheme _colors = _theme.colorScheme; @override Color get backgroundColor => ${componentColor("$tokenGroup.container")}; @override Color get actionTextColor => MaterialStateColor.resolveWith((Set<MaterialState> states) { if (states.contains(MaterialState.disabled)) { return ${componentColor("$tokenGroup.action.pressed.label-text")}; } if (states.contains(MaterialState.pressed)) { return ${componentColor("$tokenGroup.action.pressed.label-text")}; } if (states.contains(MaterialState.hovered)) { return ${componentColor("$tokenGroup.action.hover.label-text")}; } if (states.contains(MaterialState.focused)) { return ${componentColor("$tokenGroup.action.focus.label-text")}; } return ${componentColor("$tokenGroup.action.label-text")}; }); @override Color get disabledActionTextColor => ${componentColor("$tokenGroup.action.pressed.label-text")}; @override TextStyle get contentTextStyle => ${textStyle("$tokenGroup.supporting-text")}!.copyWith (color: ${componentColor("$tokenGroup.supporting-text")}, ); @override double get elevation => ${elevation("$tokenGroup.container")}; @override ShapeBorder get shape => ${shape("$tokenGroup.container")}; @override SnackBarBehavior get behavior => SnackBarBehavior.fixed; @override EdgeInsets get insetPadding => const EdgeInsets.fromLTRB(15.0, 5.0, 15.0, 10.0); @override bool get showCloseIcon => false; @override Color? get closeIconColor => ${componentColor("$tokenGroup.icon")}; @override double get actionOverflowThreshold => 0.25; } '''; }
flutter/dev/tools/gen_defaults/lib/snackbar_template.dart/0
{ "file_path": "flutter/dev/tools/gen_defaults/lib/snackbar_template.dart", "repo_id": "flutter", "token_count": 752 }
554
{ "Add": ["PLUS"], "Again": ["AGAIN"], "AltLeft": ["ALT_LEFT"], "AltRight": ["ALT_RIGHT"], "AppSwitch": ["APP_SWITCH"], "ArrowDown": ["DPAD_DOWN"], "ArrowLeft": ["DPAD_LEFT"], "ArrowRight": ["DPAD_RIGHT"], "ArrowUp": ["DPAD_UP"], "Asterisk": ["STAR"], "At": ["AT"], "AudioVolumeDown": ["VOLUME_DOWN"], "AudioVolumeMute": ["VOLUME_MUTE"], "AudioVolumeUp": ["VOLUME_UP"], "AVRInput": ["AVR_INPUT"], "AVRPower": ["AVR_POWER"], "BassBoost": ["BASSBOOST"], "Print": ["PRINT"], "Backquote": ["GRAVE"], "Backslash": ["BACKSLASH"], "Backspace": ["DEL"], "BracketLeft": ["LEFT_BRACKET"], "BracketRight": ["RIGHT_BRACKET"], "BrightnessDown": ["BRIGHTNESS_DOWN"], "BrightnessUp": ["BRIGHTNESS_UP"], "BrowserFavorites": ["BOOKMARK"], "BrowserForward": ["FORWARD"], "BrowserSearch": ["SEARCH"], "Call": ["CALL"], "Camera": ["CAMERA"], "CameraFocus": ["FOCUS"], "CapsLock": ["CAPS_LOCK"], "ChannelDown": ["CHANNEL_DOWN"], "ChannelUp": ["CHANNEL_UP"], "Clear": ["CLEAR"], "Close": ["MEDIA_CLOSE", "CLOSE"], "ClosedCaptionToggle": ["CAPTIONS"], "ColorF0Red": ["PROG_RED"], "ColorF1Green": ["PROG_GREEN"], "ColorF2Yellow": ["PROG_YELLOW"], "ColorF3Blue": ["PROG_BLUE"], "Comma": ["COMMA"], "ContextMenu": ["MENU"], "ControlLeft": ["CTRL_LEFT"], "ControlRight": ["CTRL_RIGHT"], "Convert": ["HENKAN"], "Copy": ["COPY"], "Cut": ["CUT"], "Delete": ["FORWARD_DEL"], "Digit0": ["0"], "Digit1": ["1"], "Digit2": ["2"], "Digit3": ["3"], "Digit4": ["4"], "Digit5": ["5"], "Digit6": ["6"], "Digit7": ["7"], "Digit8": ["8"], "Digit9": ["9"], "DVR": ["DVR"], "Eisu": ["EISU"], "Eject": ["MEDIA_EJECT"], "End": ["MOVE_END"], "EndCall": ["ENDCALL"], "Enter": ["ENTER"], "Equal": ["EQUALS"], "Escape": ["ESCAPE"], "Exit": ["EXIT"], "F1": ["F1"], "F2": ["F2"], "F3": ["F3"], "F4": ["F4"], "F5": ["F5"], "F6": ["F6"], "F7": ["F7"], "F8": ["F8"], "F9": ["F9"], "F10": ["F10"], "F11": ["F11"], "F12": ["F12"], "F13": ["F13"], "F14": ["F14"], "F15": ["F15"], "F16": ["F16"], "F17": ["F17"], "F18": ["F18"], "F19": ["F19"], "F20": ["F20"], "F21": ["F21"], "F22": ["F22"], "F23": ["F23"], "F24": ["F24"], "Find": ["FIND"], "Fn": ["FUNCTION"], "GameButton1": ["BUTTON_1"], "GameButton2": ["BUTTON_2"], "GameButton3": ["BUTTON_3"], "GameButton4": ["BUTTON_4"], "GameButton5": ["BUTTON_5"], "GameButton6": ["BUTTON_6"], "GameButton7": ["BUTTON_7"], "GameButton8": ["BUTTON_8"], "GameButton9": ["BUTTON_9"], "GameButton10": ["BUTTON_10"], "GameButton11": ["BUTTON_11"], "GameButton12": ["BUTTON_12"], "GameButton13": ["BUTTON_13"], "GameButton14": ["BUTTON_14"], "GameButton15": ["BUTTON_15"], "GameButton16": ["BUTTON_16"], "GameButtonA": ["BUTTON_A"], "GameButtonB": ["BUTTON_B"], "GameButtonC": ["BUTTON_C"], "GameButtonLeft1": ["BUTTON_L1"], "GameButtonLeft2": ["BUTTON_L2"], "GameButtonMode": ["BUTTON_MODE"], "GameButtonRight1": ["BUTTON_R1"], "GameButtonRight2": ["BUTTON_R2"], "GameButtonSelect": ["BUTTON_SELECT"], "GameButtonStart": ["BUTTON_START"], "GameButtonThumbLeft": ["BUTTON_THUMBL"], "GameButtonThumbRight": ["BUTTON_THUMBR"], "GameButtonX": ["BUTTON_X"], "GameButtonY": ["BUTTON_Y"], "GameButtonZ": ["BUTTON_Z"], "GoBack": ["BACK"], "GoHome": ["HOME"], "GroupNext": ["LANGUAGE_SWITCH"], "Guide": ["GUIDE"], "HeadsetHook": ["HEADSETHOOK"], "Help": ["HELP"], "HiraganaKatakana": ["KATAKANA_HIRAGANA"], "Home": ["MOVE_HOME"], "Info": ["INFO"], "Insert": ["INSERT"], "KanjiMode": ["KANA"], "KeyA": ["A"], "KeyB": ["B"], "KeyC": ["C"], "KeyD": ["D"], "KeyE": ["E"], "KeyF": ["F"], "KeyG": ["G"], "KeyH": ["H"], "KeyI": ["I"], "KeyJ": ["J"], "KeyK": ["K"], "KeyL": ["L"], "KeyM": ["M"], "KeyN": ["N"], "KeyO": ["O"], "KeyP": ["P"], "KeyQ": ["Q"], "KeyR": ["R"], "KeyS": ["S"], "KeyT": ["T"], "KeyU": ["U"], "KeyV": ["V"], "KeyW": ["W"], "KeyX": ["X"], "KeyY": ["Y"], "KeyZ": ["Z"], "IntlRo": ["RO"], "IntlYen": ["YEN"], "Lang1": [], "Lang2": [], "Lang3": ["KATAKANA"], "Lang4": ["HIRAGANA"], "LaunchAssistant": ["ASSIST"], "LaunchCalendar": ["CALENDAR"], "LaunchContacts": ["CONTACTS"], "LaunchMail": ["ENVELOPE"], "LaunchMusicPlayer": ["MUSIC"], "LaunchWebBrowser": ["EXPLORER"], "MannerMode": ["MANNER_MODE"], "MediaAudioTrack": ["MEDIA_AUDIO_TRACK"], "MediaFastForward": ["MEDIA_FAST_FORWARD"], "MediaLast": ["LAST_CHANNEL"], "MediaPause": ["MEDIA_PAUSE"], "MediaPlay": ["MEDIA_PLAY"], "MediaPlayPause": ["MEDIA_PLAY_PAUSE"], "MediaRecord": ["MEDIA_RECORD"], "MediaRewind": ["MEDIA_REWIND"], "MediaSkipBackward": ["MEDIA_SKIP_BACKWARD"], "MediaSkipForward": ["MEDIA_SKIP_FORWARD"], "MediaStepBackward": ["MEDIA_STEP_BACKWARD"], "MediaStepForward": ["MEDIA_STEP_FORWARD"], "MediaStop": ["MEDIA_STOP"], "MediaTopMenu": ["MEDIA_TOP_MENU"], "MediaTrackNext": ["MEDIA_NEXT"], "MediaTrackPrevious": ["MEDIA_PREVIOUS"], "MetaLeft": ["META_LEFT"], "MetaRight": ["META_RIGHT"], "MicrophoneVolumeMute": ["MUTE"], "Minus": ["MINUS"], "ModeChange": ["SWITCH_CHARSET"], "NavigateIn": ["NAVIGATE_IN"], "NavigateNext": ["NAVIGATE_NEXT"], "NavigateOut": ["NAVIGATE_OUT"], "NavigatePrevious": ["NAVIGATE_PREVIOUS"], "NewKey": ["NEW"], "NonConvert": ["MUHENKAN"], "Notification": ["NOTIFICATION"], "NumLock": ["NUM_LOCK"], "NumberSign": ["POUND"], "Numpad0": ["NUMPAD_0"], "Numpad1": ["NUMPAD_1"], "Numpad2": ["NUMPAD_2"], "Numpad3": ["NUMPAD_3"], "Numpad4": ["NUMPAD_4"], "Numpad5": ["NUMPAD_5"], "Numpad6": ["NUMPAD_6"], "Numpad7": ["NUMPAD_7"], "Numpad8": ["NUMPAD_8"], "Numpad9": ["NUMPAD_9"], "NumpadAdd": ["NUMPAD_ADD"], "NumpadComma": ["NUMPAD_COMMA"], "NumpadDecimal": ["NUMPAD_DOT"], "NumpadDivide": ["NUMPAD_DIVIDE"], "NumpadEnter": ["NUMPAD_ENTER"], "NumpadEqual": ["NUMPAD_EQUALS"], "NumpadMultiply": ["NUMPAD_MULTIPLY"], "NumpadParenLeft": ["NUMPAD_LEFT_PAREN"], "NumpadParenRight": ["NUMPAD_RIGHT_PAREN"], "NumpadSubtract": ["NUMPAD_SUBTRACT"], "Open": ["OPEN"], "PageDown": ["PAGE_DOWN"], "PageUp": ["PAGE_UP"], "Pairing": ["PAIRING"], "Paste": ["PASTE"], "Pause": ["BREAK"], "Period": ["PERIOD"], "Power": ["POWER"], "PrintScreen": ["SYSRQ"], "Props": ["PROPS"], "Quote": ["APOSTROPHE"], "Redo": ["REDO"], "ScrollLock": ["SCROLL_LOCK"], "Select": ["DPAD_CENTER"], "Semicolon": ["SEMICOLON"], "Settings": ["SETTINGS"], "ShiftLeft": ["SHIFT_LEFT"], "ShiftRight": ["SHIFT_RIGHT"], "Slash": ["SLASH"], "Sleep": ["SLEEP"], "Space": ["SPACE"], "STBInput": ["STB_INPUT"], "STBPower": ["STB_POWER"], "Suspend": ["SUSPEND"], "Symbol": ["SYM"], "Tab": ["TAB"], "Teletext": ["TV_TELETEXT"], "TV": ["TV"], "TV3DMode": ["3D_MODE"], "TVAntennaCable": ["TV_ANTENNA_CABLE"], "TVAudioDescription": ["TV_AUDIO_DESCRIPTION"], "TVAudioDescriptionMixDown": ["TV_AUDIO_DESCRIPTION_MIX_DOWN"], "TVAudioDescriptionMixUp": ["TV_AUDIO_DESCRIPTION_MIX_UP"], "TVContentsMenu": ["TV_CONTENTS_MENU"], "TVDataService": ["TV_DATA_SERVICE"], "TVInput": ["TV_INPUT"], "TVInputComponent1": ["TV_INPUT_COMPONENT_1"], "TVInputComponent2": ["TV_INPUT_COMPONENT_2"], "TVInputComposite1": ["TV_INPUT_COMPOSITE_1"], "TVInputComposite2": ["TV_INPUT_COMPOSITE_2"], "TVInputHDMI1": ["TV_INPUT_HDMI_1"], "TVInputHDMI2": ["TV_INPUT_HDMI_2"], "TVInputHDMI3": ["TV_INPUT_HDMI_3"], "TVInputHDMI4": ["TV_INPUT_HDMI_4"], "TVInputVGA1": ["TV_INPUT_VGA_1"], "TVNetwork": ["TV_NETWORK"], "TVNumberEntry": ["TV_NUMBER_ENTRY"], "TVPower": ["TV_POWER"], "TVRadioService": ["TV_RADIO_SERVICE"], "TVSatellite": ["TV_SATELLITE"], "TVSatelliteBS": ["TV_SATELLITE_BS"], "TVSatelliteCS": ["TV_SATELLITE_CS"], "TVSatelliteToggle": ["TV_SATELLITE_SERVICE"], "TVTerrestrialAnalog": ["TV_TERRESTRIAL_ANALOG"], "TVTerrestrialDigital": ["TV_TERRESTRIAL_DIGITAL"], "TVTimer": ["TV_TIMER_PROGRAMMING"], "Undo": ["UNDO"], "WakeUp": ["WAKEUP"], "ZenkakuHankaku": ["ZENKAKU_HANKAKU"], "ZoomIn": ["ZOOM_IN"], "ZoomOut": ["ZOOM_OUT"], "ZoomToggle": ["TV_ZOOM_MODE"] }
flutter/dev/tools/gen_keycodes/data/android_key_name_to_name.json/0
{ "file_path": "flutter/dev/tools/gen_keycodes/data/android_key_name_to_name.json", "repo_id": "flutter", "token_count": 3656 }
555
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // DO NOT EDIT -- DO NOT EDIT -- DO NOT EDIT // This file is generated by dev/tools/gen_keycodes/bin/gen_keycodes.dart and // should not be edited directly. // // Edit the template dev/tools/gen_keycodes/data/keyboard_maps.tmpl instead. // See dev/tools/gen_keycodes/README.md for more information. import 'keyboard_key.g.dart'; export 'keyboard_key.g.dart' show LogicalKeyboardKey, PhysicalKeyboardKey; /// Maps Android-specific key codes to the matching [LogicalKeyboardKey]. const Map<int, LogicalKeyboardKey> kAndroidToLogicalKey = <int, LogicalKeyboardKey>{ @@@ANDROID_KEY_CODE_MAP@@@ }; /// Maps Android-specific scan codes to the matching [PhysicalKeyboardKey]. const Map<int, PhysicalKeyboardKey> kAndroidToPhysicalKey = <int, PhysicalKeyboardKey>{ @@@ANDROID_SCAN_CODE_MAP@@@ }; /// A map of Android key codes which have printable representations, but appear /// on the number pad. Used to provide different key objects for keys like /// KEY_EQUALS and NUMPAD_EQUALS. const Map<int, LogicalKeyboardKey> kAndroidNumPadMap = <int, LogicalKeyboardKey>{ @@@ANDROID_NUMPAD_MAP@@@ }; /// Maps Fuchsia-specific IDs to the matching [LogicalKeyboardKey]. const Map<int, LogicalKeyboardKey> kFuchsiaToLogicalKey = <int, LogicalKeyboardKey>{ @@@FUCHSIA_KEY_CODE_MAP@@@ }; /// Maps Fuchsia-specific USB HID Usage IDs to the matching /// [PhysicalKeyboardKey]. const Map<int, PhysicalKeyboardKey> kFuchsiaToPhysicalKey = <int, PhysicalKeyboardKey>{ @@@FUCHSIA_SCAN_CODE_MAP@@@ }; /// Maps macOS-specific key code values representing [PhysicalKeyboardKey]. /// /// MacOS doesn't provide a scan code, but a virtual keycode to represent a physical key. const Map<int, PhysicalKeyboardKey> kMacOsToPhysicalKey = <int, PhysicalKeyboardKey>{ @@@MACOS_SCAN_CODE_MAP@@@ }; /// A map of macOS key codes which have printable representations, but appear /// on the number pad. Used to provide different key objects for keys like /// KEY_EQUALS and NUMPAD_EQUALS. const Map<int, LogicalKeyboardKey> kMacOsNumPadMap = <int, LogicalKeyboardKey>{ @@@MACOS_NUMPAD_MAP@@@ }; /// A map of macOS key codes which are numbered function keys, so that they /// can be excluded when asking "is the Fn modifier down?". const Map<int, LogicalKeyboardKey> kMacOsFunctionKeyMap = <int, LogicalKeyboardKey>{ @@@MACOS_FUNCTION_KEY_MAP@@@ }; /// A map of macOS key codes presenting [LogicalKeyboardKey]. /// /// Logical key codes are not available in macOS key events. Most of the logical keys /// are derived from its `characterIgnoringModifiers`, but those keys that don't /// have a character representation will be derived from their key codes using /// this map. const Map<int, LogicalKeyboardKey> kMacOsToLogicalKey = <int, LogicalKeyboardKey>{ @@@MACOS_KEY_CODE_MAP@@@ }; /// Maps iOS-specific key code values representing [PhysicalKeyboardKey]. /// /// iOS doesn't provide a scan code, but a virtual keycode to represent a physical key. const Map<int, PhysicalKeyboardKey> kIosToPhysicalKey = <int, PhysicalKeyboardKey>{ @@@IOS_SCAN_CODE_MAP@@@ }; /// Maps iOS specific string values of nonvisible keys to logical keys /// /// Some unprintable keys on iOS has literal names on their key label, such as /// "UIKeyInputEscape". See: /// https://developer.apple.com/documentation/uikit/uikeycommand/input_strings_for_special_keys?language=objc const Map<String, LogicalKeyboardKey> kIosSpecialLogicalMap = <String, LogicalKeyboardKey>{ @@@IOS_SPECIAL_MAP@@@ }; /// A map of iOS key codes which have printable representations, but appear /// on the number pad. Used to provide different key objects for keys like /// KEY_EQUALS and NUMPAD_EQUALS. const Map<int, LogicalKeyboardKey> kIosNumPadMap = <int, LogicalKeyboardKey>{ @@@IOS_NUMPAD_MAP@@@ }; /// A map of iOS key codes presenting [LogicalKeyboardKey]. /// /// Logical key codes are not available in iOS key events. Most of the logical keys /// are derived from its `characterIgnoringModifiers`, but those keys that don't /// have a character representation will be derived from their key codes using /// this map. const Map<int, LogicalKeyboardKey> kIosToLogicalKey = <int, LogicalKeyboardKey>{ @@@IOS_KEY_CODE_MAP@@@ }; /// Maps GLFW-specific key codes to the matching [LogicalKeyboardKey]. const Map<int, LogicalKeyboardKey> kGlfwToLogicalKey = <int, LogicalKeyboardKey>{ @@@GLFW_KEY_CODE_MAP@@@ }; /// A map of GLFW key codes which have printable representations, but appear /// on the number pad. Used to provide different key objects for keys like /// KEY_EQUALS and NUMPAD_EQUALS. const Map<int, LogicalKeyboardKey> kGlfwNumpadMap = <int, LogicalKeyboardKey>{ @@@GLFW_NUMPAD_MAP@@@ }; /// Maps GTK-specific key codes to the matching [LogicalKeyboardKey]. const Map<int, LogicalKeyboardKey> kGtkToLogicalKey = <int, LogicalKeyboardKey>{ @@@GTK_KEY_CODE_MAP@@@ }; /// A map of GTK key codes which have printable representations, but appear /// on the number pad. Used to provide different key objects for keys like /// KEY_EQUALS and NUMPAD_EQUALS. const Map<int, LogicalKeyboardKey> kGtkNumpadMap = <int, LogicalKeyboardKey>{ @@@GTK_NUMPAD_MAP@@@ }; /// Maps XKB specific key code values representing [PhysicalKeyboardKey]. const Map<int, PhysicalKeyboardKey> kLinuxToPhysicalKey = <int, PhysicalKeyboardKey>{ @@@XKB_SCAN_CODE_MAP@@@ }; /// Maps Web KeyboardEvent codes to the matching [LogicalKeyboardKey]. const Map<String, LogicalKeyboardKey> kWebToLogicalKey = <String, LogicalKeyboardKey>{ @@@WEB_LOGICAL_KEY_MAP@@@ }; /// Maps Web KeyboardEvent codes to the matching [PhysicalKeyboardKey]. const Map<String, PhysicalKeyboardKey> kWebToPhysicalKey = <String, PhysicalKeyboardKey>{ @@@WEB_PHYSICAL_KEY_MAP@@@ }; /// A map of Web KeyboardEvent codes which have printable representations, but appear /// on the number pad. Used to provide different key objects for keys like /// KEY_EQUALS and NUMPAD_EQUALS. const Map<String, LogicalKeyboardKey> kWebNumPadMap = <String, LogicalKeyboardKey>{ @@@WEB_NUMPAD_MAP@@@ }; /// A map of Web KeyboardEvent keys which needs to be decided based on location, /// typically for numpad keys and modifier keys. Used to provide different key /// objects for keys like KEY_EQUALS and NUMPAD_EQUALS. const Map<String, List<LogicalKeyboardKey?>> kWebLocationMap = <String, List<LogicalKeyboardKey?>>{ @@@WEB_LOCATION_MAP@@@ }; /// Maps Windows KeyboardEvent codes to the matching [LogicalKeyboardKey]. const Map<int, LogicalKeyboardKey> kWindowsToLogicalKey = <int, LogicalKeyboardKey>{ @@@WINDOWS_LOGICAL_KEY_MAP@@@ }; /// Maps Windows KeyboardEvent codes to the matching [PhysicalKeyboardKey]. const Map<int, PhysicalKeyboardKey> kWindowsToPhysicalKey = <int, PhysicalKeyboardKey>{ @@@WINDOWS_PHYSICAL_KEY_MAP@@@ }; /// A map of Windows KeyboardEvent codes which have printable representations, but appear /// on the number pad. Used to provide different key objects for keys like /// KEY_EQUALS and NUMPAD_EQUALS. const Map<int, LogicalKeyboardKey> kWindowsNumPadMap = <int, LogicalKeyboardKey>{ @@@WINDOWS_NUMPAD_MAP@@@ };
flutter/dev/tools/gen_keycodes/data/keyboard_maps.tmpl/0
{ "file_path": "flutter/dev/tools/gen_keycodes/data/keyboard_maps.tmpl", "repo_id": "flutter", "token_count": 2258 }
556
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:io'; import 'logical_key_data.dart'; import 'physical_key_data.dart'; String _injectDictionary(String template, Map<String, String> dictionary) { String result = template; for (final String key in dictionary.keys) { result = result.replaceAll('@@@$key@@@', dictionary[key] ?? '@@@$key@@@'); } return result; } /// Generates a file based on the information in the key data structure given to /// it. /// /// [BaseCodeGenerator] finds tokens in the template file that has the form of /// `@@@TOKEN@@@`, and replace them by looking up the key `TOKEN` from the map /// returned by [mappings]. /// /// Subclasses must implement [templatePath] and [mappings]. abstract class BaseCodeGenerator { /// Create a code generator while providing [keyData] to be used in [mappings]. BaseCodeGenerator(this.keyData, this.logicalData); /// Absolute path to the template file that this file is generated on. String get templatePath; /// A mapping from tokens to be replaced in the template to the result string. Map<String, String> mappings(); /// Substitutes the various platform specific maps into the template file for /// keyboard_maps.g.dart. String generate() { final String template = File(templatePath).readAsStringSync(); return _injectDictionary(template, mappings()); } /// The database of keys loaded from disk. final PhysicalKeyData keyData; final LogicalKeyData logicalData; } /// A code generator which also defines platform-based behavior. abstract class PlatformCodeGenerator extends BaseCodeGenerator { PlatformCodeGenerator(super.keyData, super.logicalData); /// Absolute path to the output file. /// /// How this value will be used is based on the callee. String outputPath(String platform); static String engineRoot = ''; }
flutter/dev/tools/gen_keycodes/lib/base_code_gen.dart/0
{ "file_path": "flutter/dev/tools/gen_keycodes/lib/base_code_gen.dart", "repo_id": "flutter", "token_count": 548 }
557
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:convert'; import 'dart:io'; import 'package:gen_keycodes/android_code_gen.dart'; import 'package:gen_keycodes/base_code_gen.dart'; import 'package:gen_keycodes/gtk_code_gen.dart'; import 'package:gen_keycodes/ios_code_gen.dart'; import 'package:gen_keycodes/logical_key_data.dart'; import 'package:gen_keycodes/macos_code_gen.dart'; import 'package:gen_keycodes/physical_key_data.dart'; import 'package:gen_keycodes/utils.dart'; import 'package:gen_keycodes/web_code_gen.dart'; import 'package:gen_keycodes/windows_code_gen.dart'; import 'package:path/path.dart' as path; import 'package:test/test.dart' hide TypeMatcher, isInstanceOf; String readDataFile(String fileName) { return File(path.join(dataRoot, fileName)).readAsStringSync(); } final PhysicalKeyData physicalData = PhysicalKeyData.fromJson( json.decode(readDataFile('physical_key_data.g.json')) as Map<String, dynamic>); final LogicalKeyData logicalData = LogicalKeyData.fromJson( json.decode(readDataFile('logical_key_data.g.json')) as Map<String, dynamic>); final Map<String, bool> keyGoals = parseMapOfBool( readDataFile('layout_goals.json')); void main() { setUp(() { testDataRoot = path.canonicalize(path.join(Directory.current.absolute.path, 'data')); }); tearDown((){ testDataRoot = null; }); void checkCommonOutput(String output) { expect(output, contains(RegExp('Copyright 201[34]'))); expect(output, contains('DO NOT EDIT')); expect(output, contains(RegExp(r'\b[kK]eyA\b'))); expect(output, contains(RegExp(r'\b[Dd]igit1\b'))); expect(output, contains(RegExp(r'\b[Ff]1\b'))); expect(output, contains(RegExp(r'\b[Nn]umpad1\b'))); expect(output, contains(RegExp(r'\b[Ss]hiftLeft\b'))); } test('Generate Keycodes for Android', () { const String platform = 'android'; final PlatformCodeGenerator codeGenerator = AndroidCodeGenerator( physicalData, logicalData, ); final String output = codeGenerator.generate(); expect(codeGenerator.outputPath(platform), endsWith('KeyboardMap.java')); expect(output, contains('class KeyboardMap')); expect(output, contains('scanCodeToPhysical')); expect(output, contains('keyCodeToLogical')); checkCommonOutput(output); }); test('Generate Keycodes for macOS', () { const String platform = 'macos'; final PlatformCodeGenerator codeGenerator = MacOSCodeGenerator( physicalData, logicalData, keyGoals, ); final String output = codeGenerator.generate(); expect(codeGenerator.outputPath(platform), endsWith('KeyCodeMap.g.mm')); expect(output, contains('kValueMask')); expect(output, contains('keyCodeToPhysicalKey')); expect(output, contains('keyCodeToLogicalKey')); expect(output, contains('keyCodeToModifierFlag')); expect(output, contains('modifierFlagToKeyCode')); expect(output, contains('kCapsLockPhysicalKey')); expect(output, contains('kCapsLockLogicalKey')); expect(output, contains('kLayoutGoals')); checkCommonOutput(output); }); test('Generate Keycodes for iOS', () { const String platform = 'ios'; final PlatformCodeGenerator codeGenerator = IOSCodeGenerator( physicalData, logicalData, ); final String output = codeGenerator.generate(); expect(codeGenerator.outputPath(platform), endsWith('KeyCodeMap.g.mm')); expect(output, contains('kValueMask')); expect(output, contains('keyCodeToPhysicalKey')); expect(output, contains('keyCodeToLogicalKey')); expect(output, contains('keyCodeToModifierFlag')); expect(output, contains('modifierFlagToKeyCode')); expect(output, contains('functionKeyCodes')); expect(output, contains('kCapsLockPhysicalKey')); expect(output, contains('kCapsLockLogicalKey')); checkCommonOutput(output); }); test('Generate Keycodes for Windows', () { const String platform = 'windows'; final PlatformCodeGenerator codeGenerator = WindowsCodeGenerator( physicalData, logicalData, readDataFile(path.join(dataRoot, 'windows_scancode_logical_map.json')), ); final String output = codeGenerator.generate(); expect(codeGenerator.outputPath(platform), endsWith('flutter_key_map.g.cc')); expect(output, contains('KeyboardKeyEmbedderHandler::windowsToPhysicalMap_')); expect(output, contains('KeyboardKeyEmbedderHandler::windowsToLogicalMap_')); expect(output, contains('KeyboardKeyEmbedderHandler::scanCodeToLogicalMap_')); checkCommonOutput(output); }); test('Generate Keycodes for Linux', () { const String platform = 'gtk'; final PlatformCodeGenerator codeGenerator = GtkCodeGenerator( physicalData, logicalData, readDataFile(path.join(dataRoot, 'gtk_modifier_bit_mapping.json')), readDataFile(path.join(dataRoot, 'gtk_lock_bit_mapping.json')), keyGoals, ); final String output = codeGenerator.generate(); expect(codeGenerator.outputPath(platform), endsWith('key_mapping.g.cc')); expect(output, contains('initialize_modifier_bit_to_checked_keys')); expect(output, contains('initialize_lock_bit_to_checked_keys')); checkCommonOutput(output); }); test('Generate Keycodes for Web', () { const String platform = 'web'; final PlatformCodeGenerator codeGenerator = WebCodeGenerator( physicalData, logicalData, readDataFile(path.join(dataRoot, 'web_logical_location_mapping.json')), ); final String output = codeGenerator.generate(); expect(codeGenerator.outputPath(platform), endsWith('key_map.g.dart')); expect(output, contains('kWebToLogicalKey')); expect(output, contains('kWebToPhysicalKey')); expect(output, contains('kWebLogicalLocationMap')); checkCommonOutput(output); }); test('LogicalKeyData', () async { final List<LogicalKeyEntry> entries = logicalData.entries.toList(); // Regression tests for https://github.com/flutter/flutter/pull/87098 expect( entries.indexWhere((LogicalKeyEntry entry) => entry.name == 'ShiftLeft'), isNot(-1)); expect( entries.indexWhere((LogicalKeyEntry entry) => entry.webNames.contains('ShiftLeft')), -1); // 'Shift' maps to both 'ShiftLeft' and 'ShiftRight', and should be resolved // by other ways. expect( entries.indexWhere((LogicalKeyEntry entry) => entry.webNames.contains('Shift')), -1); // Printable keys must not be added with Web key of their names. expect( entries.indexWhere((LogicalKeyEntry entry) => entry.webNames.contains('Slash')), -1); }); }
flutter/dev/tools/gen_keycodes/test/gen_keycodes_test.dart/0
{ "file_path": "flutter/dev/tools/gen_keycodes/test/gen_keycodes_test.dart", "repo_id": "flutter", "token_count": 2382 }
558
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:test/test.dart'; import '../update_icons.dart'; Map<String, String> codepointsA = <String, String>{ 'airplane': '111', 'boat': '222', }; Map<String, String> codepointsB = <String, String>{ 'airplane': '333', }; Map<String, String> codepointsC = <String, String>{ 'airplane': '111', 'train': '444', }; Map<String, String> codepointsUnderscore = <String, String>{ 'airplane__123': '111', }; void main() { group('safety checks', () { test('superset', () { expect(testIsSuperset(codepointsA, codepointsA), true); expect(testIsSuperset(codepointsA, codepointsB), true); expect(testIsSuperset(codepointsB, codepointsA), false); }); test('stability', () { expect(testIsStable(codepointsA, codepointsA), true); expect(testIsStable(codepointsA, codepointsB), false); expect(testIsStable(codepointsB, codepointsA), false); expect(testIsStable(codepointsA, codepointsC), true); expect(testIsStable(codepointsC, codepointsA), true); }); }); test('no double underscores', () { expect(Icon(codepointsUnderscore.entries.first).usage, 'Icon(Icons.airplane_123),'); }); test('usage string is correct', () { expect( Icon(const MapEntry<String, String>('abc', '')).usage, 'Icon(Icons.abc),', ); }); test('usage string is correct with replacement', () { expect( Icon(const MapEntry<String, String>('123', '')).usage, 'Icon(Icons.onetwothree),', ); expect( Icon(const MapEntry<String, String>('123_rounded', '')).usage, 'Icon(Icons.onetwothree_rounded),', ); }); test('certain icons should be mirrored in RTL', () { // Exact match expect( Icon(const MapEntry<String, String>('help', '')).isMirroredInRTL, true, ); // Variant expect( Icon(const MapEntry<String, String>('help_rounded', '')).isMirroredInRTL, true, ); // Common suffixes expect( Icon(const MapEntry<String, String>('help_alt', '')).isMirroredInRTL, true, ); expect( Icon(const MapEntry<String, String>('help_new', '')).isMirroredInRTL, true, ); expect( Icon(const MapEntry<String, String>('help_off', '')).isMirroredInRTL, true, ); expect( Icon(const MapEntry<String, String>('help_on', '')).isMirroredInRTL, true, ); // Common suffixes + variant expect( Icon(const MapEntry<String, String>('help_alt_rounded', '')).isMirroredInRTL, true, ); expect( Icon(const MapEntry<String, String>('help_new_rounded', '')).isMirroredInRTL, true, ); expect( Icon(const MapEntry<String, String>('help_off_rounded', '')).isMirroredInRTL, true, ); expect( Icon(const MapEntry<String, String>('help_on_rounded', '')).isMirroredInRTL, true, ); // No match expect( Icon(const MapEntry<String, String>('help_center_rounded', '')).isMirroredInRTL, false, ); // No match expect( Icon(const MapEntry<String, String>('arrow', '')).isMirroredInRTL, false, ); }); }
flutter/dev/tools/test/update_icons_test.dart/0
{ "file_path": "flutter/dev/tools/test/update_icons_test.dart", "repo_id": "flutter", "token_count": 1372 }
559
<svg id="svg_build_00" xmlns="http://www.w3.org/2000/svg" width="48px" height="48px" > <path id="path_1" d="M 0,19.0 L 48.0, 19.0 L 48.0, 29.0 L 0, 29.0 Z " fill="#000000" /> </svg>
flutter/dev/tools/vitool/test_assets/horizontal_bar.svg/0
{ "file_path": "flutter/dev/tools/vitool/test_assets/horizontal_bar.svg", "repo_id": "flutter", "token_count": 92 }
560
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'dart:convert' show jsonEncode; import 'dart:developer' as developer; import 'dart:ui' as ui; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:vm_service/vm_service.dart'; import 'package:vm_service/vm_service_io.dart'; void main() { LiveTestWidgetsFlutterBinding.ensureInitialized(); late VmService vmService; late LiveTestWidgetsFlutterBinding binding; setUpAll(() async { final developer.ServiceProtocolInfo info = await developer.Service.getInfo(); if (info.serverUri == null) { fail('This test _must_ be run with --enable-vmservice.'); } vmService = await vmServiceConnectUri('ws://localhost:${info.serverUri!.port}${info.serverUri!.path}ws'); await vmService.streamListen(EventStreams.kExtension); // Initialize bindings binding = LiveTestWidgetsFlutterBinding.instance; binding.framePolicy = LiveTestWidgetsFlutterBindingFramePolicy.fullyLive; binding.attachRootWidget(const SizedBox.expand()); expect(binding.framesEnabled, true); // Pump two frames to make sure we clear out any inter-frame comparisons. await binding.endOfFrame; await binding.endOfFrame; }); tearDownAll(() async { await vmService.dispose(); }); test('Image painting events - deduplicates across frames', () async { final Completer<Event> completer = Completer<Event>(); vmService .onExtensionEvent .firstWhere((Event event) => event.extensionKind == 'Flutter.ImageSizesForFrame') .then(completer.complete); final ui.Image image = await createTestImage(width: 300, height: 300); final TestCanvas canvas = TestCanvas(); paintImage( canvas: canvas, rect: const Rect.fromLTWH(50.0, 75.0, 200.0, 100.0), image: image, debugImageLabel: 'test.png', ); // Make sure that we don't report an identical image size info if we // redraw in the next frame. await binding.endOfFrame; paintImage( canvas: canvas, rect: const Rect.fromLTWH(50.0, 75.0, 200.0, 100.0), image: image, debugImageLabel: 'test.png', ); await binding.endOfFrame; final Event event = await completer.future; expect(event.extensionKind, 'Flutter.ImageSizesForFrame'); expect( jsonEncode(event.extensionData!.data), contains('"test.png":{"source":"test.png","displaySize":{"width":600.0,"height":300.0},"imageSize":{"width":300.0,"height":300.0},"displaySizeInBytes":960000,"decodedSizeInBytes":480000}'), ); }, skip: isBrowser); // [intended] uses dart:isolate and io. test('Image painting events - deduplicates across frames', () async { final Completer<Event> completer = Completer<Event>(); vmService .onExtensionEvent .firstWhere((Event event) => event.extensionKind == 'Flutter.ImageSizesForFrame') .then(completer.complete); final ui.Image image = await createTestImage(width: 300, height: 300); final TestCanvas canvas = TestCanvas(); paintImage( canvas: canvas, rect: const Rect.fromLTWH(50.0, 75.0, 200.0, 100.0), image: image, debugImageLabel: 'test.png', ); paintImage( canvas: canvas, rect: const Rect.fromLTWH(50.0, 75.0, 300.0, 300.0), image: image, debugImageLabel: 'test.png', ); await binding.endOfFrame; final Event event = await completer.future; expect(event.extensionKind, 'Flutter.ImageSizesForFrame'); expect( jsonEncode(event.extensionData!.data), contains('"test.png":{"source":"test.png","displaySize":{"width":900.0,"height":900.0},"imageSize":{"width":300.0,"height":300.0},"displaySizeInBytes":4320000,"decodedSizeInBytes":480000}'), ); }, skip: isBrowser); // [intended] uses dart:isolate and io. } class TestCanvas implements Canvas { @override void noSuchMethod(Invocation invocation) {} }
flutter/dev/tracing_tests/test/image_painting_event_test.dart/0
{ "file_path": "flutter/dev/tracing_tests/test/image_painting_event_test.dart", "repo_id": "flutter", "token_count": 1494 }
561
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; /// An example of [AnimationController] and [SlideTransition]. // Occupies the same width as the widest single digit used by AnimatedDigit. // // By stacking this widget behind AnimatedDigit's visible digit, we // ensure that AnimatedWidget's width will not change when its value // changes. Typically digits like '8' or '9' are wider than '1'. If // an app arranges several AnimatedDigits in a centered Row, we don't // want the Row to wiggle when the digits change because the overall // width of the Row changes. class _PlaceholderDigit extends StatelessWidget { const _PlaceholderDigit(); @override Widget build(BuildContext context) { final TextStyle textStyle = Theme.of(context).textTheme.displayLarge!.copyWith( fontWeight: FontWeight.w500, ); final Iterable<Widget> placeholderDigits = <int>[0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map<Widget>( (int n) { return Text('$n', style: textStyle); }, ); return Opacity( opacity: 0, child: Stack(children: placeholderDigits.toList()), ); } } // Displays a single digit [value]. // // When the value changes the old value slides upwards and out of sight // at the same as the new value slides into view. class AnimatedDigit extends StatefulWidget { const AnimatedDigit({ super.key, required this.value }); final int value; @override State<AnimatedDigit> createState() => _AnimatedDigitState(); } class _AnimatedDigitState extends State<AnimatedDigit> with SingleTickerProviderStateMixin { static const Duration defaultDuration = Duration(milliseconds: 300); late final AnimationController controller; late int incomingValue; late int outgoingValue; List<int> pendingValues = <int>[]; // widget.value updates that occurred while the animation is underway Duration duration = defaultDuration; @override void initState() { super.initState(); controller = AnimationController( duration: duration, vsync: this, ); controller.addStatusListener(handleAnimationCompleted); incomingValue = widget.value; outgoingValue = widget.value; } @override void dispose() { controller.dispose(); super.dispose(); } void handleAnimationCompleted(AnimationStatus status) { if (status == AnimationStatus.completed) { if (pendingValues.isNotEmpty) { // Display the next pending value. The duration was scaled down // in didUpdateWidget by the total number of pending values so // that all of the pending changes are shown within // defaultDuration of the last one (the past pending change). controller.duration = duration; animateValueUpdate(incomingValue, pendingValues.removeAt(0)); } else { controller.duration = defaultDuration; } } } void animateValueUpdate(int outgoing, int incoming) { setState(() { outgoingValue = outgoing; incomingValue = incoming; controller.forward(from: 0); }); } // Rebuilding the widget with a new value causes the animations to run. // If the widget is updated while the value is being changed the new // value is added to pendingValues and is taken care of when the current // animation is complete (see handleAnimationCompleted()). @override void didUpdateWidget(AnimatedDigit oldWidget) { super.didUpdateWidget(oldWidget); if (widget.value != oldWidget.value) { if (controller.isAnimating) { // We're in the middle of animating outgoingValue out and // incomingValue in. Shorten the duration of the current // animation as well as the duration for animations that // will show the pending values. pendingValues.add(widget.value); final double percentRemaining = 1 - controller.value; duration = defaultDuration * (1 / (percentRemaining + pendingValues.length)); controller.animateTo(1.0, duration: duration * percentRemaining); } else { animateValueUpdate(incomingValue, widget.value); } } } // When the controller runs forward both SlideTransitions' children // animate upwards. This takes the outgoingValue out of sight and the // incoming value into view. See animateValueUpdate(). @override Widget build(BuildContext context) { final TextStyle textStyle = Theme.of(context).textTheme.displayLarge!; return ClipRect( child: Stack( children: <Widget>[ const _PlaceholderDigit(), SlideTransition( position: controller .drive( Tween<Offset>( begin: Offset.zero, end: const Offset(0, -1), // Out of view above the top. ), ), child: Text( key: ValueKey<int>(outgoingValue), '$outgoingValue', style: textStyle, ), ), SlideTransition( position: controller .drive( Tween<Offset>( begin: const Offset(0, 1), // Out of view below the bottom. end: Offset.zero, ), ), child: Text( key: ValueKey<int>(incomingValue), '$incomingValue', style: textStyle, ), ), ], ), ); } } class AnimatedDigitApp extends StatelessWidget { const AnimatedDigitApp({ super.key }); @override Widget build(BuildContext context) { return const MaterialApp( title: 'AnimatedDigit', home: AnimatedDigitHome(), ); } } class AnimatedDigitHome extends StatefulWidget { const AnimatedDigitHome({ super.key }); @override State<AnimatedDigitHome> createState() => _AnimatedDigitHomeState(); } class _AnimatedDigitHomeState extends State<AnimatedDigitHome> { int value = 0; @override Widget build(BuildContext context) { return Scaffold( body: Center( child: AnimatedDigit(value: value % 10), ), floatingActionButton: FloatingActionButton( onPressed: () { setState(() { value += 1; }); }, tooltip: 'Increment Digit', child: const Icon(Icons.add), ), ); } } void main() { runApp(const AnimatedDigitApp()); }
flutter/examples/api/lib/animation/animation_controller/animated_digit.0.dart/0
{ "file_path": "flutter/examples/api/lib/animation/animation_controller/animated_digit.0.dart", "repo_id": "flutter", "token_count": 2364 }
562
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/cupertino.dart'; /// Flutter code sample for [CupertinoPageScaffold]. void main() => runApp(const PageScaffoldApp()); class PageScaffoldApp extends StatelessWidget { const PageScaffoldApp({super.key}); @override Widget build(BuildContext context) { return const CupertinoApp( theme: CupertinoThemeData(brightness: Brightness.light), home: PageScaffoldExample(), ); } } class PageScaffoldExample extends StatefulWidget { const PageScaffoldExample({super.key}); @override State<PageScaffoldExample> createState() => _PageScaffoldExampleState(); } class _PageScaffoldExampleState extends State<PageScaffoldExample> { int _count = 0; @override Widget build(BuildContext context) { return CupertinoPageScaffold( // Uncomment to change the background color // backgroundColor: CupertinoColors.systemPink, navigationBar: const CupertinoNavigationBar( middle: Text('CupertinoPageScaffold Sample'), ), child: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Center( child: Text('You have pressed the button $_count times.'), ), const SizedBox(height: 20.0), Center( child: CupertinoButton.filled( onPressed: () => setState(() => _count++), child: const Icon(CupertinoIcons.add), ), ), ], ), ), ); } }
flutter/examples/api/lib/cupertino/page_scaffold/cupertino_page_scaffold.0.dart/0
{ "file_path": "flutter/examples/api/lib/cupertino/page_scaffold/cupertino_page_scaffold.0.dart", "repo_id": "flutter", "token_count": 680 }
563
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/cupertino.dart'; /// Flutter code sample for [CupertinoTabScaffold]. void main() => runApp(const TabScaffoldApp()); class TabScaffoldApp extends StatelessWidget { const TabScaffoldApp({super.key}); @override Widget build(BuildContext context) { return const CupertinoApp( theme: CupertinoThemeData(brightness: Brightness.light), home: TabScaffoldExample(), ); } } class TabScaffoldExample extends StatefulWidget { const TabScaffoldExample({super.key}); @override State<TabScaffoldExample> createState() => _TabScaffoldExampleState(); } class _TabScaffoldExampleState extends State<TabScaffoldExample> { @override Widget build(BuildContext context) { return CupertinoTabScaffold( tabBar: CupertinoTabBar( items: const <BottomNavigationBarItem>[ BottomNavigationBarItem( icon: Icon(CupertinoIcons.home), label: 'Home', ), BottomNavigationBarItem( icon: Icon(CupertinoIcons.search_circle_fill), label: 'Explore', ), ], ), tabBuilder: (BuildContext context, int index) { return CupertinoTabView( builder: (BuildContext context) { return CupertinoPageScaffold( navigationBar: CupertinoNavigationBar( middle: Text('Page 1 of tab $index'), ), child: Center( child: CupertinoButton( child: const Text('Next page'), onPressed: () { Navigator.of(context).push( CupertinoPageRoute<void>( builder: (BuildContext context) { return CupertinoPageScaffold( navigationBar: CupertinoNavigationBar( middle: Text('Page 2 of tab $index'), ), child: Center( child: CupertinoButton( child: const Text('Back'), onPressed: () { Navigator.of(context).pop(); }, ), ), ); }, ), ); }, ), ), ); }, ); }, ); } }
flutter/examples/api/lib/cupertino/tab_scaffold/cupertino_tab_scaffold.0.dart/0
{ "file_path": "flutter/examples/api/lib/cupertino/tab_scaffold/cupertino_tab_scaffold.0.dart", "repo_id": "flutter", "token_count": 1424 }
564
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; /// Flutter code sample for [SliverAppBar.medium]. void main() { runApp(const AppBarMediumApp()); } class AppBarMediumApp extends StatelessWidget { const AppBarMediumApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( theme: ThemeData( useMaterial3: true, colorSchemeSeed: const Color(0xff6750A4), ), home: Material( child: CustomScrollView( slivers: <Widget>[ SliverAppBar.medium( leading: IconButton(icon: const Icon(Icons.menu), onPressed: () {}), title: const Text('Medium App Bar'), actions: <Widget>[ IconButton(icon: const Icon(Icons.more_vert), onPressed: () {}), ], ), // Just some content big enough to have something to scroll. SliverToBoxAdapter( child: Card( child: SizedBox( height: 1200, child: Padding( padding: const EdgeInsets.fromLTRB(8, 100, 8, 100), child: Text( 'Here be scrolling content...', style: Theme.of(context).textTheme.headlineSmall, ), ), ), ), ), ], ), ), ); } }
flutter/examples/api/lib/material/app_bar/sliver_app_bar.2.dart/0
{ "file_path": "flutter/examples/api/lib/material/app_bar/sliver_app_bar.2.dart", "repo_id": "flutter", "token_count": 776 }
565
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; /// Flutter code sample for [ColorScheme]. const Widget divider = SizedBox(height: 10); void main() => runApp(const ColorSchemeExample()); class ColorSchemeExample extends StatefulWidget { const ColorSchemeExample({super.key}); @override State<ColorSchemeExample> createState() => _ColorSchemeExampleState(); } class _ColorSchemeExampleState extends State<ColorSchemeExample> { Color selectedColor = ColorSeed.baseColor.color; @override Widget build(BuildContext context) { final Color? colorSeed = selectedColor == ColorSeed.baseColor.color ? null : selectedColor; final ThemeData lightTheme = ThemeData( colorSchemeSeed: colorSeed, brightness: Brightness.light, ); final ThemeData darkTheme = ThemeData( colorSchemeSeed: colorSeed, brightness: Brightness.dark, ); Widget schemeLabel(String brightness) { return Padding( padding: const EdgeInsets.symmetric(vertical: 15), child: Text( brightness, style: const TextStyle(fontWeight: FontWeight.bold), ), ); } Widget schemeView(ThemeData theme) { return Padding( padding: const EdgeInsets.symmetric(horizontal: 15), child: ColorSchemeView(colorScheme: theme.colorScheme), ); } return MaterialApp( theme: ThemeData(colorSchemeSeed: selectedColor), home: Builder( builder: (BuildContext context) => Scaffold( appBar: AppBar( title: const Text('ColorScheme'), leading: MenuAnchor( builder: (BuildContext context, MenuController controller, Widget? widget) { return IconButton( icon: Icon(Icons.circle, color: selectedColor), onPressed: () { setState(() { if (!controller.isOpen) { controller.open(); } }); }, ); }, menuChildren: List<Widget>.generate(ColorSeed.values.length, (int index) { final Color itemColor = ColorSeed.values[index].color; return MenuItemButton( leadingIcon: selectedColor == ColorSeed.values[index].color ? Icon(Icons.circle, color: itemColor) : Icon(Icons.circle_outlined, color: itemColor), onPressed: () { setState(() { selectedColor = itemColor; }); }, child: Text(ColorSeed.values[index].label), ); }), ), ), body: SingleChildScrollView( child: Padding( padding: const EdgeInsets.only(top: 5), child: Column( children: <Widget>[ Row( children: <Widget>[ Expanded( child: Column( children: <Widget>[ schemeLabel('Light ColorScheme'), schemeView(lightTheme), ], ), ), Expanded( child: Column( children: <Widget>[ schemeLabel('Dark ColorScheme'), schemeView(darkTheme), ], ), ), ], ), ], ), ), ), ), ), ); } } class ColorSchemeView extends StatelessWidget { const ColorSchemeView({super.key, required this.colorScheme}); final ColorScheme colorScheme; @override Widget build(BuildContext context) { return Column( children: <Widget>[ ColorGroup(children: <ColorChip>[ ColorChip('primary', colorScheme.primary, colorScheme.onPrimary), ColorChip('onPrimary', colorScheme.onPrimary, colorScheme.primary), ColorChip('primaryContainer', colorScheme.primaryContainer, colorScheme.onPrimaryContainer), ColorChip( 'onPrimaryContainer', colorScheme.onPrimaryContainer, colorScheme.primaryContainer, ), ]), divider, ColorGroup(children: <ColorChip>[ ColorChip('primaryFixed', colorScheme.primaryFixed, colorScheme.onPrimaryFixed), ColorChip('onPrimaryFixed', colorScheme.onPrimaryFixed, colorScheme.primaryFixed), ColorChip('primaryFixedDim', colorScheme.primaryFixedDim, colorScheme.onPrimaryFixedVariant), ColorChip( 'onPrimaryFixedVariant', colorScheme.onPrimaryFixedVariant, colorScheme.primaryFixedDim, ), ]), divider, ColorGroup(children: <ColorChip>[ ColorChip('secondary', colorScheme.secondary, colorScheme.onSecondary), ColorChip('onSecondary', colorScheme.onSecondary, colorScheme.secondary), ColorChip( 'secondaryContainer', colorScheme.secondaryContainer, colorScheme.onSecondaryContainer, ), ColorChip( 'onSecondaryContainer', colorScheme.onSecondaryContainer, colorScheme.secondaryContainer, ), ]), divider, ColorGroup(children: <ColorChip>[ ColorChip('secondaryFixed', colorScheme.secondaryFixed, colorScheme.onSecondaryFixed), ColorChip('onSecondaryFixed', colorScheme.onSecondaryFixed, colorScheme.secondaryFixed), ColorChip( 'secondaryFixedDim', colorScheme.secondaryFixedDim, colorScheme.onSecondaryFixedVariant, ), ColorChip( 'onSecondaryFixedVariant', colorScheme.onSecondaryFixedVariant, colorScheme.secondaryFixedDim, ), ]), divider, ColorGroup( children: <ColorChip>[ ColorChip('tertiary', colorScheme.tertiary, colorScheme.onTertiary), ColorChip('onTertiary', colorScheme.onTertiary, colorScheme.tertiary), ColorChip( 'tertiaryContainer', colorScheme.tertiaryContainer, colorScheme.onTertiaryContainer, ), ColorChip( 'onTertiaryContainer', colorScheme.onTertiaryContainer, colorScheme.tertiaryContainer, ), ], ), divider, ColorGroup(children: <ColorChip>[ ColorChip('tertiaryFixed', colorScheme.tertiaryFixed, colorScheme.onTertiaryFixed), ColorChip('onTertiaryFixed', colorScheme.onTertiaryFixed, colorScheme.tertiaryFixed), ColorChip('tertiaryFixedDim', colorScheme.tertiaryFixedDim, colorScheme.onTertiaryFixedVariant), ColorChip( 'onTertiaryFixedVariant', colorScheme.onTertiaryFixedVariant, colorScheme.tertiaryFixedDim, ), ]), divider, ColorGroup( children: <ColorChip>[ ColorChip('error', colorScheme.error, colorScheme.onError), ColorChip('onError', colorScheme.onError, colorScheme.error), ColorChip('errorContainer', colorScheme.errorContainer, colorScheme.onErrorContainer), ColorChip('onErrorContainer', colorScheme.onErrorContainer, colorScheme.errorContainer), ], ), divider, ColorGroup( children: <ColorChip>[ ColorChip('surfaceDim', colorScheme.surfaceDim, colorScheme.onSurface), ColorChip('surface', colorScheme.surface, colorScheme.onSurface), ColorChip('surfaceBright', colorScheme.surfaceBright, colorScheme.onSurface), ColorChip('surfaceContainerLowest', colorScheme.surfaceContainerLowest, colorScheme.onSurface), ColorChip('surfaceContainerLow', colorScheme.surfaceContainerLow, colorScheme.onSurface), ColorChip('surfaceContainer', colorScheme.surfaceContainer, colorScheme.onSurface), ColorChip('surfaceContainerHigh', colorScheme.surfaceContainerHigh, colorScheme.onSurface), ColorChip('surfaceContainerHighest', colorScheme.surfaceContainerHighest, colorScheme.onSurface), ColorChip('onSurface', colorScheme.onSurface, colorScheme.surface), ColorChip( 'onSurfaceVariant', colorScheme.onSurfaceVariant, colorScheme.surfaceContainerHighest, ), ], ), divider, ColorGroup( children: <ColorChip>[ ColorChip('outline', colorScheme.outline, null), ColorChip('shadow', colorScheme.shadow, null), ColorChip('inverseSurface', colorScheme.inverseSurface, colorScheme.onInverseSurface), ColorChip('onInverseSurface', colorScheme.onInverseSurface, colorScheme.inverseSurface), ColorChip('inversePrimary', colorScheme.inversePrimary, colorScheme.primary), ], ), ], ); } } class ColorGroup extends StatelessWidget { const ColorGroup({super.key, required this.children}); final List<Widget> children; @override Widget build(BuildContext context) { return RepaintBoundary( child: Card(clipBehavior: Clip.antiAlias, child: Column(children: children)), ); } } class ColorChip extends StatelessWidget { const ColorChip(this.label, this.color, this.onColor, {super.key}); final Color color; final Color? onColor; final String label; static Color contrastColor(Color color) { final Brightness brightness = ThemeData.estimateBrightnessForColor(color); return brightness == Brightness.dark ? Colors.white : Colors.black; } @override Widget build(BuildContext context) { final Color labelColor = onColor ?? contrastColor(color); return ColoredBox( color: color, child: Padding( padding: const EdgeInsets.all(16), child: Row( children: <Expanded>[ Expanded(child: Text(label, style: TextStyle(color: labelColor))), ], ), ), ); } } enum ColorSeed { baseColor('M3 Baseline', Color(0xff6750a4)), indigo('Indigo', Colors.indigo), blue('Blue', Colors.blue), teal('Teal', Colors.teal), green('Green', Colors.green), yellow('Yellow', Colors.yellow), orange('Orange', Colors.orange), deepOrange('Deep Orange', Colors.deepOrange), pink('Pink', Colors.pink); const ColorSeed(this.label, this.color); final String label; final Color color; }
flutter/examples/api/lib/material/color_scheme/color_scheme.0.dart/0
{ "file_path": "flutter/examples/api/lib/material/color_scheme/color_scheme.0.dart", "repo_id": "flutter", "token_count": 5052 }
566
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; /// Flutter code sample for [showDialog]. void main() => runApp(const ShowDialogExampleApp()); class ShowDialogExampleApp extends StatelessWidget { const ShowDialogExampleApp({super.key}); @override Widget build(BuildContext context) { return const MaterialApp( home: DialogExample(), ); } } class DialogExample extends StatelessWidget { const DialogExample({super.key}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('showDialog Sample')), body: Center( child: OutlinedButton( onPressed: () => _dialogBuilder(context), child: const Text('Open Dialog'), ), ), ); } Future<void> _dialogBuilder(BuildContext context) { return showDialog<void>( context: context, builder: (BuildContext context) { return AlertDialog( title: const Text('Basic dialog title'), content: const Text( 'A dialog is a type of modal window that\n' 'appears in front of app content to\n' 'provide critical information, or prompt\n' 'for a decision to be made.', ), actions: <Widget>[ TextButton( style: TextButton.styleFrom( textStyle: Theme.of(context).textTheme.labelLarge, ), child: const Text('Disable'), onPressed: () { Navigator.of(context).pop(); }, ), TextButton( style: TextButton.styleFrom( textStyle: Theme.of(context).textTheme.labelLarge, ), child: const Text('Enable'), onPressed: () { Navigator.of(context).pop(); }, ), ], ); }, ); } }
flutter/examples/api/lib/material/dialog/show_dialog.0.dart/0
{ "file_path": "flutter/examples/api/lib/material/dialog/show_dialog.0.dart", "repo_id": "flutter", "token_count": 919 }
567
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; /// Flutter code sample for [ExpansionPanelList.ExpansionPanelList.radio]. void main() => runApp(const ExpansionPanelListRadioExampleApp()); class ExpansionPanelListRadioExampleApp extends StatelessWidget { const ExpansionPanelListRadioExampleApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar(title: const Text('ExpansionPanelList.radio Sample')), body: const ExpansionPanelListRadioExample(), ), ); } } // stores ExpansionPanel state information class Item { Item({ required this.id, required this.expandedValue, required this.headerValue, }); int id; String expandedValue; String headerValue; } List<Item> generateItems(int numberOfItems) { return List<Item>.generate(numberOfItems, (int index) { return Item( id: index, headerValue: 'Panel $index', expandedValue: 'This is item number $index', ); }); } class ExpansionPanelListRadioExample extends StatefulWidget { const ExpansionPanelListRadioExample({super.key}); @override State<ExpansionPanelListRadioExample> createState() => _ExpansionPanelListRadioExampleState(); } class _ExpansionPanelListRadioExampleState extends State<ExpansionPanelListRadioExample> { final List<Item> _data = generateItems(8); @override Widget build(BuildContext context) { return SingleChildScrollView( child: Container( child: _buildPanel(), ), ); } Widget _buildPanel() { return ExpansionPanelList.radio( initialOpenPanelValue: 2, children: _data.map<ExpansionPanelRadio>((Item item) { return ExpansionPanelRadio( value: item.id, headerBuilder: (BuildContext context, bool isExpanded) { return ListTile( title: Text(item.headerValue), ); }, body: ListTile( title: Text(item.expandedValue), subtitle: const Text('To delete this panel, tap the trash can icon'), trailing: const Icon(Icons.delete), onTap: () { setState(() { _data.removeWhere((Item currentItem) => item == currentItem); }); })); }).toList(), ); } }
flutter/examples/api/lib/material/expansion_panel/expansion_panel_list.expansion_panel_list_radio.0.dart/0
{ "file_path": "flutter/examples/api/lib/material/expansion_panel/expansion_panel_list.expansion_panel_list_radio.0.dart", "repo_id": "flutter", "token_count": 961 }
568