text
stringlengths 6
13.6M
| id
stringlengths 13
176
| metadata
dict | __index_level_0__
int64 0
1.69k
|
---|---|---|---|
/*
* 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.testing;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.util.ThrowableComputable;
import com.intellij.testFramework.builders.EmptyModuleFixtureBuilder;
import com.intellij.testFramework.fixtures.IdeaProjectTestFixture;
import com.intellij.testFramework.fixtures.IdeaTestFixtureFactory;
import com.intellij.testFramework.fixtures.TestFixtureBuilder;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import java.lang.reflect.InvocationTargetException;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicReference;
/**
* Test utilities.
*/
@SuppressWarnings("ConstantConditions")
public class Testing {
private Testing() {
}
/**
* Returns a "light" test fixture containing an empty project.
*
* <p>(No modules are allowed.)
*/
public static IdeaProjectFixture makeEmptyProject() {
return new IdeaProjectFixture(
(x) -> IdeaTestFixtureFactory.getFixtureFactory().createLightFixtureBuilder("test").getFixture(), true);
}
/**
* Creates a "heavy" test fixture containing a Project with an empty Module.
*/
public static IdeaProjectFixture makeEmptyModule() {
return new IdeaProjectFixture((String testClassName) -> {
final TestFixtureBuilder<IdeaProjectTestFixture> builder =
IdeaTestFixtureFactory.getFixtureFactory().createFixtureBuilder(testClassName);
builder.addModule(EmptyModuleFixtureBuilder.class);
return builder.getFixture();
}, true);
}
public static CodeInsightProjectFixture makeCodeInsightModule() {
return new CodeInsightProjectFixture((x) -> {
final IdeaTestFixtureFactory factory = IdeaTestFixtureFactory.getFixtureFactory();
final IdeaProjectTestFixture light = factory.createLightFixtureBuilder("test").getFixture();
return factory.createCodeInsightFixture(light);
}, false);
}
@SuppressWarnings("RedundantTypeArguments")
public static <T> T computeInWriteAction(ThrowableComputable<T, Exception> callback) throws Exception {
return computeOnDispatchThread(() -> {
final Application app = ApplicationManager.getApplication();
return app.<T, Exception>runWriteAction(callback);
});
}
public static void runInWriteAction(RunnableThatThrows callback) throws Exception {
final ThrowableComputable<Object, Exception> action = () -> {
callback.run();
return null;
};
runOnDispatchThread(() -> ApplicationManager.getApplication().runWriteAction(action));
}
public static <T> T computeOnDispatchThread(ThrowableComputable<T, Exception> callback) throws Exception {
final AtomicReference<T> result = new AtomicReference<>();
runOnDispatchThread(() -> result.set(callback.compute()));
return result.get();
}
public static void runOnDispatchThread(@NotNull RunnableThatThrows callback) throws Exception {
try {
final AtomicReference<Exception> ex = new AtomicReference<>();
assert (!SwingUtilities.isEventDispatchThread());
ApplicationManager.getApplication().invokeAndWait(() -> {
try {
callback.run();
}
catch (Exception e) {
ex.set(e);
}
catch (AssertionError e) {
// Sometimes, the SDK leak detector fires, but we do not care since we do not use Android or Java SDKs.
final String msg = e.getMessage();
if (msg == null || !msg.startsWith("Leaked SDKs")) {
throw e;
}
}
});
if (ex.get() != null) {
throw Objects.requireNonNull(ex.get());
}
}
catch (InvocationTargetException e) {
if (e.getCause() instanceof AssertionError) {
throw (AssertionError)Objects.requireNonNull(e.getCause());
}
}
}
public interface RunnableThatThrows {
void run() throws Exception;
}
}
| flutter-intellij/flutter-idea/testSrc/unit/io/flutter/testing/Testing.java/0 | {
"file_path": "flutter-intellij/flutter-idea/testSrc/unit/io/flutter/testing/Testing.java",
"repo_id": "flutter-intellij",
"token_count": 1368
} | 520 |
/*
* Copyright (c) 2017, 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;
import com.google.gson.JsonObject;
/**
* Interface used by {@link VmService} to register callbacks to services.
*/
public interface RemoteServiceRunner {
/**
* Called when a service request has been received.
*
* @param params the parameters of the request
* @param completer the completer to invoke at the end of the execution
*/
void run(JsonObject params, RemoteServiceCompleter completer);
}
| flutter-intellij/flutter-idea/third_party/vmServiceDrivers/org/dartlang/vm/service/RemoteServiceRunner.java/0 | {
"file_path": "flutter-intellij/flutter-idea/third_party/vmServiceDrivers/org/dartlang/vm/service/RemoteServiceRunner.java",
"repo_id": "flutter-intellij",
"token_count": 286
} | 521 |
/*
* 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;
@SuppressWarnings({"WeakerAccess", "unused"})
public class ContextElement extends Element {
public ContextElement(JsonObject json) {
super(json);
}
/**
* @return one of <code>InstanceRef</code> or <code>Sentinel</code>
*/
public InstanceRef getValue() {
final JsonElement elem = json.get("value");
if (!elem.isJsonObject()) return null;
final JsonObject child = elem.getAsJsonObject();
final String type = child.get("type").getAsString();
if ("Sentinel".equals(type)) return null;
return new InstanceRef(child);
}
}
| flutter-intellij/flutter-idea/third_party/vmServiceDrivers/org/dartlang/vm/service/element/ContextElement.java/0 | {
"file_path": "flutter-intellij/flutter-idea/third_party/vmServiceDrivers/org/dartlang/vm/service/element/ContextElement.java",
"repo_id": "flutter-intellij",
"token_count": 422
} | 522 |
/*
* 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.JsonObject;
/**
* A {@link Flag} represents a single VM command line flag.
*/
@SuppressWarnings({"WeakerAccess", "unused"})
public class Flag extends Element {
public Flag(JsonObject json) {
super(json);
}
/**
* A description of the flag.
*/
public String getComment() {
return getAsString("comment");
}
/**
* Has this flag been modified from its default setting?
*/
public boolean getModified() {
return getAsBoolean("modified");
}
/**
* The name of the flag.
*/
public String getName() {
return getAsString("name");
}
/**
* The value of this flag as a string.
*
* If this property is absent, then the value of the flag was NULL.
*
* Can return <code>null</code>.
*/
public String getValueAsString() {
return getAsString("valueAsString");
}
}
| flutter-intellij/flutter-idea/third_party/vmServiceDrivers/org/dartlang/vm/service/element/Flag.java/0 | {
"file_path": "flutter-intellij/flutter-idea/third_party/vmServiceDrivers/org/dartlang/vm/service/element/Flag.java",
"repo_id": "flutter-intellij",
"token_count": 491
} | 523 |
/*
* 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.JsonObject;
/**
* {@link IsolateRef} is a reference to an {@link Isolate} object.
*/
@SuppressWarnings({"WeakerAccess", "unused"})
public class IsolateRef extends Response {
public IsolateRef(JsonObject json) {
super(json);
}
/**
* The id which is passed to the getIsolate RPC to load this isolate.
*/
public String getId() {
return getAsString("id");
}
/**
* Specifies whether the isolate was spawned by the VM or embedder for internal use. If `false`,
* this isolate is likely running user code.
*/
public boolean getIsSystemIsolate() {
return getAsBoolean("isSystemIsolate");
}
/**
* The id of the isolate group that this isolate belongs to.
*/
public String getIsolateGroupId() {
return getAsString("isolateGroupId");
}
/**
* A name identifying this isolate. Not guaranteed to be unique.
*/
public String getName() {
return getAsString("name");
}
/**
* A numeric id for this isolate, represented as a string. Unique.
*/
public String getNumber() {
return getAsString("number");
}
}
| flutter-intellij/flutter-idea/third_party/vmServiceDrivers/org/dartlang/vm/service/element/IsolateRef.java/0 | {
"file_path": "flutter-intellij/flutter-idea/third_party/vmServiceDrivers/org/dartlang/vm/service/element/IsolateRef.java",
"repo_id": "flutter-intellij",
"token_count": 557
} | 524 |
/*
* 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.JsonArray;
import com.google.gson.JsonObject;
/**
* The {@link SourceReport} class represents a set of reports tied to source locations in an
* isolate.
*/
@SuppressWarnings({"WeakerAccess", "unused"})
public class SourceReport extends Response {
public SourceReport(JsonObject json) {
super(json);
}
/**
* A list of ranges in the program source. These ranges correspond to ranges of executable code
* in the user's program (functions, methods, constructors, etc.)
*
* Note that ranges may nest in other ranges, in the case of nested functions.
*
* Note that ranges may be duplicated, in the case of mixins.
*/
public ElementList<SourceReportRange> getRanges() {
return new ElementList<SourceReportRange>(json.get("ranges").getAsJsonArray()) {
@Override
protected SourceReportRange basicGet(JsonArray array, int index) {
return new SourceReportRange(array.get(index).getAsJsonObject());
}
};
}
/**
* A list of scripts, referenced by index in the report's ranges.
*/
public ElementList<ScriptRef> getScripts() {
return new ElementList<ScriptRef>(json.get("scripts").getAsJsonArray()) {
@Override
protected ScriptRef basicGet(JsonArray array, int index) {
return new ScriptRef(array.get(index).getAsJsonObject());
}
};
}
}
| flutter-intellij/flutter-idea/third_party/vmServiceDrivers/org/dartlang/vm/service/element/SourceReport.java/0 | {
"file_path": "flutter-intellij/flutter-idea/third_party/vmServiceDrivers/org/dartlang/vm/service/element/SourceReport.java",
"repo_id": "flutter-intellij",
"token_count": 648
} | 525 |
/*
* 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.JsonArray;
import com.google.gson.JsonObject;
@SuppressWarnings({"WeakerAccess", "unused"})
public class VM extends Response {
public VM(JsonObject json) {
super(json);
}
/**
* Word length on target architecture (e.g. 32, 64).
*/
public int getArchitectureBits() {
return getAsInt("architectureBits");
}
/**
* The CPU we are actually running on.
*/
public String getHostCPU() {
return getAsString("hostCPU");
}
/**
* A list of isolate groups running in the VM.
*/
public ElementList<IsolateGroupRef> getIsolateGroups() {
return new ElementList<IsolateGroupRef>(json.get("isolateGroups").getAsJsonArray()) {
@Override
protected IsolateGroupRef basicGet(JsonArray array, int index) {
return new IsolateGroupRef(array.get(index).getAsJsonObject());
}
};
}
/**
* A list of isolates running in the VM.
*/
public ElementList<IsolateRef> getIsolates() {
return new ElementList<IsolateRef>(json.get("isolates").getAsJsonArray()) {
@Override
protected IsolateRef basicGet(JsonArray array, int index) {
return new IsolateRef(array.get(index).getAsJsonObject());
}
};
}
/**
* A name identifying this vm. Not guaranteed to be unique.
*/
public String getName() {
return getAsString("name");
}
/**
* The operating system we are running on.
*/
public String getOperatingSystem() {
return getAsString("operatingSystem");
}
/**
* The process id for the VM.
*/
public int getPid() {
return getAsInt("pid");
}
/**
* The time that the VM started in milliseconds since the epoch.
*
* Suitable to pass to DateTime.fromMillisecondsSinceEpoch.
*/
public int getStartTime() {
return getAsInt("startTime");
}
/**
* A list of isolate groups which contain system isolates running in the VM.
*/
public ElementList<IsolateGroupRef> getSystemIsolateGroups() {
return new ElementList<IsolateGroupRef>(json.get("systemIsolateGroups").getAsJsonArray()) {
@Override
protected IsolateGroupRef basicGet(JsonArray array, int index) {
return new IsolateGroupRef(array.get(index).getAsJsonObject());
}
};
}
/**
* A list of system isolates running in the VM.
*/
public ElementList<IsolateRef> getSystemIsolates() {
return new ElementList<IsolateRef>(json.get("systemIsolates").getAsJsonArray()) {
@Override
protected IsolateRef basicGet(JsonArray array, int index) {
return new IsolateRef(array.get(index).getAsJsonObject());
}
};
}
/**
* The CPU we are generating code for.
*/
public String getTargetCPU() {
return getAsString("targetCPU");
}
/**
* The Dart VM version string.
*/
public String getVersion() {
return getAsString("version");
}
}
| flutter-intellij/flutter-idea/third_party/vmServiceDrivers/org/dartlang/vm/service/element/VM.java/0 | {
"file_path": "flutter-intellij/flutter-idea/third_party/vmServiceDrivers/org/dartlang/vm/service/element/VM.java",
"repo_id": "flutter-intellij",
"token_count": 1222
} | 526 |
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/testSrc/unit" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/resources" type="java-resource" />
<sourceFolder url="file://$MODULE_DIR$/testData" type="java-test-resource" />
<excludeFolder url="file://$MODULE_DIR$/src/main/java/io/flutter" />
<excludeFolder url="file://$MODULE_DIR$/testSrc/config" />
<excludeFolder url="file://$MODULE_DIR$/testSrc/failures" />
<excludeFolder url="file://$MODULE_DIR$/testSrc/system" />
<excludeFolder url="file://$MODULE_DIR$/build" />
</content>
<content url="file://$MODULE_DIR$/resources" />
<content url="file://$MODULE_DIR$/src" />
<content url="file://$MODULE_DIR$/testData" />
<content url="file://$MODULE_DIR$/testSrc" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="module" module-name="intellij.android.core" />
<orderEntry type="module" module-name="intellij.android.wizard" />
<orderEntry type="module" module-name="intellij.android.wizard.model" />
<orderEntry type="module" module-name="intellij.android.adt.ui" />
<orderEntry type="module" module-name="intellij.android.adt.ui.model" />
<orderEntry type="module" module-name="intellij.android.observable" />
<orderEntry type="module" module-name="intellij.android.observable.ui" />
<orderEntry type="module" module-name="android.sdktools.flags" />
<orderEntry type="module" module-name="intellij.android.guiTestFramework" scope="TEST" />
<orderEntry type="module" module-name="intellij.android.testFramework" scope="TEST" />
<orderEntry type="module" module-name="intellij.android.designer" scope="TEST" />
<orderEntry type="library" scope="TEST" name="truth" level="project" />
<orderEntry type="module" module-name="flutter-intellij-community" />
<orderEntry type="module" module-name="intellij.android.common" />
<orderEntry type="module" module-name="intellij.android.projectSystem" />
<orderEntry type="module" module-name="intellij.android.projectSystem.gradle" />
<orderEntry type="module" module-name="intellij.android.profilers" />
<orderEntry type="module" module-name="intellij.android.profilers.ui" />
<orderEntry type="module" module-name="intellij.android.artwork" />
<orderEntry type="library" name="studio-analytics-proto" level="project" />
<orderEntry type="module" module-name="fest-swing" />
<orderEntry type="module" module-name="android.sdktools.testutils" />
<orderEntry type="module" module-name="intellij.android.gradle.dsl" />
<orderEntry type="module" module-name="intellij.android.projectSystem.gradle.psd" />
<orderEntry type="module" module-name="intellij.android.deploy" />
<orderEntry type="module" module-name="assistant" />
<orderEntry type="library" name="studio-sdk" level="project" />
<orderEntry type="library" name="studio-plugin-gradle" level="project" />
<orderEntry type="library" name="Dart" level="project" />
</component>
</module> | flutter-intellij/flutter-studio/flutter-studio.iml/0 | {
"file_path": "flutter-intellij/flutter-studio/flutter-studio.iml",
"repo_id": "flutter-intellij",
"token_count": 1230
} | 527 |
/*
* Copyright 2018 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.editor;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.projectImport.ProjectOpenProcessor;
import com.intellij.ui.EditorNotifications;
import io.flutter.FlutterUtils;
//import io.flutter.project.FlutterProjectCreator;
import io.flutter.project.FlutterProjectOpenProcessor;
import io.flutter.pub.PubRoot;
import io.flutter.utils.FlutterModuleUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class FlutterStudioProjectOpenProcessor extends FlutterProjectOpenProcessor {
@Override
public String getName() {
return "Flutter Studio";
}
@Override
public boolean canOpenProject(@Nullable VirtualFile file) {
if (file == null) return false;
final PubRoot root = PubRoot.forDirectory(file);
return root != null && root.declaresFlutter();
}
@Nullable
@Override
public Project doOpenProject(@NotNull VirtualFile virtualFile, @Nullable Project projectToClose, boolean forceOpenInNewFrame) {
final ProjectOpenProcessor importProvider = getDelegateImportProvider(virtualFile);
if (importProvider == null) return null;
importProvider.doOpenProject(virtualFile, projectToClose, forceOpenInNewFrame);
// A callback may have caused the project to be reloaded. Find the new Project object.
Project project = FlutterUtils.findProject(virtualFile.getPath());
if (project == null || project.isDisposed()) {
return project;
}
for (Module module : FlutterModuleUtils.getModules(project)) {
if (FlutterModuleUtils.declaresFlutter(module) && !FlutterModuleUtils.isFlutterModule(module)) {
FlutterModuleUtils.setFlutterModuleType(module);
FlutterModuleUtils.enableDartSDK(module);
}
}
project.save();
EditorNotifications.getInstance(project).updateAllNotifications();
//FlutterProjectCreator.disableUserConfig(project);
return project;
}
}
| flutter-intellij/flutter-studio/src/io/flutter/editor/FlutterStudioProjectOpenProcessor.java/0 | {
"file_path": "flutter-intellij/flutter-studio/src/io/flutter/editor/FlutterStudioProjectOpenProcessor.java",
"repo_id": "flutter-intellij",
"token_count": 689
} | 528 |
/*
* 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 com.android.tools.idea.tests.gui.framework.fixture.newProjectWizard;
import static com.google.common.truth.Truth.assertThat;
import static org.fest.swing.edt.GuiActionRunner.execute;
import com.android.tools.idea.tests.gui.framework.fixture.wizard.AbstractWizardFixture;
import com.android.tools.idea.tests.gui.framework.fixture.wizard.AbstractWizardStepFixture;
import com.intellij.openapi.ui.TextFieldWithBrowseButton;
import io.flutter.project.FlutterProjectStep;
import java.awt.Component;
import java.io.File;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JEditorPane;
import javax.swing.JRootPane;
import javax.swing.text.JTextComponent;
import org.fest.swing.edt.GuiQuery;
import org.fest.swing.exception.ComponentLookupException;
import org.fest.swing.fixture.JComboBoxFixture;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
// TODO(messick): Browse button for SDK; "Install SDK" button
@SuppressWarnings({"UnusedReturnValue", "unused"})
public class FlutterProjectStepFixture<W extends AbstractWizardFixture> extends AbstractWizardStepFixture<FlutterProjectStepFixture, W> {
protected FlutterProjectStepFixture(@NotNull W wizard, @NotNull JRootPane target) {
super(FlutterProjectStepFixture.class, wizard, target);
}
private static boolean isShown(JComponent field) {
return field.isVisible() && field.isShowing();
}
@NotNull
public FlutterProjectStepFixture enterProjectName(@NotNull String text) {
JTextComponent textField = findTextFieldWithLabel("Project name");
replaceText(textField, text);
return this;
}
@NotNull
public FlutterProjectStepFixture enterSdkPath(@NotNull String text) {
JComboBoxFixture comboBox = findComboBox();
//comboBox.replaceText(text); // TODO(messick) Update combo box.
FlutterProjectStep.ensureComboModelContainsCurrentItem(comboBox.target());
return this;
}
@NotNull
public FlutterProjectStepFixture enterProjectLocation(@NotNull String text) {
final TextFieldWithBrowseButton locationField = getLocationField();
replaceText(locationField.getTextField(), text);
return this;
}
@NotNull
public FlutterProjectStepFixture enterDescription(@NotNull String text) {
JTextComponent textField = findTextFieldWithLabel("Description");
replaceText(textField, text);
return this;
}
public String getProjectName() {
return findTextFieldWithLabel("Project name").getText();
}
public String getSdkPath() {
return findComboBox().selectedItem();
}
public String getProjectLocation() {
return getLocationInFileSystem().getPath();
}
public String getDescription() {
return findTextFieldWithLabel("Description").getText();
}
@NotNull
public File getLocationInFileSystem() {
final TextFieldWithBrowseButton locationField = getLocationField();
return execute(new GuiQuery<File>() {
@Override
protected File executeInEDT() {
String location = locationField.getText();
assertThat(location).isNotEmpty();
return new File(location);
}
});
}
@Nullable
public String getErrorMessage() {
Component comp = robot().finder().findByName("ValidationText");
if (comp instanceof JEditorPane) {
JEditorPane label = (JEditorPane)comp;
return label.getText();
}
return null;
}
@NotNull
protected JComboBoxFixture findComboBox() {
JComboBox comboBox = robot().finder().findByType(target(), JComboBox.class, true);
return new JComboBoxFixture(robot(), comboBox);
}
public boolean isConfiguredForModules() {
try {
return isShown(findTextFieldWithLabel("Project name")) &&
isShown(findTextFieldWithLabel("Description"));// &&
//isShown(findComboBox().target()) &&
//!isShown(getLocationField());
}
catch (ComponentLookupException ex) {
// Expect this exception when the location field is not found.
return true;
}
}
@NotNull
private TextFieldWithBrowseButton getLocationField() {
// This works for the project wizard. It might not work for the module wizard, if it were needed
// because several Android modules use TextFieldWithBrowseButton. Fortunately, we expect it to
// not be found in the module wizard because none are showing.
return robot().finder().findByType(target(), TextFieldWithBrowseButton.class);
}
}
| flutter-intellij/flutter-studio/testSrc/com/android/tools/idea/tests/gui/framework/fixture/newProjectWizard/FlutterProjectStepFixture.java/0 | {
"file_path": "flutter-intellij/flutter-studio/testSrc/com/android/tools/idea/tests/gui/framework/fixture/newProjectWizard/FlutterProjectStepFixture.java",
"repo_id": "flutter-intellij",
"token_count": 1510
} | 529 |
# Location of the bash script.
build_file: "flutter-intellij-kokoro/kokoro/macos_external/kokoro_test.sh"
before_action {
fetch_keystore {
keystore_resource {
keystore_config_id: 74840
keyname: "flutter-intellij-plugin-jxbrowser-license-key"
}
}
}
| flutter-intellij/kokoro/macos_external/presubmit.cfg/0 | {
"file_path": "flutter-intellij/kokoro/macos_external/presubmit.cfg",
"repo_id": "flutter-intellij",
"token_count": 114
} | 530 |
{
"aliceBlue": "fff0f8ff",
"antiqueWhite": "fffaebd7",
"aqua": "ff00ffff",
"aquamarine": "ff7fffd4",
"azure": "fff0ffff",
"beige": "fff5f5dc",
"bisque": "ffffe4c4",
"black": "ff000000",
"blanchedAlmond": "ffffebcd",
"blue": "ff0000ff",
"blueViolet": "ff8a2be2",
"brown": "ffa52a2a",
"burlyWood": "ffdeb887",
"cadetBlue": "ff5f9ea0",
"chartreuse": "ff7fff00",
"chocolate": "ffd2691e",
"coral": "ffff7f50",
"cornflowerBlue": "ff6495ed",
"cornsilk": "fffff8dc",
"crimson": "ffdc143c",
"cyan": "ff00ffff",
"darkBlue": "ff00008b",
"darkCyan": "ff008b8b",
"darkGoldenRod": "ffb8860b",
"darkGray": "ffa9a9a9",
"darkGreen": "ff006400",
"darkGrey": "ffa9a9a9",
"darkKhaki": "ffbdb76b",
"darkMagenta": "ff8b008b",
"darkOliveGreen": "ff556b2f",
"darkOrange": "ffff8c00",
"darkOrchid": "ff9932cc",
"darkRed": "ff8b0000",
"darkSalmon": "ffe9967a",
"darkSeaGreen": "ff8fbc8f",
"darkSlateBlue": "ff483d8b",
"darkSlateGray": "ff2f4f4f",
"darkSlateGrey": "ff2f4f4f",
"darkTurquoise": "ff00ced1",
"darkViolet": "ff9400d3",
"deepPink": "ffff1493",
"deepSkyBlue": "ff00bfff",
"dimGray": "ff696969",
"dimGrey": "ff696969",
"dodgerBlue": "ff1e90ff",
"fireBrick": "ffb22222",
"floralWhite": "fffffaf0",
"forestGreen": "ff228b22",
"fuchsia": "ffff00ff",
"gainsboro": "ffdcdcdc",
"ghostWhite": "fff8f8ff",
"gold": "ffffd700",
"goldenRod": "ffdaa520",
"gray": "ff808080",
"green": "ff008000",
"greenYellow": "ffadff2f",
"grey": "ff808080",
"honeyDew": "fff0fff0",
"hotPink": "ffff69b4",
"indianRed": "ffcd5c5c",
"indigo": "ff4b0082",
"ivory": "fffffff0",
"khaki": "fff0e68c",
"lavender": "ffe6e6fa",
"lavenderBlush": "fffff0f5",
"lawnGreen": "ff7cfc00",
"lemonChiffon": "fffffacd",
"lightBlue": "ffadd8e6",
"lightCoral": "fff08080",
"lightCyan": "ffe0ffff",
"lightGoldenRodYellow": "fffafad2",
"lightGray": "ffd3d3d3",
"lightGreen": "ff90ee90",
"lightGrey": "ffd3d3d3",
"lightPink": "ffffb6c1",
"lightSalmon": "ffffa07a",
"lightSeaGreen": "ff20b2aa",
"lightSkyBlue": "ff87cefa",
"lightSlateGray": "ff778899",
"lightSlateGrey": "ff778899",
"lightSteelBlue": "ffb0c4de",
"lightYellow": "ffffffe0",
"lime": "ff00ff00",
"limeGreen": "ff32cd32",
"linen": "fffaf0e6",
"magenta": "ffff00ff",
"maroon": "ff800000",
"mediumAquaMarine": "ff66cdaa",
"mediumBlue": "ff0000cd",
"mediumOrchid": "ffba55d3",
"mediumPurple": "ff9370db",
"mediumSeaGreen": "ff3cb371",
"mediumSlateBlue": "ff7b68ee",
"mediumSpringGreen": "ff00fa9a",
"mediumTurquoise": "ff48d1cc",
"mediumVioletRed": "ffc71585",
"midnightBlue": "ff191970",
"mintCream": "fff5fffa",
"mistyRose": "ffffe4e1",
"moccasin": "ffffe4b5",
"navajoWhite": "ffffdead",
"navy": "ff000080",
"oldLace": "fffdf5e6",
"olive": "ff808000",
"oliveDrab": "ff6b8e23",
"orange": "ffffa500",
"orangeRed": "ffff4500",
"orchid": "ffda70d6",
"paleGoldenRod": "ffeee8aa",
"paleGreen": "ff98fb98",
"paleTurquoise": "ffafeeee",
"paleVioletRed": "ffdb7093",
"papayaWhip": "ffffefd5",
"peachPuff": "ffffdab9",
"peru": "ffcd853f",
"pink": "ffffc0cb",
"plum": "ffdda0dd",
"powderBlue": "ffb0e0e6",
"purple": "ff800080",
"rebeccaPurple": "ff663399",
"red": "ffff0000",
"rosyBrown": "ffbc8f8f",
"royalBlue": "ff4169e1",
"saddleBrown": "ff8b4513",
"salmon": "fffa8072",
"sandyBrown": "fff4a460",
"seaGreen": "ff2e8b57",
"seaShell": "fffff5ee",
"sienna": "ffa0522d",
"silver": "ffc0c0c0",
"skyBlue": "ff87ceeb",
"slateBlue": "ff6a5acd",
"slateGray": "ff708090",
"slateGrey": "ff708090",
"snow": "fffffafa",
"springGreen": "ff00ff7f",
"steelBlue": "ff4682b4",
"tan": "ffd2b48c",
"teal": "ff008080",
"thistle": "ffd8bfd8",
"tomato": "ffff6347",
"turquoise": "ff40e0d0",
"violet": "ffee82ee",
"wheat": "fff5deb3",
"white": "ffffffff",
"whiteSmoke": "fff5f5f5",
"yellow": "ffffff00",
"yellowGreen": "ff9acd32"
}
| flutter-intellij/resources/flutter/colors/css.json/0 | {
"file_path": "flutter-intellij/resources/flutter/colors/css.json",
"repo_id": "flutter-intellij",
"token_count": 1931
} | 531 |
#!/bin/bash
# Initialize everything required by the plugin tool.
setup() {
# Fail on any error.
set -e
# Display commands being run. Only do this while debugging and be careful
# that no confidential information is displayed.
# set -x
export JAVA_HOME_OLD=$JAVA_HOME
curl https://download.oracle.com/java/17/archive/jdk-17.0.4.1_macos-x64_bin.tar.gz > ../java.tar.gz
(cd ..; tar fx java.tar.gz)
export JAVA_HOME=`pwd`/../jdk-17.0.4.1.jdk/Contents/Home
export PATH=$PATH:$JAVA_HOME/bin
export JAVA_OPTS=" -Djava.net.preferIPv4Stack=false -Djava.net.preferIPv6Addresses=true"
echo "JAVA_HOME=$JAVA_HOME"
java -version
# Clone and configure Flutter to the latest stable release
git clone --depth 1 -b stable --single-branch https://github.com/flutter/flutter.git ../flutter
export PATH="$PATH":`pwd`/../flutter/bin:`pwd`/../flutter/bin/cache/dart-sdk/bin
flutter config --no-analytics
flutter doctor
export FLUTTER_SDK=`pwd`/../flutter
export FLUTTER_KEYSTORE_ID=74840
export FLUTTER_KEYSTORE_NAME=flutter-intellij-plugin-auth-token
export FLUTTER_KEYSTORE_JXBROWSER_KEY_NAME=flutter-intellij-plugin-jxbrowser-license-key
export NO_FS_ROOTS_ACCESS_CHECK=true
(cd tool/plugin; echo "dart pub get `pwd`"; dart pub get --no-precompile)
./third_party/gradlew --version
}
| flutter-intellij/tool/kokoro/setup.sh/0 | {
"file_path": "flutter-intellij/tool/kokoro/setup.sh",
"repo_id": "flutter-intellij",
"token_count": 507
} | 532 |
name: plugin_tool
description: Flutter plugin tool.
version: 0.1.1
environment:
sdk: '>=3.0.0-0.0.dev <4.0.0'
dependencies:
args: ^2.0.0
cli_util: ^0.4.1
git: ^2.0.0
markdown: ^7.1.1
path: ^1.8.0
dev_dependencies:
lints: ^3.0.0
test: ^1.22.0
| flutter-intellij/tool/plugin/pubspec.yaml/0 | {
"file_path": "flutter-intellij/tool/plugin/pubspec.yaml",
"repo_id": "flutter-intellij",
"token_count": 139
} | 533 |
20a2f8dbddcf1a96ad4c720b9afd1d0876d17ffc
| flutter/bin/internal/libplist.version/0 | {
"file_path": "flutter/bin/internal/libplist.version",
"repo_id": "flutter",
"token_count": 28
} | 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 'use_cases.dart';
class MaterialBannerUseCase extends UseCase {
@override
String get name => 'MaterialBanner';
@override
String get route => '/material_banner';
@override
Widget build(BuildContext context) => const MainWidget();
}
class MainWidget extends StatefulWidget {
const MainWidget({super.key});
@override
State<MainWidget> createState() => MainWidgetState();
}
class MainWidgetState extends State<MainWidget> {
double currentSliderValue = 20;
ScaffoldFeatureController<MaterialBanner, MaterialBannerClosedReason>? controller;
@override
Widget build(BuildContext context) {
VoidCallback? onPress;
if (controller == null) {
onPress = () {
setState(() {
controller = ScaffoldMessenger.of(context).showMaterialBanner(
MaterialBanner(
padding: const EdgeInsets.all(20),
content: const Text('Hello, I am a Material Banner'),
leading: const Icon(Icons.agriculture_outlined),
backgroundColor: Colors.green,
actions: <Widget>[
TextButton(
onPressed: () {
controller!.close();
setState(() {
controller = null;
});
},
child: const Text('DISMISS'),
),
],
),
);
});
};
}
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
title: const Text('MaterialBanner'),
),
body: Center(
child: ElevatedButton(
onPressed: onPress,
child: const Text('Show a MaterialBanner'),
),
),
);
}
}
| flutter/dev/a11y_assessments/lib/use_cases/material_banner.dart/0 | {
"file_path": "flutter/dev/a11y_assessments/lib/use_cases/material_banner.dart",
"repo_id": "flutter",
"token_count": 865
} | 535 |
#include "ephemeral/Flutter-Generated.xcconfig"
| flutter/dev/a11y_assessments/macos/Flutter/Flutter-Release.xcconfig/0 | {
"file_path": "flutter/dev/a11y_assessments/macos/Flutter/Flutter-Release.xcconfig",
"repo_id": "flutter",
"token_count": 19
} | 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:a11y_assessments/use_cases/material_banner.dart';
import 'package:flutter_test/flutter_test.dart';
import 'test_utils.dart';
void main() {
testWidgets('material banner can run', (WidgetTester tester) async {
await pumpsUseCase(tester, MaterialBannerUseCase());
expect(find.text('Show a MaterialBanner'), findsOneWidget);
await tester.tap(find.text('Show a MaterialBanner'));
await tester.pumpAndSettle();
expect(find.text('Hello, I am a Material Banner'), findsOneWidget);
await tester.tap(find.text('DISMISS'));
await tester.pumpAndSettle();
expect(find.text('Hello, I am a Material Banner'), findsNothing);
});
}
| flutter/dev/a11y_assessments/test/material_banner_test.dart/0 | {
"file_path": "flutter/dev/a11y_assessments/test/material_banner_test.dart",
"repo_id": "flutter",
"token_count": 277
} | 537 |
The files in this directory are used as part of the tests in the
`flutter_tools` package. Some are here because here these tests need a
`pubspec.yaml` that references the flutter framework (which is
intentionally not true of the `flutter_tools` package). Others are
here mostly out of peer pressure. | flutter/dev/automated_tests/flutter_test/README.md/0 | {
"file_path": "flutter/dev/automated_tests/flutter_test/README.md",
"repo_id": "flutter",
"token_count": 74
} | 538 |
# complex_layout
## Scrolling benchmark
To run the scrolling benchmark on a device:
```
flutter drive --profile test_driver/scroll_perf.dart
```
Results should be in the file `build/complex_layout_scroll_perf.timeline_summary.json`.
More detailed logs should be in `build/complex_layout_scroll_perf.timeline.json`.
## Startup benchmark
To measure startup time on a device:
```
flutter run --profile --trace-startup
```
The results should be in the logs.
Additional results should be in the file `build/start_up_info.json`.
| flutter/dev/benchmarks/complex_layout/README.md/0 | {
"file_path": "flutter/dev/benchmarks/complex_layout/README.md",
"repo_id": "flutter",
"token_count": 161
} | 539 |
// 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';
class ColorFilterCachePage extends StatefulWidget {
const ColorFilterCachePage({super.key});
@override
State<ColorFilterCachePage> createState() => _ColorFilterCachePageState();
}
class _ColorFilterCachePageState extends State<ColorFilterCachePage>
with TickerProviderStateMixin {
final ScrollController _controller = ScrollController();
@override
void initState() {
super.initState();
_controller.addListener(() {
if (_controller.offset < 20) {
_controller.animateTo(150, duration: const Duration(milliseconds: 1000), curve: Curves.ease);
} else if (_controller.offset > 130) {
_controller.animateTo(0, duration: const Duration(milliseconds: 1000), curve: Curves.ease);
}
});
Timer(const Duration(milliseconds: 1000), () {
_controller.animateTo(150, 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: 150),
ColorFiltered(
colorFilter: ColorFilter.mode(Colors.green[300]!, BlendMode.luminosity),
child: Container(
clipBehavior: Clip.antiAlias,
decoration: const BoxDecoration(boxShadow: <BoxShadow>[
BoxShadow(
color: Colors.red,
blurRadius: 5.0,
),
], color: Colors.blue, backgroundBlendMode: BlendMode.luminosity),
child: Column(
children: <Widget>[
const Text('Color Filter Cache Pref Test'),
Image.asset(
'food/butternut_squash_soup.png',
package: 'flutter_gallery_assets',
fit: BoxFit.cover,
width: 330,
height: 210,
),
const Text('Color Filter Cache Pref Test'),
],
),
),
),
const SizedBox(height: 1000),
],
),
);
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
}
| flutter/dev/benchmarks/macrobenchmarks/lib/src/color_filter_cache.dart/0 | {
"file_path": "flutter/dev/benchmarks/macrobenchmarks/lib/src/color_filter_cache.dart",
"repo_id": "flutter",
"token_count": 1100
} | 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.
import 'dart:math' as math;
import 'dart:ui';
import 'recorder.dart';
/// Draws many pictures in a grid with only the middle picture visible on the
/// screen, all others are clipped out, for example:
///
/// +-------------+-------------+-------------+---...
/// | | | |
/// | invisible | invisible | invisible |
/// | | | |
/// +-----------------------------------------+---...
/// | | | |
/// | invisible | invisible | invisible |
/// | | | |
/// +-----------------------------------------+---...
/// | | | |
/// | invisible | invisible | VISIBLE |
/// | | | |
/// +-------------+-------------+-------------+---...
/// | | | |
/// : : : :
///
/// We used to unnecessarily allocate DOM nodes, consuming memory and CPU time.
class BenchClippedOutPictures extends SceneBuilderRecorder {
BenchClippedOutPictures() : super(name: benchmarkName);
static const String benchmarkName = 'clipped_out_pictures';
static final Paint paint = Paint();
double angle = 0.0;
static const int kRows = 20;
static const int kColumns = 20;
@override
void onDrawFrame(SceneBuilder sceneBuilder) {
final Size viewSize = view.physicalSize / view.devicePixelRatio;
final Size pictureSize = Size(
viewSize.width / kColumns,
viewSize.height / kRows,
);
// Fills a single cell with random text.
void fillCell(int row, int column) {
sceneBuilder.pushOffset(
column * pictureSize.width,
row * pictureSize.height,
);
final PictureRecorder pictureRecorder = PictureRecorder();
final Canvas canvas = Canvas(pictureRecorder);
canvas.save();
canvas.drawCircle(Offset(pictureSize.width / 2, pictureSize.height / 2), 5.0, paint);
canvas.drawRect(Rect.fromCenter(
center: Offset(pictureSize.width / 2, pictureSize.height / 2),
width: pictureSize.width / 6,
height: pictureSize.height / 6,
), paint);
canvas.restore();
final Picture picture = pictureRecorder.endRecording();
sceneBuilder.addPicture(Offset.zero, picture);
sceneBuilder.pop();
}
// Starting with the top-left cell, fill every cell.
sceneBuilder.pushClipRect(Rect.fromCircle(
center: Offset(viewSize.width / 2, viewSize.height / 2),
radius: math.min(viewSize.width, viewSize.height) / 6,
));
sceneBuilder.pushOffset(
5.0 * math.cos(angle),
5.0 * math.sin(angle),
);
angle += math.pi / 20;
for (int row = 0; row < 10; row++) {
for (int column = 0; column < 10; column++) {
fillCell(row, column);
}
}
sceneBuilder.pop();
sceneBuilder.pop();
}
}
| flutter/dev/benchmarks/macrobenchmarks/lib/src/web/bench_clipped_out_pictures.dart/0 | {
"file_path": "flutter/dev/benchmarks/macrobenchmarks/lib/src/web/bench_clipped_out_pictures.dart",
"repo_id": "flutter",
"token_count": 1321
} | 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 'dart:async';
import 'package:flutter/widgets.dart';
import 'recorder.dart';
import 'test_data.dart';
/// Creates several list views containing text items, then continuously scrolls
/// them up and down.
///
/// Measures our ability to lazily render virtually infinitely big content.
class BenchSimpleLazyTextScroll extends WidgetRecorder {
BenchSimpleLazyTextScroll() : super(name: benchmarkName);
static const String benchmarkName = 'bench_simple_lazy_text_scroll';
@override
Widget createWidget() {
return const Directionality(
textDirection: TextDirection.ltr,
child: Row(
children: <Widget>[
Flexible(
child: _TestScrollingWidget(
initialScrollOffset: 0,
scrollDistance: 300,
scrollDuration: Duration(seconds: 1),
),
),
Flexible(
child: _TestScrollingWidget(
initialScrollOffset: 1000,
scrollDistance: 500,
scrollDuration: Duration(milliseconds: 1500),
),
),
Flexible(
child: _TestScrollingWidget(
initialScrollOffset: 2000,
scrollDistance: 700,
scrollDuration: Duration(milliseconds: 2000),
),
),
],
),
);
}
}
class _TestScrollingWidget extends StatefulWidget {
const _TestScrollingWidget({
required this.initialScrollOffset,
required this.scrollDistance,
required this.scrollDuration,
});
final double initialScrollOffset;
final double scrollDistance;
final Duration scrollDuration;
@override
State<StatefulWidget> createState() {
return _TestScrollingWidgetState();
}
}
class _TestScrollingWidgetState extends State<_TestScrollingWidget> {
late ScrollController scrollController;
@override
void initState() {
super.initState();
scrollController = ScrollController(
initialScrollOffset: widget.initialScrollOffset,
);
// Without the timer the animation doesn't begin.
Timer.run(() async {
bool forward = true;
while (true) {
await scrollController.animateTo(
forward
? widget.initialScrollOffset + widget.scrollDistance
: widget.initialScrollOffset,
curve: Curves.linear,
duration: widget.scrollDuration,
);
forward = !forward;
}
});
}
@override
void dispose() {
scrollController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return ListView.builder(
controller: scrollController,
itemCount: 10000,
itemBuilder: (BuildContext context, int index) {
return Text(lipsum[index % lipsum.length]);
},
);
}
}
| flutter/dev/benchmarks/macrobenchmarks/lib/src/web/bench_simple_lazy_text_scroll.dart/0 | {
"file_path": "flutter/dev/benchmarks/macrobenchmarks/lib/src/web/bench_simple_lazy_text_scroll.dart",
"repo_id": "flutter",
"token_count": 1144
} | 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 'package:flutter_driver/flutter_driver.dart';
import 'package:macrobenchmarks/common.dart';
import 'util.dart';
void main() {
macroPerfTest(
'tessellation_perf_dynamic',
kPathTessellationRouteName,
pageDelay: const Duration(seconds: 1),
duration: const Duration(seconds: 10),
setupOps: (FlutterDriver driver) async {
final SerializableFinder animateButton =
find.byValueKey('animate_button');
await driver.tap(animateButton);
await Future<void>.delayed(const Duration(seconds: 1));
},
);
}
| flutter/dev/benchmarks/macrobenchmarks/test_driver/path_tessellation_dynamic_perf_test.dart/0 | {
"file_path": "flutter/dev/benchmarks/macrobenchmarks/test_driver/path_tessellation_dynamic_perf_test.dart",
"repo_id": "flutter",
"token_count": 246
} | 543 |
// 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/services.dart';
import '../common.dart';
const int _kNumIterations = 100000;
void main() {
assert(false,
"Don't run benchmarks in debug mode! Use 'flutter run --release'.");
final BenchmarkResultPrinter printer = BenchmarkResultPrinter();
const StandardMessageCodec codec = StandardMessageCodec();
final Stopwatch watch = Stopwatch();
watch.start();
for (int i = 0; i < _kNumIterations; i += 1) {
codec.encodeMessage(null);
}
watch.stop();
printer.addResult(
description: 'StandardMessageCodec null',
value: watch.elapsedMicroseconds.toDouble() / _kNumIterations,
unit: 'us per iteration',
name: 'StandardMessageCodec_null',
);
watch.reset();
watch.start();
for (int i = 0; i < _kNumIterations; i += 1) {
codec.encodeMessage(12345);
}
watch.stop();
printer.addResult(
description: 'StandardMessageCodec int',
value: watch.elapsedMicroseconds.toDouble() / _kNumIterations,
unit: 'us per iteration',
name: 'StandardMessageCodec_int',
);
watch.reset();
watch.start();
for (int i = 0; i < _kNumIterations; i += 1) {
codec.encodeMessage('This is a performance test.');
}
watch.stop();
printer.addResult(
description: 'StandardMessageCodec string',
value: watch.elapsedMicroseconds.toDouble() / _kNumIterations,
unit: 'us per iteration',
name: 'StandardMessageCodec_string',
);
watch.reset();
watch.start();
for (int i = 0; i < _kNumIterations; i += 1) {
codec.encodeMessage(<Object>[1234, 'This is a performance test.', 1.25, true]);
}
watch.stop();
printer.addResult(
description: 'StandardMessageCodec heterogenous list',
value: watch.elapsedMicroseconds.toDouble() / _kNumIterations,
unit: 'us per iteration',
name: 'StandardMessageCodec_heterogenous_list',
);
watch.reset();
watch.start();
for (int i = 0; i < _kNumIterations; i += 1) {
codec.encodeMessage(<String, Object>{
'integer': 1234,
'string': 'This is a performance test.',
'float': 1.25,
'boolean': true,
});
}
watch.stop();
printer.addResult(
description: 'StandardMessageCodec heterogenous map',
value: watch.elapsedMicroseconds.toDouble() / _kNumIterations,
unit: 'us per iteration',
name: 'StandardMessageCodec_heterogenous_map',
);
watch.reset();
watch.start();
for (int i = 0; i < _kNumIterations; i += 1) {
codec.encodeMessage('special chars >\u263A\u{1F602}<');
}
watch.stop();
printer.addResult(
description: 'StandardMessageCodec unicode',
value: watch.elapsedMicroseconds.toDouble() / _kNumIterations,
unit: 'us per iteration',
name: 'StandardMessageCodec_unicode',
);
watch.reset();
printer.printToStdout();
}
| flutter/dev/benchmarks/microbenchmarks/lib/foundation/standard_message_codec_bench.dart/0 | {
"file_path": "flutter/dev/benchmarks/microbenchmarks/lib/foundation/standard_message_codec_bench.dart",
"repo_id": "flutter",
"token_count": 1035
} | 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';
import 'package:flutter_test/flutter_test.dart';
import '../common.dart';
import 'build_bench.dart';
Future<void> main() async {
debugProfileBuildsEnabledUserWidgets = true;
final BenchmarkResultPrinter printer = BenchmarkResultPrinter();
printer.addResultStatistics(
description: 'Stock build User Widgets Profiled',
values: await runBuildBenchmark(),
unit: 'Β΅s per iteration',
name: 'stock_build_iteration_user_widgets_profiled',
);
printer.printToStdout();
}
| flutter/dev/benchmarks/microbenchmarks/lib/stocks/build_bench_profiled.dart/0 | {
"file_path": "flutter/dev/benchmarks/microbenchmarks/lib/stocks/build_bench_profiled.dart",
"repo_id": "flutter",
"token_count": 218
} | 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 <UIKit/UIKit.h>
#import "AppDelegate.h"
int main(int argc, char * argv[]) {
NSString * appDelegateClassName;
@autoreleasepool {
// Setup code that might create autoreleased objects goes here.
appDelegateClassName = NSStringFromClass([AppDelegate class]);
}
return UIApplicationMain(argc, argv, nil, appDelegateClassName);
}
| flutter/dev/benchmarks/platform_channels_benchmarks/ios/Runner/main.m/0 | {
"file_path": "flutter/dev/benchmarks/platform_channels_benchmarks/ios/Runner/main.m",
"repo_id": "flutter",
"token_count": 170
} | 546 |
#include "Generated.xcconfig"
| flutter/dev/benchmarks/platform_views_layout_hybrid_composition/ios/Flutter/Debug.xcconfig/0 | {
"file_path": "flutter/dev/benchmarks/platform_views_layout_hybrid_composition/ios/Flutter/Debug.xcconfig",
"repo_id": "flutter",
"token_count": 12
} | 547 |
// 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 "DummyPlatformView.h"
@implementation DummyPlatformViewFactory {
NSObject<FlutterBinaryMessenger>* _messenger;
}
- (instancetype)initWithMessenger:(NSObject<FlutterBinaryMessenger>*)messenger {
self = [super init];
if (self) {
_messenger = messenger;
}
return self;
}
- (NSObject<FlutterPlatformView>*)createWithFrame:(CGRect)frame
viewIdentifier:(int64_t)viewId
arguments:(id _Nullable)args {
return [[DummyPlatformView alloc] initWithFrame:frame
viewIdentifier:viewId
arguments:args
binaryMessenger:_messenger];
}
- (NSObject<FlutterMessageCodec>*)createArgsCodec {
return [FlutterStringCodec sharedInstance];
}
@end
@implementation DummyPlatformView {
UITextView* _view;
FlutterMethodChannel* _channel;
}
- (instancetype)initWithFrame:(CGRect)frame
viewIdentifier:(int64_t)viewId
arguments:(id _Nullable)args
binaryMessenger:(NSObject<FlutterBinaryMessenger>*)messenger {
if ([super init]) {
_view = [[UITextView alloc] initWithFrame:CGRectMake(0.0, 0.0, 250.0, 100.0)];
_view.textColor = UIColor.blueColor;
_view.backgroundColor = UIColor.lightGrayColor;
[_view setFont:[UIFont systemFontOfSize:52]];
_view.text = @"DummyPlatformView";
}
return self;
}
- (UIView*)view {
return _view;
}
@end
| flutter/dev/benchmarks/platform_views_layout_hybrid_composition/ios/Runner/DummyPlatformView.m/0 | {
"file_path": "flutter/dev/benchmarks/platform_views_layout_hybrid_composition/ios/Runner/DummyPlatformView.m",
"repo_id": "flutter",
"token_count": 731
} | 548 |
// 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.
// Snapshot from http://www.nasdaq.com/screening/company-list.aspx
// Fetched 2/23/2014.
// "Symbol","Name","LastSale","MarketCap","IPOyear","Sector","industry","Summary Quote",
// Data in stock_data.json
import 'dart:convert';
import 'dart:math' as math;
import 'package:flutter/foundation.dart';
import 'package:http/http.dart' as http;
final math.Random _rng = math.Random();
class Stock {
Stock(this.symbol, this.name, this.lastSale, this.marketCap, this.percentChange);
Stock.fromFields(List<String> fields) {
// TODO(jackson): This class should only have static data, not lastSale, etc.
// "Symbol","Name","LastSale","MarketCap","IPOyear","Sector","industry","Summary Quote",
lastSale = 0.0;
try {
lastSale = double.parse(fields[2]);
} catch (_) { }
symbol = fields[0];
name = fields[1];
marketCap = fields[4];
percentChange = (_rng.nextDouble() * 20) - 10;
}
late String symbol;
late String name;
late double lastSale;
late String marketCap;
late double percentChange;
}
class StockData extends ChangeNotifier {
StockData() {
if (actuallyFetchData) {
_httpClient = http.Client();
_fetchNextChunk();
}
}
final List<String> _symbols = <String>[];
final Map<String, Stock> _stocks = <String, Stock>{};
List<String> get allSymbols => _symbols;
Stock? operator [](String symbol) => _stocks[symbol];
bool get loading => _httpClient != null;
void add(List<dynamic> data) {
for (final List<dynamic> fields in data.cast<List<dynamic>>()) {
final Stock stock = Stock.fromFields(fields.cast<String>());
_symbols.add(stock.symbol);
_stocks[stock.symbol] = stock;
}
_symbols.sort();
notifyListeners();
}
static const int _chunkCount = 30;
int _nextChunk = 0;
Uri _urlToFetch(int chunk) => Uri.https(
'domokit.github.io', 'examples/stocks/data/stock_data_$chunk.json');
http.Client? _httpClient;
static bool actuallyFetchData = true;
void _fetchNextChunk() {
_httpClient!.get(_urlToFetch(_nextChunk++)).then<void>((http.Response response) {
final String json = response.body;
const JsonDecoder decoder = JsonDecoder();
add(decoder.convert(json) as List<dynamic>);
if (_nextChunk < _chunkCount) {
_fetchNextChunk();
} else {
_end();
}
});
}
void _end() {
_httpClient!.close();
_httpClient = null;
}
}
| flutter/dev/benchmarks/test_apps/stocks/lib/stock_data.dart/0 | {
"file_path": "flutter/dev/benchmarks/test_apps/stocks/lib/stock_data.dart",
"repo_id": "flutter",
"token_count": 975
} | 549 |
#!/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.
set -e
# This script is only meant to be run by the Cirrus CI system, not locally.
# It must be run from the root of the Flutter repo.
function error() {
echo "$@" 1>&2
}
function accept_android_licenses() {
yes "y" | flutter doctor --android-licenses
}
echo "Flutter SDK directory is: $PWD"
# Accept licenses.
echo "Accepting Android licenses."
accept_android_licenses || (error "Accepting Android licenses failed." && false)
| flutter/dev/bots/accept_android_sdk_licenses.sh/0 | {
"file_path": "flutter/dev/bots/accept_android_sdk_licenses.sh",
"repo_id": "flutter",
"token_count": 185
} | 550 |
// 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 'package:convert/convert.dart';
import 'package:crypto/crypto.dart';
import 'package:file/file.dart';
import 'package:path/path.dart' as path;
import 'package:platform/platform.dart' show LocalPlatform, Platform;
import 'package:process/process.dart';
import 'common.dart';
import 'process_runner.dart';
class ArchivePublisher {
ArchivePublisher(
this.tempDir,
this.revision,
this.branch,
this.version,
this.outputFile,
this.dryRun, {
ProcessManager? processManager,
bool subprocessOutput = true,
required this.fs,
this.platform = const LocalPlatform(),
}) : assert(revision.length == 40),
platformName = platform.operatingSystem.toLowerCase(),
metadataGsPath = '$gsReleaseFolder/${getMetadataFilename(platform)}',
_processRunner = ProcessRunner(
processManager: processManager,
subprocessOutput: subprocessOutput,
);
final Platform platform;
final FileSystem fs;
final String platformName;
final String metadataGsPath;
final Branch branch;
final String revision;
final Map<String, String> version;
final Directory tempDir;
final File outputFile;
final ProcessRunner _processRunner;
final bool dryRun;
String get destinationArchivePath => '${branch.name}/$platformName/${path.basename(outputFile.path)}';
static String getMetadataFilename(Platform platform) => 'releases_${platform.operatingSystem.toLowerCase()}.json';
Future<String> _getChecksum(File archiveFile) async {
final AccumulatorSink<Digest> digestSink = AccumulatorSink<Digest>();
final ByteConversionSink sink = sha256.startChunkedConversion(digestSink);
final Stream<List<int>> stream = archiveFile.openRead();
await stream.forEach((List<int> chunk) {
sink.add(chunk);
});
sink.close();
return digestSink.events.single.toString();
}
/// Publish the archive to Google Storage.
///
/// This method will throw if the target archive already exists on cloud
/// storage.
Future<void> publishArchive([bool forceUpload = false]) async {
final String destGsPath = '$gsReleaseFolder/$destinationArchivePath';
if (!forceUpload) {
if (await _cloudPathExists(destGsPath) && !dryRun) {
throw PreparePackageException(
'File $destGsPath already exists on cloud storage!',
);
}
}
await _cloudCopy(
src: outputFile.absolute.path,
dest: destGsPath,
);
assert(tempDir.existsSync());
final String gcsPath = '$gsReleaseFolder/${getMetadataFilename(platform)}';
await _publishMetadata(gcsPath);
}
/// Downloads and updates the metadata file without publishing it.
Future<void> generateLocalMetadata() async {
await _updateMetadata('$gsReleaseFolder/${getMetadataFilename(platform)}');
}
Future<Map<String, dynamic>> _addRelease(Map<String, dynamic> jsonData) async {
jsonData['base_url'] = '$baseUrl$releaseFolder';
if (!jsonData.containsKey('current_release')) {
jsonData['current_release'] = <String, String>{};
}
(jsonData['current_release'] as Map<String, dynamic>)[branch.name] = revision;
if (!jsonData.containsKey('releases')) {
jsonData['releases'] = <Map<String, dynamic>>[];
}
final Map<String, dynamic> newEntry = <String, dynamic>{};
newEntry['hash'] = revision;
newEntry['channel'] = branch.name;
newEntry['version'] = version[frameworkVersionTag];
newEntry['dart_sdk_version'] = version[dartVersionTag];
newEntry['dart_sdk_arch'] = version[dartTargetArchTag];
newEntry['release_date'] = DateTime.now().toUtc().toIso8601String();
newEntry['archive'] = destinationArchivePath;
newEntry['sha256'] = await _getChecksum(outputFile);
// Search for any entries with the same hash and channel and remove them.
final List<dynamic> releases = jsonData['releases'] as List<dynamic>;
jsonData['releases'] = <Map<String, dynamic>>[
for (final Map<String, dynamic> entry in releases.cast<Map<String, dynamic>>())
if (entry['hash'] != newEntry['hash'] ||
entry['channel'] != newEntry['channel'] ||
entry['dart_sdk_arch'] != newEntry['dart_sdk_arch'])
entry,
newEntry,
]..sort((Map<String, dynamic> a, Map<String, dynamic> b) {
final DateTime aDate = DateTime.parse(a['release_date'] as String);
final DateTime bDate = DateTime.parse(b['release_date'] as String);
return bDate.compareTo(aDate);
});
return jsonData;
}
Future<void> _updateMetadata(String gsPath) async {
// We can't just cat the metadata from the server with 'gsutil cat', because
// Windows wants to echo the commands that execute in gsutil.bat to the
// stdout when we do that. So, we copy the file locally and then read it
// back in.
final File metadataFile = fs.file(
path.join(tempDir.absolute.path, getMetadataFilename(platform)),
);
await _runGsUtil(<String>['cp', gsPath, metadataFile.absolute.path]);
Map<String, dynamic> jsonData = <String, dynamic>{};
if (!dryRun) {
final String currentMetadata = metadataFile.readAsStringSync();
if (currentMetadata.isEmpty) {
throw PreparePackageException('Empty metadata received from server');
}
try {
jsonData = json.decode(currentMetadata) as Map<String, dynamic>;
} on FormatException catch (e) {
throw PreparePackageException('Unable to parse JSON metadata received from cloud: $e');
}
}
// Run _addRelease, even on a dry run, so we can inspect the metadata on a
// dry run. On a dry run, the only thing in the metadata file be the new
// release.
jsonData = await _addRelease(jsonData);
const JsonEncoder encoder = JsonEncoder.withIndent(' ');
metadataFile.writeAsStringSync(encoder.convert(jsonData));
}
/// Publishes the metadata file to GCS.
Future<void> _publishMetadata(String gsPath) async {
final File metadataFile = fs.file(
path.join(tempDir.absolute.path, getMetadataFilename(platform)),
);
await _cloudCopy(
src: metadataFile.absolute.path,
dest: gsPath,
// This metadata file is used by the website, so we don't want a long
// latency between publishing a release and it being available on the
// site.
cacheSeconds: shortCacheSeconds,
);
}
Future<String> _runGsUtil(
List<String> args, {
Directory? workingDirectory,
bool failOk = false,
}) async {
if (dryRun) {
print('gsutil.py -- $args');
return '';
}
return _processRunner.runProcess(
<String>['python3', path.join(platform.environment['DEPOT_TOOLS']!, 'gsutil.py'), '--', ...args],
workingDirectory: workingDirectory,
failOk: failOk,
);
}
/// Determine if a file exists at a given [cloudPath].
Future<bool> _cloudPathExists(String cloudPath) async {
try {
await _runGsUtil(
<String>['stat', cloudPath],
);
} on PreparePackageException {
// `gsutil stat gs://path/to/file` will exit with 1 if file does not exist
return false;
}
return true;
}
Future<String> _cloudCopy({
required String src,
required String dest,
int? cacheSeconds,
}) async {
// We often don't have permission to overwrite, but
// we have permission to remove, so that's what we do.
await _runGsUtil(<String>['rm', dest], failOk: true);
String? mimeType;
if (dest.endsWith('.tar.xz')) {
mimeType = 'application/x-gtar';
}
if (dest.endsWith('.zip')) {
mimeType = 'application/zip';
}
if (dest.endsWith('.json')) {
mimeType = 'application/json';
}
return _runGsUtil(<String>[
// Use our preferred MIME type for the files we care about
// and let gsutil figure it out for anything else.
if (mimeType != null) ...<String>['-h', 'Content-Type:$mimeType'],
if (cacheSeconds != null) ...<String>['-h', 'Cache-Control:max-age=$cacheSeconds'],
'cp',
src,
dest,
]);
}
}
| flutter/dev/bots/prepare_package/archive_publisher.dart/0 | {
"file_path": "flutter/dev/bots/prepare_package/archive_publisher.dart",
"repo_id": "flutter",
"token_count": 2970
} | 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.
@TestOn('mac-os')
library;
import '../../../packages/flutter_tools/test/src/fake_process_manager.dart';
import '../test.dart';
import './common.dart';
void main() async {
const String flutterRoot = '/a/b/c';
final List<String> allExpectedFiles = binariesWithEntitlements(flutterRoot) + binariesWithoutEntitlements(flutterRoot);
final String allFilesStdout = allExpectedFiles.join('\n');
final List<String> allExpectedXcframeworks = signedXcframeworks(flutterRoot);
final String allXcframeworksStdout = allExpectedXcframeworks.join('\n');
final List<String> withEntitlements = binariesWithEntitlements(flutterRoot);
group('verifyExist', () {
test('Not all files found', () async {
final ProcessManager processManager = FakeProcessManager.list(
<FakeCommand>[
const FakeCommand(
command: <String>[
'find',
'/a/b/c/bin/cache',
'-type',
'f',
],
stdout: '/a/b/c/bin/cache/artifacts/engine/android-arm-profile/darwin-x64/gen_snapshot',
),
const FakeCommand(
command: <String>[
'file',
'--mime-type',
'-b',
'/a/b/c/bin/cache/artifacts/engine/android-arm-profile/darwin-x64/gen_snapshot',
],
stdout: 'application/x-mach-binary',
),
],
);
expect(
() async => verifyExist(flutterRoot, processManager: processManager),
throwsExceptionWith('Did not find all expected binaries!'),
);
});
test('All files found', () async {
final List<FakeCommand> commandList = <FakeCommand>[];
final FakeCommand findCmd = FakeCommand(
command: const <String>[
'find',
'$flutterRoot/bin/cache',
'-type',
'f',],
stdout: allFilesStdout,
);
commandList.add(findCmd);
for (final String expectedFile in allExpectedFiles) {
commandList.add(
FakeCommand(
command: <String>[
'file',
'--mime-type',
'-b',
expectedFile,
],
stdout: 'application/x-mach-binary',
)
);
}
final ProcessManager processManager = FakeProcessManager.list(commandList);
await expectLater(verifyExist('/a/b/c', processManager: processManager), completes);
});
});
group('find paths', () {
test('All binary files found', () async {
final List<FakeCommand> commandList = <FakeCommand>[];
final FakeCommand findCmd = FakeCommand(
command: const <String>[
'find',
'$flutterRoot/bin/cache',
'-type',
'f',],
stdout: allFilesStdout,
);
commandList.add(findCmd);
for (final String expectedFile in allExpectedFiles) {
commandList.add(
FakeCommand(
command: <String>[
'file',
'--mime-type',
'-b',
expectedFile,
],
stdout: 'application/x-mach-binary',
)
);
}
final ProcessManager processManager = FakeProcessManager.list(commandList);
final List<String> foundFiles = await findBinaryPaths('$flutterRoot/bin/cache', processManager: processManager);
expect(foundFiles, allExpectedFiles);
});
test('Empty file list', () async {
final List<FakeCommand> commandList = <FakeCommand>[];
const FakeCommand findCmd = FakeCommand(
command: <String>[
'find',
'$flutterRoot/bin/cache',
'-type',
'f',],
);
commandList.add(findCmd);
final ProcessManager processManager = FakeProcessManager.list(commandList);
final List<String> foundFiles = await findBinaryPaths('$flutterRoot/bin/cache', processManager: processManager);
expect(foundFiles, <String>[]);
});
test('All xcframeworks files found', () async {
final List<FakeCommand> commandList = <FakeCommand>[
FakeCommand(
command: const <String>[
'find',
'$flutterRoot/bin/cache',
'-type',
'd',
'-name',
'*xcframework',
],
stdout: allXcframeworksStdout,
)
];
final ProcessManager processManager = FakeProcessManager.list(commandList);
final List<String> foundFiles = await findXcframeworksPaths('$flutterRoot/bin/cache', processManager: processManager);
expect(foundFiles, allExpectedXcframeworks);
});
group('isBinary', () {
test('isTrue', () async {
final List<FakeCommand> commandList = <FakeCommand>[];
const String fileToCheck = '/a/b/c/one.zip';
const FakeCommand findCmd = FakeCommand(
command: <String>[
'file',
'--mime-type',
'-b',
fileToCheck,
],
stdout: 'application/x-mach-binary',
);
commandList.add(findCmd);
final ProcessManager processManager = FakeProcessManager.list(commandList);
final bool result = await isBinary(fileToCheck, processManager: processManager);
expect(result, isTrue);
});
test('isFalse', () async {
final List<FakeCommand> commandList = <FakeCommand>[];
const String fileToCheck = '/a/b/c/one.zip';
const FakeCommand findCmd = FakeCommand(
command: <String>[
'file',
'--mime-type',
'-b',
fileToCheck,
],
stdout: 'text/xml',
);
commandList.add(findCmd);
final ProcessManager processManager = FakeProcessManager.list(commandList);
final bool result = await isBinary(fileToCheck, processManager: processManager);
expect(result, isFalse);
});
});
group('hasExpectedEntitlements', () {
test('expected entitlements', () async {
final List<FakeCommand> commandList = <FakeCommand>[];
const String fileToCheck = '/a/b/c/one.zip';
const FakeCommand codesignCmd = FakeCommand(
command: <String>[
'codesign',
'--display',
'--entitlements',
':-',
fileToCheck,
],
);
commandList.add(codesignCmd);
final ProcessManager processManager = FakeProcessManager.list(commandList);
final bool result = await hasExpectedEntitlements(fileToCheck, flutterRoot, processManager: processManager);
expect(result, isTrue);
});
test('unexpected entitlements', () async {
final List<FakeCommand> commandList = <FakeCommand>[];
const String fileToCheck = '/a/b/c/one.zip';
const FakeCommand codesignCmd = FakeCommand(
command: <String>[
'codesign',
'--display',
'--entitlements',
':-',
fileToCheck,
],
exitCode: 1,
);
commandList.add(codesignCmd);
final ProcessManager processManager = FakeProcessManager.list(commandList);
final bool result = await hasExpectedEntitlements(fileToCheck, flutterRoot, processManager: processManager);
expect(result, isFalse);
});
});
});
group('verifySignatures', () {
test('succeeds if every binary is codesigned and has correct entitlements', () async {
final List<FakeCommand> commandList = <FakeCommand>[];
final FakeCommand findCmd = FakeCommand(
command: const <String>[
'find',
'$flutterRoot/bin/cache',
'-type',
'f',],
stdout: allFilesStdout,
);
commandList.add(findCmd);
for (final String expectedFile in allExpectedFiles) {
commandList.add(
FakeCommand(
command: <String>[
'file',
'--mime-type',
'-b',
expectedFile,
],
stdout: 'application/x-mach-binary',
)
);
}
commandList.add(
FakeCommand(
command: const <String>[
'find',
'$flutterRoot/bin/cache',
'-type',
'd',
'-name',
'*xcframework',
],
stdout: allXcframeworksStdout,
),
);
for (final String expectedFile in allExpectedFiles) {
commandList.add(
FakeCommand(
command: <String>[
'codesign',
'-vvv',
expectedFile,
],
)
);
if (withEntitlements.contains(expectedFile)) {
commandList.add(
FakeCommand(
command: <String>[
'codesign',
'--display',
'--entitlements',
':-',
expectedFile,
],
stdout: expectedEntitlements.join('\n'),
)
);
}
}
for (final String expectedXcframework in allExpectedXcframeworks) {
commandList.add(
FakeCommand(
command: <String>[
'codesign',
'-vvv',
expectedXcframework,
],
)
);
}
final ProcessManager processManager = FakeProcessManager.list(commandList);
await expectLater(verifySignatures(flutterRoot, processManager: processManager), completes);
});
test('fails if binaries do not have the right entitlements', () async {
final List<FakeCommand> commandList = <FakeCommand>[];
final FakeCommand findCmd = FakeCommand(
command: const <String>[
'find',
'$flutterRoot/bin/cache',
'-type',
'f',],
stdout: allFilesStdout,
);
commandList.add(findCmd);
for (final String expectedFile in allExpectedFiles) {
commandList.add(
FakeCommand(
command: <String>[
'file',
'--mime-type',
'-b',
expectedFile,
],
stdout: 'application/x-mach-binary',
)
);
}
commandList.add(
FakeCommand(
command: const <String>[
'find',
'$flutterRoot/bin/cache',
'-type',
'd',
'-name',
'*xcframework',
],
stdout: allXcframeworksStdout,
),
);
for (final String expectedFile in allExpectedFiles) {
commandList.add(
FakeCommand(
command: <String>[
'codesign',
'-vvv',
expectedFile,
],
)
);
if (withEntitlements.contains(expectedFile)) {
commandList.add(
FakeCommand(
command: <String>[
'codesign',
'--display',
'--entitlements',
':-',
expectedFile,
],
)
);
}
}
for (final String expectedXcframework in allExpectedXcframeworks) {
commandList.add(
FakeCommand(
command: <String>[
'codesign',
'-vvv',
expectedXcframework,
],
)
);
}
final ProcessManager processManager = FakeProcessManager.list(commandList);
expect(
() async => verifySignatures(flutterRoot, processManager: processManager),
throwsExceptionWith('Test failed because files found with the wrong entitlements'),
);
});
});
}
| flutter/dev/bots/test/codesign_test.dart/0 | {
"file_path": "flutter/dev/bots/test/codesign_test.dart",
"repo_id": "flutter",
"token_count": 5665
} | 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 'dart:io' as io;
import 'package:args/args.dart';
import 'package:conductor_core/conductor_core.dart';
import 'package:conductor_core/packages_autoroller.dart';
import 'package:file/file.dart';
import 'package:file/local.dart';
import 'package:meta/meta.dart' show visibleForTesting;
import 'package:platform/platform.dart';
import 'package:process/process.dart';
const String kTokenOption = 'token';
const String kGithubClient = 'github-client';
const String kUpstreamRemote = 'upstream-remote';
const String kGithubAccountName = 'flutter-pub-roller-bot';
Future<void> main(List<String> args) {
return run(args);
}
@visibleForTesting
Future<void> run(
List<String> args, {
FileSystem fs = const LocalFileSystem(),
ProcessManager processManager = const LocalProcessManager(),
}) async {
final ArgParser parser = ArgParser();
parser.addOption(
kTokenOption,
help: 'Path to GitHub access token file.',
mandatory: true,
);
parser.addOption(
kGithubClient,
help: 'Path to GitHub CLI client. If not provided, it is assumed `gh` is '
'present on the PATH.',
);
parser.addOption(
kUpstreamRemote,
help: 'The upstream git remote that the feature branch will be merged to.',
hide: true,
defaultsTo: 'https://github.com/flutter/flutter.git',
);
final ArgResults results;
try {
results = parser.parse(args);
} on FormatException {
io.stdout.writeln('''
Usage:
${parser.usage}
''');
rethrow;
}
const String mirrorUrl = 'https://github.com/flutter-pub-roller-bot/flutter.git';
final String upstreamUrl = results[kUpstreamRemote]! as String;
final String tokenPath = results[kTokenOption]! as String;
final File tokenFile = fs.file(tokenPath);
if (!tokenFile.existsSync()) {
throw ArgumentError(
'Provided token path $tokenPath but no file exists at ${tokenFile.absolute.path}',
);
}
final String token = tokenFile.readAsStringSync().trim();
if (token.isEmpty) {
throw ArgumentError(
'Tried to read a GitHub access token from file ${tokenFile.path} but it was empty',
);
}
final FrameworkRepository framework = FrameworkRepository(
_localCheckouts(token),
mirrorRemote: const Remote.mirror(mirrorUrl),
upstreamRemote: Remote.upstream(upstreamUrl),
);
await PackageAutoroller(
framework: framework,
githubClient: results[kGithubClient] as String? ?? 'gh',
orgName: _parseOrgName(mirrorUrl),
token: token,
processManager: processManager,
githubUsername: kGithubAccountName,
).roll();
}
String _parseOrgName(String remoteUrl) {
final RegExp pattern = RegExp(r'^https:\/\/github\.com\/(.*)\/');
final RegExpMatch? match = pattern.firstMatch(remoteUrl);
if (match == null) {
throw FormatException(
'Malformed upstream URL "$remoteUrl", should start with "https://github.com/"',
);
}
return match.group(1)!;
}
Checkouts _localCheckouts(String token) {
const FileSystem fileSystem = LocalFileSystem();
const ProcessManager processManager = LocalProcessManager();
const Platform platform = LocalPlatform();
final Stdio stdio = VerboseStdio(
stdout: io.stdout,
stderr: io.stderr,
stdin: io.stdin,
filter: (String message) => message.replaceAll(token, '[GitHub TOKEN]'),
);
return Checkouts(
fileSystem: fileSystem,
parentDirectory: _localFlutterRoot.parent,
platform: platform,
processManager: processManager,
stdio: stdio,
);
}
Directory get _localFlutterRoot {
String filePath;
const FileSystem fileSystem = LocalFileSystem();
const Platform platform = LocalPlatform();
filePath = platform.script.toFilePath();
final String checkoutsDirname = fileSystem.path.normalize(
fileSystem.path.join(
fileSystem.path.dirname(filePath), // flutter/dev/conductor/core/bin
'..', // flutter/dev/conductor/core
'..', // flutter/dev/conductor
'..', // flutter/dev
'..', // flutter
),
);
return fileSystem.directory(checkoutsDirname);
}
@visibleForTesting
void validateTokenFile(String filePath, [FileSystem fs = const LocalFileSystem()]) {
}
| flutter/dev/conductor/core/bin/packages_autoroller.dart/0 | {
"file_path": "flutter/dev/conductor/core/bin/packages_autoroller.dart",
"repo_id": "flutter",
"token_count": 1434
} | 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.
//
// Generated code. Do not modify.
// source: conductor_state.proto
//
// @dart = 2.12
// ignore_for_file: annotate_overrides, camel_case_types
// ignore_for_file: constant_identifier_names, library_prefixes
// ignore_for_file: non_constant_identifier_names, prefer_final_fields
// ignore_for_file: unnecessary_import, unnecessary_this, unused_import
import 'dart:convert' as $convert;
import 'dart:core' as $core;
import 'dart:typed_data' as $typed_data;
@$core.Deprecated('Use releasePhaseDescriptor instead')
const ReleasePhase$json = {
'1': 'ReleasePhase',
'2': [
{'1': 'APPLY_ENGINE_CHERRYPICKS', '2': 0},
{'1': 'VERIFY_ENGINE_CI', '2': 1},
{'1': 'APPLY_FRAMEWORK_CHERRYPICKS', '2': 2},
{'1': 'PUBLISH_VERSION', '2': 3},
{'1': 'VERIFY_RELEASE', '2': 5},
{'1': 'RELEASE_COMPLETED', '2': 6},
],
'4': [
{'1': 4, '2': 4},
],
};
/// Descriptor for `ReleasePhase`. Decode as a `google.protobuf.EnumDescriptorProto`.
final $typed_data.Uint8List releasePhaseDescriptor =
$convert.base64Decode('CgxSZWxlYXNlUGhhc2USHAoYQVBQTFlfRU5HSU5FX0NIRVJSWVBJQ0tTEAASFAoQVkVSSUZZX0'
'VOR0lORV9DSRABEh8KG0FQUExZX0ZSQU1FV09SS19DSEVSUllQSUNLUxACEhMKD1BVQkxJU0hf'
'VkVSU0lPThADEhIKDlZFUklGWV9SRUxFQVNFEAUSFQoRUkVMRUFTRV9DT01QTEVURUQQBiIECA'
'QQBA==');
@$core.Deprecated('Use cherrypickStateDescriptor instead')
const CherrypickState$json = {
'1': 'CherrypickState',
'2': [
{'1': 'PENDING', '2': 0},
{'1': 'PENDING_WITH_CONFLICT', '2': 1},
{'1': 'COMPLETED', '2': 2},
{'1': 'ABANDONED', '2': 3},
],
};
/// Descriptor for `CherrypickState`. Decode as a `google.protobuf.EnumDescriptorProto`.
final $typed_data.Uint8List cherrypickStateDescriptor =
$convert.base64Decode('Cg9DaGVycnlwaWNrU3RhdGUSCwoHUEVORElORxAAEhkKFVBFTkRJTkdfV0lUSF9DT05GTElDVB'
'ABEg0KCUNPTVBMRVRFRBACEg0KCUFCQU5ET05FRBAD');
@$core.Deprecated('Use releaseTypeDescriptor instead')
const ReleaseType$json = {
'1': 'ReleaseType',
'2': [
{'1': 'STABLE_INITIAL', '2': 0},
{'1': 'STABLE_HOTFIX', '2': 1},
{'1': 'BETA_INITIAL', '2': 2},
{'1': 'BETA_HOTFIX', '2': 3},
],
};
/// Descriptor for `ReleaseType`. Decode as a `google.protobuf.EnumDescriptorProto`.
final $typed_data.Uint8List releaseTypeDescriptor =
$convert.base64Decode('CgtSZWxlYXNlVHlwZRISCg5TVEFCTEVfSU5JVElBTBAAEhEKDVNUQUJMRV9IT1RGSVgQARIQCg'
'xCRVRBX0lOSVRJQUwQAhIPCgtCRVRBX0hPVEZJWBAD');
@$core.Deprecated('Use remoteDescriptor instead')
const Remote$json = {
'1': 'Remote',
'2': [
{'1': 'name', '3': 1, '4': 1, '5': 9, '10': 'name'},
{'1': 'url', '3': 2, '4': 1, '5': 9, '10': 'url'},
],
};
/// Descriptor for `Remote`. Decode as a `google.protobuf.DescriptorProto`.
final $typed_data.Uint8List remoteDescriptor =
$convert.base64Decode('CgZSZW1vdGUSEgoEbmFtZRgBIAEoCVIEbmFtZRIQCgN1cmwYAiABKAlSA3VybA==');
@$core.Deprecated('Use cherrypickDescriptor instead')
const Cherrypick$json = {
'1': 'Cherrypick',
'2': [
{'1': 'trunkRevision', '3': 1, '4': 1, '5': 9, '10': 'trunkRevision'},
{'1': 'appliedRevision', '3': 2, '4': 1, '5': 9, '10': 'appliedRevision'},
{'1': 'state', '3': 3, '4': 1, '5': 14, '6': '.conductor_state.CherrypickState', '10': 'state'},
],
};
/// Descriptor for `Cherrypick`. Decode as a `google.protobuf.DescriptorProto`.
final $typed_data.Uint8List cherrypickDescriptor =
$convert.base64Decode('CgpDaGVycnlwaWNrEiQKDXRydW5rUmV2aXNpb24YASABKAlSDXRydW5rUmV2aXNpb24SKAoPYX'
'BwbGllZFJldmlzaW9uGAIgASgJUg9hcHBsaWVkUmV2aXNpb24SNgoFc3RhdGUYAyABKA4yIC5j'
'b25kdWN0b3Jfc3RhdGUuQ2hlcnJ5cGlja1N0YXRlUgVzdGF0ZQ==');
@$core.Deprecated('Use repositoryDescriptor instead')
const Repository$json = {
'1': 'Repository',
'2': [
{'1': 'candidateBranch', '3': 1, '4': 1, '5': 9, '10': 'candidateBranch'},
{'1': 'startingGitHead', '3': 2, '4': 1, '5': 9, '10': 'startingGitHead'},
{'1': 'currentGitHead', '3': 3, '4': 1, '5': 9, '10': 'currentGitHead'},
{'1': 'checkoutPath', '3': 4, '4': 1, '5': 9, '10': 'checkoutPath'},
{'1': 'upstream', '3': 5, '4': 1, '5': 11, '6': '.conductor_state.Remote', '10': 'upstream'},
{'1': 'mirror', '3': 6, '4': 1, '5': 11, '6': '.conductor_state.Remote', '10': 'mirror'},
{'1': 'cherrypicks', '3': 7, '4': 3, '5': 11, '6': '.conductor_state.Cherrypick', '10': 'cherrypicks'},
{'1': 'dartRevision', '3': 8, '4': 1, '5': 9, '10': 'dartRevision'},
{'1': 'workingBranch', '3': 9, '4': 1, '5': 9, '10': 'workingBranch'},
],
};
/// Descriptor for `Repository`. Decode as a `google.protobuf.DescriptorProto`.
final $typed_data.Uint8List repositoryDescriptor =
$convert.base64Decode('CgpSZXBvc2l0b3J5EigKD2NhbmRpZGF0ZUJyYW5jaBgBIAEoCVIPY2FuZGlkYXRlQnJhbmNoEi'
'gKD3N0YXJ0aW5nR2l0SGVhZBgCIAEoCVIPc3RhcnRpbmdHaXRIZWFkEiYKDmN1cnJlbnRHaXRI'
'ZWFkGAMgASgJUg5jdXJyZW50R2l0SGVhZBIiCgxjaGVja291dFBhdGgYBCABKAlSDGNoZWNrb3'
'V0UGF0aBIzCgh1cHN0cmVhbRgFIAEoCzIXLmNvbmR1Y3Rvcl9zdGF0ZS5SZW1vdGVSCHVwc3Ry'
'ZWFtEi8KBm1pcnJvchgGIAEoCzIXLmNvbmR1Y3Rvcl9zdGF0ZS5SZW1vdGVSBm1pcnJvchI9Cg'
'tjaGVycnlwaWNrcxgHIAMoCzIbLmNvbmR1Y3Rvcl9zdGF0ZS5DaGVycnlwaWNrUgtjaGVycnlw'
'aWNrcxIiCgxkYXJ0UmV2aXNpb24YCCABKAlSDGRhcnRSZXZpc2lvbhIkCg13b3JraW5nQnJhbm'
'NoGAkgASgJUg13b3JraW5nQnJhbmNo');
@$core.Deprecated('Use conductorStateDescriptor instead')
const ConductorState$json = {
'1': 'ConductorState',
'2': [
{'1': 'releaseChannel', '3': 1, '4': 1, '5': 9, '10': 'releaseChannel'},
{'1': 'releaseVersion', '3': 2, '4': 1, '5': 9, '10': 'releaseVersion'},
{'1': 'engine', '3': 4, '4': 1, '5': 11, '6': '.conductor_state.Repository', '10': 'engine'},
{'1': 'framework', '3': 5, '4': 1, '5': 11, '6': '.conductor_state.Repository', '10': 'framework'},
{'1': 'createdDate', '3': 6, '4': 1, '5': 3, '10': 'createdDate'},
{'1': 'lastUpdatedDate', '3': 7, '4': 1, '5': 3, '10': 'lastUpdatedDate'},
{'1': 'logs', '3': 8, '4': 3, '5': 9, '10': 'logs'},
{'1': 'currentPhase', '3': 9, '4': 1, '5': 14, '6': '.conductor_state.ReleasePhase', '10': 'currentPhase'},
{'1': 'conductorVersion', '3': 10, '4': 1, '5': 9, '10': 'conductorVersion'},
{'1': 'releaseType', '3': 11, '4': 1, '5': 14, '6': '.conductor_state.ReleaseType', '10': 'releaseType'},
],
};
/// Descriptor for `ConductorState`. Decode as a `google.protobuf.DescriptorProto`.
final $typed_data.Uint8List conductorStateDescriptor =
$convert.base64Decode('Cg5Db25kdWN0b3JTdGF0ZRImCg5yZWxlYXNlQ2hhbm5lbBgBIAEoCVIOcmVsZWFzZUNoYW5uZW'
'wSJgoOcmVsZWFzZVZlcnNpb24YAiABKAlSDnJlbGVhc2VWZXJzaW9uEjMKBmVuZ2luZRgEIAEo'
'CzIbLmNvbmR1Y3Rvcl9zdGF0ZS5SZXBvc2l0b3J5UgZlbmdpbmUSOQoJZnJhbWV3b3JrGAUgAS'
'gLMhsuY29uZHVjdG9yX3N0YXRlLlJlcG9zaXRvcnlSCWZyYW1ld29yaxIgCgtjcmVhdGVkRGF0'
'ZRgGIAEoA1ILY3JlYXRlZERhdGUSKAoPbGFzdFVwZGF0ZWREYXRlGAcgASgDUg9sYXN0VXBkYX'
'RlZERhdGUSEgoEbG9ncxgIIAMoCVIEbG9ncxJBCgxjdXJyZW50UGhhc2UYCSABKA4yHS5jb25k'
'dWN0b3Jfc3RhdGUuUmVsZWFzZVBoYXNlUgxjdXJyZW50UGhhc2USKgoQY29uZHVjdG9yVmVyc2'
'lvbhgKIAEoCVIQY29uZHVjdG9yVmVyc2lvbhI+CgtyZWxlYXNlVHlwZRgLIAEoDjIcLmNvbmR1'
'Y3Rvcl9zdGF0ZS5SZWxlYXNlVHlwZVILcmVsZWFzZVR5cGU=');
| flutter/dev/conductor/core/lib/src/proto/conductor_state.pbjson.dart/0 | {
"file_path": "flutter/dev/conductor/core/lib/src/proto/conductor_state.pbjson.dart",
"repo_id": "flutter",
"token_count": 3925
} | 554 |
// 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' as io;
import 'package:conductor_core/conductor_core.dart';
import 'package:conductor_core/packages_autoroller.dart';
import 'package:file/memory.dart';
import 'package:platform/platform.dart';
import '../bin/packages_autoroller.dart' show run;
import 'common.dart';
void main() {
const String flutterRoot = '/flutter';
const String checkoutsParentDirectory = '$flutterRoot/dev/conductor';
const String githubClient = 'gh';
const String token = '0123456789abcdef';
const String orgName = 'flutter-roller';
const String mirrorUrl = 'https://githost.com/flutter-roller/flutter.git';
final String localPathSeparator = const LocalPlatform().pathSeparator;
final String localOperatingSystem = const LocalPlatform().operatingSystem;
late MemoryFileSystem fileSystem;
late TestStdio stdio;
late FrameworkRepository framework;
late PackageAutoroller autoroller;
late FakeProcessManager processManager;
setUp(() {
stdio = TestStdio();
fileSystem = MemoryFileSystem.test();
processManager = FakeProcessManager.empty();
final FakePlatform platform = FakePlatform(
environment: <String, String>{
'HOME': <String>['path', 'to', 'home'].join(localPathSeparator),
},
operatingSystem: localOperatingSystem,
pathSeparator: localPathSeparator,
);
final Checkouts checkouts = Checkouts(
fileSystem: fileSystem,
parentDirectory: fileSystem.directory(checkoutsParentDirectory)
..createSync(recursive: true),
platform: platform,
processManager: processManager,
stdio: stdio,
);
framework = FrameworkRepository(
checkouts,
mirrorRemote: const Remote(
name: RemoteName.mirror,
url: mirrorUrl,
),
);
autoroller = PackageAutoroller(
githubClient: githubClient,
token: token,
framework: framework,
orgName: orgName,
processManager: processManager,
stdio: stdio,
githubUsername: 'flutter-pub-roller-bot',
);
});
test('GitHub token is redacted from exceptions while pushing', () async {
final StreamController<List<int>> controller =
StreamController<List<int>>();
processManager.addCommands(<FakeCommand>[
FakeCommand(command: const <String>[
'gh',
'auth',
'login',
'--hostname',
'github.com',
'--git-protocol',
'https',
'--with-token',
], stdin: io.IOSink(controller.sink)),
const FakeCommand(command: <String>[
'git',
'clone',
'--origin',
'upstream',
'--',
FrameworkRepository.defaultUpstream,
'$checkoutsParentDirectory/flutter_conductor_checkouts/framework',
]),
const FakeCommand(command: <String>[
'git',
'remote',
'add',
'mirror',
mirrorUrl,
]),
const FakeCommand(command: <String>[
'git',
'fetch',
'mirror',
]),
const FakeCommand(command: <String>[
'git',
'checkout',
FrameworkRepository.defaultBranch,
]),
const FakeCommand(command: <String>[
'git',
'rev-parse',
'HEAD',
], stdout: 'deadbeef'),
const FakeCommand(command: <String>[
'git',
'ls-remote',
'--heads',
'mirror',
]),
const FakeCommand(command: <String>[
'git',
'checkout',
'-b',
'packages-autoroller-branch-1',
]),
const FakeCommand(command: <String>[
'$checkoutsParentDirectory/flutter_conductor_checkouts/framework/bin/flutter',
'help',
]),
const FakeCommand(command: <String>[
'$checkoutsParentDirectory/flutter_conductor_checkouts/framework/bin/flutter',
'--verbose',
'update-packages',
'--force-upgrade',
]),
const FakeCommand(command: <String>[
'git',
'status',
'--porcelain',
], stdout: '''
M packages/foo/pubspec.yaml
M packages/bar/pubspec.yaml
M dev/integration_tests/test_foo/pubspec.yaml
'''),
const FakeCommand(command: <String>[
'git',
'add',
'--all',
]),
const FakeCommand(command: <String>[
'git',
'commit',
'--message',
'roll packages',
'--author="fluttergithubbot <[email protected]>"',
]),
const FakeCommand(command: <String>[
'git',
'rev-parse',
'HEAD',
], stdout: '000deadbeef'),
const FakeCommand(command: <String>[
'git',
'push',
'https://[email protected]/$orgName/flutter.git',
'packages-autoroller-branch-1:packages-autoroller-branch-1',
], exitCode: 1, stderr: 'Authentication error!'),
]);
await expectLater(
() async {
final Future<void> rollFuture = autoroller.roll();
await controller.stream.drain<Object?>();
await rollFuture;
},
throwsA(isA<Exception>().having(
(Exception exc) => exc.toString(),
'message',
isNot(contains(token)),
)),
);
});
test('Does not attempt to roll if bot already has an open PR', () async {
final StreamController<List<int>> controller =
StreamController<List<int>>();
processManager.addCommands(<FakeCommand>[
FakeCommand(command: const <String>[
'gh',
'auth',
'login',
'--hostname',
'github.com',
'--git-protocol',
'https',
'--with-token',
], stdin: io.IOSink(controller.sink)),
const FakeCommand(command: <String>[
'gh',
'pr',
'list',
'--author',
'flutter-pub-roller-bot',
'--repo',
'flutter/flutter',
'--state',
'open',
'--search',
'Roll pub packages',
'--json',
'number',
// Non empty array means there are open PRs by the bot with the tool label
// We expect no further commands to be run
], stdout: '[{"number": 123}]'),
]);
final Future<void> rollFuture = autoroller.roll();
await controller.stream.drain<Object?>();
await rollFuture;
expect(processManager, hasNoRemainingExpectations);
expect(stdio.stdout, contains('flutter-pub-roller-bot already has open tool PRs'));
expect(stdio.stdout, contains(r'[{number: 123}]'));
});
test('Does not commit or create a PR if no changes were made', () async {
final StreamController<List<int>> controller =
StreamController<List<int>>();
processManager.addCommands(<FakeCommand>[
FakeCommand(command: const <String>[
'gh',
'auth',
'login',
'--hostname',
'github.com',
'--git-protocol',
'https',
'--with-token',
], stdin: io.IOSink(controller.sink)),
const FakeCommand(command: <String>[
'gh',
'pr',
'list',
'--author',
'flutter-pub-roller-bot',
'--repo',
'flutter/flutter',
'--state',
'open',
'--search',
'Roll pub packages',
'--json',
'number',
// Returns empty array, as there are no other open roll PRs from the bot
], stdout: '[]'),
const FakeCommand(command: <String>[
'git',
'clone',
'--origin',
'upstream',
'--',
FrameworkRepository.defaultUpstream,
'$checkoutsParentDirectory/flutter_conductor_checkouts/framework',
]),
const FakeCommand(command: <String>[
'git',
'remote',
'add',
'mirror',
mirrorUrl,
]),
const FakeCommand(command: <String>[
'git',
'fetch',
'mirror',
]),
const FakeCommand(command: <String>[
'git',
'checkout',
FrameworkRepository.defaultBranch,
]),
const FakeCommand(command: <String>[
'git',
'rev-parse',
'HEAD',
], stdout: 'deadbeef'),
const FakeCommand(command: <String>[
'git',
'ls-remote',
'--heads',
'mirror',
]),
const FakeCommand(command: <String>[
'git',
'checkout',
'-b',
'packages-autoroller-branch-1',
]),
const FakeCommand(command: <String>[
'$checkoutsParentDirectory/flutter_conductor_checkouts/framework/bin/flutter',
'help',
]),
const FakeCommand(command: <String>[
'$checkoutsParentDirectory/flutter_conductor_checkouts/framework/bin/flutter',
'--verbose',
'update-packages',
'--force-upgrade',
]),
// Because there is no stdout to git status, the script should exit cleanly here
const FakeCommand(command: <String>[
'git',
'status',
'--porcelain',
]),
]);
final Future<void> rollFuture = autoroller.roll();
await controller.stream.drain<Object?>();
await rollFuture;
expect(processManager, hasNoRemainingExpectations);
});
test('can roll with correct inputs', () async {
final StreamController<List<int>> controller =
StreamController<List<int>>();
processManager.addCommands(<FakeCommand>[
FakeCommand(command: const <String>[
'gh',
'auth',
'login',
'--hostname',
'github.com',
'--git-protocol',
'https',
'--with-token',
], stdin: io.IOSink(controller.sink)),
const FakeCommand(command: <String>[
'gh',
'pr',
'list',
'--author',
'flutter-pub-roller-bot',
'--repo',
'flutter/flutter',
'--state',
'open',
'--search',
'Roll pub packages',
'--json',
'number',
// Returns empty array, as there are no other open roll PRs from the bot
], stdout: '[]'),
const FakeCommand(command: <String>[
'git',
'clone',
'--origin',
'upstream',
'--',
FrameworkRepository.defaultUpstream,
'$checkoutsParentDirectory/flutter_conductor_checkouts/framework',
]),
const FakeCommand(command: <String>[
'git',
'remote',
'add',
'mirror',
mirrorUrl,
]),
const FakeCommand(command: <String>[
'git',
'fetch',
'mirror',
]),
const FakeCommand(command: <String>[
'git',
'checkout',
FrameworkRepository.defaultBranch,
]),
const FakeCommand(command: <String>[
'git',
'rev-parse',
'HEAD',
], stdout: 'deadbeef'),
const FakeCommand(command: <String>[
'git',
'ls-remote',
'--heads',
'mirror',
]),
const FakeCommand(command: <String>[
'git',
'checkout',
'-b',
'packages-autoroller-branch-1',
]),
const FakeCommand(command: <String>[
'$checkoutsParentDirectory/flutter_conductor_checkouts/framework/bin/flutter',
'help',
]),
const FakeCommand(command: <String>[
'$checkoutsParentDirectory/flutter_conductor_checkouts/framework/bin/flutter',
'--verbose',
'update-packages',
'--force-upgrade',
]),
const FakeCommand(command: <String>[
'git',
'status',
'--porcelain',
], stdout: '''
M packages/foo/pubspec.yaml
M packages/bar/pubspec.yaml
M dev/integration_tests/test_foo/pubspec.yaml
'''),
const FakeCommand(command: <String>[
'git',
'status',
'--porcelain',
], stdout: '''
M packages/foo/pubspec.yaml
M packages/bar/pubspec.yaml
M dev/integration_tests/test_foo/pubspec.yaml
'''),
const FakeCommand(command: <String>[
'git',
'add',
'--all',
]),
const FakeCommand(command: <String>[
'git',
'commit',
'--message',
'roll packages',
'--author="flutter-pub-roller-bot <[email protected]>"',
]),
const FakeCommand(command: <String>[
'git',
'rev-parse',
'HEAD',
], stdout: '000deadbeef'),
const FakeCommand(command: <String>[
'git',
'push',
'https://[email protected]/$orgName/flutter.git',
'packages-autoroller-branch-1:packages-autoroller-branch-1',
]),
const FakeCommand(command: <String>[
'gh',
'pr',
'create',
'--title',
'Roll pub packages',
'--body',
'This PR was generated by `flutter update-packages --force-upgrade`.',
'--head',
'flutter-roller:packages-autoroller-branch-1',
'--base',
FrameworkRepository.defaultBranch,
'--label',
'tool',
'--label',
'autosubmit',
]),
const FakeCommand(command: <String>[
'gh',
'auth',
'logout',
'--hostname',
'github.com',
]),
]);
final Future<void> rollFuture = autoroller.roll();
final String givenToken =
await controller.stream.transform(const Utf8Decoder()).join();
expect(givenToken.trim(), token);
await rollFuture;
expect(processManager, hasNoRemainingExpectations);
});
group('command argument validations', () {
const String tokenPath = '/path/to/token';
test('validates that file exists at --token option', () async {
await expectLater(
() => run(
<String>['--token', tokenPath],
fs: fileSystem,
processManager: processManager,
),
throwsA(isA<ArgumentError>().having(
(ArgumentError err) => err.message,
'message',
contains('Provided token path $tokenPath but no file exists at'),
)),
);
expect(processManager, hasNoRemainingExpectations);
});
test('validates that the token file is not empty', () async {
fileSystem.file(tokenPath)
..createSync(recursive: true)
..writeAsStringSync('');
await expectLater(
() => run(
<String>['--token', tokenPath],
fs: fileSystem,
processManager: processManager,
),
throwsA(isA<ArgumentError>().having(
(ArgumentError err) => err.message,
'message',
contains('Tried to read a GitHub access token from file $tokenPath but it was empty'),
)),
);
expect(processManager, hasNoRemainingExpectations);
});
});
test('VerboseStdio logger can filter out confidential pattern', () async {
const String token = 'secret';
const String replacement = 'replacement';
final VerboseStdio stdio = VerboseStdio(
stdin: _NoOpStdin(),
stderr: _NoOpStdout(),
stdout: _NoOpStdout(),
filter: (String msg) => msg.replaceAll(token, replacement),
);
stdio.printStatus('Hello');
expect(stdio.logs.last, '[status] Hello');
stdio.printStatus('Using $token');
expect(stdio.logs.last, '[status] Using $replacement');
stdio.printWarning('Using $token');
expect(stdio.logs.last, '[warning] Using $replacement');
stdio.printError('Using $token');
expect(stdio.logs.last, '[error] Using $replacement');
stdio.printTrace('Using $token');
expect(stdio.logs.last, '[trace] Using $replacement');
});
}
class _NoOpStdin extends Fake implements io.Stdin {}
class _NoOpStdout extends Fake implements io.Stdout {
@override
void writeln([Object? object]) {}
}
| flutter/dev/conductor/core/test/packages_autoroller_test.dart/0 | {
"file_path": "flutter/dev/conductor/core/test/packages_autoroller_test.dart",
"repo_id": "flutter",
"token_count": 7038
} | 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.
import 'dart:convert';
import 'dart:io';
import 'package:args/args.dart';
import 'package:flutter_devicelab/framework/ab.dart';
import 'package:flutter_devicelab/framework/utils.dart';
String kRawSummaryOpt = 'raw-summary';
String kTabTableOpt = 'tsv-table';
String kAsciiTableOpt = 'ascii-table';
void _usage(String error) {
stderr.writeln(error);
stderr.writeln('Usage:\n');
stderr.writeln(_argParser.usage);
exitCode = 1;
}
Future<void> main(List<String> rawArgs) async {
ArgResults args;
try {
args = _argParser.parse(rawArgs);
} on FormatException catch (error) {
_usage('${error.message}\n');
return;
}
final List<String> jsonFiles = args.rest.isNotEmpty ? args.rest : <String>[ 'ABresults.json' ];
for (final String filename in jsonFiles) {
final File file = File(filename);
if (!file.existsSync()) {
_usage('File "$filename" does not exist');
return;
}
ABTest test;
try {
test = ABTest.fromJsonMap(
const JsonDecoder().convert(await file.readAsString()) as Map<String, dynamic>
);
} catch (error) {
_usage('Could not parse json file "$filename"');
return;
}
if (args[kRawSummaryOpt] as bool) {
section('Raw results for "$filename"');
print(test.rawResults());
}
if (args[kTabTableOpt] as bool) {
section('A/B comparison for "$filename"');
print(test.printSummary());
}
if (args[kAsciiTableOpt] as bool) {
section('Formatted summary for "$filename"');
print(test.asciiSummary());
}
}
}
/// Command-line options for the `summarize.dart` command.
final ArgParser _argParser = ArgParser()
..addFlag(
kAsciiTableOpt,
defaultsTo: true,
help: 'Prints the summary in a table formatted nicely for terminal output.',
)
..addFlag(
kTabTableOpt,
defaultsTo: true,
help: 'Prints the summary in a table with tabs for easy spreadsheet entry.',
)
..addFlag(
kRawSummaryOpt,
defaultsTo: true,
help: 'Prints all per-run data collected by the A/B test formatted with\n'
'tabs for easy spreadsheet entry.',
);
| flutter/dev/devicelab/bin/summarize.dart/0 | {
"file_path": "flutter/dev/devicelab/bin/summarize.dart",
"repo_id": "flutter",
"token_count": 860
} | 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 '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;
final String platformLineSep = Platform.isWindows ? '\r\n': '\n';
/// Tests that AARs can be built on module projects.
Future<void> main() async {
await task(() async {
section('Find Java');
final String? javaHome = await findJavaHome();
if (javaHome == null) {
return TaskResult.failure('Could not find Java');
}
print('\nUsing JAVA_HOME=$javaHome');
final Directory tempDir = Directory.systemTemp.createTempSync('flutter_module_test.');
final Directory projectDir = Directory(path.join(tempDir.path, 'hello'));
try {
section('Create module project');
await inDirectory(tempDir, () async {
await flutter(
'create',
options: <String>['--org', 'io.flutter.devicelab', '--template', 'module', 'hello'],
);
});
section('Create plugin that supports android platform');
await inDirectory(tempDir, () async {
await flutter(
'create',
options: <String>['--org', 'io.flutter.devicelab', '--template', 'plugin', '--platforms=android', 'plugin_with_android'],
);
});
section("Create plugin that doesn't support android project");
await inDirectory(tempDir, () async {
await flutter(
'create',
options: <String>['--org', 'io.flutter.devicelab', '--template', 'plugin', '--platforms=ios', 'plugin_without_android'],
);
});
section('Add plugins to pubspec.yaml');
final File modulePubspec = File(path.join(projectDir.path, 'pubspec.yaml'));
String content = modulePubspec.readAsStringSync();
content = content.replaceFirst(
'${platformLineSep}dependencies:$platformLineSep',
'${platformLineSep}dependencies:$platformLineSep'
' plugin_with_android:$platformLineSep'
' path: ../plugin_with_android$platformLineSep'
' plugin_without_android:$platformLineSep'
' path: ../plugin_without_android$platformLineSep'
' webcrypto: 0.5.2$platformLineSep', // Plugin that uses NDK.
);
modulePubspec.writeAsStringSync(content, flush: true);
section('Run packages get in module project');
await inDirectory(projectDir, () async {
await flutter(
'packages',
options: <String>['get'],
);
});
section('Build release AAR');
await inDirectory(projectDir, () async {
await flutter(
'build',
options: <String>['aar', '--verbose'],
);
});
final String repoPath = path.join(
projectDir.path,
'build',
'host',
'outputs',
'repo',
);
section('Check release Maven artifacts');
checkFileExists(path.join(
repoPath,
'io',
'flutter',
'devicelab',
'hello',
'flutter_release',
'1.0',
'flutter_release-1.0.aar',
));
final String releasePom = path.join(
repoPath,
'io',
'flutter',
'devicelab',
'hello',
'flutter_release',
'1.0',
'flutter_release-1.0.pom',
);
checkFileExists(releasePom);
checkFileExists(path.join(
repoPath,
'io',
'flutter',
'devicelab',
'plugin_with_android',
'plugin_with_android_release',
'1.0',
'plugin_with_android_release-1.0.aar',
));
checkFileExists(path.join(
repoPath,
'io',
'flutter',
'devicelab',
'plugin_with_android',
'plugin_with_android_release',
'1.0',
'plugin_with_android_release-1.0.pom',
));
section('Check AOT blobs in release POM');
checkFileContains(<String>[
'flutter_embedding_release',
'armeabi_v7a_release',
'arm64_v8a_release',
'x86_64_release',
'plugin_with_android_release',
], releasePom);
section('Check assets in release AAR');
checkCollectionContains<String>(
<String>[
...flutterAssets,
// AOT snapshots
'jni/arm64-v8a/libapp.so',
'jni/armeabi-v7a/libapp.so',
'jni/x86_64/libapp.so',
],
await getFilesInAar(
path.join(
repoPath,
'io',
'flutter',
'devicelab',
'hello',
'flutter_release',
'1.0',
'flutter_release-1.0.aar',
)
)
);
section('Check debug Maven artifacts');
checkFileExists(path.join(
repoPath,
'io',
'flutter',
'devicelab',
'hello',
'flutter_debug',
'1.0',
'flutter_debug-1.0.aar',
));
final String debugPom = path.join(
repoPath,
'io',
'flutter',
'devicelab',
'hello',
'flutter_debug',
'1.0',
'flutter_debug-1.0.pom',
);
checkFileExists(debugPom);
checkFileExists(path.join(
repoPath,
'io',
'flutter',
'devicelab',
'plugin_with_android',
'plugin_with_android_debug',
'1.0',
'plugin_with_android_debug-1.0.aar',
));
checkFileExists(path.join(
repoPath,
'io',
'flutter',
'devicelab',
'plugin_with_android',
'plugin_with_android_debug',
'1.0',
'plugin_with_android_debug-1.0.pom',
));
section('Check AOT blobs in debug POM');
checkFileContains(<String>[
'flutter_embedding_debug',
'x86_debug',
'x86_64_debug',
'armeabi_v7a_debug',
'arm64_v8a_debug',
'plugin_with_android_debug',
], debugPom);
section('Check assets in debug AAR');
final Iterable<String> debugAar = await getFilesInAar(path.join(
repoPath,
'io',
'flutter',
'devicelab',
'hello',
'flutter_debug',
'1.0',
'flutter_debug-1.0.aar',
));
checkCollectionContains<String>(<String>[
...flutterAssets,
...debugAssets,
], debugAar);
return TaskResult.success(null);
} on TaskResult catch (taskResult) {
return taskResult;
} catch (e) {
return TaskResult.failure(e.toString());
} finally {
rmTree(tempDir);
}
});
}
| flutter/dev/devicelab/bin/tasks/build_aar_module_test.dart/0 | {
"file_path": "flutter/dev/devicelab/bin/tasks/build_aar_module_test.dart",
"repo_id": "flutter",
"token_count": 3313
} | 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 'package:flutter_devicelab/framework/devices.dart';
import 'package:flutter_devicelab/framework/framework.dart';
import 'package:flutter_devicelab/framework/utils.dart';
import 'package:flutter_devicelab/tasks/perf_tests.dart';
const String kPackageName = 'com.example.macrobenchmarks';
class FastScrollHeavyGridViewMemoryTest extends MemoryTest {
FastScrollHeavyGridViewMemoryTest()
: super(
'${flutterDirectory.path}/dev/benchmarks/macrobenchmarks',
'test_memory/heavy_gridview.dart', kPackageName,
);
@override
AndroidDevice? get device => super.device as AndroidDevice?;
@override
int get iterationCount => 5;
@override
Future<void> useMemory() async {
await launchApp();
await recordStart();
await device!.shellExec('input', <String>['swipe', '50 1500 50 50 50']);
await Future<void>.delayed(const Duration(milliseconds: 1500));
await device!.shellExec('input', <String>['swipe', '50 1500 50 50 50']);
await Future<void>.delayed(const Duration(milliseconds: 1500));
await device!.shellExec('input', <String>['swipe', '50 1500 50 50 50']);
await Future<void>.delayed(const Duration(milliseconds: 1500));
await recordEnd();
}
}
Future<void> main() async {
deviceOperatingSystem = DeviceOperatingSystem.android;
await task(FastScrollHeavyGridViewMemoryTest().run);
}
| flutter/dev/devicelab/bin/tasks/fast_scroll_heavy_gridview__memory.dart/0 | {
"file_path": "flutter/dev/devicelab/bin/tasks/fast_scroll_heavy_gridview__memory.dart",
"repo_id": "flutter",
"token_count": 507
} | 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:flutter_devicelab/framework/devices.dart';
import 'package:flutter_devicelab/framework/framework.dart';
import 'package:flutter_devicelab/tasks/integration_tests.dart';
/// Verify that dart defines work on iOS.
Future<void> main() async {
deviceOperatingSystem = DeviceOperatingSystem.ios;
await task(dartDefinesTask());
}
| flutter/dev/devicelab/bin/tasks/ios_defines_test.dart/0 | {
"file_path": "flutter/dev/devicelab/bin/tasks/ios_defines_test.dart",
"repo_id": "flutter",
"token_count": 153
} | 559 |
// 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/utils.dart';
import 'package:flutter_devicelab/tasks/perf_tests.dart';
Future<void> main() async {
deviceOperatingSystem = DeviceOperatingSystem.ios;
await task(() async {
final String platformViewDirectoryPath = '${flutterDirectory.path}/examples/platform_view';
final Directory platformViewDirectory = dir(
platformViewDirectoryPath
);
await inDirectory(platformViewDirectory, () async {
await flutter('pub', options: <String>['get']);
// Pre-cache the iOS artifacts; this may be the first test run on this machine.
await flutter(
'precache',
options: <String>[
'--no-android',
'--no-fuchsia',
'--no-linux',
'--no-macos',
'--no-web',
'--no-windows',
],
);
});
final TaskFunction taskFunction = createPlatformViewStartupTest();
return taskFunction();
});
}
| flutter/dev/devicelab/bin/tasks/platform_view_ios__start_up.dart/0 | {
"file_path": "flutter/dev/devicelab/bin/tasks/platform_view_ios__start_up.dart",
"repo_id": "flutter",
"token_count": 467
} | 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 'package:flutter_devicelab/framework/devices.dart';
import 'package:flutter_devicelab/framework/framework.dart';
import 'package:flutter_devicelab/framework/task_result.dart';
/// Smoke test of a successful task.
Future<void> main() async {
deviceOperatingSystem = DeviceOperatingSystem.fake;
await task(() async {
final Device device = await devices.workingDevice;
if (device.deviceId == 'FAKE_SUCCESS') {
return TaskResult.success(<String, dynamic>{
'metric1': 42,
'metric2': 123,
'not_a_metric': 'something',
}, benchmarkScoreKeys: <String>[
'metric1',
'metric2',
]);
} else {
return TaskResult.failure('Failed');
}
});
}
| flutter/dev/devicelab/bin/tasks/smoke_test_device.dart/0 | {
"file_path": "flutter/dev/devicelab/bin/tasks/smoke_test_device.dart",
"repo_id": "flutter",
"token_count": 327
} | 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 'dart:async';
import 'dart:convert';
import 'dart:developer';
import 'dart:io';
import 'dart:isolate';
import 'package:logging/logging.dart';
import 'package:path/path.dart' as path;
import 'package:process/process.dart';
import 'package:stack_trace/stack_trace.dart';
import 'devices.dart';
import 'host_agent.dart';
import 'running_processes.dart';
import 'task_result.dart';
import 'utils.dart';
/// Identifiers for devices that should never be rebooted.
final Set<String> noRebootForbidList = <String>{
'822ef7958bba573829d85eef4df6cbdd86593730', // 32bit iPhone requires manual intervention on reboot.
};
/// The maximum number of test runs before a device must be rebooted.
///
/// This number was chosen arbitrarily.
const int maximumRuns = 30;
/// Represents a unit of work performed in the CI environment that can
/// succeed, fail and be retried independently of others.
typedef TaskFunction = Future<TaskResult> Function();
bool _isTaskRegistered = false;
/// Registers a [task] to run, returns the result when it is complete.
///
/// The task does not run immediately but waits for the request via the
/// VM service protocol to run it.
///
/// It is OK for a [task] to perform many things. However, only one task can be
/// registered per Dart VM.
///
/// If no `processManager` is provided, a default [LocalProcessManager] is created
/// for the task.
Future<TaskResult> task(TaskFunction task, { ProcessManager? processManager }) async {
if (_isTaskRegistered) {
throw StateError('A task is already registered');
}
_isTaskRegistered = true;
processManager ??= const LocalProcessManager();
// TODO(ianh): allow overriding logging.
Logger.root.level = Level.ALL;
Logger.root.onRecord.listen((LogRecord rec) {
print('${rec.level.name}: ${rec.time}: ${rec.message}');
});
final _TaskRunner runner = _TaskRunner(task, processManager);
runner.keepVmAliveUntilTaskRunRequested();
return runner.whenDone;
}
class _TaskRunner {
_TaskRunner(this.task, this.processManager) {
registerExtension('ext.cocoonRunTask',
(String method, Map<String, String> parameters) async {
final Duration? taskTimeout = parameters.containsKey('timeoutInMinutes')
? Duration(minutes: int.parse(parameters['timeoutInMinutes']!))
: null;
final bool runFlutterConfig = parameters['runFlutterConfig'] != 'false'; // used by tests to avoid changing the configuration
final bool runProcessCleanup = parameters['runProcessCleanup'] != 'false';
final String? localEngine = parameters['localEngine'];
final String? localEngineHost = parameters['localEngineHost'];
final TaskResult result = await run(
taskTimeout,
runProcessCleanup: runProcessCleanup,
runFlutterConfig: runFlutterConfig,
localEngine: localEngine,
localEngineHost: localEngineHost,
);
return ServiceExtensionResponse.result(json.encode(result.toJson()));
});
registerExtension('ext.cocoonRunnerReady',
(String method, Map<String, String> parameters) async {
return ServiceExtensionResponse.result('"ready"');
});
}
final TaskFunction task;
final ProcessManager processManager;
Future<Device?> _getWorkingDeviceIfAvailable() async {
try {
return await devices.workingDevice;
} on DeviceException {
return null;
}
}
// TODO(ianh): workaround for https://github.com/dart-lang/sdk/issues/23797
RawReceivePort? _keepAlivePort;
Timer? _startTaskTimeout;
bool _taskStarted = false;
final Completer<TaskResult> _completer = Completer<TaskResult>();
static final Logger logger = Logger('TaskRunner');
/// Signals that this task runner finished running the task.
Future<TaskResult> get whenDone => _completer.future;
Future<TaskResult> run(Duration? taskTimeout, {
bool runFlutterConfig = true,
bool runProcessCleanup = true,
required String? localEngine,
required String? localEngineHost,
}) async {
try {
_taskStarted = true;
print('Running task with a timeout of $taskTimeout.');
final String exe = Platform.isWindows ? '.exe' : '';
late Set<RunningProcessInfo> beforeRunningDartInstances;
if (runProcessCleanup) {
section('Checking running Dart$exe processes');
beforeRunningDartInstances = await getRunningProcesses(
processName: 'dart$exe',
processManager: processManager,
);
final Set<RunningProcessInfo> allProcesses = await getRunningProcesses(processManager: processManager);
beforeRunningDartInstances.forEach(print);
for (final RunningProcessInfo info in allProcesses) {
if (info.commandLine.contains('iproxy')) {
print('[LEAK]: ${info.commandLine} ${info.creationDate} ${info.pid} ');
}
}
}
if (runFlutterConfig) {
print('Enabling configs for macOS and Linux...');
final int configResult = await exec(path.join(flutterDirectory.path, 'bin', 'flutter'), <String>[
'config',
'-v',
'--enable-macos-desktop',
'--enable-linux-desktop',
if (localEngine != null) ...<String>['--local-engine', localEngine],
if (localEngineHost != null) ...<String>['--local-engine-host', localEngineHost],
], canFail: true);
if (configResult != 0) {
print('Failed to enable configuration, tasks may not run.');
}
}
final Device? device = await _getWorkingDeviceIfAvailable();
// Some tests assume the phone is in home
await device?.home();
late TaskResult result;
IOSink? sink;
try {
if (device != null && device.canStreamLogs && hostAgent.dumpDirectory != null) {
sink = File(path.join(hostAgent.dumpDirectory!.path, '${device.deviceId}.log')).openWrite();
await device.startLoggingToSink(sink);
}
Future<TaskResult> futureResult = _performTask();
if (taskTimeout != null) {
futureResult = futureResult.timeout(taskTimeout);
}
result = await futureResult;
} finally {
if (device != null && device.canStreamLogs) {
await device.stopLoggingToSink();
await sink?.close();
}
}
if (runProcessCleanup) {
section('Terminating lingering Dart$exe processes after task...');
final Set<RunningProcessInfo> afterRunningDartInstances = await getRunningProcesses(
processName: 'dart$exe',
processManager: processManager,
);
for (final RunningProcessInfo info in afterRunningDartInstances) {
if (!beforeRunningDartInstances.contains(info)) {
print('$info was leaked by this test.');
if (result is TaskResultCheckProcesses) {
result = TaskResult.failure('This test leaked dart processes');
}
if (await info.terminate(processManager: processManager)) {
print('Killed process id ${info.pid}.');
} else {
print('Failed to kill process ${info.pid}.');
}
}
}
}
_completer.complete(result);
return result;
} on TimeoutException catch (err, stackTrace) {
print('Task timed out in framework.dart after $taskTimeout.');
print(err);
print(stackTrace);
return TaskResult.failure('Task timed out after $taskTimeout');
} finally {
await checkForRebootRequired();
await forceQuitRunningProcesses();
_closeKeepAlivePort();
}
}
Future<void> checkForRebootRequired() async {
print('Checking for reboot');
try {
final Device device = await devices.workingDevice;
if (noRebootForbidList.contains(device.deviceId)) {
return;
}
final File rebootFile = _rebootFile();
int runCount;
if (rebootFile.existsSync()) {
runCount = int.tryParse(rebootFile.readAsStringSync().trim()) ?? 0;
} else {
runCount = 0;
}
if (runCount < maximumRuns) {
rebootFile
..createSync()
..writeAsStringSync((runCount + 1).toString());
return;
}
rebootFile.deleteSync();
print('rebooting');
await device.reboot();
} on TimeoutException {
// Could not find device in order to reboot.
} on DeviceException {
// No attached device needed to reboot.
}
}
/// Causes the Dart VM to stay alive until a request to run the task is
/// received via the VM service protocol.
void keepVmAliveUntilTaskRunRequested() {
if (_taskStarted) {
throw StateError('Task already started.');
}
// Merely creating this port object will cause the VM to stay alive and keep
// the VM service server running until the port is disposed of.
_keepAlivePort = RawReceivePort();
// Timeout if nothing bothers to connect and ask us to run the task.
const Duration taskStartTimeout = Duration(seconds: 60);
_startTaskTimeout = Timer(taskStartTimeout, () {
if (!_taskStarted) {
logger.severe('Task did not start in $taskStartTimeout.');
_closeKeepAlivePort();
exitCode = 1;
}
});
}
/// Disables the keepalive port, allowing the VM to exit.
void _closeKeepAlivePort() {
_startTaskTimeout?.cancel();
_keepAlivePort?.close();
}
Future<TaskResult> _performTask() {
final Completer<TaskResult> completer = Completer<TaskResult>();
Chain.capture(() async {
completer.complete(await task());
}, onError: (dynamic taskError, Chain taskErrorStack) {
final String message = 'Task failed: $taskError';
stderr
..writeln(message)
..writeln('\nStack trace:')
..writeln(taskErrorStack.terse);
// IMPORTANT: We're completing the future _successfully_ but with a value
// that indicates a task failure. This is intentional. At this point we
// are catching errors coming from arbitrary (and untrustworthy) task
// code. Our goal is to convert the failure into a readable message.
// Propagating it further is not useful.
if (!completer.isCompleted) {
completer.complete(TaskResult.failure(message));
}
});
return completer.future;
}
}
File _rebootFile() {
if (Platform.isLinux || Platform.isMacOS) {
return File(path.join(Platform.environment['HOME']!, '.reboot-count'));
}
if (!Platform.isWindows) {
throw StateError('Unexpected platform ${Platform.operatingSystem}');
}
return File(path.join(Platform.environment['USERPROFILE']!, '.reboot-count'));
}
| flutter/dev/devicelab/lib/framework/framework.dart/0 | {
"file_path": "flutter/dev/devicelab/lib/framework/framework.dart",
"repo_id": "flutter",
"token_count": 3931
} | 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 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:path/path.dart' as path;
import '../framework/framework.dart';
import '../framework/task_result.dart';
import '../framework/utils.dart';
TaskFunction dartPluginRegistryTest({
String? deviceIdOverride,
Map<String, String>? environment,
}) {
final Directory tempDir = Directory.systemTemp
.createTempSync('flutter_devicelab_dart_plugin_test.');
return () async {
try {
section('Create implementation plugin');
await inDirectory(tempDir, () async {
await flutter(
'create',
options: <String>[
'--template=plugin',
'--org',
'io.flutter.devicelab',
'--platforms',
'macos',
'aplugin_platform_implementation',
],
environment: environment,
);
});
final File pluginMain = File(path.join(
tempDir.absolute.path,
'aplugin_platform_implementation',
'lib',
'aplugin_platform_implementation.dart',
));
if (!pluginMain.existsSync()) {
return TaskResult.failure('${pluginMain.path} does not exist');
}
// Patch plugin main dart file.
await pluginMain.writeAsString('''
class ApluginPlatformInterfaceMacOS {
static void registerWith() {
print('ApluginPlatformInterfaceMacOS.registerWith() was called');
}
}
''', flush: true);
// Patch plugin main pubspec file.
final File pluginImplPubspec = File(path.join(
tempDir.absolute.path,
'aplugin_platform_implementation',
'pubspec.yaml',
));
String pluginImplPubspecContent = await pluginImplPubspec.readAsString();
pluginImplPubspecContent = pluginImplPubspecContent.replaceFirst(
' pluginClass: ApluginPlatformImplementationPlugin',
' pluginClass: ApluginPlatformImplementationPlugin\n'
' dartPluginClass: ApluginPlatformInterfaceMacOS\n',
);
pluginImplPubspecContent = pluginImplPubspecContent.replaceFirst(
' platforms:\n',
' implements: aplugin_platform_interface\n'
' platforms:\n');
await pluginImplPubspec.writeAsString(pluginImplPubspecContent,
flush: true);
section('Create interface plugin');
await inDirectory(tempDir, () async {
await flutter(
'create',
options: <String>[
'--template=plugin',
'--org',
'io.flutter.devicelab',
'--platforms',
'macos',
'aplugin_platform_interface',
],
environment: environment,
);
});
final File pluginInterfacePubspec = File(path.join(
tempDir.absolute.path,
'aplugin_platform_interface',
'pubspec.yaml',
));
String pluginInterfacePubspecContent =
await pluginInterfacePubspec.readAsString();
pluginInterfacePubspecContent =
pluginInterfacePubspecContent.replaceFirst(
' pluginClass: ApluginPlatformInterfacePlugin',
' default_package: aplugin_platform_implementation\n');
pluginInterfacePubspecContent =
pluginInterfacePubspecContent.replaceFirst(
'dependencies:',
'dependencies:\n'
' aplugin_platform_implementation:\n'
' path: ../aplugin_platform_implementation\n');
await pluginInterfacePubspec.writeAsString(pluginInterfacePubspecContent,
flush: true);
section('Create app');
await inDirectory(tempDir, () async {
await flutter(
'create',
options: <String>[
'--template=app',
'--org',
'io.flutter.devicelab',
'--platforms',
'macos',
'app',
],
environment: environment,
);
});
final File appPubspec = File(path.join(
tempDir.absolute.path,
'app',
'pubspec.yaml',
));
String appPubspecContent = await appPubspec.readAsString();
appPubspecContent = appPubspecContent.replaceFirst(
'dependencies:',
'dependencies:\n'
' aplugin_platform_interface:\n'
' path: ../aplugin_platform_interface\n');
await appPubspec.writeAsString(appPubspecContent, flush: true);
section('Flutter run for macos');
late Process run;
await inDirectory(path.join(tempDir.path, 'app'), () async {
run = await startFlutter(
'run',
options: <String>['-d', 'macos', '-v'],
);
});
Completer<void> registryExecutedCompleter = Completer<void>();
final StreamSubscription<void> stdoutSub = run.stdout
.transform<String>(utf8.decoder)
.transform<String>(const LineSplitter())
.listen((String line) {
if (line.contains('ApluginPlatformInterfaceMacOS.registerWith() was called')) {
registryExecutedCompleter.complete();
}
print('stdout: $line');
});
final StreamSubscription<void> stderrSub = run.stderr
.transform<String>(utf8.decoder)
.transform<String>(const LineSplitter())
.listen((String line) {
print('stderr: $line');
});
final Future<void> stdoutDone = stdoutSub.asFuture<void>();
final Future<void> stderrDone = stderrSub.asFuture<void>();
Future<void> waitForStreams() {
return Future.wait<void>(<Future<void>>[stdoutDone, stderrDone]);
}
Future<void> waitOrExit(Future<void> future) async {
final dynamic result = await Future.any<dynamic>(
<Future<dynamic>>[
future,
run.exitCode,
],
);
if (result is int) {
await waitForStreams();
throw 'process exited with code $result';
}
}
section('Wait for registry execution');
await waitOrExit(registryExecutedCompleter.future);
// Hot restart.
run.stdin.write('R');
await run.stdin.flush();
await run.stdin.close();
registryExecutedCompleter = Completer<void>();
section('Wait for registry execution after hot restart');
await waitOrExit(registryExecutedCompleter.future);
run.kill();
section('Wait for stdout/stderr streams');
await waitForStreams();
unawaited(stdoutSub.cancel());
unawaited(stderrSub.cancel());
return TaskResult.success(null);
} finally {
rmTree(tempDir);
}
};
}
| flutter/dev/devicelab/lib/tasks/dart_plugin_registry_tests.dart/0 | {
"file_path": "flutter/dev/devicelab/lib/tasks/dart_plugin_registry_tests.dart",
"repo_id": "flutter",
"token_count": 2963
} | 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_devicelab/framework/ab.dart';
import 'package:flutter_devicelab/framework/task_result.dart';
import 'common.dart';
void main() {
test('ABTest', () {
final ABTest ab = ABTest(localEngine: 'engine', localEngineHost: 'engine', taskName: 'test');
for (int i = 0; i < 5; i++) {
final TaskResult aResult = TaskResult.fromJson(<String, dynamic>{
'success': true,
'data': <String, dynamic>{
'i': i,
'j': 10 * i,
'not_a_metric': 'something',
},
'benchmarkScoreKeys': <String>['i', 'j'],
});
ab.addAResult(aResult);
final TaskResult bResult = TaskResult.fromJson(<String, dynamic>{
'success': true,
'data': <String, dynamic>{
'i': i + 1,
'k': 10 * i + 1,
},
'benchmarkScoreKeys': <String>['i', 'k'],
});
ab.addBResult(bResult);
}
ab.finalize();
expect(
ab.rawResults(),
'i:\n'
' A:\t0.00\t1.00\t2.00\t3.00\t4.00\t\n'
' B:\t1.00\t2.00\t3.00\t4.00\t5.00\t\n'
'j:\n'
' A:\t0.00\t10.00\t20.00\t30.00\t40.00\t\n'
' B:\tN/A\n'
'k:\n'
' A:\tN/A\n'
' B:\t1.00\t11.00\t21.00\t31.00\t41.00\t\n',
);
expect(
ab.printSummary(),
'Score\tAverage A (noise)\tAverage B (noise)\tSpeed-up\n'
'i\t2.00 (70.71%)\t3.00 (47.14%)\t0.67x\t\n'
'j\t20.00 (70.71%)\t\t\n'
'k\t\t21.00 (67.34%)\t\n');
});
}
| flutter/dev/devicelab/test/ab_test.dart/0 | {
"file_path": "flutter/dev/devicelab/test/ab_test.dart",
"repo_id": "flutter",
"token_count": 877
} | 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.
apply plugin: 'com.android.application'
android {
compileSdk 34
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
defaultConfig {
applicationId "io.flutter.add2app"
minSdkVersion 21
targetSdkVersion 34
versionCode 1
versionName "1.0"
}
}
dependencies {
implementation project(':flutter')
implementation 'androidx.appcompat:appcompat:1.1.0'
}
| flutter/dev/integration_tests/android_custom_host_app/SampleApp/build.gradle/0 | {
"file_path": "flutter/dev/integration_tests/android_custom_host_app/SampleApp/build.gradle",
"repo_id": "flutter",
"token_count": 242
} | 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';
import 'headings_constants.dart';
export 'headings_constants.dart';
/// A test page with an app bar and some body text for testing heading flags.
class HeadingsPage extends StatelessWidget {
const HeadingsPage({super.key});
static const ValueKey<String> _appBarTitleKey = ValueKey<String>(appBarTitleKeyValue);
static const ValueKey<String> _bodyTextKey = ValueKey<String>(bodyTextKeyValue);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
leading: const BackButton(key: ValueKey<String>('back')),
title: const Text('Heading', key: _appBarTitleKey),
),
body: const Center(
child: Text('Body text', key: _bodyTextKey),
),
);
}
}
| flutter/dev/integration_tests/android_semantics_testing/lib/src/tests/headings_page.dart/0 | {
"file_path": "flutter/dev/integration_tests/android_semantics_testing/lib/src/tests/headings_page.dart",
"repo_id": "flutter",
"token_count": 313
} | 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.
package io.flutter.integration.android_verified_input;
import android.content.Context;
import android.hardware.input.InputManager;
import android.os.Build;
import android.view.MotionEvent;
import android.view.VerifiedInputEvent;
import android.view.View;
import android.widget.Button;
import androidx.annotation.NonNull;
import java.util.Map;
import io.flutter.Log;
import io.flutter.plugin.platform.PlatformView;
class VerifiedInputView implements PlatformView {
private static final String TAG = "VerifiedInputView";
@NonNull
private final Button mButton;
VerifiedInputView(@NonNull Context context, @NonNull Map<String, Object> creationParams) {
mButton = new Button(context);
mButton.setText("click me");
mButton.setOnTouchListener(
(view, event) -> {
if (MotionEvent.ACTION_DOWN == event.getAction()) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
InputManager inputManager = context.getSystemService(InputManager.class);
VerifiedInputEvent verify = inputManager.verifyInputEvent(event);
// If verifyInputEvent returns an object, the input event was verified
final boolean verified = (verify != null);
Log.i(TAG, "VerifiedInputEvent is verified : " + verified);
// Notify the test harness whether or not the input event was verified.
MainActivity.mMethodChannel.invokeMethod("notify_verified_input", verified);
if (verified) {
mButton.setBackgroundColor(context.getColor(R.color.green));
mButton.setText("click me (verified)");
} else {
mButton.setBackgroundColor(context.getColor(R.color.red));
mButton.setText("click me (verification failed)");
}
}
return true;
}
return false;
});
}
@NonNull
@Override
public View getView() {
return mButton;
}
@Override
public void dispose() {
}
}
| flutter/dev/integration_tests/android_verified_input/android/app/src/main/java/io/flutter/integration/android_verified_input/VerifiedInputView.java/0 | {
"file_path": "flutter/dev/integration_tests/android_verified_input/android/app/src/main/java/io/flutter/integration/android_verified_input/VerifiedInputView.java",
"repo_id": "flutter",
"token_count": 1162
} | 567 |
name: android_verified_input
description: "An integration test for verified MotionEvents."
publish_to: 'none' # Remove this line if you wish to publish to pub.dev
version: 1.0.0+1
environment:
sdk: '>=3.2.0-0 <4.0.0'
# Dependencies specify other packages that your package needs in order to work.
# To automatically upgrade your package dependencies to the latest versions
# consider running `flutter pub upgrade --major-versions`. Alternatively,
# dependencies can be manually updated by changing the version numbers below to
# the latest version available on pub.dev. To see which dependencies have newer
# versions available, run `flutter pub outdated`.
dependencies:
flutter:
sdk: flutter
flutter_driver:
sdk: flutter
async: 2.11.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
boolean_selector: 2.1.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
characters: 1.3.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
collection: 1.18.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
file: 7.0.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
matcher: 0.12.16+1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
material_color_utilities: 0.8.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
meta: 1.12.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
path: 1.9.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
source_span: 1.10.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
stack_trace: 1.11.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
stream_channel: 2.1.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
string_scanner: 1.2.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
sync_http: 0.3.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
term_glyph: 1.2.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
test_api: 0.7.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
vector_math: 2.1.4 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
vm_service: 14.2.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
webdriver: 3.0.3 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
dev_dependencies:
flutter_test:
sdk: flutter
test: 1.25.2
_fe_analyzer_shared: 67.0.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
analyzer: 6.4.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
args: 2.4.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
clock: 1.1.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
convert: 3.1.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
coverage: 1.7.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
crypto: 3.0.3 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
fake_async: 1.3.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
frontend_server_client: 3.2.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
glob: 2.1.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
http_multi_server: 3.2.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
http_parser: 4.0.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
io: 1.0.4 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
js: 0.7.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
leak_tracker: 10.0.4 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
leak_tracker_flutter_testing: 3.0.3 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
leak_tracker_testing: 3.0.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
logging: 1.2.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
mime: 1.0.5 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
node_preamble: 2.0.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
package_config: 2.1.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
pool: 1.5.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
pub_semver: 2.1.4 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
shelf: 1.4.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
shelf_packages_handler: 3.0.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
shelf_static: 1.1.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
shelf_web_socket: 1.0.4 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
source_map_stack_trace: 2.1.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
source_maps: 0.10.12 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
test_core: 0.6.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
typed_data: 1.3.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
watcher: 1.1.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
web: 0.5.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
web_socket_channel: 2.4.4 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
webkit_inspection_protocol: 1.2.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
yaml: 3.1.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
# PUBSPEC CHECKSUM: 6c23
| flutter/dev/integration_tests/android_verified_input/pubspec.yaml/0 | {
"file_path": "flutter/dev/integration_tests/android_verified_input/pubspec.yaml",
"repo_id": "flutter",
"token_count": 2229
} | 568 |
// 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:channels/main.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
final Finder statusField = find.byKey(const ValueKey<String>('status'));
final Finder stepButton = find.byKey(const ValueKey<String>('step'));
String getStatus(WidgetTester tester) => tester.widget<Text>(statusField).data!;
void main() {
testWidgets('step through', (WidgetTester tester) async {
await tester.pumpWidget(const TestApp());
await tester.pumpAndSettle();
int step = -1;
while (getStatus(tester) == 'ok') {
step++;
print('>> Tapping for step $step...');
// TODO(goderbauer): Setting the pointer ID to something large to avoid
// that the test events clash with ghost events from the device to
// further investigate https://github.com/flutter/flutter/issues/116663.
await tester.tap(stepButton, pointer: 500 + step);
await tester.pump();
expect(statusField, findsNothing);
print('>> Waiting for step $step to complete...');
while (tester.widgetList(statusField).isEmpty) {
await tester.pumpAndSettle();
}
}
final String status = getStatus(tester);
if (status != 'complete') {
fail('Failed at step $step with status $status');
}
});
}
| flutter/dev/integration_tests/channels/integration_test/main_test.dart/0 | {
"file_path": "flutter/dev/integration_tests/channels/integration_test/main_test.dart",
"repo_id": "flutter",
"token_count": 509
} | 569 |
# Deferred components integration test app
## Setup
This integration test app requires manually downloading additional assets to build. Run
`./download_assets.sh`
before running any of the tests.
## Tests
This app contains two sets of tests:
* `flutter drive` tests that run a debug mode app to validate framework side logic
* `run_release_test.sh <bundletool.jar path>` which builds and installs a release version of this app and
validates the loading units are loaded correctly. A path to bundletool.jar must be provided
| flutter/dev/integration_tests/deferred_components_test/README.md/0 | {
"file_path": "flutter/dev/integration_tests/deferred_components_test/README.md",
"repo_id": "flutter",
"token_count": 133
} | 570 |
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.4-all.zip
| flutter/dev/integration_tests/flavors/android/gradle/wrapper/gradle-wrapper.properties/0 | {
"file_path": "flutter/dev/integration_tests/flavors/android/gradle/wrapper/gradle-wrapper.properties",
"repo_id": "flutter",
"token_count": 71
} | 571 |
<!-- 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. -->
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<!-- The INTERNET permission is required for development. Specifically,
flutter needs it to communicate with the running application
to allow setting breakpoints, to provide hot reload, etc.
-->
<uses-permission android:name="android.permission.INTERNET"/>
<application android:label="Gallery" android:icon="@mipmap/ic_launcher" android:name="${applicationName}">
<activity android:name=".MainActivity"
android:theme="@android:style/Theme.Light.NoTitleBar"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:exported="true"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<!-- Don't delete the meta-data below.
This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
<meta-data
android:name="flutterEmbedding"
android:value="2" />
</application>
<!-- Required to query activities that can process text, see:
https://developer.android.com/training/package-visibility and
https://developer.android.com/reference/android/content/Intent#ACTION_PROCESS_TEXT.
In particular, this is used by the Flutter engine in io.flutter.plugin.text.ProcessTextPlugin. -->
<queries>
<intent>
<action android:name="android.intent.action.PROCESS_TEXT"/>
<data android:mimeType="text/plain"/>
</intent>
</queries>
</manifest>
| flutter/dev/integration_tests/flutter_gallery/android/app/src/main/AndroidManifest.xml/0 | {
"file_path": "flutter/dev/integration_tests/flutter_gallery/android/app/src/main/AndroidManifest.xml",
"repo_id": "flutter",
"token_count": 793
} | 572 |
// 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.
/// A token that composes an expression. There are several kinds of tokens
/// that represent arithmetic operation symbols, numbers and pieces of numbers.
/// We need to represent pieces of numbers because the user may have only
/// entered a partial expression so far.
class ExpressionToken {
ExpressionToken(this.stringRep);
final String? stringRep;
@override
String toString() => stringRep!;
}
/// A token that represents a number.
class NumberToken extends ExpressionToken {
NumberToken(String super.stringRep, this.number);
NumberToken.fromNumber(num number) : this('$number', number);
final num number;
}
/// A token that represents an integer.
class IntToken extends NumberToken {
IntToken(String stringRep) : super(stringRep, int.parse(stringRep));
}
/// A token that represents a floating point number.
class FloatToken extends NumberToken {
FloatToken(String stringRep) : super(stringRep, _parse(stringRep));
static double _parse(String stringRep) {
String toParse = stringRep;
if (toParse.startsWith('.')) {
toParse = '0$toParse';
}
if (toParse.endsWith('.')) {
toParse = '${toParse}0';
}
return double.parse(toParse);
}
}
/// A token that represents a number that is the result of a computation.
class ResultToken extends NumberToken {
ResultToken(num number) : super.fromNumber(round(number));
/// rounds `number` to 14 digits of precision. A double precision
/// floating point number is guaranteed to have at least this many
/// decimal digits of precision.
static num round(num number) {
if (number is int) {
return number;
}
return double.parse(number.toStringAsPrecision(14));
}
}
/// A token that represents the unary minus prefix.
class LeadingNegToken extends ExpressionToken {
LeadingNegToken() : super('-');
}
enum Operation { Addition, Subtraction, Multiplication, Division }
/// A token that represents an arithmetic operation symbol.
class OperationToken extends ExpressionToken {
OperationToken(this.operation)
: super(opString(operation));
Operation operation;
static String? opString(Operation operation) {
return switch (operation) {
Operation.Addition => ' + ',
Operation.Subtraction => ' - ',
Operation.Multiplication => ' \u00D7 ',
Operation.Division => ' \u00F7 ',
};
}
}
/// As the user taps different keys the current expression can be in one
/// of several states.
enum ExpressionState {
/// The expression is empty or an operation symbol was just entered.
/// A new number must be started now.
Start,
/// A minus sign was entered as a leading negative prefix.
LeadingNeg,
/// We are in the midst of a number without a point.
Number,
/// A point was just entered.
Point,
/// We are in the midst of a number with a point.
NumberWithPoint,
/// A result is being displayed
Result,
}
/// An expression that can be displayed in a calculator. It is the result
/// of a sequence of user entries. It is represented by a sequence of tokens.
///
/// The tokens are not in one to one correspondence with the key taps because we
/// use one token per number, not one token per digit. A [CalcExpression] is
/// immutable. The `append*` methods return a new [CalcExpression] that
/// represents the appropriate expression when one additional key tap occurs.
class CalcExpression {
CalcExpression(this._list, this.state);
CalcExpression.empty()
: this(<ExpressionToken>[], ExpressionState.Start);
CalcExpression.result(FloatToken result)
: _list = <ExpressionToken?>[],
state = ExpressionState.Result {
_list.add(result);
}
/// The tokens comprising the expression.
final List<ExpressionToken?> _list;
/// The state of the expression.
final ExpressionState state;
/// The string representation of the expression. This will be displayed
/// in the calculator's display panel.
@override
String toString() {
final StringBuffer buffer = StringBuffer();
buffer.writeAll(_list);
return buffer.toString();
}
/// Append a digit to the current expression and return a new expression
/// representing the result. Returns null to indicate that it is not legal
/// to append a digit in the current state.
CalcExpression? appendDigit(int digit) {
ExpressionState newState = ExpressionState.Number;
ExpressionToken? newToken;
final List<ExpressionToken?> outList = _list.toList();
switch (state) {
case ExpressionState.Start:
// Start a new number with digit.
newToken = IntToken('$digit');
case ExpressionState.LeadingNeg:
// Replace the leading neg with a negative number starting with digit.
outList.removeLast();
newToken = IntToken('-$digit');
case ExpressionState.Number:
final ExpressionToken last = outList.removeLast()!;
newToken = IntToken('${last.stringRep}$digit');
case ExpressionState.Point:
case ExpressionState.NumberWithPoint:
final ExpressionToken last = outList.removeLast()!;
newState = ExpressionState.NumberWithPoint;
newToken = FloatToken('${last.stringRep}$digit');
case ExpressionState.Result:
// Cannot enter a number now
return null;
}
outList.add(newToken);
return CalcExpression(outList, newState);
}
/// Append a point to the current expression and return a new expression
/// representing the result. Returns null to indicate that it is not legal
/// to append a point in the current state.
CalcExpression? appendPoint() {
ExpressionToken? newToken;
final List<ExpressionToken?> outList = _list.toList();
switch (state) {
case ExpressionState.Start:
newToken = FloatToken('.');
case ExpressionState.LeadingNeg:
case ExpressionState.Number:
final ExpressionToken last = outList.removeLast()!;
final String value = last.stringRep!;
newToken = FloatToken('$value.');
case ExpressionState.Point:
case ExpressionState.NumberWithPoint:
case ExpressionState.Result:
// Cannot enter a point now
return null;
}
outList.add(newToken);
return CalcExpression(outList, ExpressionState.Point);
}
/// Append an operation symbol to the current expression and return a new
/// expression representing the result. Returns null to indicate that it is not
/// legal to append an operation symbol in the current state.
CalcExpression? appendOperation(Operation op) {
switch (state) {
case ExpressionState.Start:
case ExpressionState.LeadingNeg:
case ExpressionState.Point:
// Cannot enter operation now.
return null;
case ExpressionState.Number:
case ExpressionState.NumberWithPoint:
case ExpressionState.Result:
break;
}
final List<ExpressionToken?> outList = _list.toList();
outList.add(OperationToken(op));
return CalcExpression(outList, ExpressionState.Start);
}
/// Append a leading minus sign to the current expression and return a new
/// expression representing the result. Returns null to indicate that it is not
/// legal to append a leading minus sign in the current state.
CalcExpression? appendLeadingNeg() {
switch (state) {
case ExpressionState.Start:
break;
case ExpressionState.LeadingNeg:
case ExpressionState.Point:
case ExpressionState.Number:
case ExpressionState.NumberWithPoint:
case ExpressionState.Result:
// Cannot enter leading neg now.
return null;
}
final List<ExpressionToken?> outList = _list.toList();
outList.add(LeadingNegToken());
return CalcExpression(outList, ExpressionState.LeadingNeg);
}
/// Append a minus sign to the current expression and return a new expression
/// representing the result. Returns null to indicate that it is not legal
/// to append a minus sign in the current state. Depending on the current
/// state the minus sign will be interpreted as either a leading negative
/// sign or a subtraction operation.
CalcExpression? appendMinus() {
switch (state) {
case ExpressionState.Start:
return appendLeadingNeg();
case ExpressionState.LeadingNeg:
case ExpressionState.Point:
case ExpressionState.Number:
case ExpressionState.NumberWithPoint:
case ExpressionState.Result:
return appendOperation(Operation.Subtraction);
}
}
/// Computes the result of the current expression and returns a new
/// ResultExpression containing the result. Returns null to indicate that
/// it is not legal to compute a result in the current state.
CalcExpression? computeResult() {
switch (state) {
case ExpressionState.Start:
case ExpressionState.LeadingNeg:
case ExpressionState.Point:
case ExpressionState.Result:
// Cannot compute result now.
return null;
case ExpressionState.Number:
case ExpressionState.NumberWithPoint:
break;
}
// We make a copy of _list because CalcExpressions are supposed to
// be immutable.
final List<ExpressionToken?> list = _list.toList();
// We obey order-of-operations by computing the sum of the 'terms',
// where a "term" is defined to be a sequence of numbers separated by
// multiplication or division symbols.
num currentTermValue = removeNextTerm(list);
while (list.isNotEmpty) {
final OperationToken opToken = list.removeAt(0)! as OperationToken;
final num nextTermValue = removeNextTerm(list);
switch (opToken.operation) {
case Operation.Addition:
currentTermValue += nextTermValue;
case Operation.Subtraction:
currentTermValue -= nextTermValue;
case Operation.Multiplication:
case Operation.Division:
// Logic error.
assert(false);
}
}
final List<ExpressionToken> outList = <ExpressionToken>[
ResultToken(currentTermValue),
];
return CalcExpression(outList, ExpressionState.Result);
}
/// Removes the next "term" from `list` and returns its numeric value.
/// A "term" is a sequence of number tokens separated by multiplication
/// and division symbols.
static num removeNextTerm(List<ExpressionToken?> list) {
assert(list.isNotEmpty);
final NumberToken firstNumToken = list.removeAt(0)! as NumberToken;
num currentValue = firstNumToken.number;
while (list.isNotEmpty) {
bool isDivision = false;
final OperationToken nextOpToken = list.first! as OperationToken;
switch (nextOpToken.operation) {
case Operation.Addition:
case Operation.Subtraction:
// We have reached the end of the current term
return currentValue;
case Operation.Multiplication:
break;
case Operation.Division:
isDivision = true;
}
// Remove the operation token.
list.removeAt(0);
// Remove the next number token.
final NumberToken nextNumToken = list.removeAt(0)! as NumberToken;
final num nextNumber = nextNumToken.number;
if (isDivision) {
currentValue /= nextNumber;
} else {
currentValue *= nextNumber;
}
}
return currentValue;
}
}
| flutter/dev/integration_tests/flutter_gallery/lib/demo/calculator/logic.dart/0 | {
"file_path": "flutter/dev/integration_tests/flutter_gallery/lib/demo/calculator/logic.dart",
"repo_id": "flutter",
"token_count": 3678
} | 573 |
// 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 FortnightlyDemo extends StatelessWidget {
const FortnightlyDemo({super.key});
static const String routeName = '/fortnightly';
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Fortnightly Demo',
theme: _fortnightlyTheme,
home: Scaffold(
body: Stack(
children: <Widget>[
const FruitPage(),
SafeArea(
child: ShortAppBar(
onBackPressed: () {
Navigator.pop(context);
},
),
),
],
),
),
);
}
}
class ShortAppBar extends StatelessWidget {
const ShortAppBar({ super.key, this.onBackPressed });
final VoidCallback? onBackPressed;
@override
Widget build(BuildContext context) {
return SizedBox(
width: 96,
height: 50,
child: Material(
color: Theme.of(context).colorScheme.surface,
elevation: 4,
shape: const BeveledRectangleBorder(
borderRadius: BorderRadius.only(bottomRight: Radius.circular(22)),
),
child: Row(
children: <Widget>[
IconButton(
icon: const Icon(Icons.arrow_back),
tooltip: 'Back',
onPressed: onBackPressed,
),
const SizedBox(width: 12),
Image.asset(
'logos/fortnightly/fortnightly_logo.png',
package: 'flutter_gallery_assets',
),
],
),
),
);
}
}
class FruitPage extends StatelessWidget {
const FruitPage({super.key});
static final String paragraph1 = '''
Have you ever held a quince? It's strange;
covered in a fuzz somewhere between peach skin and a spider web. And it's
hard as soft lumber. You'd be forgiven for thinking it's veneered Larch-wood.
But inhale the aroma and you'll instantly know you have something wonderful.
Its scent can fill a room for days. And all this before you've even cooked it.
'''.replaceAll('\n', ' ');
static final String paragraph2 = '''
Pomegranates on the other hand have become
almost ubiquitous. You can find its juice in any bodega, Walmart, and even some
gas stations. But at what cost? The pomegranate juice craze of the aughts made
"megafarmers" Lynda and Stewart Resnick billions. Unfortunately, it takes a lot
of water to make that much pomegranate juice. Water the Resnicks get from their
majority stake in the Kern Water Bank. How did one family come to hold control
over water meant for the whole central valley of California? The story will shock you.
'''.replaceAll('\n', ' ');
@override
Widget build(BuildContext context) {
final TextTheme textTheme = Theme.of(context).primaryTextTheme;
return SingleChildScrollView(
child: SafeArea(
top: false,
child: ColoredBox(
color: Theme.of(context).colorScheme.surface,
child: Column(
children: <Widget>[
Container(
constraints: const BoxConstraints.expand(height: 248),
child: Image.asset(
'food/fruits.png',
package: 'flutter_gallery_assets',
fit: BoxFit.fitWidth,
),
),
const SizedBox(height: 17),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Row(
children: <Widget>[
Text(
'US',
style: textTheme.labelSmall,
),
Text(
' Β¬ ',
// TODO(larche): Replace textTheme.headline2.color with a ColorScheme value when known.
style: textTheme.labelSmall!.apply(color: textTheme.displayMedium!.color),
),
Text(
'CULTURE',
style: textTheme.labelSmall,
),
],
),
const SizedBox(height: 10),
Text(
'Quince for Wisdom, Persimmon for Luck, Pomegranate for Love',
style: textTheme.headlineMedium,
),
const SizedBox(height: 10),
Text(
'How these crazy fruits sweetened our hearts, relationships, '
'and puffed pastries',
style: textTheme.bodyMedium,
),
Padding(
padding: const EdgeInsets.symmetric(vertical: 16),
child: Row(
children: <Widget>[
const CircleAvatar(
backgroundImage: ExactAssetImage(
'people/square/trevor.png',
package: 'flutter_gallery_assets',
),
radius: 20,
),
const SizedBox(width: 12),
Text(
'by',
style: textTheme.displayMedium,
),
const SizedBox(width: 4),
const Text(
'Connor Eghan',
style: TextStyle(
fontFamily: 'Merriweather',
fontSize: 18,
fontWeight: FontWeight.w500,
color: Colors.black,
),
),
],
),
),
Text(
'$paragraph1\n\n$paragraph2',
style: textTheme.bodyLarge,
),
],
),
),
],
),
),
),
);
}
}
final ThemeData _fortnightlyTheme = _buildFortnightlyTheme();
ThemeData _buildFortnightlyTheme() {
final ThemeData base = ThemeData.light();
return base.copyWith(
primaryTextTheme: _buildTextTheme(base.primaryTextTheme),
scaffoldBackgroundColor: Colors.white,
);
}
TextTheme _buildTextTheme(TextTheme base) {
TextTheme theme = base.apply(bodyColor: Colors.black);
theme = theme.apply(displayColor: Colors.black);
theme = theme.copyWith(
headlineMedium: base.headlineMedium!.copyWith(
fontFamily: 'Merriweather',
fontStyle: FontStyle.italic,
fontSize: 28,
fontWeight: FontWeight.w800,
color: Colors.black,
height: .88,
),
displayMedium: base.displayMedium!.copyWith(
fontFamily: 'LibreFranklin',
fontSize: 18,
fontWeight: FontWeight.w500,
color: Colors.black.withAlpha(153),
),
headlineSmall: base.headlineSmall!.copyWith(fontWeight: FontWeight.w500),
bodyMedium: base.bodyMedium!.copyWith(
fontFamily: 'Merriweather',
fontSize: 14,
fontWeight: FontWeight.w300,
color: const Color(0xFF666666),
height: 1.11,
),
bodyLarge: base.bodyLarge!.copyWith(
fontFamily: 'Merriweather',
fontSize: 16,
fontWeight: FontWeight.w300,
color: const Color(0xFF666666),
height: 1.4,
letterSpacing: .25,
),
labelSmall: const TextStyle(
fontFamily: 'LibreFranklin',
fontSize: 10,
fontWeight: FontWeight.w700,
color: Colors.black,
),
);
return theme;
}
| flutter/dev/integration_tests/flutter_gallery/lib/demo/fortnightly/fortnightly.dart/0 | {
"file_path": "flutter/dev/integration_tests/flutter_gallery/lib/demo/fortnightly/fortnightly.dart",
"repo_id": "flutter",
"token_count": 4117
} | 574 |
// 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:flutter/services.dart';
import 'package:intl/intl.dart';
// This demo is based on
// https://material.io/design/components/dialogs.html#full-screen-dialog
enum DismissDialogAction {
cancel,
discard,
save,
}
class DateTimeItem extends StatelessWidget {
DateTimeItem({ super.key, required DateTime dateTime, required this.onChanged })
: date = DateTime(dateTime.year, dateTime.month, dateTime.day),
time = TimeOfDay(hour: dateTime.hour, minute: dateTime.minute);
final DateTime date;
final TimeOfDay time;
final ValueChanged<DateTime> onChanged;
@override
Widget build(BuildContext context) {
final ThemeData theme = Theme.of(context);
return DefaultTextStyle(
style: theme.textTheme.titleMedium!,
child: Row(
children: <Widget>[
Expanded(
child: Container(
padding: const EdgeInsets.symmetric(vertical: 8.0),
decoration: BoxDecoration(
border: Border(bottom: BorderSide(color: theme.dividerColor))
),
child: InkWell(
onTap: () {
showDatePicker(
context: context,
initialDate: date,
firstDate: date.subtract(const Duration(days: 30)),
lastDate: date.add(const Duration(days: 30)),
)
.then((DateTime? value) {
if (value != null) {
onChanged(DateTime(value.year, value.month, value.day, time.hour, time.minute));
}
});
},
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text(DateFormat('EEE, MMM d yyyy').format(date)),
const Icon(Icons.arrow_drop_down, color: Colors.black54),
],
),
),
),
),
Container(
margin: const EdgeInsets.only(left: 8.0),
padding: const EdgeInsets.symmetric(vertical: 8.0),
decoration: BoxDecoration(
border: Border(bottom: BorderSide(color: theme.dividerColor))
),
child: InkWell(
onTap: () {
showTimePicker(
context: context,
initialTime: time,
)
.then((TimeOfDay? value) {
if (value != null) {
onChanged(DateTime(date.year, date.month, date.day, value.hour, value.minute));
}
});
},
child: Row(
children: <Widget>[
Text(time.format(context)),
const Icon(Icons.arrow_drop_down, color: Colors.black54),
],
),
),
),
],
),
);
}
}
class FullScreenDialogDemo extends StatefulWidget {
const FullScreenDialogDemo({super.key});
@override
FullScreenDialogDemoState createState() => FullScreenDialogDemoState();
}
class FullScreenDialogDemoState extends State<FullScreenDialogDemo> {
DateTime _fromDateTime = DateTime.now();
DateTime _toDateTime = DateTime.now();
bool? _allDayValue = false;
bool _saveNeeded = false;
bool _hasLocation = false;
bool _hasName = false;
late String _eventName;
Future<void> _handlePopInvoked(bool didPop) async {
if (didPop) {
return;
}
final ThemeData theme = Theme.of(context);
final TextStyle dialogTextStyle = theme.textTheme.titleMedium!.copyWith(color: theme.textTheme.bodySmall!.color);
final bool? shouldDiscard = await showDialog<bool>(
context: context,
builder: (BuildContext context) {
return AlertDialog(
content: Text(
'Discard new event?',
style: dialogTextStyle,
),
actions: <Widget>[
TextButton(
child: const Text('CANCEL'),
onPressed: () {
// Pop the confirmation dialog and indicate that the page should
// not be popped.
Navigator.of(context).pop(false);
},
),
TextButton(
child: const Text('DISCARD'),
onPressed: () {
// Pop the confirmation dialog and indicate that the page should
// be popped, too.
Navigator.of(context).pop(true);
},
),
],
);
},
);
if (shouldDiscard ?? false) {
// Since this is the root route, quit the app where possible by invoking
// the SystemNavigator. If this wasn't the root route, then
// Navigator.maybePop could be used instead.
// See https://github.com/flutter/flutter/issues/11490
SystemNavigator.pop();
}
}
@override
Widget build(BuildContext context) {
final ThemeData theme = Theme.of(context);
return Scaffold(
appBar: AppBar(
title: Text(_hasName ? _eventName : 'Event Name TBD'),
actions: <Widget> [
TextButton(
child: Text('SAVE', style: theme.textTheme.bodyMedium!.copyWith(color: Colors.white)),
onPressed: () {
Navigator.pop(context, DismissDialogAction.save);
},
),
],
),
body: Form(
canPop: !_saveNeeded && !_hasLocation && !_hasName,
onPopInvoked: _handlePopInvoked,
child: Scrollbar(
child: ListView(
primary: true,
padding: const EdgeInsets.all(16.0),
children: <Widget>[
Container(
padding: const EdgeInsets.symmetric(vertical: 8.0),
alignment: Alignment.bottomLeft,
child: TextField(
decoration: const InputDecoration(
labelText: 'Event name',
filled: true,
),
style: theme.textTheme.headlineSmall,
onChanged: (String value) {
setState(() {
_hasName = value.isNotEmpty;
if (_hasName) {
_eventName = value;
}
});
},
),
),
Container(
padding: const EdgeInsets.symmetric(vertical: 8.0),
alignment: Alignment.bottomLeft,
child: TextField(
decoration: const InputDecoration(
labelText: 'Location',
hintText: 'Where is the event?',
filled: true,
),
onChanged: (String value) {
setState(() {
_hasLocation = value.isNotEmpty;
});
},
),
),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text('From', style: theme.textTheme.bodySmall),
DateTimeItem(
dateTime: _fromDateTime,
onChanged: (DateTime value) {
setState(() {
_fromDateTime = value;
_saveNeeded = true;
});
},
),
],
),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text('To', style: theme.textTheme.bodySmall),
DateTimeItem(
dateTime: _toDateTime,
onChanged: (DateTime value) {
setState(() {
_toDateTime = value;
_saveNeeded = true;
});
},
),
const Text('All-day'),
],
),
Container(
decoration: BoxDecoration(
border: Border(bottom: BorderSide(color: theme.dividerColor))
),
child: Row(
children: <Widget> [
Checkbox(
value: _allDayValue,
onChanged: (bool? value) {
setState(() {
_allDayValue = value;
_saveNeeded = true;
});
},
),
const Text('All-day'),
],
),
),
]
.map<Widget>((Widget child) {
return Container(
padding: const EdgeInsets.symmetric(vertical: 8.0),
height: 96.0,
child: child,
);
})
.toList(),
),
),
),
);
}
}
| flutter/dev/integration_tests/flutter_gallery/lib/demo/material/full_screen_dialog_demo.dart/0 | {
"file_path": "flutter/dev/integration_tests/flutter_gallery/lib/demo/material/full_screen_dialog_demo.dart",
"repo_id": "flutter",
"token_count": 5077
} | 575 |
// 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 '../../gallery/demo.dart';
class SliderDemo extends StatefulWidget {
const SliderDemo({super.key});
static const String routeName = '/material/slider';
@override
State<SliderDemo> createState() => _SliderDemoState();
}
Path _downTriangle(double size, Offset thumbCenter, { bool invert = false }) {
final Path thumbPath = Path();
final double height = math.sqrt(3.0) / 2.0;
final double centerHeight = size * height / 3.0;
final double halfSize = size / 2.0;
final double sign = invert ? -1.0 : 1.0;
thumbPath.moveTo(thumbCenter.dx - halfSize, thumbCenter.dy + sign * centerHeight);
thumbPath.lineTo(thumbCenter.dx, thumbCenter.dy - 2.0 * sign * centerHeight);
thumbPath.lineTo(thumbCenter.dx + halfSize, thumbCenter.dy + sign * centerHeight);
thumbPath.close();
return thumbPath;
}
Path _rightTriangle(double size, Offset thumbCenter, { bool invert = false }) {
final Path thumbPath = Path();
final double halfSize = size / 2.0;
final double sign = invert ? -1.0 : 1.0;
thumbPath.moveTo(thumbCenter.dx + halfSize * sign, thumbCenter.dy);
thumbPath.lineTo(thumbCenter.dx - halfSize * sign, thumbCenter.dy - size);
thumbPath.lineTo(thumbCenter.dx - halfSize * sign, thumbCenter.dy + size);
thumbPath.close();
return thumbPath;
}
Path _upTriangle(double size, Offset thumbCenter) => _downTriangle(size, thumbCenter, invert: true);
Path _leftTriangle(double size, Offset thumbCenter) => _rightTriangle(size, thumbCenter, invert: true);
class _CustomRangeThumbShape extends RangeSliderThumbShape {
static const double _thumbSize = 4.0;
static const double _disabledThumbSize = 3.0;
@override
Size getPreferredSize(bool isEnabled, bool isDiscrete) {
return isEnabled ? const Size.fromRadius(_thumbSize) : const Size.fromRadius(_disabledThumbSize);
}
static final Animatable<double> sizeTween = Tween<double>(
begin: _disabledThumbSize,
end: _thumbSize,
);
@override
void paint(
PaintingContext context,
Offset center, {
required Animation<double> activationAnimation,
required Animation<double> enableAnimation,
bool isDiscrete = false,
bool isEnabled = false,
bool? isOnTop,
required SliderThemeData sliderTheme,
TextDirection? textDirection,
Thumb? thumb,
bool? isPressed,
}) {
final Canvas canvas = context.canvas;
final ColorTween colorTween = ColorTween(
begin: sliderTheme.disabledThumbColor,
end: sliderTheme.thumbColor,
);
final double size = _thumbSize * sizeTween.evaluate(enableAnimation);
late Path thumbPath;
switch (textDirection) {
case TextDirection.rtl:
switch (thumb) {
case Thumb.start:
thumbPath = _rightTriangle(size, center);
case Thumb.end:
thumbPath = _leftTriangle(size, center);
case null:
break;
}
case TextDirection.ltr:
switch (thumb) {
case Thumb.start:
thumbPath = _leftTriangle(size, center);
case Thumb.end:
thumbPath = _rightTriangle(size, center);
case null:
break;
}
case null:
break;
}
canvas.drawPath(thumbPath, Paint()..color = colorTween.evaluate(enableAnimation)!);
}
}
class _CustomThumbShape extends SliderComponentShape {
static const double _thumbSize = 4.0;
static const double _disabledThumbSize = 3.0;
@override
Size getPreferredSize(bool isEnabled, bool isDiscrete) {
return isEnabled ? const Size.fromRadius(_thumbSize) : const Size.fromRadius(_disabledThumbSize);
}
static final Animatable<double> sizeTween = Tween<double>(
begin: _disabledThumbSize,
end: _thumbSize,
);
@override
void paint(
PaintingContext context,
Offset thumbCenter, {
Animation<double>? activationAnimation,
required Animation<double> enableAnimation,
bool? isDiscrete,
TextPainter? labelPainter,
RenderBox? parentBox,
required SliderThemeData sliderTheme,
TextDirection? textDirection,
double? value,
double? textScaleFactor,
Size? sizeWithOverflow,
}) {
final Canvas canvas = context.canvas;
final ColorTween colorTween = ColorTween(
begin: sliderTheme.disabledThumbColor,
end: sliderTheme.thumbColor,
);
final double size = _thumbSize * sizeTween.evaluate(enableAnimation);
final Path thumbPath = _downTriangle(size, thumbCenter);
canvas.drawPath(thumbPath, Paint()..color = colorTween.evaluate(enableAnimation)!);
}
}
class _CustomValueIndicatorShape extends SliderComponentShape {
static const double _indicatorSize = 4.0;
static const double _disabledIndicatorSize = 3.0;
static const double _slideUpHeight = 40.0;
@override
Size getPreferredSize(bool isEnabled, bool isDiscrete) {
return Size.fromRadius(isEnabled ? _indicatorSize : _disabledIndicatorSize);
}
static final Animatable<double> sizeTween = Tween<double>(
begin: _disabledIndicatorSize,
end: _indicatorSize,
);
@override
void paint(
PaintingContext context,
Offset thumbCenter, {
required Animation<double> activationAnimation,
required Animation<double> enableAnimation,
bool? isDiscrete,
required TextPainter labelPainter,
RenderBox? parentBox,
required SliderThemeData sliderTheme,
TextDirection? textDirection,
double? value,
double? textScaleFactor,
Size? sizeWithOverflow,
}) {
final Canvas canvas = context.canvas;
final ColorTween enableColor = ColorTween(
begin: sliderTheme.disabledThumbColor,
end: sliderTheme.valueIndicatorColor,
);
final Tween<double> slideUpTween = Tween<double>(
begin: 0.0,
end: _slideUpHeight,
);
final double size = _indicatorSize * sizeTween.evaluate(enableAnimation);
final Offset slideUpOffset = Offset(0.0, -slideUpTween.evaluate(activationAnimation));
final Path thumbPath = _upTriangle(size, thumbCenter + slideUpOffset);
final Color paintColor = enableColor.evaluate(enableAnimation)!.withAlpha((255.0 * activationAnimation.value).round());
canvas.drawPath(
thumbPath,
Paint()..color = paintColor,
);
canvas.drawLine(
thumbCenter,
thumbCenter + slideUpOffset,
Paint()
..color = paintColor
..style = PaintingStyle.stroke
..strokeWidth = 2.0);
labelPainter.paint(canvas, thumbCenter + slideUpOffset + Offset(-labelPainter.width / 2.0, -labelPainter.height - 4.0));
}
}
class _SliderDemoState extends State<SliderDemo> {
@override
Widget build(BuildContext context) {
const List<ComponentDemoTabData> demos = <ComponentDemoTabData>[
ComponentDemoTabData(
tabName: 'SINGLE',
description: 'Sliders containing 1 thumb',
demoWidget: _Sliders(),
documentationUrl: 'https://api.flutter.dev/flutter/material/Slider-class.html',
),
ComponentDemoTabData(
tabName: 'RANGE',
description: 'Sliders containing 2 thumbs',
demoWidget: _RangeSliders(),
documentationUrl: 'https://api.flutter.dev/flutter/material/RangeSlider-class.html',
),
];
return const TabbedComponentDemoScaffold(
title: 'Sliders',
demos: demos,
isScrollable: false,
showExampleCodeAction: false,
);
}
}
class _Sliders extends StatefulWidget {
const _Sliders();
@override
_SlidersState createState() => _SlidersState();
}
class _SlidersState extends State<_Sliders> {
double _continuousValue = 25.0;
double _discreteValue = 20.0;
double _discreteCustomValue = 25.0;
@override
Widget build(BuildContext context) {
final ThemeData theme = Theme.of(context);
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 40.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Semantics(
label: 'Editable numerical value',
child: SizedBox(
width: 64,
height: 48,
child: TextField(
textAlign: TextAlign.center,
onSubmitted: (String value) {
final double? newValue = double.tryParse(value);
if (newValue != null && newValue != _continuousValue) {
setState(() {
_continuousValue = newValue.clamp(0.0, 100.0);
});
}
},
keyboardType: TextInputType.number,
controller: TextEditingController(
text: _continuousValue.toStringAsFixed(0),
),
),
),
),
Slider.adaptive(
label: _continuousValue.toStringAsFixed(6),
value: _continuousValue,
max: 100.0,
onChanged: (double value) {
setState(() {
_continuousValue = value;
});
},
),
const Text('Continuous with Editable Numerical Value'),
],
),
const Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Slider.adaptive(value: 0.25, onChanged: null),
Text('Disabled'),
],
),
Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Slider.adaptive(
value: _discreteValue,
max: 200.0,
divisions: 5,
label: '${_discreteValue.round()}',
onChanged: (double value) {
setState(() {
_discreteValue = value;
});
},
),
const Text('Discrete'),
],
),
Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
SliderTheme(
data: theme.sliderTheme.copyWith(
activeTrackColor: Colors.deepPurple,
inactiveTrackColor: theme.colorScheme.onSurface.withOpacity(0.5),
activeTickMarkColor: theme.colorScheme.onSurface.withOpacity(0.7),
inactiveTickMarkColor: theme.colorScheme.surface.withOpacity(0.7),
overlayColor: theme.colorScheme.onSurface.withOpacity(0.12),
thumbColor: Colors.deepPurple,
valueIndicatorColor: Colors.deepPurpleAccent,
thumbShape: _CustomThumbShape(),
valueIndicatorShape: _CustomValueIndicatorShape(),
valueIndicatorTextStyle: theme.textTheme.bodyLarge!.copyWith(color: theme.colorScheme.onSurface),
),
child: Slider(
value: _discreteCustomValue,
max: 200.0,
divisions: 5,
semanticFormatterCallback: (double value) => value.round().toString(),
label: '${_discreteCustomValue.round()}',
onChanged: (double value) {
setState(() {
_discreteCustomValue = value;
});
},
),
),
const Text('Discrete with Custom Theme'),
],
),
],
),
);
}
}
class _RangeSliders extends StatefulWidget {
const _RangeSliders();
@override
_RangeSlidersState createState() => _RangeSlidersState();
}
class _RangeSlidersState extends State<_RangeSliders> {
RangeValues _continuousValues = const RangeValues(25.0, 75.0);
RangeValues _discreteValues = const RangeValues(40.0, 120.0);
RangeValues _discreteCustomValues = const RangeValues(40.0, 160.0);
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 40.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
RangeSlider(
values: _continuousValues,
max: 100.0,
onChanged: (RangeValues values) {
setState(() {
_continuousValues = values;
});
},
),
const Text('Continuous'),
],
),
Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
RangeSlider(values: const RangeValues(0.25, 0.75), onChanged: null),
const Text('Disabled'),
],
),
Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
RangeSlider(
values: _discreteValues,
max: 200.0,
divisions: 5,
labels: RangeLabels('${_discreteValues.start.round()}', '${_discreteValues.end.round()}'),
onChanged: (RangeValues values) {
setState(() {
_discreteValues = values;
});
},
),
const Text('Discrete'),
],
),
Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
SliderTheme(
data: SliderThemeData(
activeTrackColor: Colors.deepPurple,
inactiveTrackColor: Colors.black26,
activeTickMarkColor: Colors.white70,
inactiveTickMarkColor: Colors.black,
overlayColor: Colors.black12,
thumbColor: Colors.deepPurple,
rangeThumbShape: _CustomRangeThumbShape(),
showValueIndicator: ShowValueIndicator.never,
),
child: RangeSlider(
values: _discreteCustomValues,
max: 200.0,
divisions: 5,
labels: RangeLabels('${_discreteCustomValues.start.round()}', '${_discreteCustomValues.end.round()}'),
onChanged: (RangeValues values) {
setState(() {
_discreteCustomValues = values;
});
},
),
),
const Text('Discrete with Custom Theme'),
],
),
],
),
);
}
}
| flutter/dev/integration_tests/flutter_gallery/lib/demo/material/slider_demo.dart/0 | {
"file_path": "flutter/dev/integration_tests/flutter_gallery/lib/demo/material/slider_demo.dart",
"repo_id": "flutter",
"token_count": 6857
} | 576 |
// 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 'product.dart';
List<Product> loadProducts(Category category) {
const List<Product> allProducts = <Product>[
Product(
category: Category.accessories,
id: 0,
isFeatured: true,
name: 'Vagabond sack',
price: 120,
),
Product(
category: Category.accessories,
id: 1,
isFeatured: true,
name: 'Stella sunglasses',
price: 58,
),
Product(
category: Category.accessories,
id: 2,
isFeatured: false,
name: 'Whitney belt',
price: 35,
),
Product(
category: Category.accessories,
id: 3,
isFeatured: true,
name: 'Garden strand',
price: 98,
),
Product(
category: Category.accessories,
id: 4,
isFeatured: false,
name: 'Strut earrings',
price: 34,
),
Product(
category: Category.accessories,
id: 5,
isFeatured: false,
name: 'Varsity socks',
price: 12,
),
Product(
category: Category.accessories,
id: 6,
isFeatured: false,
name: 'Weave keyring',
price: 16,
),
Product(
category: Category.accessories,
id: 7,
isFeatured: true,
name: 'Gatsby hat',
price: 40,
),
Product(
category: Category.accessories,
id: 8,
isFeatured: true,
name: 'Shrug bag',
price: 198,
),
Product(
category: Category.home,
id: 9,
isFeatured: true,
name: 'Gilt desk trio',
price: 58,
),
Product(
category: Category.home,
id: 10,
isFeatured: false,
name: 'Copper wire rack',
price: 18,
),
Product(
category: Category.home,
id: 11,
isFeatured: false,
name: 'Soothe ceramic set',
price: 28,
),
Product(
category: Category.home,
id: 12,
isFeatured: false,
name: 'Hurrahs tea set',
price: 34,
),
Product(
category: Category.home,
id: 13,
isFeatured: true,
name: 'Blue stone mug',
price: 18,
),
Product(
category: Category.home,
id: 14,
isFeatured: true,
name: 'Rainwater tray',
price: 27,
),
Product(
category: Category.home,
id: 15,
isFeatured: true,
name: 'Chambray napkins',
price: 16,
),
Product(
category: Category.home,
id: 16,
isFeatured: true,
name: 'Succulent planters',
price: 16,
),
Product(
category: Category.home,
id: 17,
isFeatured: false,
name: 'Quartet table',
price: 175,
),
Product(
category: Category.home,
id: 18,
isFeatured: true,
name: 'Kitchen quattro',
price: 129,
),
Product(
category: Category.clothing,
id: 19,
isFeatured: false,
name: 'Clay sweater',
price: 48,
),
Product(
category: Category.clothing,
id: 20,
isFeatured: false,
name: 'Sea tunic',
price: 45,
),
Product(
category: Category.clothing,
id: 21,
isFeatured: false,
name: 'Plaster tunic',
price: 38,
),
Product(
category: Category.clothing,
id: 22,
isFeatured: false,
name: 'White pinstripe shirt',
price: 70,
),
Product(
category: Category.clothing,
id: 23,
isFeatured: false,
name: 'Chambray shirt',
price: 70,
),
Product(
category: Category.clothing,
id: 24,
isFeatured: true,
name: 'Seabreeze sweater',
price: 60,
),
Product(
category: Category.clothing,
id: 25,
isFeatured: false,
name: 'Gentry jacket',
price: 178,
),
Product(
category: Category.clothing,
id: 26,
isFeatured: false,
name: 'Navy trousers',
price: 74,
),
Product(
category: Category.clothing,
id: 27,
isFeatured: true,
name: 'Walter henley (white)',
price: 38,
),
Product(
category: Category.clothing,
id: 28,
isFeatured: true,
name: 'Surf and perf shirt',
price: 48,
),
Product(
category: Category.clothing,
id: 29,
isFeatured: true,
name: 'Ginger scarf',
price: 98,
),
Product(
category: Category.clothing,
id: 30,
isFeatured: true,
name: 'Ramona crossover',
price: 68,
),
Product(
category: Category.clothing,
id: 31,
isFeatured: false,
name: 'Chambray shirt',
price: 38,
),
Product(
category: Category.clothing,
id: 32,
isFeatured: false,
name: 'Classic white collar',
price: 58,
),
Product(
category: Category.clothing,
id: 33,
isFeatured: true,
name: 'Cerise scallop tee',
price: 42,
),
Product(
category: Category.clothing,
id: 34,
isFeatured: false,
name: 'Shoulder rolls tee',
price: 27,
),
Product(
category: Category.clothing,
id: 35,
isFeatured: false,
name: 'Grey slouch tank',
price: 24,
),
Product(
category: Category.clothing,
id: 36,
isFeatured: false,
name: 'Sunshirt dress',
price: 58,
),
Product(
category: Category.clothing,
id: 37,
isFeatured: true,
name: 'Fine lines tee',
price: 58,
),
];
if (category == Category.all) {
return allProducts;
} else {
return allProducts.where((Product p) => p.category == category).toList();
}
}
| flutter/dev/integration_tests/flutter_gallery/lib/demo/shrine/model/products_repository.dart/0 | {
"file_path": "flutter/dev/integration_tests/flutter_gallery/lib/demo/shrine/model/products_repository.dart",
"repo_id": "flutter",
"token_count": 2745
} | 577 |
// 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/foundation.dart' show defaultTargetPlatform;
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
class _LinkTextSpan extends TextSpan {
// Beware!
//
// This class is only safe because the TapGestureRecognizer is not
// given a deadline and therefore never allocates any resources.
//
// In any other situation -- setting a deadline, using any of the less trivial
// recognizers, etc -- you would have to manage the gesture recognizer's
// lifetime and call dispose() when the TextSpan was no longer being rendered.
//
// Since TextSpan itself is @immutable, this means that you would have to
// manage the recognizer from outside the TextSpan, e.g. in the State of a
// stateful widget that then hands the recognizer to the TextSpan.
_LinkTextSpan({ super.style, required String url, String? text }) : super(
text: text ?? url,
recognizer: TapGestureRecognizer()..onTap = () {
launchUrl(Uri.parse(url), mode: LaunchMode.externalApplication);
}
);
}
void showGalleryAboutDialog(BuildContext context) {
final ThemeData themeData = Theme.of(context);
final TextStyle? aboutTextStyle = themeData.textTheme.bodyLarge;
final TextStyle linkStyle = themeData.textTheme.bodyLarge!.copyWith(color: themeData.colorScheme.primary);
showAboutDialog(
context: context,
applicationVersion: 'January 2019',
applicationIcon: const FlutterLogo(),
applicationLegalese: 'Β© 2014 The Flutter Authors',
children: <Widget>[
Padding(
padding: const EdgeInsets.only(top: 24.0),
child: RichText(
text: TextSpan(
children: <TextSpan>[
TextSpan(
style: aboutTextStyle,
text: 'Flutter is an open-source project to help developers '
'build high-performance, high-fidelity, mobile apps for '
'${defaultTargetPlatform == TargetPlatform.iOS ? 'multiple platforms' : 'iOS and Android'} '
'from a single codebase. This design lab is a playground '
"and showcase of Flutter's many widgets, behaviors, "
'animations, layouts, and more. Learn more about Flutter at ',
),
_LinkTextSpan(
style: linkStyle,
url: 'https://flutter.dev',
),
TextSpan(
style: aboutTextStyle,
text: '.\n\nTo see the source code for this app, please visit the ',
),
_LinkTextSpan(
style: linkStyle,
url: 'https://goo.gl/iv1p4G',
text: 'flutter github repo',
),
TextSpan(
style: aboutTextStyle,
text: '.',
),
],
),
),
),
],
);
}
| flutter/dev/integration_tests/flutter_gallery/lib/gallery/about.dart/0 | {
"file_path": "flutter/dev/integration_tests/flutter_gallery/lib/gallery/about.dart",
"repo_id": "flutter",
"token_count": 1277
} | 578 |
// 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/services.dart';
import 'package:flutter_gallery/gallery/example_code_parser.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
test('Flutter gallery example code parser test', () async {
final TestAssetBundle bundle = TestAssetBundle();
final String? codeSnippet0 = await getExampleCode('test_0', bundle);
expect(codeSnippet0, 'test 0 0\ntest 0 1');
final String? codeSnippet1 = await getExampleCode('test_1', bundle);
expect(codeSnippet1, 'test 1 0\ntest 1 1');
final String? codeSnippet3 = await getExampleCode('test_2_windows_breaks', bundle);
expect(codeSnippet3, 'windows test 2 0\nwindows test 2 1');
});
}
const String testCodeFile = '''
// A fake test file
// START test_0
test 0 0
test 0 1
// END
// Some comments
// START test_1
test 1 0
test 1 1
// END
// START test_2_windows_breaks\r\nwindows test 2 0\r\nwindows test 2 1\r\n// END
''';
class TestAssetBundle extends AssetBundle {
@override
Future<ByteData> load(String key) async {
return ByteData.sublistView(Uint8List(0));
}
@override
Future<String> loadString(String key, { bool cache = true }) async {
if (key == 'lib/gallery/example_code.dart') {
return testCodeFile;
}
return '';
}
@override
Future<T> loadStructuredData<T>(String key, Future<T> Function(String value) parser) async {
return parser(await loadString(key));
}
@override
String toString() => '$runtimeType@$hashCode()';
}
| flutter/dev/integration_tests/flutter_gallery/test/example_code_parser_test.dart/0 | {
"file_path": "flutter/dev/integration_tests/flutter_gallery/test/example_code_parser_test.dart",
"repo_id": "flutter",
"token_count": 571
} | 579 |
// 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 file is NOT auto generated.
// DO NOT update it by running dev/tools/bin/generate_gradle_lockfiles.dart.
buildscript {
ext.kotlin_version = '1.7.10'
repositories {
google()
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:7.3.0'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
configurations.classpath {
resolutionStrategy.activateDependencyLocking()
}
}
allprojects {
repositories {
google()
mavenCentral()
}
}
rootProject.buildDir = '../build'
subprojects {
project.buildDir = "${rootProject.buildDir}/${project.name}"
}
subprojects {
project.evaluationDependsOn(':app')
dependencyLocking {
ignoredDependencies.add('io.flutter:*')
lockFile = file("${rootProject.projectDir}/project-${project.name}.lockfile")
if (!project.hasProperty('local-engine-repo')) {
lockAllConfigurations()
}
}
}
tasks.register("clean", Delete) {
delete rootProject.buildDir
}
| flutter/dev/integration_tests/gradle_deprecated_settings/android/build.gradle/0 | {
"file_path": "flutter/dev/integration_tests/gradle_deprecated_settings/android/build.gradle",
"repo_id": "flutter",
"token_count": 486
} | 580 |
// 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 io.flutter.integration.platformviews;
import android.app.AlertDialog;
import android.content.Context;
import android.graphics.PixelFormat;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.TextView;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.platform.PlatformView;
public class SimplePlatformView implements PlatformView, MethodChannel.MethodCallHandler {
private final FrameLayout view;
private final MethodChannel methodChannel;
private final io.flutter.integration.platformviews.TouchPipe touchPipe;
SimplePlatformView(Context context, MethodChannel methodChannel) {
this.methodChannel = methodChannel;
this.methodChannel.setMethodCallHandler(this);
view = new FrameLayout(context) {
@Override
public boolean onTouchEvent(MotionEvent event) {
return true;
}
};
view.setBackgroundColor(0xff0000ff);
touchPipe = new TouchPipe(this.methodChannel, view);
}
@Override
public View getView() {
return view;
}
@Override
public void dispose() {}
@Override
public void onMethodCall(MethodCall methodCall, MethodChannel.Result result) {
switch (methodCall.method) {
case "pipeTouchEvents":
touchPipe.enable();
result.success(null);
return;
case "stopTouchEvents":
touchPipe.disable();
result.success(null);
return;
case "showAndHideAlertDialog":
showAndHideAlertDialog(result);
return;
case "addChildViewAndWaitForClick":
addWindow(result);
return;
}
result.notImplemented();
}
private void showAndHideAlertDialog(MethodChannel.Result result) {
Context context = view.getContext();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
TextView textView = new TextView(context);
textView.setText("This alert dialog will close in 1 second");
builder.setView(textView);
final AlertDialog alertDialog = builder.show();
result.success(null);
view.postDelayed(new Runnable() {
@Override
public void run() {
alertDialog.hide();
}
}, 1000);
}
private void addWindow(final MethodChannel.Result result) {
Context context = view.getContext();
final Button button = new Button(context);
button.setText("This view was added to the Android view");
view.addView(button);
button.setOnClickListener(v -> {
view.removeView(button);
result.success(null);
});
}
}
| flutter/dev/integration_tests/hybrid_android_views/android/app/src/main/java/io/flutter/integration/androidviews/SimplePlatformView.java/0 | {
"file_path": "flutter/dev/integration_tests/hybrid_android_views/android/app/src/main/java/io/flutter/integration/androidviews/SimplePlatformView.java",
"repo_id": "flutter",
"token_count": 1263
} | 581 |
// 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';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:path_provider/path_provider.dart';
import 'android_platform_view.dart';
import 'future_data_handler.dart';
import 'motion_event_diff.dart';
import 'page.dart';
const String kEventsFileName = 'touchEvents';
class MotionEventsPage extends PageWidget {
const MotionEventsPage({Key? key})
: super('Motion Event Tests', const ValueKey<String>('MotionEventsListTile'), key: key);
@override
Widget build(BuildContext context) {
return const MotionEventsBody();
}
}
class MotionEventsBody extends StatefulWidget {
const MotionEventsBody({super.key});
@override
State createState() => MotionEventsBodyState();
}
class MotionEventsBodyState extends State<MotionEventsBody> {
static const int kEventsBufferSize = 1000;
MethodChannel? viewChannel;
/// The list of motion events that were passed to the FlutterView.
List<Map<String, dynamic>> flutterViewEvents = <Map<String, dynamic>>[];
/// The list of motion events that were passed to the embedded view.
List<Map<String, dynamic>> embeddedViewEvents = <Map<String, dynamic>>[];
@override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
SizedBox(
height: 300.0,
child: AndroidPlatformView(
key: const ValueKey<String>('PlatformView'),
viewType: 'simple_view',
onPlatformViewCreated: onPlatformViewCreated,
),
),
Expanded(
child: ListView.builder(
itemBuilder: buildEventTile,
itemCount: flutterViewEvents.length,
),
),
Row(
children: <Widget>[
Expanded(
child: ElevatedButton(
onPressed: listenToFlutterViewEvents,
child: const Text('RECORD'),
),
),
Expanded(
child: ElevatedButton(
child: const Text('CLEAR'),
onPressed: () {
setState(() {
flutterViewEvents.clear();
embeddedViewEvents.clear();
});
},
),
),
Expanded(
child: ElevatedButton(
child: const Text('SAVE'),
onPressed: () {
const StandardMessageCodec codec = StandardMessageCodec();
saveRecordedEvents(
codec.encodeMessage(flutterViewEvents)!, context);
},
),
),
Expanded(
child: ElevatedButton(
key: const ValueKey<String>('play'),
child: const Text('PLAY FILE'),
onPressed: () { playEventsFile(); },
),
),
Expanded(
child: ElevatedButton(
key: const ValueKey<String>('back'),
child: const Text('BACK'),
onPressed: () { Navigator.pop(context); },
),
),
],
),
],
);
}
Future<String> playEventsFile() async {
const StandardMessageCodec codec = StandardMessageCodec();
try {
final ByteData data = await rootBundle.load('packages/assets_for_android_views/assets/touchEvents');
final List<dynamic> unTypedRecordedEvents = codec.decodeMessage(data) as List<dynamic>;
final List<Map<String, dynamic>> recordedEvents = unTypedRecordedEvents
.cast<Map<dynamic, dynamic>>()
.map<Map<String, dynamic>>((Map<dynamic, dynamic> e) =>e.cast<String, dynamic>())
.toList();
await viewChannel!.invokeMethod<void>('pipeTouchEvents');
print('replaying ${recordedEvents.length} motion events');
for (final Map<String, dynamic> event in recordedEvents.reversed) {
await channel.invokeMethod<void>('synthesizeEvent', event);
}
await viewChannel!.invokeMethod<void>('stopTouchEvents');
if (flutterViewEvents.length != embeddedViewEvents.length) {
return 'Synthesized ${flutterViewEvents.length} events but the embedded view received ${embeddedViewEvents.length} events';
}
final StringBuffer diff = StringBuffer();
for (int i = 0; i < flutterViewEvents.length; ++i) {
final String currentDiff = diffMotionEvents(flutterViewEvents[i], embeddedViewEvents[i]);
if (currentDiff.isEmpty) {
continue;
}
if (diff.isNotEmpty) {
diff.write(', ');
}
diff.write(currentDiff);
}
return diff.toString();
} catch (e) {
return e.toString();
}
}
@override
void initState() {
super.initState();
channel.setMethodCallHandler(onMethodChannelCall);
}
Future<void> saveRecordedEvents(ByteData data, BuildContext context) async {
if (await channel.invokeMethod<bool>('getStoragePermission') != true) {
if (context.mounted) {
showMessage(context, 'External storage permissions are required to save events');
}
return;
}
try {
final Directory outDir = (await getExternalStorageDirectory())!;
// This test only runs on Android so we can assume path separator is '/'.
final File file = File('${outDir.path}/$kEventsFileName');
await file.writeAsBytes(data.buffer.asUint8List(0, data.lengthInBytes), flush: true);
if (!context.mounted) {
return;
}
showMessage(context, 'Saved original events to ${file.path}');
} catch (e) {
if (!context.mounted) {
return;
}
showMessage(context, 'Failed saving $e');
}
}
void showMessage(BuildContext context, String message) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text(message),
duration: const Duration(seconds: 3),
));
}
void onPlatformViewCreated(int id) {
viewChannel = MethodChannel('simple_view/$id')
..setMethodCallHandler(onViewMethodChannelCall);
driverDataHandler.registerHandler('run test').complete(playEventsFile);
}
void listenToFlutterViewEvents() {
viewChannel!.invokeMethod<void>('pipeTouchEvents');
Timer(const Duration(seconds: 3), () {
viewChannel!.invokeMethod<void>('stopTouchEvents');
});
}
Future<dynamic> onMethodChannelCall(MethodCall call) {
switch (call.method) {
case 'onTouch':
final Map<dynamic, dynamic> map = call.arguments as Map<dynamic, dynamic>;
flutterViewEvents.insert(0, map.cast<String, dynamic>());
if (flutterViewEvents.length > kEventsBufferSize) {
flutterViewEvents.removeLast();
}
setState(() {});
}
return Future<dynamic>.value();
}
Future<dynamic> onViewMethodChannelCall(MethodCall call) {
switch (call.method) {
case 'onTouch':
final Map<dynamic, dynamic> map = call.arguments as Map<dynamic, dynamic>;
embeddedViewEvents.insert(0, map.cast<String, dynamic>());
if (embeddedViewEvents.length > kEventsBufferSize) {
embeddedViewEvents.removeLast();
}
setState(() {});
}
return Future<dynamic>.value();
}
Widget buildEventTile(BuildContext context, int index) {
if (embeddedViewEvents.length > index) {
return TouchEventDiff(
flutterViewEvents[index], embeddedViewEvents[index]);
}
return Text(
'Unmatched event, action: ${flutterViewEvents[index]['action']}');
}
}
class TouchEventDiff extends StatelessWidget {
const TouchEventDiff(this.originalEvent, this.synthesizedEvent, {super.key});
final Map<String, dynamic> originalEvent;
final Map<String, dynamic> synthesizedEvent;
@override
Widget build(BuildContext context) {
Color color;
final String diff = diffMotionEvents(originalEvent, synthesizedEvent);
String msg;
final int action = synthesizedEvent['action'] as int;
final String actionName = getActionName(getActionMasked(action), action);
if (diff.isEmpty) {
color = Colors.green;
msg = 'Matched event (action $actionName)';
} else {
color = Colors.red;
msg = '[$actionName] $diff';
}
return GestureDetector(
onLongPress: () {
print('expected:');
prettyPrintEvent(originalEvent);
print('\nactual:');
prettyPrintEvent(synthesizedEvent);
},
child: Container(
color: color,
margin: const EdgeInsets.only(bottom: 2.0),
child: Text(msg),
),
);
}
void prettyPrintEvent(Map<String, dynamic> event) {
final StringBuffer buffer = StringBuffer();
final int action = event['action'] as int;
final int maskedAction = getActionMasked(action);
final String actionName = getActionName(maskedAction, action);
buffer.write('$actionName ');
if (maskedAction == 5 || maskedAction == 6) {
buffer.write('pointer: ${getPointerIdx(action)} ');
}
final List<Map<dynamic, dynamic>> coords = (event['pointerCoords'] as List<dynamic>).cast<Map<dynamic, dynamic>>();
for (int i = 0; i < coords.length; i++) {
buffer.write('p$i x: ${coords[i]['x']} y: ${coords[i]['y']}, pressure: ${coords[i]['pressure']} ');
}
print(buffer);
}
}
| flutter/dev/integration_tests/hybrid_android_views/lib/motion_events_page.dart/0 | {
"file_path": "flutter/dev/integration_tests/hybrid_android_views/lib/motion_events_page.dart",
"repo_id": "flutter",
"token_count": 3858
} | 582 |
// 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 "ButtonFactory.h"
@interface PlatformButton: NSObject<FlutterPlatformView>
@property (strong, nonatomic) UIButton *button;
@property (assign, nonatomic) int counter;
@end
@implementation PlatformButton
- (instancetype)init
{
self = [super init];
if (self) {
_counter = 0;
_button = [[UIButton alloc] init];
[_button setTitle:@"Initial Button Title" forState:UIControlStateNormal];
[_button addTarget:self action:@selector(buttonTapped) forControlEvents:UIControlEventTouchUpInside];
}
return self;
}
- (UIView *)view {
return self.button;
}
- (void)buttonTapped {
self.counter += 1;
NSString *title = [NSString stringWithFormat:@"Button Tapped %d", self.counter];
[self.button setTitle:title forState:UIControlStateNormal];
}
@end
@implementation ButtonFactory
- (NSObject<FlutterPlatformView> *)createWithFrame:(CGRect)frame viewIdentifier:(int64_t)viewId arguments:(id)args {
return [[PlatformButton alloc] init];
}
@end
| flutter/dev/integration_tests/ios_platform_view_tests/ios/Runner/ButtonFactory.m/0 | {
"file_path": "flutter/dev/integration_tests/ios_platform_view_tests/ios/Runner/ButtonFactory.m",
"repo_id": "flutter",
"token_count": 376
} | 583 |
// 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 cupertinoContextMenuDemo
class CupertinoContextMenuDemo extends StatelessWidget {
const CupertinoContextMenuDemo({super.key});
@override
Widget build(BuildContext context) {
final GalleryLocalizations galleryLocalizations = GalleryLocalizations.of(context)!;
return CupertinoPageScaffold(
navigationBar: CupertinoNavigationBar(
automaticallyImplyLeading: false,
middle: Text(
galleryLocalizations.demoCupertinoContextMenuTitle,
),
),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Center(
child: SizedBox(
width: 100,
height: 100,
child: CupertinoContextMenu(
actions: <Widget>[
CupertinoContextMenuAction(
onPressed: () {
Navigator.pop(context);
},
child: Text(
galleryLocalizations.demoCupertinoContextMenuActionOne,
),
),
CupertinoContextMenuAction(
onPressed: () {
Navigator.pop(context);
},
child: Text(
galleryLocalizations.demoCupertinoContextMenuActionTwo,
),
),
],
child: const FlutterLogo(size: 250),
),
),
),
const SizedBox(height: 20),
Padding(
padding: const EdgeInsets.all(30),
child: Text(
galleryLocalizations.demoCupertinoContextMenuActionText,
textAlign: TextAlign.center,
style: const TextStyle(
color: Colors.black,
),
),
),
],
),
);
}
}
// END
| flutter/dev/integration_tests/new_gallery/lib/demos/cupertino/cupertino_context_menu_demo.dart/0 | {
"file_path": "flutter/dev/integration_tests/new_gallery/lib/demos/cupertino/cupertino_context_menu_demo.dart",
"repo_id": "flutter",
"token_count": 1132
} | 584 |
// 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';
import 'material_demo_types.dart';
class SelectionControlsDemo extends StatelessWidget {
const SelectionControlsDemo({super.key, required this.type});
final SelectionControlsDemoType type;
String _title(BuildContext context) {
switch (type) {
case SelectionControlsDemoType.checkbox:
return GalleryLocalizations.of(context)!
.demoSelectionControlsCheckboxTitle;
case SelectionControlsDemoType.radio:
return GalleryLocalizations.of(context)!
.demoSelectionControlsRadioTitle;
case SelectionControlsDemoType.switches:
return GalleryLocalizations.of(context)!
.demoSelectionControlsSwitchTitle;
}
}
@override
Widget build(BuildContext context) {
Widget? controls;
switch (type) {
case SelectionControlsDemoType.checkbox:
controls = _CheckboxDemo();
case SelectionControlsDemoType.radio:
controls = _RadioDemo();
case SelectionControlsDemoType.switches:
controls = _SwitchDemo();
}
return Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
title: Text(_title(context)),
),
body: controls,
);
}
}
// BEGIN selectionControlsDemoCheckbox
class _CheckboxDemo extends StatefulWidget {
@override
_CheckboxDemoState createState() => _CheckboxDemoState();
}
class _CheckboxDemoState extends State<_CheckboxDemo> with RestorationMixin {
RestorableBoolN checkboxValueA = RestorableBoolN(true);
RestorableBoolN checkboxValueB = RestorableBoolN(false);
RestorableBoolN checkboxValueC = RestorableBoolN(null);
@override
String get restorationId => 'checkbox_demo';
@override
void restoreState(RestorationBucket? oldBucket, bool initialRestore) {
registerForRestoration(checkboxValueA, 'checkbox_a');
registerForRestoration(checkboxValueB, 'checkbox_b');
registerForRestoration(checkboxValueC, 'checkbox_c');
}
@override
void dispose() {
checkboxValueA.dispose();
checkboxValueB.dispose();
checkboxValueC.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Checkbox(
value: checkboxValueA.value,
onChanged: (bool? value) {
setState(() {
checkboxValueA.value = value;
});
},
),
Checkbox(
value: checkboxValueB.value,
onChanged: (bool? value) {
setState(() {
checkboxValueB.value = value;
});
},
),
Checkbox(
value: checkboxValueC.value,
tristate: true,
onChanged: (bool? value) {
setState(() {
checkboxValueC.value = value;
});
},
),
],
),
// Disabled checkboxes
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Checkbox(
value: checkboxValueA.value,
onChanged: null,
),
Checkbox(
value: checkboxValueB.value,
onChanged: null,
),
Checkbox(
value: checkboxValueC.value,
tristate: true,
onChanged: null,
),
],
),
],
);
}
}
// END
// BEGIN selectionControlsDemoRadio
class _RadioDemo extends StatefulWidget {
@override
_RadioDemoState createState() => _RadioDemoState();
}
class _RadioDemoState extends State<_RadioDemo> with RestorationMixin {
final RestorableInt radioValue = RestorableInt(0);
@override
String get restorationId => 'radio_demo';
@override
void restoreState(RestorationBucket? oldBucket, bool initialRestore) {
registerForRestoration(radioValue, 'radio_value');
}
void handleRadioValueChanged(int? value) {
setState(() {
radioValue.value = value!;
});
}
@override
void dispose() {
radioValue.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
for (int index = 0; index < 2; ++index)
Radio<int>(
value: index,
groupValue: radioValue.value,
onChanged: handleRadioValueChanged,
),
],
),
// Disabled radio buttons
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
for (int index = 0; index < 2; ++index)
Radio<int>(
value: index,
groupValue: radioValue.value,
onChanged: null,
),
],
),
],
);
}
}
// END
// BEGIN selectionControlsDemoSwitches
class _SwitchDemo extends StatefulWidget {
@override
_SwitchDemoState createState() => _SwitchDemoState();
}
class _SwitchDemoState extends State<_SwitchDemo> with RestorationMixin {
RestorableBool switchValueA = RestorableBool(true);
RestorableBool switchValueB = RestorableBool(false);
@override
String get restorationId => 'switch_demo';
@override
void restoreState(RestorationBucket? oldBucket, bool initialRestore) {
registerForRestoration(switchValueA, 'switch_value1');
registerForRestoration(switchValueB, 'switch_value2');
}
@override
void dispose() {
switchValueA.dispose();
switchValueB.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Switch(
value: switchValueA.value,
onChanged: (bool value) {
setState(() {
switchValueA.value = value;
});
},
),
Switch(
value: switchValueB.value,
onChanged: (bool value) {
setState(() {
switchValueB.value = value;
});
},
),
],
),
// Disabled switches
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Switch(
value: switchValueA.value,
onChanged: null,
),
Switch(
value: switchValueB.value,
onChanged: null,
),
],
),
],
);
}
}
// END
| flutter/dev/integration_tests/new_gallery/lib/demos/material/selection_controls_demo.dart/0 | {
"file_path": "flutter/dev/integration_tests/new_gallery/lib/demos/material/selection_controls_demo.dart",
"repo_id": "flutter",
"token_count": 3365
} | 585 |
// 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 '../../themes/gallery_theme_data.dart';
import 'transformations_demo_board.dart';
import 'transformations_demo_color_picker.dart';
const Color backgroundColor = Color(0xFF272727);
// The panel for editing a board point.
@immutable
class EditBoardPoint extends StatelessWidget {
const EditBoardPoint({
super.key,
required this.boardPoint,
this.onColorSelection,
});
final BoardPoint boardPoint;
final ValueChanged<Color>? onColorSelection;
@override
Widget build(BuildContext context) {
final Set<Color> boardPointColors = <Color>{
Colors.white,
GalleryThemeData.darkColorScheme.primary,
GalleryThemeData.darkColorScheme.primaryContainer,
GalleryThemeData.darkColorScheme.secondary,
backgroundColor,
};
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Text(
'${boardPoint.q}, ${boardPoint.r}',
textAlign: TextAlign.right,
style: const TextStyle(fontWeight: FontWeight.bold),
),
ColorPicker(
colors: boardPointColors,
selectedColor: boardPoint.color,
onColorSelection: onColorSelection,
),
],
);
}
}
| flutter/dev/integration_tests/new_gallery/lib/demos/reference/transformations_demo_edit_board_point.dart/0 | {
"file_path": "flutter/dev/integration_tests/new_gallery/lib/demos/reference/transformations_demo_edit_board_point.dart",
"repo_id": "flutter",
"token_count": 534
} | 586 |
// 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/gestures.dart';
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
import '../gallery_localizations.dart';
void showAboutDialog({
required BuildContext context,
}) {
showDialog<void>(
context: context,
builder: (BuildContext context) {
return _AboutDialog();
},
);
}
Future<String> getVersionNumber() async {
return '2.10.2+021002';
}
class _AboutDialog extends StatelessWidget {
@override
Widget build(BuildContext context) {
final ColorScheme colorScheme = Theme.of(context).colorScheme;
final TextTheme textTheme = Theme.of(context).textTheme;
final TextStyle bodyTextStyle =
textTheme.bodyLarge!.apply(color: colorScheme.onPrimary);
final GalleryLocalizations localizations = GalleryLocalizations.of(context)!;
const String name = 'Flutter Gallery'; // Don't need to localize.
const String legalese = 'Β© 2021 The Flutter team'; // Don't need to localize.
final String repoText = localizations.githubRepo(name);
final String seeSource = localizations.aboutDialogDescription(repoText);
final int repoLinkIndex = seeSource.indexOf(repoText);
final int repoLinkIndexEnd = repoLinkIndex + repoText.length;
final String seeSourceFirst = seeSource.substring(0, repoLinkIndex);
final String seeSourceSecond = seeSource.substring(repoLinkIndexEnd);
return AlertDialog(
backgroundColor: colorScheme.background,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
content: Container(
constraints: const BoxConstraints(maxWidth: 400),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
FutureBuilder<String>(
future: getVersionNumber(),
builder: (BuildContext context, AsyncSnapshot<String> snapshot) => SelectableText(
snapshot.hasData ? '$name ${snapshot.data}' : name,
style: textTheme.headlineMedium!.apply(
color: colorScheme.onPrimary,
),
),
),
const SizedBox(height: 24),
SelectableText.rich(
TextSpan(
children: <InlineSpan>[
TextSpan(
style: bodyTextStyle,
text: seeSourceFirst,
),
TextSpan(
style: bodyTextStyle.copyWith(
color: colorScheme.primary,
),
text: repoText,
recognizer: TapGestureRecognizer()
..onTap = () async {
final Uri url =
Uri.parse('https://github.com/flutter/gallery/');
if (await canLaunchUrl(url)) {
await launchUrl(url);
}
},
),
TextSpan(
style: bodyTextStyle,
text: seeSourceSecond,
),
],
),
),
const SizedBox(height: 18),
SelectableText(
legalese,
style: bodyTextStyle,
),
],
),
),
actions: <Widget>[
TextButton(
onPressed: () {
Navigator.of(context).push(MaterialPageRoute<void>(
builder: (BuildContext context) => Theme(
data: Theme.of(context).copyWith(
textTheme: Typography.material2018(
platform: Theme.of(context).platform,
).black,
cardColor: Colors.white,
),
child: const LicensePage(
applicationName: name,
applicationLegalese: legalese,
),
),
));
},
child: Text(
MaterialLocalizations.of(context).viewLicensesButtonLabel,
),
),
TextButton(
onPressed: () {
Navigator.pop(context);
},
child: Text(MaterialLocalizations.of(context).closeButtonLabel),
),
],
);
}
}
| flutter/dev/integration_tests/new_gallery/lib/pages/about.dart/0 | {
"file_path": "flutter/dev/integration_tests/new_gallery/lib/pages/about.dart",
"repo_id": "flutter",
"token_count": 2197
} | 587 |
// 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';
import 'backlayer.dart';
import 'header_form.dart';
class EatForm extends BackLayerItem {
const EatForm({super.key}) : super(index: 2);
@override
State<EatForm> createState() => _EatFormState();
}
class _EatFormState extends State<EatForm> with RestorationMixin {
final RestorableTextEditingController dinerController = RestorableTextEditingController();
final RestorableTextEditingController dateController = RestorableTextEditingController();
final RestorableTextEditingController timeController = RestorableTextEditingController();
final RestorableTextEditingController locationController = RestorableTextEditingController();
@override
String get restorationId => 'eat_form';
@override
void restoreState(RestorationBucket? oldBucket, bool initialRestore) {
registerForRestoration(dinerController, 'diner_controller');
registerForRestoration(dateController, 'date_controller');
registerForRestoration(timeController, 'time_controller');
registerForRestoration(locationController, 'location_controller');
}
@override
void dispose() {
dinerController.dispose();
dateController.dispose();
timeController.dispose();
locationController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final GalleryLocalizations localizations = GalleryLocalizations.of(context)!;
return HeaderForm(
fields: <HeaderFormField>[
HeaderFormField(
index: 0,
iconData: Icons.person,
title: localizations.craneFormDiners,
textController: dinerController.value,
),
HeaderFormField(
index: 1,
iconData: Icons.date_range,
title: localizations.craneFormDate,
textController: dateController.value,
),
HeaderFormField(
index: 2,
iconData: Icons.access_time,
title: localizations.craneFormTime,
textController: timeController.value,
),
HeaderFormField(
index: 3,
iconData: Icons.restaurant_menu,
title: localizations.craneFormLocation,
textController: locationController.value,
),
],
);
}
}
| flutter/dev/integration_tests/new_gallery/lib/studies/crane/eat_form.dart/0 | {
"file_path": "flutter/dev/integration_tests/new_gallery/lib/studies/crane/eat_form.dart",
"repo_id": "flutter",
"token_count": 858
} | 588 |
// 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 VerticalFractionBar extends StatelessWidget {
const VerticalFractionBar({
super.key,
this.color,
required this.fraction,
});
final Color? color;
final double fraction;
@override
Widget build(BuildContext context) {
return LayoutBuilder(builder: (BuildContext context, BoxConstraints constraints) {
return SizedBox(
height: constraints.maxHeight,
width: 4,
child: Column(
children: <Widget>[
SizedBox(
height: (1 - fraction) * constraints.maxHeight,
child: Container(
color: Colors.black,
),
),
SizedBox(
height: fraction * constraints.maxHeight,
child: Container(color: color),
),
],
),
);
});
}
}
| flutter/dev/integration_tests/new_gallery/lib/studies/rally/charts/vertical_fraction_bar.dart/0 | {
"file_path": "flutter/dev/integration_tests/new_gallery/lib/studies/rally/charts/vertical_fraction_bar.dart",
"repo_id": "flutter",
"token_count": 442
} | 589 |
// 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 'colors.dart';
class BottomDrawer extends StatelessWidget {
const BottomDrawer({
super.key,
this.onVerticalDragUpdate,
this.onVerticalDragEnd,
required this.leading,
required this.trailing,
});
final GestureDragUpdateCallback? onVerticalDragUpdate;
final GestureDragEndCallback? onVerticalDragEnd;
final Widget leading;
final Widget trailing;
@override
Widget build(BuildContext context) {
final ThemeData theme = Theme.of(context);
return GestureDetector(
behavior: HitTestBehavior.opaque,
onVerticalDragUpdate: onVerticalDragUpdate,
onVerticalDragEnd: onVerticalDragEnd,
child: Material(
color: theme.bottomSheetTheme.backgroundColor,
borderRadius: const BorderRadius.only(
topLeft: Radius.circular(12),
topRight: Radius.circular(12),
),
child: ListView(
padding: const EdgeInsets.all(12),
physics: const NeverScrollableScrollPhysics(),
children: <Widget>[
const SizedBox(height: 28),
leading,
const SizedBox(height: 8),
const Divider(
color: ReplyColors.blue200,
thickness: 0.25,
indent: 18,
endIndent: 160,
),
const SizedBox(height: 16),
Padding(
padding: const EdgeInsetsDirectional.only(start: 18),
child: Text(
'FOLDERS',
style: theme.textTheme.bodySmall!.copyWith(
color:
theme.navigationRailTheme.unselectedLabelTextStyle!.color,
),
),
),
const SizedBox(height: 4),
trailing,
],
),
),
);
}
}
| flutter/dev/integration_tests/new_gallery/lib/studies/reply/bottom_drawer.dart/0 | {
"file_path": "flutter/dev/integration_tests/new_gallery/lib/studies/reply/bottom_drawer.dart",
"repo_id": "flutter",
"token_count": 914
} | 590 |
// 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';
import 'package:flutter/material.dart';
import 'package:scoped_model/scoped_model.dart';
import '../../gallery_localizations.dart';
import '../../layout/adaptive.dart';
import '../../layout/text_scale.dart';
import 'colors.dart';
import 'model/app_state_model.dart';
import 'model/product.dart';
import 'page_status.dart';
import 'shopping_cart.dart';
// These curves define the emphasized easing curve.
const Cubic _accelerateCurve = Cubic(0.548, 0, 0.757, 0.464);
const Cubic _decelerateCurve = Cubic(0.23, 0.94, 0.41, 1);
// The time at which the accelerate and decelerate curves switch off
const double _peakVelocityTime = 0.248210;
// Percent (as a decimal) of animation that should be completed at _peakVelocityTime
const double _peakVelocityProgress = 0.379146;
// Radius of the shape on the top start of the sheet for mobile layouts.
const double _mobileCornerRadius = 24.0;
// Radius of the shape on the top start and bottom start of the sheet for mobile layouts.
const double _desktopCornerRadius = 12.0;
// Width for just the cart icon and no thumbnails.
const double _cartIconWidth = 64.0;
// Height for just the cart icon and no thumbnails.
const double _cartIconHeight = 56.0;
// Height of a thumbnail.
const double _defaultThumbnailHeight = 40.0;
// Gap between thumbnails.
const double _thumbnailGap = 16.0;
// Maximum number of thumbnails shown in the cart.
const int _maxThumbnailCount = 3;
double _thumbnailHeight(BuildContext context) {
return _defaultThumbnailHeight * reducedTextScale(context);
}
double _paddedThumbnailHeight(BuildContext context) {
return _thumbnailHeight(context) + _thumbnailGap;
}
class ExpandingBottomSheet extends StatefulWidget {
const ExpandingBottomSheet({
super.key,
required this.hideController,
required this.expandingController,
});
final AnimationController hideController;
final AnimationController expandingController;
@override
ExpandingBottomSheetState createState() => ExpandingBottomSheetState();
static ExpandingBottomSheetState? of(BuildContext context,
{bool isNullOk = false}) {
final ExpandingBottomSheetState? result = context.findAncestorStateOfType<ExpandingBottomSheetState>();
if (isNullOk || result != null) {
return result;
}
throw FlutterError(
'ExpandingBottomSheet.of() called with a context that does not contain a ExpandingBottomSheet.\n');
}
}
// Emphasized Easing is a motion curve that has an organic, exciting feeling.
// It's very fast to begin with and then very slow to finish. Unlike standard
// curves, like [Curves.fastOutSlowIn], it can't be expressed in a cubic bezier
// curve formula. It's quintic, not cubic. But it _can_ be expressed as one
// curve followed by another, which we do here.
Animation<T> _getEmphasizedEasingAnimation<T>({
required T begin,
required T peak,
required T end,
required bool isForward,
required Animation<double> parent,
}) {
Curve firstCurve;
Curve secondCurve;
double firstWeight;
double secondWeight;
if (isForward) {
firstCurve = _accelerateCurve;
secondCurve = _decelerateCurve;
firstWeight = _peakVelocityTime;
secondWeight = 1 - _peakVelocityTime;
} else {
firstCurve = _decelerateCurve.flipped;
secondCurve = _accelerateCurve.flipped;
firstWeight = 1 - _peakVelocityTime;
secondWeight = _peakVelocityTime;
}
return TweenSequence<T>(
<TweenSequenceItem<T>>[
TweenSequenceItem<T>(
weight: firstWeight,
tween: Tween<T>(
begin: begin,
end: peak,
).chain(CurveTween(curve: firstCurve)),
),
TweenSequenceItem<T>(
weight: secondWeight,
tween: Tween<T>(
begin: peak,
end: end,
).chain(CurveTween(curve: secondCurve)),
),
],
).animate(parent);
}
// Calculates the value where two double Animations should be joined. Used by
// callers of _getEmphasisedEasing<double>().
double _getPeakPoint({required double begin, required double end}) {
return begin + (end - begin) * _peakVelocityProgress;
}
class ExpandingBottomSheetState extends State<ExpandingBottomSheet> {
final GlobalKey _expandingBottomSheetKey =
GlobalKey(debugLabel: 'Expanding bottom sheet');
// The width of the Material, calculated by _widthFor() & based on the number
// of products in the cart. 64.0 is the width when there are 0 products
// (_kWidthForZeroProducts)
double _width = _cartIconWidth;
double _height = _cartIconHeight;
// Controller for the opening and closing of the ExpandingBottomSheet
AnimationController get _controller => widget.expandingController;
// Animations for the opening and closing of the ExpandingBottomSheet
late Animation<double> _widthAnimation;
late Animation<double> _heightAnimation;
late Animation<double> _thumbnailOpacityAnimation;
late Animation<double> _cartOpacityAnimation;
late Animation<double> _topStartShapeAnimation;
late Animation<double> _bottomStartShapeAnimation;
late Animation<Offset> _slideAnimation;
late Animation<double> _gapAnimation;
Animation<double> _getWidthAnimation(double screenWidth) {
if (_controller.status == AnimationStatus.forward) {
// Opening animation
return Tween<double>(begin: _width, end: screenWidth).animate(
CurvedAnimation(
parent: _controller.view,
curve: const Interval(0, 0.3, curve: Curves.fastOutSlowIn),
),
);
} else {
// Closing animation
return _getEmphasizedEasingAnimation(
begin: _width,
peak: _getPeakPoint(begin: _width, end: screenWidth),
end: screenWidth,
isForward: false,
parent: CurvedAnimation(
parent: _controller.view, curve: const Interval(0, 0.87)),
);
}
}
Animation<double> _getHeightAnimation(double screenHeight) {
if (_controller.status == AnimationStatus.forward) {
// Opening animation
return _getEmphasizedEasingAnimation(
begin: _height,
peak: _getPeakPoint(begin: _height, end: screenHeight),
end: screenHeight,
isForward: true,
parent: _controller.view,
);
} else {
// Closing animation
return Tween<double>(
begin: _height,
end: screenHeight,
).animate(
CurvedAnimation(
parent: _controller.view,
curve: const Interval(0.434, 1), // not used
// only the reverseCurve will be used
reverseCurve: Interval(0.434, 1, curve: Curves.fastOutSlowIn.flipped),
),
);
}
}
Animation<double> _getDesktopGapAnimation(double gapHeight) {
final double collapsedGapHeight = gapHeight;
const double expandedGapHeight = 0.0;
if (_controller.status == AnimationStatus.forward) {
// Opening animation
return _getEmphasizedEasingAnimation(
begin: collapsedGapHeight,
peak: collapsedGapHeight +
(expandedGapHeight - collapsedGapHeight) * _peakVelocityProgress,
end: expandedGapHeight,
isForward: true,
parent: _controller.view,
);
} else {
// Closing animation
return Tween<double>(
begin: collapsedGapHeight,
end: expandedGapHeight,
).animate(
CurvedAnimation(
parent: _controller.view,
curve: const Interval(0.434, 1), // not used
// only the reverseCurve will be used
reverseCurve: Interval(0.434, 1, curve: Curves.fastOutSlowIn.flipped),
),
);
}
}
// Animation of the top-start cut corner. It's cut when closed and not cut when open.
Animation<double> _getShapeTopStartAnimation(BuildContext context) {
final bool isDesktop = isDisplayDesktop(context);
final double cornerRadius = isDesktop ? _desktopCornerRadius : _mobileCornerRadius;
if (_controller.status == AnimationStatus.forward) {
return Tween<double>(begin: cornerRadius, end: 0).animate(
CurvedAnimation(
parent: _controller.view,
curve: const Interval(0, 0.3, curve: Curves.fastOutSlowIn),
),
);
} else {
return _getEmphasizedEasingAnimation(
begin: cornerRadius,
peak: _getPeakPoint(begin: cornerRadius, end: 0),
end: 0,
isForward: false,
parent: _controller.view,
);
}
}
// Animation of the bottom-start cut corner. It's cut when closed and not cut when open.
Animation<double> _getShapeBottomStartAnimation(BuildContext context) {
final bool isDesktop = isDisplayDesktop(context);
final double cornerRadius = isDesktop ? _desktopCornerRadius : 0.0;
if (_controller.status == AnimationStatus.forward) {
return Tween<double>(begin: cornerRadius, end: 0).animate(
CurvedAnimation(
parent: _controller.view,
curve: const Interval(0, 0.3, curve: Curves.fastOutSlowIn),
),
);
} else {
return _getEmphasizedEasingAnimation(
begin: cornerRadius,
peak: _getPeakPoint(begin: cornerRadius, end: 0),
end: 0,
isForward: false,
parent: _controller.view,
);
}
}
Animation<double> _getThumbnailOpacityAnimation() {
return Tween<double>(begin: 1, end: 0).animate(
CurvedAnimation(
parent: _controller.view,
curve: _controller.status == AnimationStatus.forward
? const Interval(0, 0.3)
: const Interval(0.532, 0.766),
),
);
}
Animation<double> _getCartOpacityAnimation() {
return CurvedAnimation(
parent: _controller.view,
curve: _controller.status == AnimationStatus.forward
? const Interval(0.3, 0.6)
: const Interval(0.766, 1),
);
}
// Returns the correct width of the ExpandingBottomSheet based on the number of
// products and the text scaling options in the cart in the mobile layout.
double _mobileWidthFor(int numProducts, BuildContext context) {
final int cartThumbnailGap = numProducts > 0 ? 16 : 0;
final double thumbnailsWidth =
min(numProducts, _maxThumbnailCount) * _paddedThumbnailHeight(context);
final num overflowNumberWidth =
numProducts > _maxThumbnailCount ? 30 * cappedTextScale(context) : 0;
return _cartIconWidth +
cartThumbnailGap +
thumbnailsWidth +
overflowNumberWidth;
}
// Returns the correct height of the ExpandingBottomSheet based on the text scaling
// options in the mobile layout.
double _mobileHeightFor(BuildContext context) {
return _paddedThumbnailHeight(context);
}
// Returns the correct width of the ExpandingBottomSheet based on the text scaling
// options in the desktop layout.
double _desktopWidthFor(BuildContext context) {
return _paddedThumbnailHeight(context) + 8;
}
// Returns the correct height of the ExpandingBottomSheet based on the number of
// products and the text scaling options in the cart in the desktop layout.
double _desktopHeightFor(int numProducts, BuildContext context) {
final int cartThumbnailGap = numProducts > 0 ? 8 : 0;
final double thumbnailsHeight =
min(numProducts, _maxThumbnailCount) * _paddedThumbnailHeight(context);
final num overflowNumberHeight =
numProducts > _maxThumbnailCount ? 28 * reducedTextScale(context) : 0;
return _cartIconHeight +
cartThumbnailGap +
thumbnailsHeight +
overflowNumberHeight;
}
// Returns true if the cart is open or opening and false otherwise.
bool get _isOpen {
final AnimationStatus status = _controller.status;
return status == AnimationStatus.completed ||
status == AnimationStatus.forward;
}
// Opens the ExpandingBottomSheet if it's closed, otherwise does nothing.
void open() {
if (!_isOpen) {
_controller.forward();
}
}
// Closes the ExpandingBottomSheet if it's open or opening, otherwise does nothing.
void close() {
if (_isOpen) {
_controller.reverse();
}
}
// Changes the padding between the start edge of the Material and the cart icon
// based on the number of products in the cart (padding increases when > 0
// products.)
EdgeInsetsDirectional _horizontalCartPaddingFor(int numProducts) {
return (numProducts == 0)
? const EdgeInsetsDirectional.only(start: 20, end: 8)
: const EdgeInsetsDirectional.only(start: 32, end: 8);
}
// Changes the padding above and below the cart icon
// based on the number of products in the cart (padding increases when > 0
// products.)
EdgeInsets _verticalCartPaddingFor(int numProducts) {
return (numProducts == 0)
? const EdgeInsets.only(top: 16, bottom: 16)
: const EdgeInsets.only(top: 16, bottom: 24);
}
bool get _cartIsVisible => _thumbnailOpacityAnimation.value == 0;
// We take 16 pts off of the bottom padding to ensure the collapsed shopping
// cart is not too tall.
double get _bottomSafeArea {
return max(MediaQuery.of(context).viewPadding.bottom - 16, 0);
}
Widget _buildThumbnails(BuildContext context, int numProducts) {
final bool isDesktop = isDisplayDesktop(context);
Widget thumbnails;
if (isDesktop) {
thumbnails = Column(
children: <Widget>[
AnimatedPadding(
padding: _verticalCartPaddingFor(numProducts),
duration: const Duration(milliseconds: 225),
child: const Icon(Icons.shopping_cart),
),
SizedBox(
width: _width,
height: min(numProducts, _maxThumbnailCount) *
_paddedThumbnailHeight(context),
child: const ProductThumbnailRow(),
),
const ExtraProductsNumber(),
],
);
} else {
thumbnails = Column(
children: <Widget>[
Row(
children: <Widget>[
AnimatedPadding(
padding: _horizontalCartPaddingFor(numProducts),
duration: const Duration(milliseconds: 225),
child: const Icon(Icons.shopping_cart),
),
Container(
// Accounts for the overflow number
width: min(numProducts, _maxThumbnailCount) *
_paddedThumbnailHeight(context) +
(numProducts > 0 ? _thumbnailGap : 0),
height: _height - _bottomSafeArea,
padding: const EdgeInsets.symmetric(vertical: 8),
child: const ProductThumbnailRow(),
),
const ExtraProductsNumber(),
],
),
],
);
}
return ExcludeSemantics(
child: Opacity(
opacity: _thumbnailOpacityAnimation.value,
child: thumbnails,
),
);
}
Widget _buildShoppingCartPage() {
return Opacity(
opacity: _cartOpacityAnimation.value,
child: const ShoppingCartPage(),
);
}
Widget _buildCart(BuildContext context) {
// numProducts is the number of different products in the cart (does not
// include multiples of the same product).
final bool isDesktop = isDisplayDesktop(context);
final AppStateModel model = ScopedModel.of<AppStateModel>(context);
final int numProducts = model.productsInCart.keys.length;
final int totalCartQuantity = model.totalCartQuantity;
final Size screenSize = MediaQuery.of(context).size;
final double screenWidth = screenSize.width;
final double screenHeight = screenSize.height;
final double expandedCartWidth = isDesktop
? (360 * cappedTextScale(context)).clamp(360, screenWidth).toDouble()
: screenWidth;
_width = isDesktop
? _desktopWidthFor(context)
: _mobileWidthFor(numProducts, context);
_widthAnimation = _getWidthAnimation(expandedCartWidth);
_height = isDesktop
? _desktopHeightFor(numProducts, context)
: _mobileHeightFor(context) + _bottomSafeArea;
_heightAnimation = _getHeightAnimation(screenHeight);
_topStartShapeAnimation = _getShapeTopStartAnimation(context);
_bottomStartShapeAnimation = _getShapeBottomStartAnimation(context);
_thumbnailOpacityAnimation = _getThumbnailOpacityAnimation();
_cartOpacityAnimation = _getCartOpacityAnimation();
_gapAnimation = isDesktop
? _getDesktopGapAnimation(116)
: const AlwaysStoppedAnimation<double>(0);
final Widget child = SizedBox(
width: _widthAnimation.value,
height: _heightAnimation.value,
child: Material(
animationDuration: Duration.zero,
shape: BeveledRectangleBorder(
borderRadius: BorderRadiusDirectional.only(
topStart: Radius.circular(_topStartShapeAnimation.value),
bottomStart: Radius.circular(_bottomStartShapeAnimation.value),
),
),
elevation: 4,
color: shrinePink50,
child: _cartIsVisible
? _buildShoppingCartPage()
: _buildThumbnails(context, numProducts),
),
);
final Widget childWithInteraction = productPageIsVisible(context)
? Semantics(
button: true,
enabled: true,
label: GalleryLocalizations.of(context)!
.shrineScreenReaderCart(totalCartQuantity),
child: MouseRegion(
cursor: SystemMouseCursors.click,
child: GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: open,
child: child,
),
),
)
: child;
return Padding(
padding: EdgeInsets.only(top: _gapAnimation.value),
child: childWithInteraction,
);
}
// Builder for the hide and reveal animation when the backdrop opens and closes
Widget _buildSlideAnimation(BuildContext context, Widget child) {
final bool isDesktop = isDisplayDesktop(context);
if (isDesktop) {
return child;
} else {
final int textDirectionScalar =
Directionality.of(context) == TextDirection.ltr ? 1 : -1;
_slideAnimation = _getEmphasizedEasingAnimation(
begin: Offset(1.0 * textDirectionScalar, 0.0),
peak: Offset(_peakVelocityProgress * textDirectionScalar, 0),
end: Offset.zero,
isForward: widget.hideController.status == AnimationStatus.forward,
parent: widget.hideController,
);
return SlideTransition(
position: _slideAnimation,
child: child,
);
}
}
@override
Widget build(BuildContext context) {
return AnimatedSize(
key: _expandingBottomSheetKey,
duration: const Duration(milliseconds: 225),
curve: Curves.easeInOut,
alignment: AlignmentDirectional.topStart,
child: AnimatedBuilder(
animation: widget.hideController,
builder: (BuildContext context, Widget? child) => AnimatedBuilder(
animation: widget.expandingController,
builder: (BuildContext context, Widget? child) => ScopedModelDescendant<AppStateModel>(
builder: (BuildContext context, Widget? child, AppStateModel model) =>
_buildSlideAnimation(context, _buildCart(context)),
),
),
),
);
}
}
class ProductThumbnailRow extends StatefulWidget {
const ProductThumbnailRow({super.key});
@override
State<ProductThumbnailRow> createState() => _ProductThumbnailRowState();
}
class _ProductThumbnailRowState extends State<ProductThumbnailRow> {
final GlobalKey<AnimatedListState> _listKey = GlobalKey<AnimatedListState>();
// _list represents what's currently on screen. If _internalList updates,
// it will need to be updated to match it.
late _ListModel _list;
// _internalList represents the list as it is updated by the AppStateModel.
late List<int> _internalList;
@override
void initState() {
super.initState();
_list = _ListModel(
listKey: _listKey,
initialItems:
ScopedModel.of<AppStateModel>(context).productsInCart.keys.toList(),
removedItemBuilder: _buildRemovedThumbnail,
);
_internalList = List<int>.from(_list.list);
}
Product _productWithId(int productId) {
final AppStateModel model = ScopedModel.of<AppStateModel>(context);
final Product product = model.getProductById(productId);
return product;
}
Widget _buildRemovedThumbnail(
int item, BuildContext context, Animation<double> animation) {
return ProductThumbnail(animation, animation, _productWithId(item));
}
Widget _buildThumbnail(
BuildContext context, int index, Animation<double> animation) {
final Animation<double> thumbnailSize = Tween<double>(begin: 0.8, end: 1).animate(
CurvedAnimation(
curve: const Interval(0.33, 1, curve: Curves.easeIn),
parent: animation,
),
);
final Animation<double> opacity = CurvedAnimation(
curve: const Interval(0.33, 1),
parent: animation,
);
return ProductThumbnail(
thumbnailSize, opacity, _productWithId(_list[index]));
}
// If the lists are the same length, assume nothing has changed.
// If the internalList is shorter than the ListModel, an item has been removed.
// If the internalList is longer, then an item has been added.
void _updateLists() {
// Update _internalList based on the model
_internalList =
ScopedModel.of<AppStateModel>(context).productsInCart.keys.toList();
final Set<int> internalSet = Set<int>.from(_internalList);
final Set<int> listSet = Set<int>.from(_list.list);
final Set<int> difference = internalSet.difference(listSet);
if (difference.isEmpty) {
return;
}
for (final int product in difference) {
if (_internalList.length < _list.length) {
_list.remove(product);
} else if (_internalList.length > _list.length) {
_list.add(product);
}
}
while (_internalList.length != _list.length) {
int index = 0;
// Check bounds and that the list elements are the same
while (_internalList.isNotEmpty &&
_list.length > 0 &&
index < _internalList.length &&
index < _list.length &&
_internalList[index] == _list[index]) {
index++;
}
}
}
Widget _buildAnimatedList(BuildContext context) {
final bool isDesktop = isDisplayDesktop(context);
return AnimatedList(
key: _listKey,
shrinkWrap: true,
itemBuilder: _buildThumbnail,
initialItemCount: _list.length,
scrollDirection: isDesktop ? Axis.vertical : Axis.horizontal,
physics: const NeverScrollableScrollPhysics(), // Cart shouldn't scroll
);
}
@override
Widget build(BuildContext context) {
return ScopedModelDescendant<AppStateModel>(
builder: (BuildContext context, Widget? child, AppStateModel model) {
_updateLists();
return _buildAnimatedList(context);
},
);
}
}
class ExtraProductsNumber extends StatelessWidget {
const ExtraProductsNumber({super.key});
// Calculates the number to be displayed at the end of the row if there are
// more than three products in the cart. This calculates overflow products,
// including their duplicates (but not duplicates of products shown as
// thumbnails).
int _calculateOverflow(AppStateModel model) {
final Map<int, int> productMap = model.productsInCart;
// List created to be able to access products by index instead of ID.
// Order is guaranteed because productsInCart returns a LinkedHashMap.
final List<int> products = productMap.keys.toList();
int overflow = 0;
final int numProducts = products.length;
for (int i = _maxThumbnailCount; i < numProducts; i++) {
overflow += productMap[products[i]]!;
}
return overflow;
}
Widget _buildOverflow(AppStateModel model, BuildContext context) {
if (model.productsInCart.length <= _maxThumbnailCount) {
return Container();
}
final int numOverflowProducts = _calculateOverflow(model);
// Maximum of 99 so padding doesn't get messy.
final int displayedOverflowProducts =
numOverflowProducts <= 99 ? numOverflowProducts : 99;
return Text(
'+$displayedOverflowProducts',
style: Theme.of(context).primaryTextTheme.labelLarge,
);
}
@override
Widget build(BuildContext context) {
return ScopedModelDescendant<AppStateModel>(
builder: (BuildContext builder, Widget? child, AppStateModel model) => _buildOverflow(model, context),
);
}
}
class ProductThumbnail extends StatelessWidget {
const ProductThumbnail(this.animation, this.opacityAnimation, this.product,
{super.key});
final Animation<double> animation;
final Animation<double> opacityAnimation;
final Product product;
@override
Widget build(BuildContext context) {
final bool isDesktop = isDisplayDesktop(context);
return FadeTransition(
opacity: opacityAnimation,
child: ScaleTransition(
scale: animation,
child: Container(
width: _thumbnailHeight(context),
height: _thumbnailHeight(context),
decoration: BoxDecoration(
image: DecorationImage(
image: ExactAssetImage(
product.assetName, // asset name
package: product.assetPackage, // asset package
),
fit: BoxFit.cover,
),
borderRadius: const BorderRadius.all(Radius.circular(10)),
),
margin: isDesktop
? const EdgeInsetsDirectional.only(start: 12, end: 12, bottom: 16)
: const EdgeInsetsDirectional.only(start: 16),
),
),
);
}
}
// _ListModel manipulates an internal list and an AnimatedList
class _ListModel {
_ListModel({
required this.listKey,
required this.removedItemBuilder,
Iterable<int>? initialItems,
}) : _items = initialItems?.toList() ?? <int>[];
final GlobalKey<AnimatedListState> listKey;
final Widget Function(int, BuildContext, Animation<double>)
removedItemBuilder;
final List<int> _items;
AnimatedListState? get _animatedList => listKey.currentState;
void add(int product) {
_insert(_items.length, product);
}
void _insert(int index, int item) {
_items.insert(index, item);
_animatedList!
.insertItem(index, duration: const Duration(milliseconds: 225));
}
void remove(int product) {
final int index = _items.indexOf(product);
if (index >= 0) {
_removeAt(index);
}
}
void _removeAt(int index) {
final int removedItem = _items.removeAt(index);
_animatedList!.removeItem(index, (BuildContext context, Animation<double> animation) {
return removedItemBuilder(removedItem, context, animation);
});
}
int get length => _items.length;
int operator [](int index) => _items[index];
int indexOf(int item) => _items.indexOf(item);
List<int> get list => _items;
}
| flutter/dev/integration_tests/new_gallery/lib/studies/shrine/expanding_bottom_sheet.dart/0 | {
"file_path": "flutter/dev/integration_tests/new_gallery/lib/studies/shrine/expanding_bottom_sheet.dart",
"repo_id": "flutter",
"token_count": 9928
} | 591 |
// 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,
required this.imageAspectRatio,
});
static const double spacerHeight = 44;
static const double horizontalPadding = 28;
final Product bottom;
final Product? top;
final double imageAspectRatio;
@override
Widget build(BuildContext context) {
return LayoutBuilder(builder: (BuildContext context, BoxConstraints constraints) {
return ListView(
physics: const ClampingScrollPhysics(),
children: <Widget>[
Padding(
padding: const EdgeInsetsDirectional.only(start: horizontalPadding),
child: top != null
? MobileProductCard(
imageAspectRatio: imageAspectRatio,
product: top!,
)
: const SizedBox(
height: spacerHeight,
),
),
const SizedBox(height: spacerHeight),
Padding(
padding: const EdgeInsetsDirectional.only(end: horizontalPadding),
child: MobileProductCard(
imageAspectRatio: imageAspectRatio,
product: bottom,
),
),
],
);
});
}
}
class OneProductCardColumn extends StatelessWidget {
const OneProductCardColumn({
super.key,
required this.product,
required this.reverse,
});
final Product product;
// Whether the product column should align to the bottom.
final bool reverse;
@override
Widget build(BuildContext context) {
return ListView(
physics: const ClampingScrollPhysics(),
reverse: reverse,
children: <Widget>[
const SizedBox(
height: 40,
),
MobileProductCard(
product: product,
),
],
);
}
}
| flutter/dev/integration_tests/new_gallery/lib/studies/shrine/supplemental/product_columns.dart/0 | {
"file_path": "flutter/dev/integration_tests/new_gallery/lib/studies/shrine/supplemental/product_columns.dart",
"repo_id": "flutter",
"token_count": 893
} | 592 |
// 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:flutter_driver/driver_extension.dart';
/// This sample application creates a hard to render frame, causing the
/// driver script to race the raster thread. If the driver script wins the
/// race, it will screenshot the previous frame. If the raster thread wins
/// it, it will screenshot the latest frame.
void main() {
enableFlutterDriverExtension();
runApp(const Toggler());
}
class Toggler extends StatefulWidget {
const Toggler({super.key});
@override
State<Toggler> createState() => TogglerState();
}
class TogglerState extends State<Toggler> {
bool _visible = false;
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('FlutterDriver test'),
),
body: Material(
child: Column(
children: <Widget>[
TextButton(
key: const ValueKey<String>('toggle'),
child: const Text('Toggle visibility'),
onPressed: () {
setState(() {
_visible = !_visible;
});
},
),
Expanded(
child: ListView(
children: _buildRows(_visible ? 10 : 0),
),
),
],
),
),
),
);
}
}
List<Widget> _buildRows(int count) {
return List<Widget>.generate(count, (int i) {
return Row(
children: _buildCells(i / count),
);
});
}
/// Builds cells that are known to take time to render causing a delay on the
/// raster thread.
List<Widget> _buildCells(double epsilon) {
return List<Widget>.generate(15, (int i) {
return Expanded(
child: Material(
// A magic color that the test will be looking for on the screenshot.
color: const Color(0xffff0102),
borderRadius: BorderRadius.all(Radius.circular(i.toDouble() + epsilon)),
elevation: 5.0,
child: const SizedBox(height: 10.0, width: 10.0),
),
);
});
}
| flutter/dev/integration_tests/ui/lib/screenshot.dart/0 | {
"file_path": "flutter/dev/integration_tests/ui/lib/screenshot.dart",
"repo_id": "flutter",
"token_count": 969
} | 593 |
// 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:web_integration/a.dart'
if (dart.library.io) 'package:web_integration/b.dart' as message1;
import 'package:web_integration/c.dart'
if (dart.library.html) 'package:web_integration/d.dart' as message2;
void main() {
if (message1.message == 'a' && message2.message == 'd') {
print('--- TEST SUCCEEDED ---');
} else {
print('--- TEST FAILED ---');
}
}
| flutter/dev/integration_tests/web/test/test.dart/0 | {
"file_path": "flutter/dev/integration_tests/web/test/test.dart",
"repo_id": "flutter",
"token_count": 194
} | 594 |
# Flutter Web integration tests
To run the tests in this package [download][1] the chromedriver matching the
version of Chrome. To find out the version of your Chrome installation visit
chrome://version.
Start `chromedriver` using the following command:
```
chromedriver --port=4444
```
An integration test is run using the `flutter drive` command. Some tests are
written for a specific [web renderer][2] and/or specific [build mode][4].
Before running a test, check the `_runWebLongRunningTests` function defined in
[dev/bots/test.dart][3], and determine the right web renderer and the build
mode you'd like to run the test in.
Here's an example of running an integration test:
```
flutter drive --target=test_driver/text_editing_integration.dart \
-d web-server \
--browser-name=chrome \
--profile \
--web-renderer=html
```
This example runs the test in profile mode (`--profile`) using the HTML
renderer (`--web-renderer=html`).
More resources:
* chromedriver: https://chromedriver.chromium.org/getting-started
* FlutterDriver: https://github.com/flutter/flutter/wiki/Running-Flutter-Driver-tests-with-Web
* `package:integration_test`: https://pub.dev/packages/integration_test
[1]: https://chromedriver.chromium.org/downloads
[2]: https://flutter.dev/docs/development/tools/web-renderers
[3]: https://github.com/flutter/flutter/blob/master/dev/bots/test.dart
[4]: https://flutter.dev/docs/testing/build-modes
| flutter/dev/integration_tests/web_e2e_tests/README.md/0 | {
"file_path": "flutter/dev/integration_tests/web_e2e_tests/README.md",
"repo_id": "flutter",
"token_count": 444
} | 595 |
// 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 'dart:typed_data';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
import 'package:wide_gamut_test/main.dart' as app;
// See: https://developer.apple.com/documentation/metal/mtlpixelformat/mtlpixelformatbgr10_xr.
double _decodeBGR10(int x) {
const double max = 1.25098;
const double min = -0.752941;
const double intercept = min;
const double slope = (max - min) / 1024.0;
return (x * slope) + intercept;
}
double _decodeHalf(int x) {
if (x == 0x7c00) {
return double.infinity;
}
if (x == 0xfc00) {
return -double.infinity;
}
final double sign = x & 0x8000 == 0 ? 1.0 : -1.0;
final int exponent = (x >> 10) & 0x1f;
final int fraction = x & 0x3ff;
if (exponent == 0) {
return sign * math.pow(2.0, -14) * (fraction / 1024.0);
} else {
return sign * math.pow(2.0, exponent - 15) * (1.0 + fraction / 1024.0);
}
}
bool _isAlmost(double x, double y, double epsilon) {
return (x - y).abs() < epsilon;
}
List<double> _deepRed = <double>[1.0931, -0.2268, -0.1501];
bool _findRGBAF16Color(
Uint8List bytes, int width, int height, List<double> color) {
final ByteData byteData = ByteData.sublistView(bytes);
expect(bytes.lengthInBytes, width * height * 8);
expect(bytes.lengthInBytes, byteData.lengthInBytes);
bool foundDeepRed = false;
for (int i = 0; i < bytes.lengthInBytes; i += 8) {
final int pixel = byteData.getUint64(i, Endian.host);
final double blue = _decodeHalf((pixel >> 32) & 0xffff);
final double green = _decodeHalf((pixel >> 16) & 0xffff);
final double red = _decodeHalf((pixel >> 0) & 0xffff);
if (_isAlmost(red, color[0], 0.01) &&
_isAlmost(green, color[1], 0.01) &&
_isAlmost(blue, color[2], 0.01)) {
foundDeepRed = true;
}
}
return foundDeepRed;
}
bool _findBGRA10Color(
Uint8List bytes, int width, int height, List<double> color) {
final ByteData byteData = ByteData.sublistView(bytes);
expect(bytes.lengthInBytes, width * height * 8);
expect(bytes.lengthInBytes, byteData.lengthInBytes);
bool foundDeepRed = false;
for (int i = 0; i < bytes.lengthInBytes; i += 8) {
final int pixel = byteData.getUint64(i, Endian.host);
final double blue = _decodeBGR10((pixel >> 6) & 0x3ff);
final double green = _decodeBGR10((pixel >> 22) & 0x3ff);
final double red = _decodeBGR10((pixel >> 38) & 0x3ff);
if (_isAlmost(red, color[0], 0.01) &&
_isAlmost(green, color[1], 0.01) &&
_isAlmost(blue, color[2], 0.01)) {
foundDeepRed = true;
}
}
return foundDeepRed;
}
bool _findBGR10Color(
Uint8List bytes, int width, int height, List<double> color) {
final ByteData byteData = ByteData.sublistView(bytes);
expect(bytes.lengthInBytes, width * height * 4);
expect(bytes.lengthInBytes, byteData.lengthInBytes);
bool foundDeepRed = false;
for (int i = 0; i < bytes.lengthInBytes; i += 4) {
final int pixel = byteData.getUint32(i, Endian.host);
final double blue = _decodeBGR10(pixel & 0x3ff);
final double green = _decodeBGR10((pixel >> 10) & 0x3ff);
final double red = _decodeBGR10((pixel >> 20) & 0x3ff);
if (_isAlmost(red, color[0], 0.01) &&
_isAlmost(green, color[1], 0.01) &&
_isAlmost(blue, color[2], 0.01)) {
foundDeepRed = true;
}
}
return foundDeepRed;
}
bool _findColor(List<Object?> result, List<double> color) {
expect(result, isNotNull);
expect(result.length, 4);
final int width = (result[0] as int?)!;
final int height = (result[1] as int?)!;
final String format = (result[2] as String?)!;
if (format == 'MTLPixelFormatBGR10_XR') {
return _findBGR10Color((result[3] as Uint8List?)!, width, height, color);
} else if (format == 'MTLPixelFormatBGRA10_XR') {
return _findBGRA10Color((result[3] as Uint8List?)!, width, height, color);
} else if (format == 'MTLPixelFormatRGBA16Float') {
return _findRGBAF16Color((result[3] as Uint8List?)!, width, height, color);
} else {
fail('Unsupported pixel format: $format');
}
}
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
group('end-to-end test', () {
testWidgets('look for display p3 deepest red', (WidgetTester tester) async {
app.run(app.Setup.image);
await tester.pumpAndSettle(const Duration(seconds: 2));
const MethodChannel channel = MethodChannel('flutter/screenshot');
final List<Object?> result =
await channel.invokeMethod('test') as List<Object?>;
expect(_findColor(result, _deepRed), isTrue);
});
testWidgets('look for display p3 deepest red', (WidgetTester tester) async {
app.run(app.Setup.canvasSaveLayer);
await tester.pumpAndSettle(const Duration(seconds: 2));
const MethodChannel channel = MethodChannel('flutter/screenshot');
final List<Object?> result =
await channel.invokeMethod('test') as List<Object?>;
expect(_findColor(result, _deepRed), isTrue);
});
testWidgets('no p3 deepest red without image', (WidgetTester tester) async {
app.run(app.Setup.none);
await tester.pumpAndSettle(const Duration(seconds: 2));
const MethodChannel channel = MethodChannel('flutter/screenshot');
final List<Object?> result =
await channel.invokeMethod('test') as List<Object?>;
expect(_findColor(result, _deepRed), isFalse);
expect(_findColor(result, <double>[0.0, 1.0, 0.0]), isFalse);
});
testWidgets('p3 deepest red with blur', (WidgetTester tester) async {
app.run(app.Setup.blur);
await tester.pumpAndSettle(const Duration(seconds: 2));
const MethodChannel channel = MethodChannel('flutter/screenshot');
final List<Object?> result =
await channel.invokeMethod('test') as List<Object?>;
expect(_findColor(result, _deepRed), isTrue);
expect(_findColor(result, <double>[0.0, 1.0, 0.0]), isTrue);
});
testWidgets('draw image with wide gamut works', (WidgetTester tester) async {
app.run(app.Setup.drawnImage);
await tester.pumpAndSettle(const Duration(seconds: 2));
const MethodChannel channel = MethodChannel('flutter/screenshot');
final List<Object?> result =
await channel.invokeMethod('test') as List<Object?>;
expect(_findColor(result, <double>[0.0, 1.0, 0.0]), isTrue);
});
});
}
| flutter/dev/integration_tests/wide_gamut_test/integration_test/app_test.dart/0 | {
"file_path": "flutter/dev/integration_tests/wide_gamut_test/integration_test/app_test.dart",
"repo_id": "flutter",
"token_count": 2539
} | 596 |
#include "Generated.xcconfig"
| flutter/dev/manual_tests/ios/Flutter/Debug.xcconfig/0 | {
"file_path": "flutter/dev/manual_tests/ios/Flutter/Debug.xcconfig",
"repo_id": "flutter",
"token_count": 12
} | 597 |
// 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 CardModel {
CardModel(this.value, this.height, this.color);
int value;
double height;
Color color;
String get label => 'Card $value';
Key get key => ObjectKey(this);
GlobalKey get targetKey => GlobalObjectKey(this);
}
enum MarkerType { topLeft, bottomRight, touch }
class _MarkerPainter extends CustomPainter {
const _MarkerPainter({
required this.size,
required this.type,
});
final double size;
final MarkerType type;
@override
void paint(Canvas canvas, _) {
final Paint paint = Paint()..color = const Color(0x8000FF00);
final double r = size / 2.0;
canvas.drawCircle(Offset(r, r), r, paint);
paint
..color = const Color(0xFFFFFFFF)
..style = PaintingStyle.stroke
..strokeWidth = 1.0;
switch (type) {
case MarkerType.topLeft:
canvas.drawLine(Offset(r, r), Offset(r + r - 1.0, r), paint);
canvas.drawLine(Offset(r, r), Offset(r, r + r - 1.0), paint);
case MarkerType.bottomRight:
canvas.drawLine(Offset(r, r), Offset(1.0, r), paint);
canvas.drawLine(Offset(r, r), Offset(r, 1.0), paint);
case MarkerType.touch:
break;
}
}
@override
bool shouldRepaint(_MarkerPainter oldPainter) {
return oldPainter.size != size
|| oldPainter.type != type;
}
}
class Marker extends StatelessWidget {
const Marker({
super.key,
this.type = MarkerType.touch,
this.position,
this.size = 40.0,
});
final Offset? position;
final double size;
final MarkerType type;
@override
Widget build(BuildContext context) {
return Positioned(
left: position!.dx - size / 2.0,
top: position!.dy - size / 2.0,
width: size,
height: size,
child: IgnorePointer(
child: CustomPaint(
painter: _MarkerPainter(
size: size,
type: type,
),
),
),
);
}
}
class OverlayGeometryApp extends StatefulWidget {
const OverlayGeometryApp({super.key});
@override
OverlayGeometryAppState createState() => OverlayGeometryAppState();
}
typedef CardTapCallback = void Function(GlobalKey targetKey, Offset globalPosition);
class CardBuilder extends SliverChildDelegate {
CardBuilder({List<CardModel>? cardModels, this.onTapUp }) : cardModels = cardModels ?? <CardModel>[];
final List<CardModel> cardModels;
final CardTapCallback? onTapUp;
static const TextStyle cardLabelStyle =
TextStyle(color: Colors.white, fontSize: 18.0, fontWeight: FontWeight.bold);
@override
Widget? build(BuildContext context, int index) {
if (index >= cardModels.length) {
return null;
}
final CardModel cardModel = cardModels[index];
return GestureDetector(
key: cardModel.key,
onTapUp: (TapUpDetails details) { onTapUp!(cardModel.targetKey, details.globalPosition); },
child: Card(
key: cardModel.targetKey,
color: cardModel.color,
child: Container(
height: cardModel.height,
padding: const EdgeInsets.all(8.0),
child: Center(child: Text(cardModel.label, style: cardLabelStyle)),
),
),
);
}
@override
int get estimatedChildCount => cardModels.length;
@override
bool shouldRebuild(CardBuilder oldDelegate) {
return oldDelegate.cardModels != cardModels;
}
}
class OverlayGeometryAppState extends State<OverlayGeometryApp> {
List<CardModel> cardModels = <CardModel>[];
Map<MarkerType, Offset> markers = <MarkerType, Offset>{};
double markersScrollOffset = 0.0;
@override
void initState() {
super.initState();
final List<double> cardHeights = <double>[
48.0, 63.0, 82.0, 146.0, 60.0, 55.0, 84.0, 96.0, 50.0,
48.0, 63.0, 82.0, 146.0, 60.0, 55.0, 84.0, 96.0, 50.0,
48.0, 63.0, 82.0, 146.0, 60.0, 55.0, 84.0, 96.0, 50.0,
];
cardModels = List<CardModel>.generate(cardHeights.length, (int i) {
final Color? color = Color.lerp(Colors.red.shade300, Colors.blue.shade900, i / cardHeights.length);
return CardModel(i, cardHeights[i], color!);
});
}
bool handleScrollNotification(ScrollNotification notification) {
if (notification is ScrollUpdateNotification && notification.depth == 0) {
setState(() {
final double dy = markersScrollOffset - notification.metrics.extentBefore;
markersScrollOffset = notification.metrics.extentBefore;
markers.forEach((MarkerType type, Offset oldPosition) {
markers[type] = oldPosition.translate(0.0, dy);
});
});
}
return false;
}
void handleTapUp(GlobalKey target, Offset globalPosition) {
setState(() {
markers[MarkerType.touch] = globalPosition;
final RenderBox? box = target.currentContext?.findRenderObject() as RenderBox?;
markers[MarkerType.topLeft] = box!.localToGlobal(Offset.zero);
final Size size = box.size;
markers[MarkerType.bottomRight] = box.localToGlobal(Offset(size.width, size.height));
final ScrollableState scrollable = Scrollable.of(target.currentContext!);
markersScrollOffset = scrollable.position.pixels;
});
}
@override
Widget build(BuildContext context) {
return Stack(
children: <Widget>[
Scaffold(
appBar: AppBar(title: const Text('Tap a Card')),
body: Container(
padding: const EdgeInsets.symmetric(vertical: 12.0, horizontal: 8.0),
child: NotificationListener<ScrollNotification>(
onNotification: handleScrollNotification,
child: ListView.custom(
childrenDelegate: CardBuilder(
cardModels: cardModels,
onTapUp: handleTapUp,
),
),
),
),
),
for (final MarkerType type in markers.keys)
Marker(type: type, position: markers[type]),
],
);
}
}
void main() {
runApp(
const MaterialApp(
title: 'Cards',
home: OverlayGeometryApp(),
),
);
}
| flutter/dev/manual_tests/lib/overlay_geometry.dart/0 | {
"file_path": "flutter/dev/manual_tests/lib/overlay_geometry.dart",
"repo_id": "flutter",
"token_count": 2505
} | 598 |
analyzer:
exclude:
- '**'
| flutter/dev/missing_dependency_tests/analysis_options.yaml/0 | {
"file_path": "flutter/dev/missing_dependency_tests/analysis_options.yaml",
"repo_id": "flutter",
"token_count": 16
} | 599 |
## Token Defaults Generator
Script that generates component theme data defaults based on token data.
## Usage
Run this program from the root of the git repository:
```
dart dev/tools/gen_defaults/bin/gen_defaults.dart [-v]
```
This updates `generated/used_tokens.csv` and the various component theme files.
## Templates
There is a template file for every component that needs defaults from
the token database. These templates are implemented as subclasses of
`TokenTemplate`. This base class provides some utilities and a structure
for adding a new block of generated code to the bottom of a given file.
Templates need to override the `generate` method to provide the generated
code block as a string.
See `lib/fab_template.dart` for an example that generates defaults for the
Floating Action Button.
## Tokens
Tokens are stored in JSON files in `data/`, and are sourced from
an internal Google database.
`template.dart` should provide nearly all useful token resolvers
(e.g. `color`, `shape`, etc.). For special cases in which one shouldn't
be defined, use `getToken` to get the raw token value. The script, through
the various revolvers and `getToken`, validates tokens, keeps track of
which tokens are used, and generates `generated/used_tokens.csv`.
| flutter/dev/tools/gen_defaults/README.md/0 | {
"file_path": "flutter/dev/tools/gen_defaults/README.md",
"repo_id": "flutter",
"token_count": 324
} | 600 |
{
"version": "v0_206",
"md.comp.assist-chip.container.height": 32.0,
"md.comp.assist-chip.container.shape": "md.sys.shape.corner.small",
"md.comp.assist-chip.disabled.label-text.color": "onSurface",
"md.comp.assist-chip.disabled.label-text.opacity": 0.38,
"md.comp.assist-chip.dragged.container.elevation": "md.sys.elevation.level4",
"md.comp.assist-chip.dragged.label-text.color": "onSurface",
"md.comp.assist-chip.dragged.state-layer.color": "onSurface",
"md.comp.assist-chip.dragged.state-layer.opacity": "md.sys.state.dragged.state-layer-opacity",
"md.comp.assist-chip.elevated.container.color": "surfaceContainerLow",
"md.comp.assist-chip.elevated.container.elevation": "md.sys.elevation.level1",
"md.comp.assist-chip.elevated.container.shadow-color": "shadow",
"md.comp.assist-chip.elevated.disabled.container.color": "onSurface",
"md.comp.assist-chip.elevated.disabled.container.elevation": "md.sys.elevation.level0",
"md.comp.assist-chip.elevated.disabled.container.opacity": 0.12,
"md.comp.assist-chip.elevated.focus.container.elevation": "md.sys.elevation.level1",
"md.comp.assist-chip.elevated.hover.container.elevation": "md.sys.elevation.level2",
"md.comp.assist-chip.elevated.pressed.container.elevation": "md.sys.elevation.level1",
"md.comp.assist-chip.flat.container.elevation": "md.sys.elevation.level0",
"md.comp.assist-chip.flat.disabled.outline.color": "onSurface",
"md.comp.assist-chip.flat.disabled.outline.opacity": 0.12,
"md.comp.assist-chip.flat.focus.outline.color": "onSurface",
"md.comp.assist-chip.flat.outline.color": "outline",
"md.comp.assist-chip.flat.outline.width": 1.0,
"md.comp.assist-chip.focus.indicator.color": "secondary",
"md.comp.assist-chip.focus.indicator.outline.offset": "md.sys.state.focus-indicator.outer-offset",
"md.comp.assist-chip.focus.indicator.thickness": "md.sys.state.focus-indicator.thickness",
"md.comp.assist-chip.focus.label-text.color": "onSurface",
"md.comp.assist-chip.focus.state-layer.color": "onSurface",
"md.comp.assist-chip.focus.state-layer.opacity": "md.sys.state.focus.state-layer-opacity",
"md.comp.assist-chip.hover.label-text.color": "onSurface",
"md.comp.assist-chip.hover.state-layer.color": "onSurface",
"md.comp.assist-chip.hover.state-layer.opacity": "md.sys.state.hover.state-layer-opacity",
"md.comp.assist-chip.label-text.color": "onSurface",
"md.comp.assist-chip.label-text.text-style": "labelLarge",
"md.comp.assist-chip.pressed.label-text.color": "onSurface",
"md.comp.assist-chip.pressed.state-layer.color": "onSurface",
"md.comp.assist-chip.pressed.state-layer.opacity": "md.sys.state.pressed.state-layer-opacity",
"md.comp.assist-chip.with-icon.disabled.icon.color": "onSurface",
"md.comp.assist-chip.with-icon.disabled.icon.opacity": 0.38,
"md.comp.assist-chip.with-icon.dragged.icon.color": "primary",
"md.comp.assist-chip.with-icon.focus.icon.color": "primary",
"md.comp.assist-chip.with-icon.hover.icon.color": "primary",
"md.comp.assist-chip.with-icon.icon.color": "primary",
"md.comp.assist-chip.with-icon.icon.size": 18.0,
"md.comp.assist-chip.with-icon.pressed.icon.color": "primary"
}
| flutter/dev/tools/gen_defaults/data/chip_assist.json/0 | {
"file_path": "flutter/dev/tools/gen_defaults/data/chip_assist.json",
"repo_id": "flutter",
"token_count": 1282
} | 601 |
{
"version": "v0_206",
"md.comp.fab.primary.small.container.color": "primaryContainer",
"md.comp.fab.primary.small.container.elevation": "md.sys.elevation.level3",
"md.comp.fab.primary.small.container.height": 40.0,
"md.comp.fab.primary.small.container.shadow-color": "shadow",
"md.comp.fab.primary.small.container.shape": "md.sys.shape.corner.medium",
"md.comp.fab.primary.small.container.width": 40.0,
"md.comp.fab.primary.small.focus.container.elevation": "md.sys.elevation.level3",
"md.comp.fab.primary.small.focus.icon.color": "onPrimaryContainer",
"md.comp.fab.primary.small.focus.indicator.color": "secondary",
"md.comp.fab.primary.small.focus.indicator.outline.offset": "md.sys.state.focus-indicator.outer-offset",
"md.comp.fab.primary.small.focus.indicator.thickness": "md.sys.state.focus-indicator.thickness",
"md.comp.fab.primary.small.focus.state-layer.color": "onPrimaryContainer",
"md.comp.fab.primary.small.focus.state-layer.opacity": "md.sys.state.focus.state-layer-opacity",
"md.comp.fab.primary.small.hover.container.elevation": "md.sys.elevation.level4",
"md.comp.fab.primary.small.hover.icon.color": "onPrimaryContainer",
"md.comp.fab.primary.small.hover.state-layer.color": "onPrimaryContainer",
"md.comp.fab.primary.small.hover.state-layer.opacity": "md.sys.state.hover.state-layer-opacity",
"md.comp.fab.primary.small.icon.color": "onPrimaryContainer",
"md.comp.fab.primary.small.icon.size": 24.0,
"md.comp.fab.primary.small.lowered.container.elevation": "md.sys.elevation.level1",
"md.comp.fab.primary.small.lowered.focus.container.elevation": "md.sys.elevation.level1",
"md.comp.fab.primary.small.lowered.hover.container.elevation": "md.sys.elevation.level2",
"md.comp.fab.primary.small.lowered.pressed.container.elevation": "md.sys.elevation.level1",
"md.comp.fab.primary.small.pressed.container.elevation": "md.sys.elevation.level3",
"md.comp.fab.primary.small.pressed.icon.color": "onPrimaryContainer",
"md.comp.fab.primary.small.pressed.state-layer.color": "onPrimaryContainer",
"md.comp.fab.primary.small.pressed.state-layer.opacity": "md.sys.state.pressed.state-layer-opacity"
}
| flutter/dev/tools/gen_defaults/data/fab_small_primary.json/0 | {
"file_path": "flutter/dev/tools/gen_defaults/data/fab_small_primary.json",
"repo_id": "flutter",
"token_count": 808
} | 602 |
{
"version": "v0_206",
"md.comp.radio-button.disabled.selected.icon.color": "onSurface",
"md.comp.radio-button.disabled.selected.icon.opacity": 0.38,
"md.comp.radio-button.disabled.unselected.icon.color": "onSurface",
"md.comp.radio-button.disabled.unselected.icon.opacity": 0.38,
"md.comp.radio-button.icon.size": 20.0,
"md.comp.radio-button.selected.focus.icon.color": "primary",
"md.comp.radio-button.selected.focus.state-layer.color": "primary",
"md.comp.radio-button.selected.focus.state-layer.opacity": "md.sys.state.focus.state-layer-opacity",
"md.comp.radio-button.selected.hover.icon.color": "primary",
"md.comp.radio-button.selected.hover.state-layer.color": "primary",
"md.comp.radio-button.selected.hover.state-layer.opacity": "md.sys.state.hover.state-layer-opacity",
"md.comp.radio-button.selected.icon.color": "primary",
"md.comp.radio-button.selected.pressed.icon.color": "primary",
"md.comp.radio-button.selected.pressed.state-layer.color": "onSurface",
"md.comp.radio-button.selected.pressed.state-layer.opacity": "md.sys.state.pressed.state-layer-opacity",
"md.comp.radio-button.state-layer.size": 40.0,
"md.comp.radio-button.unselected.focus.icon.color": "onSurface",
"md.comp.radio-button.unselected.focus.state-layer.color": "onSurface",
"md.comp.radio-button.unselected.focus.state-layer.opacity": "md.sys.state.focus.state-layer-opacity",
"md.comp.radio-button.unselected.hover.icon.color": "onSurface",
"md.comp.radio-button.unselected.hover.state-layer.color": "onSurface",
"md.comp.radio-button.unselected.hover.state-layer.opacity": "md.sys.state.hover.state-layer-opacity",
"md.comp.radio-button.unselected.icon.color": "onSurfaceVariant",
"md.comp.radio-button.unselected.pressed.icon.color": "onSurface",
"md.comp.radio-button.unselected.pressed.state-layer.color": "primary",
"md.comp.radio-button.unselected.pressed.state-layer.opacity": "md.sys.state.pressed.state-layer-opacity"
}
| flutter/dev/tools/gen_defaults/data/radio_button.json/0 | {
"file_path": "flutter/dev/tools/gen_defaults/data/radio_button.json",
"repo_id": "flutter",
"token_count": 723
} | 603 |
{
"version": "v0_206",
"md.comp.top-app-bar.small.container.color": "surface",
"md.comp.top-app-bar.small.container.elevation": "md.sys.elevation.level0",
"md.comp.top-app-bar.small.container.height": 64.0,
"md.comp.top-app-bar.small.container.shape": "md.sys.shape.corner.none",
"md.comp.top-app-bar.small.headline.color": "onSurface",
"md.comp.top-app-bar.small.headline.text-style": "titleLarge",
"md.comp.top-app-bar.small.leading-icon.color": "onSurface",
"md.comp.top-app-bar.small.leading-icon.size": 24.0,
"md.comp.top-app-bar.small.on-scroll.container.color": "surfaceContainer",
"md.comp.top-app-bar.small.on-scroll.container.elevation": "md.sys.elevation.level2",
"md.comp.top-app-bar.small.trailing-icon.color": "onSurfaceVariant",
"md.comp.top-app-bar.small.trailing-icon.size": 24.0
}
| flutter/dev/tools/gen_defaults/data/top_app_bar_small.json/0 | {
"file_path": "flutter/dev/tools/gen_defaults/data/top_app_bar_small.json",
"repo_id": "flutter",
"token_count": 344
} | 604 |
// 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 RadioTemplate extends TokenTemplate {
const RadioTemplate(super.blockName, super.fileName, super.tokens, {
super.colorSchemePrefix = '_colors.',
});
@override
String generate() => '''
class _RadioDefaultsM3 extends RadioThemeData {
_RadioDefaultsM3(this.context);
final BuildContext context;
late final ThemeData _theme = Theme.of(context);
late final ColorScheme _colors = _theme.colorScheme;
@override
MaterialStateProperty<Color> get fillColor {
return MaterialStateProperty.resolveWith((Set<MaterialState> states) {
if (states.contains(MaterialState.selected)) {
if (states.contains(MaterialState.disabled)) {
return ${componentColor('md.comp.radio-button.disabled.selected.icon')};
}
if (states.contains(MaterialState.pressed)) {
return ${componentColor('md.comp.radio-button.selected.pressed.icon')};
}
if (states.contains(MaterialState.hovered)) {
return ${componentColor('md.comp.radio-button.selected.hover.icon')};
}
if (states.contains(MaterialState.focused)) {
return ${componentColor('md.comp.radio-button.selected.focus.icon')};
}
return ${componentColor('md.comp.radio-button.selected.icon')};
}
if (states.contains(MaterialState.disabled)) {
return ${componentColor('md.comp.radio-button.disabled.unselected.icon')};
}
if (states.contains(MaterialState.pressed)) {
return ${componentColor('md.comp.radio-button.unselected.pressed.icon')};
}
if (states.contains(MaterialState.hovered)) {
return ${componentColor('md.comp.radio-button.unselected.hover.icon')};
}
if (states.contains(MaterialState.focused)) {
return ${componentColor('md.comp.radio-button.unselected.focus.icon')};
}
return ${componentColor('md.comp.radio-button.unselected.icon')};
});
}
@override
MaterialStateProperty<Color> get overlayColor {
return MaterialStateProperty.resolveWith((Set<MaterialState> states) {
if (states.contains(MaterialState.selected)) {
if (states.contains(MaterialState.pressed)) {
return ${componentColor('md.comp.radio-button.selected.pressed.state-layer')};
}
if (states.contains(MaterialState.hovered)) {
return ${componentColor('md.comp.radio-button.selected.hover.state-layer')};
}
if (states.contains(MaterialState.focused)) {
return ${componentColor('md.comp.radio-button.selected.focus.state-layer')};
}
return Colors.transparent;
}
if (states.contains(MaterialState.pressed)) {
return ${componentColor('md.comp.radio-button.unselected.pressed.state-layer')};
}
if (states.contains(MaterialState.hovered)) {
return ${componentColor('md.comp.radio-button.unselected.hover.state-layer')};
}
if (states.contains(MaterialState.focused)) {
return ${componentColor('md.comp.radio-button.unselected.focus.state-layer')};
}
return Colors.transparent;
});
}
@override
MaterialTapTargetSize get materialTapTargetSize => _theme.materialTapTargetSize;
@override
VisualDensity get visualDensity => _theme.visualDensity;
}
''';
}
| flutter/dev/tools/gen_defaults/lib/radio_template.dart/0 | {
"file_path": "flutter/dev/tools/gen_defaults/lib/radio_template.dart",
"repo_id": "flutter",
"token_count": 1278
} | 605 |
// 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.
// TODO(davidmartos96): Remove this tag once this test's state leaks/test
// dependencies have been fixed.
// https://github.com/flutter/flutter/issues/142716
// Fails with "flutter test --test-randomize-ordering-seed=20240201"
@Tags(<String>['no-shuffle'])
library;
import 'dart:async';
import 'dart:io';
import 'package:gen_defaults/template.dart';
import 'package:gen_defaults/token_logger.dart';
import 'package:path/path.dart' as path;
import 'package:test/test.dart';
void main() {
final TokenLogger logger = tokenLogger;
// Required init with empty at least once to init late fields.
// Then we can use the `clear` method.
logger.init(allTokens: <String, dynamic>{}, versionMap: <String, List<String>>{});
setUp(() {
// Cleanup the global token logger before each test, to not be tied to a particular
// test order.
logger.clear();
});
test('Templates will append to the end of a file', () {
final Directory tempDir = Directory.systemTemp.createTempSync('gen_defaults');
try {
// Create a temporary file with some content.
final File tempFile = File(path.join(tempDir.path, 'test_template.txt'));
tempFile.createSync();
tempFile.writeAsStringSync('''
// This is a file with stuff in it.
// This part shouldn't be changed by
// the template.
''');
// Have a test template append new parameterized content to the end of
// the file.
final Map<String, dynamic> tokens = <String, dynamic>{'version': '0.0', 'foo': 'Foobar', 'bar': 'Barfoo'};
TestTemplate('Test', tempFile.path, tokens).updateFile();
expect(tempFile.readAsStringSync(), '''
// This is a file with stuff in it.
// This part shouldn't be changed by
// the template.
// BEGIN GENERATED TOKEN PROPERTIES - Test
// Do not edit by hand. The code between the "BEGIN GENERATED" and
// "END GENERATED" comments are generated from data in the Material
// Design token database by the script:
// dev/tools/gen_defaults/bin/gen_defaults.dart.
static final String tokenFoo = 'Foobar';
static final String tokenBar = 'Barfoo';
// END GENERATED TOKEN PROPERTIES - Test
''');
} finally {
tempDir.deleteSync(recursive: true);
}
});
test('Templates will update over previously generated code at the end of a file', () {
final Directory tempDir = Directory.systemTemp.createTempSync('gen_defaults');
try {
// Create a temporary file with some content.
final File tempFile = File(path.join(tempDir.path, 'test_template.txt'));
tempFile.createSync();
tempFile.writeAsStringSync('''
// This is a file with stuff in it.
// This part shouldn't be changed by
// the template.
// BEGIN GENERATED TOKEN PROPERTIES - Test
// Do not edit by hand. The code between the "BEGIN GENERATED" and
// "END GENERATED" comments are generated from data in the Material
// Design token database by the script:
// dev/tools/gen_defaults/bin/gen_defaults.dart.
static final String tokenFoo = 'Foobar';
static final String tokenBar = 'Barfoo';
// END GENERATED TOKEN PROPERTIES - Test
''');
// Have a test template append new parameterized content to the end of
// the file.
final Map<String, dynamic> tokens = <String, dynamic>{'version': '0.0', 'foo': 'foo', 'bar': 'bar'};
TestTemplate('Test', tempFile.path, tokens).updateFile();
expect(tempFile.readAsStringSync(), '''
// This is a file with stuff in it.
// This part shouldn't be changed by
// the template.
// BEGIN GENERATED TOKEN PROPERTIES - Test
// Do not edit by hand. The code between the "BEGIN GENERATED" and
// "END GENERATED" comments are generated from data in the Material
// Design token database by the script:
// dev/tools/gen_defaults/bin/gen_defaults.dart.
static final String tokenFoo = 'foo';
static final String tokenBar = 'bar';
// END GENERATED TOKEN PROPERTIES - Test
''');
} finally {
tempDir.deleteSync(recursive: true);
}
});
test('Multiple templates can modify different code blocks in the same file', () {
final Directory tempDir = Directory.systemTemp.createTempSync('gen_defaults');
try {
// Create a temporary file with some content.
final File tempFile = File(path.join(tempDir.path, 'test_template.txt'));
tempFile.createSync();
tempFile.writeAsStringSync('''
// This is a file with stuff in it.
// This part shouldn't be changed by
// the template.
''');
// Update file with a template for 'Block 1'
{
final Map<String, dynamic> tokens = <String, dynamic>{'version': '0.0', 'foo': 'foo', 'bar': 'bar'};
TestTemplate('Block 1', tempFile.path, tokens).updateFile();
}
expect(tempFile.readAsStringSync(), '''
// This is a file with stuff in it.
// This part shouldn't be changed by
// the template.
// BEGIN GENERATED TOKEN PROPERTIES - Block 1
// Do not edit by hand. The code between the "BEGIN GENERATED" and
// "END GENERATED" comments are generated from data in the Material
// Design token database by the script:
// dev/tools/gen_defaults/bin/gen_defaults.dart.
static final String tokenFoo = 'foo';
static final String tokenBar = 'bar';
// END GENERATED TOKEN PROPERTIES - Block 1
''');
// Update file with a template for 'Block 2', which should append but not
// disturb the code in 'Block 1'.
{
final Map<String, dynamic> tokens = <String, dynamic>{'version': '0.0', 'foo': 'bar', 'bar': 'foo'};
TestTemplate('Block 2', tempFile.path, tokens).updateFile();
}
expect(tempFile.readAsStringSync(), '''
// This is a file with stuff in it.
// This part shouldn't be changed by
// the template.
// BEGIN GENERATED TOKEN PROPERTIES - Block 1
// Do not edit by hand. The code between the "BEGIN GENERATED" and
// "END GENERATED" comments are generated from data in the Material
// Design token database by the script:
// dev/tools/gen_defaults/bin/gen_defaults.dart.
static final String tokenFoo = 'foo';
static final String tokenBar = 'bar';
// END GENERATED TOKEN PROPERTIES - Block 1
// BEGIN GENERATED TOKEN PROPERTIES - Block 2
// Do not edit by hand. The code between the "BEGIN GENERATED" and
// "END GENERATED" comments are generated from data in the Material
// Design token database by the script:
// dev/tools/gen_defaults/bin/gen_defaults.dart.
static final String tokenFoo = 'bar';
static final String tokenBar = 'foo';
// END GENERATED TOKEN PROPERTIES - Block 2
''');
// Update 'Block 1' again which should just update that block,
// leaving 'Block 2' undisturbed.
{
final Map<String, dynamic> tokens = <String, dynamic>{'version': '0.0', 'foo': 'FOO', 'bar': 'BAR'};
TestTemplate('Block 1', tempFile.path, tokens).updateFile();
}
expect(tempFile.readAsStringSync(), '''
// This is a file with stuff in it.
// This part shouldn't be changed by
// the template.
// BEGIN GENERATED TOKEN PROPERTIES - Block 1
// Do not edit by hand. The code between the "BEGIN GENERATED" and
// "END GENERATED" comments are generated from data in the Material
// Design token database by the script:
// dev/tools/gen_defaults/bin/gen_defaults.dart.
static final String tokenFoo = 'FOO';
static final String tokenBar = 'BAR';
// END GENERATED TOKEN PROPERTIES - Block 1
// BEGIN GENERATED TOKEN PROPERTIES - Block 2
// Do not edit by hand. The code between the "BEGIN GENERATED" and
// "END GENERATED" comments are generated from data in the Material
// Design token database by the script:
// dev/tools/gen_defaults/bin/gen_defaults.dart.
static final String tokenFoo = 'bar';
static final String tokenBar = 'foo';
// END GENERATED TOKEN PROPERTIES - Block 2
''');
} finally {
tempDir.deleteSync(recursive: true);
}
});
test('Templates can get proper shapes from given data', () {
const Map<String, dynamic> tokens = <String, dynamic>{
'foo.shape': 'shape.large',
'bar.shape': 'shape.full',
'shape.large': <String, dynamic>{
'family': 'SHAPE_FAMILY_ROUNDED_CORNERS',
'topLeft': 1.0,
'topRight': 2.0,
'bottomLeft': 3.0,
'bottomRight': 4.0,
},
'shape.full': <String, dynamic>{
'family': 'SHAPE_FAMILY_CIRCULAR',
},
};
final TestTemplate template = TestTemplate('Test', 'foobar.dart', tokens);
expect(template.shape('foo'), 'const RoundedRectangleBorder(borderRadius: BorderRadius.only(topLeft: Radius.circular(1.0), topRight: Radius.circular(2.0), bottomLeft: Radius.circular(3.0), bottomRight: Radius.circular(4.0)))');
expect(template.shape('bar'), 'const StadiumBorder()');
});
group('Tokens logger', () {
final List<String> printLog = List<String>.empty(growable: true);
final Map<String, List<String>> versionMap = <String, List<String>>{};
final Map<String, dynamic> allTokens = <String, dynamic>{};
// Add to printLog instead of printing to stdout
void Function() overridePrint(void Function() testFn) => () {
final ZoneSpecification spec = ZoneSpecification(
print: (_, __, ___, String msg) {
printLog.add(msg);
}
);
return Zone.current.fork(specification: spec).run<void>(testFn);
};
setUp(() {
logger.init(allTokens: allTokens, versionMap: versionMap);
});
tearDown(() {
logger.clear();
printLog.clear();
versionMap.clear();
allTokens.clear();
});
String errorColoredString(String str) => '\x1B[31m$str\x1B[0m';
const Map<String, List<String>> testVersions = <String, List<String>>{
'v1.0.0': <String>['file_1.json'],
'v2.0.0': <String>['file_2.json, file_3.json'],
};
test('can print empty usage', overridePrint(() {
logger.printVersionUsage(verbose: true);
expect(printLog, contains('Versions used: '));
logger.printTokensUsage(verbose: true);
expect(printLog, contains('Tokens used: 0/0'));
}));
test('can print version usage', overridePrint(() {
versionMap.addAll(testVersions);
logger.printVersionUsage(verbose: false);
expect(printLog, contains('Versions used: v1.0.0, v2.0.0'));
}));
test('can print version usage (verbose)', overridePrint(() {
versionMap.addAll(testVersions);
logger.printVersionUsage(verbose: true);
expect(printLog, contains('Versions used: v1.0.0, v2.0.0'));
expect(printLog, contains(' v1.0.0:'));
expect(printLog, contains(' file_1.json'));
expect(printLog, contains(' v2.0.0:'));
expect(printLog, contains(' file_2.json, file_3.json'));
}));
test('can log and print tokens usage', overridePrint(() {
allTokens['foo'] = 'value';
logger.log('foo');
logger.printTokensUsage(verbose: false);
expect(printLog, contains('Tokens used: 1/1'));
}));
test('can log and print tokens usage (verbose)', overridePrint(() {
allTokens['foo'] = 'value';
logger.log('foo');
logger.printTokensUsage(verbose: true);
expect(printLog, contains('β
foo'));
expect(printLog, contains('Tokens used: 1/1'));
}));
test('detects invalid logs', overridePrint(() {
allTokens['foo'] = 'value';
logger.log('baz');
logger.log('foobar');
logger.printTokensUsage(verbose: true);
expect(printLog, contains('β foo'));
expect(printLog, contains('Tokens used: 0/1'));
expect(printLog, contains(errorColoredString('Some referenced tokens do not exist: 2')));
expect(printLog, contains(' baz'));
expect(printLog, contains(' foobar'));
}));
test("color function doesn't log when providing a default", overridePrint(() {
allTokens['color_foo_req'] = 'value';
// color_foo_opt is not available, but because it has a default value, it won't warn about it
TestColorTemplate('block', 'filename', allTokens).generate();
logger.printTokensUsage(verbose: true);
expect(printLog, contains('β
color_foo_req'));
expect(printLog, contains('Tokens used: 1/1'));
}));
test('color function logs when not providing a default', overridePrint(() {
// Nor color_foo_req or color_foo_opt are available, but only color_foo_req will be logged.
// This mimics a token being removed, but expected to exist.
TestColorTemplate('block', 'filename', allTokens).generate();
logger.printTokensUsage(verbose: true);
expect(printLog, contains('Tokens used: 0/0'));
expect(printLog, contains(errorColoredString('Some referenced tokens do not exist: 1')));
expect(printLog, contains(' color_foo_req'));
}));
test('border function logs width token when available', overridePrint(() {
allTokens['border_foo.color'] = 'red';
allTokens['border_foo.width'] = 3.0;
TestBorderTemplate('block', 'filename', allTokens).generate();
logger.printTokensUsage(verbose: true);
expect(printLog, contains('β
border_foo.color'));
expect(printLog, contains('β
border_foo.width'));
expect(printLog, contains('Tokens used: 2/2'));
}));
test('border function logs height token when width token not available', overridePrint(() {
allTokens['border_foo.color'] = 'red';
allTokens['border_foo.height'] = 3.0;
TestBorderTemplate('block', 'filename', allTokens).generate();
logger.printTokensUsage(verbose: true);
expect(printLog, contains('β
border_foo.color'));
expect(printLog, contains('β
border_foo.height'));
expect(printLog, contains('Tokens used: 2/2'));
}));
test("border function doesn't log when width or height tokens not available", overridePrint(() {
allTokens['border_foo.color'] = 'red';
TestBorderTemplate('block', 'filename', allTokens).generate();
logger.printTokensUsage(verbose: true);
expect(printLog, contains('β
border_foo.color'));
expect(printLog, contains('Tokens used: 1/1'));
}));
test('can log and dump versions & tokens to a file', overridePrint(() {
versionMap.addAll(testVersions);
allTokens['foo'] = 'value';
allTokens['bar'] = 'value';
logger.log('foo');
logger.log('bar');
logger.dumpToFile('test.json');
final String fileContent = File('test.json').readAsStringSync();
expect(fileContent, contains('Versions used, v1.0.0, v2.0.0'));
expect(fileContent, contains('bar,'));
expect(fileContent, contains('foo'));
}));
test('integration test', overridePrint(() {
allTokens['foo'] = 'value';
allTokens['bar'] = 'value';
TestTemplate('block', 'filename', allTokens).generate();
logger.printTokensUsage(verbose: true);
expect(printLog, contains('β
foo'));
expect(printLog, contains('β
bar'));
expect(printLog, contains('Tokens used: 2/2'));
}));
});
}
class TestTemplate extends TokenTemplate {
TestTemplate(super.blockName, super.fileName, super.tokens);
@override
String generate() => '''
static final String tokenFoo = '${getToken('foo')}';
static final String tokenBar = '${getToken('bar')}';
''';
}
class TestColorTemplate extends TokenTemplate {
TestColorTemplate(super.blockName, super.fileName, super.tokens);
@override
String generate() => '''
static final Color color_1 = '${color('color_foo_req')}';
static final Color color_2 = '${color('color_foo_opt', 'Colors.red')}';
''';
}
class TestBorderTemplate extends TokenTemplate {
TestBorderTemplate(super.blockName, super.fileName, super.tokens);
@override
String generate() => '''
static final BorderSide border = '${border('border_foo')}';
''';
}
| flutter/dev/tools/gen_defaults/test/gen_defaults_test.dart/0 | {
"file_path": "flutter/dev/tools/gen_defaults/test/gen_defaults_test.dart",
"repo_id": "flutter",
"token_count": 5560
} | 606 |
// Copyright 2013 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 <map>
#include <set>
#include "flutter/shell/platform/darwin/ios/framework/Source/KeyCodeMap_Internal.h"
// DO NOT EDIT -- DO NOT EDIT -- DO NOT EDIT
// This file is generated by
// flutter/flutter:dev/tools/gen_keycodes/bin/gen_keycodes.dart and should not
// be edited directly.
//
// Edit the template
// flutter/flutter:dev/tools/gen_keycodes/data/ios_key_code_map_mm.tmpl instead.
//
// See flutter/flutter:dev/tools/gen_keycodes/README.md for more information.
@@@MASK_CONSTANTS@@@
// 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 std::map<uint32_t, uint64_t> keyCodeToPhysicalKey = {
@@@IOS_SCAN_CODE_MAP@@@
};
// Maps iOS-specific virtual key code values to logical keys representing
// LogicalKeyboardKey
const std::map<uint32_t, uint64_t> keyCodeToLogicalKey = {
@@@IOS_KEYCODE_LOGICAL_MAP@@@
};
// Maps iOS-specific virtual key codes to an equivalent modifier flag enum
// value.
const std::map<uint32_t, ModifierFlag> keyCodeToModifierFlag = {
@@@KEYCODE_TO_MODIFIER_FLAG_MAP@@@
};
// Maps modifier flag enum values to an iOS-specific virtual key code.
const std::map<ModifierFlag, uint32_t> modifierFlagToKeyCode = {
@@@MODIFIER_FLAG_TO_KEYCODE_MAP@@@
};
// A set of virtual key codes mapping to function keys, so that may be
// identified as such.
const std::set<uint32_t> functionKeyCodes = {
@@@IOS_FUNCTION_KEY_SET@@@
};
API_AVAILABLE(ios(13.4))
NSDictionary<NSString*, NSNumber*>* specialKeyMapping = [[NSDictionary alloc] initWithDictionary:@{
@@@SPECIAL_KEY_MAPPING@@@
}];
@@@SPECIAL_KEY_CONSTANTS@@@
| flutter/dev/tools/gen_keycodes/data/ios_key_code_map_mm.tmpl/0 | {
"file_path": "flutter/dev/tools/gen_keycodes/data/ios_key_code_map_mm.tmpl",
"repo_id": "flutter",
"token_count": 619
} | 607 |
{
"0": ["Digit0", null, null, "Numpad0"],
"1": ["Digit1", null, null, "Numpad1"],
"2": ["Digit2", null, null, "Numpad2"],
"3": ["Digit3", null, null, "Numpad3"],
"4": ["Digit4", null, null, "Numpad4"],
"5": ["Digit5", null, null, "Numpad5"],
"6": ["Digit6", null, null, "Numpad6"],
"7": ["Digit7", null, null, "Numpad7"],
"8": ["Digit8", null, null, "Numpad8"],
"9": ["Digit9", null, null, "Numpad9"],
".": ["Period", null, null, "NumpadDecimal"],
"Insert": ["Insert", null, null, "Numpad0"],
"End": ["End", null, null, "Numpad1"],
"ArrowDown": ["ArrowDown", null, null, "Numpad2"],
"PageDown": ["PageDown", null, null, "Numpad3"],
"ArrowLeft": ["ArrowLeft", null, null, "Numpad4"],
"Clear": ["Clear", null, null, "Numpad5"],
"ArrowRight": ["ArrowRight", null, null, "Numpad6"],
"Home": ["Home", null, null, "Numpad7"],
"ArrowUp": ["ArrowUp", null, null, "Numpad8"],
"PageUp": ["PageUp", null, null, "Numpad9"],
"Delete": ["Delete", null, null, "NumpadDecimal"],
"/": ["Slash", null, null, "NumpadDivide"],
"*": ["Asterisk", null, null, "NumpadMultiply"],
"-": ["Minus", null, null, "NumpadSubtract"],
"+": ["Add", null, null, "NumpadAdd"],
"Enter": ["Enter", null, null, "NumpadEnter"],
"Shift": ["ShiftLeft", "ShiftLeft", "ShiftRight", null],
"Control": ["ControlLeft", "ControlLeft", "ControlRight", null],
"Alt": ["AltLeft", "AltLeft", "AltRight", null],
"AltGraph": ["AltGraph", null, "AltGraph", null],
"Meta": ["MetaLeft", "MetaLeft", "MetaRight", null]
}
| flutter/dev/tools/gen_keycodes/data/web_logical_location_mapping.json/0 | {
"file_path": "flutter/dev/tools/gen_keycodes/data/web_logical_location_mapping.json",
"repo_id": "flutter",
"token_count": 707
} | 608 |
// 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:path/path.dart' as path;
import 'base_code_gen.dart';
import 'logical_key_data.dart';
import 'physical_key_data.dart';
import 'utils.dart';
String _toUpperSnake(String lowerCamel) {
// Converts 'myTVFoo' to 'myTvFoo'.
final String trueUpperCamel = lowerCamel.replaceAllMapped(
RegExp(r'([A-Z]{3,})'),
(Match match) {
final String matched = match.group(1)!;
return matched.substring(0, 1)
+ matched.substring(1, matched.length - 2).toLowerCase()
+ matched.substring(matched.length - 2, matched.length - 1);
});
// Converts 'myTvFoo' to 'MY_TV_FOO'.
return trueUpperCamel.replaceAllMapped(
RegExp(r'([A-Z])'),
(Match match) => '_${match.group(1)!}').toUpperCase();
}
/// Generates the common/testing/key_codes.h based on the information in the key
/// data structure given to it.
class KeyCodesJavaGenerator extends BaseCodeGenerator {
KeyCodesJavaGenerator(super.keyData, super.logicalData);
/// Gets the generated definitions of PhysicalKeyboardKeys.
String get _physicalDefinitions {
final OutputLines<int> lines = OutputLines<int>('Physical Key list');
for (final PhysicalKeyEntry entry in keyData.entries) {
lines.add(entry.usbHidCode, '''
public static final long PHYSICAL_${_toUpperSnake(entry.constantName)} = ${toHex(entry.usbHidCode)}L;''');
}
return lines.sortedJoin().trimRight();
}
/// Gets the generated definitions of PhysicalKeyboardKeys.
String get _logicalDefinitions {
final OutputLines<int> lines = OutputLines<int>('Logical Key list', behavior: DeduplicateBehavior.kSkip);
for (final LogicalKeyEntry entry in logicalData.entries) {
lines.add(entry.value, '''
public static final long LOGICAL_${_toUpperSnake(entry.constantName)} = ${toHex(entry.value, digits: 11)}L;''');
}
return lines.sortedJoin().trimRight();
}
@override
String get templatePath => path.join(dataRoot, 'key_codes_java.tmpl');
@override
Map<String, String> mappings() {
return <String, String>{
'LOGICAL_KEY_DEFINITIONS': _logicalDefinitions,
'PHYSICAL_KEY_DEFINITIONS': _physicalDefinitions,
};
}
}
| flutter/dev/tools/gen_keycodes/lib/testing_key_codes_java_gen.dart/0 | {
"file_path": "flutter/dev/tools/gen_keycodes/lib/testing_key_codes_java_gen.dart",
"repo_id": "flutter",
"token_count": 840
} | 609 |
// 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 json;
import 'dart:io';
import 'localizations_utils.dart';
// The first suffix in kPluralSuffixes must be "Other". "Other" is special
// because it's the only one that is required.
const List<String> kPluralSuffixes = <String>['Other', 'Zero', 'One', 'Two', 'Few', 'Many'];
final RegExp kPluralRegexp = RegExp(r'(\w*)(' + kPluralSuffixes.skip(1).join(r'|') + r')$');
class ValidationError implements Exception {
ValidationError(this. message);
final String message;
@override
String toString() => message;
}
/// Sanity checking of the @foo metadata in the English translations, *_en.arb.
///
/// - For each foo, resource, there must be a corresponding @foo.
/// - For each @foo resource, there must be a corresponding foo, except
/// for plurals, for which there must be a fooOther.
/// - Each @foo resource must have a Map value with a String valued
/// description entry.
///
/// Throws an exception upon failure.
void validateEnglishLocalizations(File file) {
final StringBuffer errorMessages = StringBuffer();
if (!file.existsSync()) {
errorMessages.writeln('English localizations do not exist: $file');
throw ValidationError(errorMessages.toString());
}
final Map<String, dynamic> bundle = json.decode(file.readAsStringSync()) as Map<String, dynamic>;
for (final String resourceId in bundle.keys) {
if (resourceId.startsWith('@')) {
continue;
}
if (bundle['@$resourceId'] != null) {
continue;
}
bool checkPluralResource(String suffix) {
final int suffixIndex = resourceId.indexOf(suffix);
return suffixIndex != -1 && bundle['@${resourceId.substring(0, suffixIndex)}'] != null;
}
if (kPluralSuffixes.any(checkPluralResource)) {
continue;
}
errorMessages.writeln('A value was not specified for @$resourceId');
}
for (final String atResourceId in bundle.keys) {
if (!atResourceId.startsWith('@')) {
continue;
}
final dynamic atResourceValue = bundle[atResourceId];
final Map<String, dynamic>? atResource =
atResourceValue is Map<String, dynamic> ? atResourceValue : null;
if (atResource == null) {
errorMessages.writeln('A map value was not specified for $atResourceId');
continue;
}
final bool optional = atResource.containsKey('optional');
final String? description = atResource['description'] as String?;
if (description == null && !optional) {
errorMessages.writeln('No description specified for $atResourceId');
}
final String? plural = atResource['plural'] as String?;
final String resourceId = atResourceId.substring(1);
if (plural != null) {
final String resourceIdOther = '${resourceId}Other';
if (!bundle.containsKey(resourceIdOther)) {
errorMessages.writeln('Default plural resource $resourceIdOther undefined');
}
} else {
if (!optional && !bundle.containsKey(resourceId)) {
errorMessages.writeln('No matching $resourceId defined for $atResourceId');
}
}
}
if (errorMessages.isNotEmpty) {
throw ValidationError(errorMessages.toString());
}
}
/// This removes undefined localizations (localizations that aren't present in
/// the canonical locale anymore) by:
///
/// 1. Looking up the canonical (English, in this case) localizations.
/// 2. For each locale, getting the resources.
/// 3. Determining the set of keys that aren't plural variations (we're only
/// interested in the base terms being translated and not their variants)
/// 4. Determining the set of invalid keys; that is those that are (non-plural)
/// keys in the resources for this locale, but which _aren't_ keys in the
/// canonical list.
/// 5. Removes the invalid mappings from this resource's locale.
void removeUndefinedLocalizations(
Map<LocaleInfo, Map<String, String>> localeToResources,
) {
final Map<String, String> canonicalLocalizations = localeToResources[LocaleInfo.fromString('en')]!;
final Set<String> canonicalKeys = Set<String>.from(canonicalLocalizations.keys);
localeToResources.forEach((LocaleInfo locale, Map<String, String> resources) {
bool isPluralVariation(String key) {
final Match? pluralMatch = kPluralRegexp.firstMatch(key);
if (pluralMatch == null) {
return false;
}
final String? prefix = pluralMatch[1];
return resources.containsKey('${prefix}Other');
}
final Set<String> keys = Set<String>.from(
resources.keys.where((String key) => !isPluralVariation(key))
);
final Set<String> invalidKeys = keys.difference(canonicalKeys);
resources.removeWhere((String key, String value) => invalidKeys.contains(key));
});
}
/// Enforces the following invariants in our localizations:
///
/// - Resource keys are valid, i.e. they appear in the canonical list.
/// - Resource keys are complete for language-level locales, e.g. "es", "he".
///
/// Uses "en" localizations as the canonical source of locale keys that other
/// locales are compared against.
///
/// If validation fails, throws an exception.
void validateLocalizations(
Map<LocaleInfo, Map<String, String>> localeToResources,
Map<LocaleInfo, Map<String, dynamic>> localeToAttributes, {
bool removeUndefined = false,
}) {
final Map<String, String> canonicalLocalizations = localeToResources[LocaleInfo.fromString('en')]!;
final Set<String> canonicalKeys = Set<String>.from(canonicalLocalizations.keys);
final StringBuffer errorMessages = StringBuffer();
bool explainMissingKeys = false;
for (final LocaleInfo locale in localeToResources.keys) {
final Map<String, String> resources = localeToResources[locale]!;
// Whether `key` corresponds to one of the plural variations of a key with
// the same prefix and suffix "Other".
//
// Many languages require only a subset of these variations, so we do not
// require them so long as the "Other" variation exists.
bool isPluralVariation(String key) {
final Match? pluralMatch = kPluralRegexp.firstMatch(key);
if (pluralMatch == null) {
return false;
}
final String? prefix = pluralMatch[1];
return resources.containsKey('${prefix}Other');
}
final Set<String> keys = Set<String>.from(
resources.keys.where((String key) => !isPluralVariation(key))
);
// Make sure keys are valid (i.e. they also exist in the canonical
// localizations)
final Set<String> invalidKeys = keys.difference(canonicalKeys);
if (invalidKeys.isNotEmpty && !removeUndefined) {
errorMessages.writeln('Locale "$locale" contains invalid resource keys: ${invalidKeys.join(', ')}');
}
// For language-level locales only, check that they have a complete list of
// keys, or opted out of using certain ones.
if (locale.length == 1) {
final Map<String, dynamic>? attributes = localeToAttributes[locale];
final List<String?> missingKeys = <String?>[];
for (final String missingKey in canonicalKeys.difference(keys)) {
final dynamic attribute = attributes?[missingKey];
final bool intentionallyOmitted = attribute is Map && attribute.containsKey('notUsed');
if (!intentionallyOmitted && !isPluralVariation(missingKey)) {
missingKeys.add(missingKey);
}
}
if (missingKeys.isNotEmpty) {
explainMissingKeys = true;
errorMessages.writeln('Locale "$locale" is missing the following resource keys: ${missingKeys.join(', ')}');
}
}
}
if (errorMessages.isNotEmpty) {
if (explainMissingKeys) {
errorMessages
..writeln()
..writeln(
'If a resource key is intentionally omitted, add an attribute corresponding '
'to the key name with a "notUsed" property explaining why. Example:'
)
..writeln()
..writeln('"@anteMeridiemAbbreviation": {')
..writeln(' "notUsed": "Sindhi time format does not use a.m. indicator"')
..writeln('}');
}
throw ValidationError(errorMessages.toString());
}
}
| flutter/dev/tools/localization/localizations_validator.dart/0 | {
"file_path": "flutter/dev/tools/localization/localizations_validator.dart",
"repo_id": "flutter",
"token_count": 2740
} | 610 |
<svg id="svg_build_00" xmlns="http://www.w3.org/2000/svg" width="48px" height="48px" >
<g if="group_2" transform="translate(0,15.0)">
<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" />
</g>
</svg>
| flutter/dev/tools/vitool/test_assets/bar_group_translate.svg/0 | {
"file_path": "flutter/dev/tools/vitool/test_assets/bar_group_translate.svg",
"repo_id": "flutter",
"token_count": 122
} | 611 |
package com.example.tracing_tests
import io.flutter.embedding.android.FlutterActivity
class MainActivity : FlutterActivity()
| flutter/dev/tracing_tests/android/app/src/main/kotlin/com/example/tracing_tests/MainActivity.kt/0 | {
"file_path": "flutter/dev/tracing_tests/android/app/src/main/kotlin/com/example/tracing_tests/MainActivity.kt",
"repo_id": "flutter",
"token_count": 36
} | 612 |
// 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:developer';
import 'package:flutter/foundation.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
class TestWidget extends LeafRenderObjectWidget {
const TestWidget({
super.key,
});
@override
RenderObject createRenderObject(BuildContext context) => RenderTest();
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
// This string is searched for verbatim by dev/bots/test.dart:
properties.add(MessageProperty('test', 'TestWidget.debugFillProperties called'));
}
}
class RenderTest extends RenderBox {
@override
bool get sizedByParent => true;
@override
void performResize() {
Timeline.instantSync('RenderTest.performResize called');
size = constraints.biggest;
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
// This string is searched for verbatim by dev/bots/test.dart:
properties.add(MessageProperty('test', 'RenderTest.debugFillProperties called'));
}
}
Future<void> main() async {
// This section introduces strings that we can search for in dev/bots/test.dart
// as a sanity check:
if (kDebugMode) {
print('BUILT IN DEBUG MODE');
}
if (kProfileMode) {
print('BUILT IN PROFILE MODE');
}
if (kReleaseMode) {
print('BUILT IN RELEASE MODE');
}
// The point of this file is to make sure that toTimelineArguments is not
// called when we have debugProfileBuildsEnabled (et al) turned on. If that
// method is not called then the debugFillProperties methods above should also
// not get called and we should end up tree-shaking the entire Diagnostics
// logic out of the app. The dev/bots/test.dart test checks for this by
// looking for the strings in the methods above.
debugProfileBuildsEnabled = true;
debugProfileLayoutsEnabled = true;
debugProfilePaintsEnabled = true;
runApp(const TestWidget());
}
| flutter/dev/tracing_tests/lib/test.dart/0 | {
"file_path": "flutter/dev/tracing_tests/lib/test.dart",
"repo_id": "flutter",
"token_count": 657
} | 613 |
// 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 [CupertinoFormRow].
void main() => runApp(const CupertinoFormRowApp());
class CupertinoFormRowApp extends StatelessWidget {
const CupertinoFormRowApp({super.key});
@override
Widget build(BuildContext context) {
return const CupertinoApp(
theme: CupertinoThemeData(brightness: Brightness.light),
home: CupertinoFormRowExample(),
);
}
}
class CupertinoFormRowExample extends StatefulWidget {
const CupertinoFormRowExample({super.key});
@override
State<CupertinoFormRowExample> createState() => _CupertinoFormRowExampleState();
}
class _CupertinoFormRowExampleState extends State<CupertinoFormRowExample> {
bool airplaneMode = false;
@override
Widget build(BuildContext context) {
return CupertinoPageScaffold(
navigationBar: const CupertinoNavigationBar(
middle: Text('CupertinoFormSection Sample'),
),
// Add safe area widget to place the CupertinoFormSection below the navigation bar.
child: SafeArea(
child: CupertinoFormSection(
header: const Text('Connectivity'),
children: <Widget>[
CupertinoFormRow(
prefix: const PrefixWidget(
icon: CupertinoIcons.airplane,
title: 'Airplane Mode',
color: CupertinoColors.systemOrange,
),
child: CupertinoSwitch(
value: airplaneMode,
onChanged: (bool value) {
setState(() {
airplaneMode = value;
});
},
),
),
const CupertinoFormRow(
prefix: PrefixWidget(
icon: CupertinoIcons.wifi,
title: 'Wi-Fi',
color: CupertinoColors.systemBlue,
),
error: Text('Home network unavailable'),
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[Text('Not connected'), SizedBox(width: 5), Icon(CupertinoIcons.forward)],
),
),
const CupertinoFormRow(
prefix: PrefixWidget(
icon: CupertinoIcons.bluetooth,
title: 'Bluetooth',
color: CupertinoColors.activeBlue,
),
helper: Padding(
padding: EdgeInsets.symmetric(vertical: 4.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text('Headphone'),
Text('Connected'),
],
),
),
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
Text('On'),
SizedBox(width: 5),
Icon(CupertinoIcons.forward),
],
),
),
const CupertinoFormRow(
prefix: PrefixWidget(
icon: CupertinoIcons.bluetooth,
title: 'Mobile Data',
color: CupertinoColors.systemGreen,
),
child: Icon(CupertinoIcons.forward),
),
],
),
),
);
}
}
class PrefixWidget extends StatelessWidget {
const PrefixWidget({
super.key,
required this.icon,
required this.title,
required this.color,
});
final IconData icon;
final String title;
final Color color;
@override
Widget build(BuildContext context) {
return Row(
children: <Widget>[
Container(
padding: const EdgeInsets.all(4.0),
decoration: BoxDecoration(
color: color,
borderRadius: BorderRadius.circular(4.0),
),
child: Icon(icon, color: CupertinoColors.white),
),
const SizedBox(width: 15),
Text(title)
],
);
}
}
| flutter/examples/api/lib/cupertino/form_row/cupertino_form_row.0.dart/0 | {
"file_path": "flutter/examples/api/lib/cupertino/form_row/cupertino_form_row.0.dart",
"repo_id": "flutter",
"token_count": 2069
} | 614 |
// 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 [CupertinoSegmentedControl].
enum Sky { midnight, viridian, cerulean }
Map<Sky, Color> skyColors = <Sky, Color>{
Sky.midnight: const Color(0xff191970),
Sky.viridian: const Color(0xff40826d),
Sky.cerulean: const Color(0xff007ba7),
};
void main() => runApp(const SegmentedControlApp());
class SegmentedControlApp extends StatelessWidget {
const SegmentedControlApp({super.key});
@override
Widget build(BuildContext context) {
return const CupertinoApp(
theme: CupertinoThemeData(brightness: Brightness.light),
home: SegmentedControlExample(),
);
}
}
class SegmentedControlExample extends StatefulWidget {
const SegmentedControlExample({super.key});
@override
State<SegmentedControlExample> createState() => _SegmentedControlExampleState();
}
class _SegmentedControlExampleState extends State<SegmentedControlExample> {
Sky _selectedSegment = Sky.midnight;
@override
Widget build(BuildContext context) {
return CupertinoPageScaffold(
backgroundColor: skyColors[_selectedSegment],
navigationBar: CupertinoNavigationBar(
// This Cupertino segmented control has the enum "Sky" as the type.
middle: CupertinoSegmentedControl<Sky>(
selectedColor: skyColors[_selectedSegment],
// Provide horizontal padding around the children.
padding: const EdgeInsets.symmetric(horizontal: 12),
// This represents a currently selected segmented control.
groupValue: _selectedSegment,
// Callback that sets the selected segmented control.
onValueChanged: (Sky value) {
setState(() {
_selectedSegment = value;
});
},
children: const <Sky, Widget>{
Sky.midnight: Padding(
padding: EdgeInsets.symmetric(horizontal: 20),
child: Text('Midnight'),
),
Sky.viridian: Padding(
padding: EdgeInsets.symmetric(horizontal: 20),
child: Text('Viridian'),
),
Sky.cerulean: Padding(
padding: EdgeInsets.symmetric(horizontal: 20),
child: Text('Cerulean'),
),
},
),
),
child: Center(
child: Text(
'Selected Segment: ${_selectedSegment.name}',
style: const TextStyle(color: CupertinoColors.white),
),
),
);
}
}
| flutter/examples/api/lib/cupertino/segmented_control/cupertino_segmented_control.0.dart/0 | {
"file_path": "flutter/examples/api/lib/cupertino/segmented_control/cupertino_segmented_control.0.dart",
"repo_id": "flutter",
"token_count": 1065
} | 615 |
// 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 [AppBar].
void main() => runApp(const AppBarApp());
class AppBarApp extends StatelessWidget {
const AppBarApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: AppBarExample(),
);
}
}
class AppBarExample extends StatelessWidget {
const AppBarExample({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('AppBar Demo'),
actions: <Widget>[
IconButton(
icon: const Icon(Icons.add_alert),
tooltip: 'Show Snackbar',
onPressed: () {
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('This is a snackbar')));
},
),
IconButton(
icon: const Icon(Icons.navigate_next),
tooltip: 'Go to the next page',
onPressed: () {
Navigator.push(context, MaterialPageRoute<void>(
builder: (BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Next page'),
),
body: const Center(
child: Text(
'This is the next page',
style: TextStyle(fontSize: 24),
),
),
);
},
));
},
),
],
),
body: const Center(
child: Text(
'This is the home page',
style: TextStyle(fontSize: 24),
),
),
);
}
}
| flutter/examples/api/lib/material/app_bar/app_bar.0.dart/0 | {
"file_path": "flutter/examples/api/lib/material/app_bar/app_bar.0.dart",
"repo_id": "flutter",
"token_count": 949
} | 616 |
// 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:flutter/rendering.dart';
/// Flutter code sample for [BottomAppBar] with Material 3.
void main() {
runApp(const BottomAppBarDemo());
}
class BottomAppBarDemo extends StatefulWidget {
const BottomAppBarDemo({super.key});
@override
State createState() => _BottomAppBarDemoState();
}
class _BottomAppBarDemoState extends State<BottomAppBarDemo> {
static const List<Color> colors = <Color>[
Colors.yellow,
Colors.orange,
Colors.pink,
Colors.purple,
Colors.cyan,
];
static final List<Widget> items = List<Widget>.generate(
colors.length,
(int index) => Container(color: colors[index], height: 150.0),
).reversed.toList();
late ScrollController _controller;
bool _showFab = true;
bool _isElevated = true;
bool _isVisible = true;
FloatingActionButtonLocation get _fabLocation =>
_isVisible ? FloatingActionButtonLocation.endContained : FloatingActionButtonLocation.endFloat;
void _listen() {
switch (_controller.position.userScrollDirection) {
case ScrollDirection.idle:
break;
case ScrollDirection.forward:
_show();
case ScrollDirection.reverse:
_hide();
}
}
void _show() {
if (!_isVisible) {
setState(() => _isVisible = true);
}
}
void _hide() {
if (_isVisible) {
setState(() => _isVisible = false);
}
}
void _onShowFabChanged(bool value) {
setState(() {
_showFab = value;
});
}
void _onElevatedChanged(bool value) {
setState(() {
_isElevated = value;
});
}
void _addNewItem() {
setState(() {
items.insert(
0,
Container(color: colors[items.length % 5], height: 150.0),
);
});
}
@override
void initState() {
super.initState();
_controller = ScrollController();
_controller.addListener(_listen);
}
@override
void dispose() {
_controller.removeListener(_listen);
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(useMaterial3: true),
home: Scaffold(
appBar: AppBar(
title: const Text('Bottom App Bar Demo'),
),
body: Column(
children: <Widget>[
SwitchListTile(
title: const Text('Floating Action Button'),
value: _showFab,
onChanged: _onShowFabChanged,
),
SwitchListTile(
title: const Text('Bottom App Bar Elevation'),
value: _isElevated,
onChanged: _onElevatedChanged,
),
Expanded(
child: ListView(
controller: _controller,
children: items.toList(),
),
),
],
),
floatingActionButton: _showFab
? FloatingActionButton(
onPressed: _addNewItem,
tooltip: 'Add New Item',
elevation: _isVisible ? 0.0 : null,
child: const Icon(Icons.add),
)
: null,
floatingActionButtonLocation: _fabLocation,
bottomNavigationBar: _DemoBottomAppBar(isElevated: _isElevated, isVisible: _isVisible),
),
);
}
}
class _DemoBottomAppBar extends StatelessWidget {
const _DemoBottomAppBar({
required this.isElevated,
required this.isVisible,
});
final bool isElevated;
final bool isVisible;
@override
Widget build(BuildContext context) {
return AnimatedContainer(
duration: const Duration(milliseconds: 200),
height: isVisible ? 80.0 : 0,
child: BottomAppBar(
elevation: isElevated ? null : 0.0,
child: Row(
children: <Widget>[
IconButton(
tooltip: 'Open popup menu',
icon: const Icon(Icons.more_vert),
onPressed: () {
final SnackBar snackBar = SnackBar(
content: const Text('Yay! A SnackBar!'),
action: SnackBarAction(
label: 'Undo',
onPressed: () {},
),
);
// Find the ScaffoldMessenger in the widget tree
// and use it to show a SnackBar.
ScaffoldMessenger.of(context).showSnackBar(snackBar);
},
),
IconButton(
tooltip: 'Search',
icon: const Icon(Icons.search),
onPressed: () {},
),
IconButton(
tooltip: 'Favorite',
icon: const Icon(Icons.favorite),
onPressed: () {},
),
],
),
),
);
}
}
| flutter/examples/api/lib/material/bottom_app_bar/bottom_app_bar.2.dart/0 | {
"file_path": "flutter/examples/api/lib/material/bottom_app_bar/bottom_app_bar.2.dart",
"repo_id": "flutter",
"token_count": 2284
} | 617 |
// 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 custom labeled checkbox.
void main() => runApp(const LabeledCheckboxApp());
class LabeledCheckboxApp extends StatelessWidget {
const LabeledCheckboxApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(useMaterial3: true),
home: const LabeledCheckboxExample(),
);
}
}
class LabeledCheckbox extends StatelessWidget {
const LabeledCheckbox({
super.key,
required this.label,
required this.padding,
required this.value,
required this.onChanged,
});
final String label;
final EdgeInsets padding;
final bool value;
final ValueChanged<bool> onChanged;
@override
Widget build(BuildContext context) {
return InkWell(
onTap: () {
onChanged(!value);
},
child: Padding(
padding: padding,
child: Row(
children: <Widget>[
Expanded(child: Text(label)),
Checkbox(
value: value,
onChanged: (bool? newValue) {
onChanged(newValue!);
},
),
],
),
),
);
}
}
class LabeledCheckboxExample extends StatefulWidget {
const LabeledCheckboxExample({super.key});
@override
State<LabeledCheckboxExample> createState() => _LabeledCheckboxExampleState();
}
class _LabeledCheckboxExampleState extends State<LabeledCheckboxExample> {
bool _isSelected = false;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Custom Labeled Checkbox Sample')),
body: Center(
child: LabeledCheckbox(
label: 'This is the label text',
padding: const EdgeInsets.symmetric(horizontal: 20.0),
value: _isSelected,
onChanged: (bool newValue) {
setState(() {
_isSelected = newValue;
});
},
),
),
);
}
}
| flutter/examples/api/lib/material/checkbox_list_tile/custom_labeled_checkbox.1.dart/0 | {
"file_path": "flutter/examples/api/lib/material/checkbox_list_tile/custom_labeled_checkbox.1.dart",
"repo_id": "flutter",
"token_count": 879
} | 618 |
// 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 [showDateRangePicker].
void main() => runApp(const DatePickerApp());
class DatePickerApp extends StatelessWidget {
const DatePickerApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
restorationScopeId: 'app',
home: DatePickerExample(restorationId: 'main'),
);
}
}
class DatePickerExample extends StatefulWidget {
const DatePickerExample({super.key, this.restorationId});
final String? restorationId;
@override
State<DatePickerExample> createState() => _DatePickerExampleState();
}
/// RestorationProperty objects can be used because of RestorationMixin.
class _DatePickerExampleState extends State<DatePickerExample> with RestorationMixin {
// In this example, the restoration ID for the mixin is passed in through
// the [StatefulWidget]'s constructor.
@override
String? get restorationId => widget.restorationId;
final RestorableDateTimeN _startDate = RestorableDateTimeN(DateTime(2021));
final RestorableDateTimeN _endDate = RestorableDateTimeN(DateTime(2021, 1, 5));
late final RestorableRouteFuture<DateTimeRange?> _restorableDateRangePickerRouteFuture =
RestorableRouteFuture<DateTimeRange?>(
onComplete: _selectDateRange,
onPresent: (NavigatorState navigator, Object? arguments) {
return navigator.restorablePush(_dateRangePickerRoute, arguments: <String, dynamic>{
'initialStartDate': _startDate.value?.millisecondsSinceEpoch,
'initialEndDate': _endDate.value?.millisecondsSinceEpoch,
});
},
);
void _selectDateRange(DateTimeRange? newSelectedDate) {
if (newSelectedDate != null) {
setState(() {
_startDate.value = newSelectedDate.start;
_endDate.value = newSelectedDate.end;
});
}
}
@override
void restoreState(RestorationBucket? oldBucket, bool initialRestore) {
registerForRestoration(_startDate, 'start_date');
registerForRestoration(_endDate, 'end_date');
registerForRestoration(_restorableDateRangePickerRouteFuture, 'date_picker_route_future');
}
@pragma('vm:entry-point')
static Route<DateTimeRange?> _dateRangePickerRoute(
BuildContext context,
Object? arguments,
) {
return DialogRoute<DateTimeRange?>(
context: context,
builder: (BuildContext context) {
return DateRangePickerDialog(
restorationId: 'date_picker_dialog',
initialDateRange: _initialDateTimeRange(arguments! as Map<dynamic, dynamic>),
firstDate: DateTime(2021),
currentDate: DateTime(2021, 1, 25),
lastDate: DateTime(2022),
);
},
);
}
static DateTimeRange? _initialDateTimeRange(Map<dynamic, dynamic> arguments) {
if (arguments['initialStartDate'] != null && arguments['initialEndDate'] != null) {
return DateTimeRange(
start: DateTime.fromMillisecondsSinceEpoch(arguments['initialStartDate'] as int),
end: DateTime.fromMillisecondsSinceEpoch(arguments['initialEndDate'] as int),
);
}
return null;
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: OutlinedButton(
onPressed: () {
_restorableDateRangePickerRouteFuture.present();
},
child: const Text('Open Date Range Picker'),
),
),
);
}
}
| flutter/examples/api/lib/material/date_picker/show_date_range_picker.0.dart/0 | {
"file_path": "flutter/examples/api/lib/material/date_picker/show_date_range_picker.0.dart",
"repo_id": "flutter",
"token_count": 1271
} | 619 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.