code
stringlengths
8
3.25M
repository
stringlengths
15
175
metadata
stringlengths
66
249
// 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. import 'dart:async'; import 'package:ui/ui.dart' as ui; import '../browser_detection.dart'; import '../dom.dart'; import '../platform_dispatcher.dart'; import '../text_editing/text_editing.dart'; import 'semantics.dart'; /// Text editing used by accesibility mode. /// /// [SemanticsTextEditingStrategy] assumes the caller will own the creation, /// insertion and disposal of the DOM element. Due to this /// [initializeElementPlacement], [initializeTextEditing] and /// [disable] strategies are handled differently. /// /// This class is still responsible for hooking up the DOM element with the /// [HybridTextEditing] instance so that changes are communicated to Flutter. class SemanticsTextEditingStrategy extends DefaultTextEditingStrategy { /// Creates a [SemanticsTextEditingStrategy] that eagerly instantiates /// [domElement] so the caller can insert it before calling /// [SemanticsTextEditingStrategy.enable]. SemanticsTextEditingStrategy(super.owner); /// Initializes the [SemanticsTextEditingStrategy] singleton. /// /// This method must be called prior to accessing [instance]. static SemanticsTextEditingStrategy ensureInitialized( HybridTextEditing owner) { if (_instance != null && _instance?.owner == owner) { return _instance!; } return _instance = SemanticsTextEditingStrategy(owner); } /// The [SemanticsTextEditingStrategy] singleton. static SemanticsTextEditingStrategy get instance => _instance!; static SemanticsTextEditingStrategy? _instance; /// The text field whose DOM element is currently used for editing. /// /// If this field is null, no editing takes place. TextField? activeTextField; /// Current input configuration supplied by the "flutter/textinput" channel. InputConfiguration? inputConfig; /// The semantics implementation does not operate on DOM nodes, but only /// remembers the config and callbacks. This is because the DOM nodes are /// supplied in the semantics update and enabled by [activate]. @override void enable( InputConfiguration inputConfig, { required OnChangeCallback onChange, required OnActionCallback onAction, }) { this.inputConfig = inputConfig; this.onChange = onChange; this.onAction = onAction; } /// Attaches the DOM element owned by [textField] to the text editing /// strategy. /// /// This method must be called after [enable] to name sure that [inputConfig], /// [onChange], and [onAction] are not null. void activate(TextField textField) { assert( inputConfig != null && onChange != null && onAction != null, '"enable" should be called before "enableFromSemantics" and initialize input configuration', ); if (activeTextField == textField) { // The specified field is already active. Skip. return; } else if (activeTextField != null) { // Another text field is currently active. Deactivate it before switching. disable(); } activeTextField = textField; domElement = textField.editableElement; _syncStyle(); super.enable(inputConfig!, onChange: onChange!, onAction: onAction!); } /// Detaches the DOM element owned by [textField] from this text editing /// strategy. /// /// Typically at this point the element loses focus (blurs) and stops being /// used for editing. void deactivate(TextField textField) { if (activeTextField == textField) { disable(); } } @override void disable() { // We don't want to remove the DOM element because the caller is responsible // for that. However we still want to stop editing, cleanup the handlers. if (!isEnabled) { return; } isEnabled = false; style = null; geometry = null; for (int i = 0; i < subscriptions.length; i++) { subscriptions[i].cancel(); } subscriptions.clear(); lastEditingState = null; // If the text element still has focus, remove focus from the editable // element to cause the on-screen keyboard, if any, to hide (e.g. on iOS, // Android). // Otherwise, the keyboard stays on screen even when the user navigates to // a different screen (e.g. by hitting the "back" button). domElement?.blur(); domElement = null; activeTextField = null; _queuedStyle = null; } @override void addEventHandlers() { if (inputConfiguration.autofillGroup != null) { subscriptions .addAll(inputConfiguration.autofillGroup!.addInputEventListeners()); } // Subscribe to text and selection changes. subscriptions.add( DomSubscription(activeDomElement, 'input', handleChange)); subscriptions.add( DomSubscription(activeDomElement, 'keydown', maybeSendAction)); subscriptions.add( DomSubscription(domDocument, 'selectionchange', handleChange)); preventDefaultForMouseEvents(); } @override void initializeTextEditing(InputConfiguration inputConfig, {OnChangeCallback? onChange, OnActionCallback? onAction}) { isEnabled = true; inputConfiguration = inputConfig; applyConfiguration(inputConfig); } @override void placeElement() { // If this text editing element is a part of an autofill group. if (hasAutofillGroup) { placeForm(); } activeDomElement.focus(); } @override void initializeElementPlacement() { // Element placement is done by [TextField]. } @override void placeForm() { } @override void updateElementPlacement(EditableTextGeometry textGeometry) { // Element placement is done by [TextField]. } EditableTextStyle? _queuedStyle; @override void updateElementStyle(EditableTextStyle textStyle) { _queuedStyle = textStyle; _syncStyle(); } /// Apply style to the element, if both style and element are available. /// /// Because style is supplied by the "flutter/textinput" channel and the DOM /// element is supplied by the semantics tree, the existence of both at the /// same time is not guaranteed. void _syncStyle() { if (_queuedStyle == null || domElement == null) { return; } super.updateElementStyle(_queuedStyle!); } } /// Manages semantics objects that represent editable text fields. /// /// This role is implemented via a content-editable HTML element. This role does /// not proactively switch modes depending on the current /// [EngineSemanticsOwner.gestureMode]. However, in Chrome on Android it ignores /// browser gestures when in pointer mode. In Safari on iOS pointer events are /// used to detect text box invocation. This is because Safari issues touch /// events even when Voiceover is enabled. class TextField extends PrimaryRoleManager { TextField(SemanticsObject semanticsObject) : super.blank(PrimaryRole.textField, semanticsObject) { _setupDomElement(); } /// The element used for editing, e.g. `<input>`, `<textarea>`. DomHTMLElement? editableElement; /// Same as [editableElement] but null-checked. DomHTMLElement get activeEditableElement { assert( editableElement != null, 'The textField does not have an active editable element', ); return editableElement!; } @override bool focusAsRouteDefault() { final DomHTMLElement? editableElement = this.editableElement; if (editableElement == null) { return false; } editableElement.focus(); return true; } /// Timer that times when to set the location of the input text. /// /// This is only used for iOS. In iOS, virtual keyboard shifts the screen. /// There is no callback to know if the keyboard is up and how much the screen /// has shifted. Therefore instead of listening to the shift and passing this /// information to Flutter Framework, we are trying to stop the shift. /// /// In iOS, the virtual keyboard shifts the screen up if the focused input /// element is under the keyboard or very close to the keyboard. Before the /// focus is called we are positioning it offscreen. The location of the input /// in iOS is set to correct place, 100ms after focus. We use this timer for /// timing this delay. Timer? _positionInputElementTimer; static const Duration _delayBeforePlacement = Duration(milliseconds: 100); void _initializeEditableElement() { assert(editableElement == null, 'Editable element has already been initialized'); editableElement = semanticsObject.hasFlag(ui.SemanticsFlag.isMultiline) ? createDomHTMLTextAreaElement() : createDomHTMLInputElement(); // On iOS, even though the semantic text field is transparent, the cursor // and text highlighting are still visible. The cursor and text selection // are made invisible by CSS in [FlutterViewEmbedder.reset]. // But there's one more case where iOS highlights text. That's when there's // and autocorrect suggestion. To disable that, we have to do the following: activeEditableElement ..spellcheck = false ..setAttribute('autocorrect', 'off') ..setAttribute('autocomplete', 'off') ..setAttribute('data-semantics-role', 'text-field'); activeEditableElement.style ..position = 'absolute' // `top` and `left` are intentionally set to zero here. // // The text field would live inside a `<flt-semantics>` which should // already be positioned using semantics.rect. // // See also: // // * [SemanticsObject.recomputePositionAndSize], which sets the position // and size of the parent `<flt-semantics>` element. ..top = '0' ..left = '0' ..width = '${semanticsObject.rect!.width}px' ..height = '${semanticsObject.rect!.height}px'; append(activeEditableElement); } void _setupDomElement() { switch (browserEngine) { case BrowserEngine.blink: case BrowserEngine.firefox: _initializeForBlink(); case BrowserEngine.webkit: _initializeForWebkit(); } } /// Chrome on Android reports text field activation as a "click" event. /// /// When in browser gesture mode, the focus is forwarded to the framework as /// a tap to initialize editing. void _initializeForBlink() { _initializeEditableElement(); activeEditableElement.addEventListener('focus', createDomEventListener((DomEvent event) { if (EngineSemantics.instance.gestureMode != GestureMode.browserGestures) { return; } EnginePlatformDispatcher.instance.invokeOnSemanticsAction( semanticsObject.id, ui.SemanticsAction.didGainAccessibilityFocus, null); })); activeEditableElement.addEventListener('blur', createDomEventListener((DomEvent event) { if (EngineSemantics.instance.gestureMode != GestureMode.browserGestures) { return; } EnginePlatformDispatcher.instance.invokeOnSemanticsAction( semanticsObject.id, ui.SemanticsAction.didLoseAccessibilityFocus, null); })); } /// Safari on iOS reports text field activation via pointer events. /// /// This emulates a tap recognizer to detect the activation. Because pointer /// events are present regardless of whether accessibility is enabled or not, /// this mode is always enabled. /// /// In iOS, the virtual keyboard shifts the screen up if the focused input /// element is under the keyboard or very close to the keyboard. To avoid the shift, /// the creation of the editable element is delayed until a tap is detected. /// /// In the absence of an editable DOM element, role of 'textbox' is assigned to the /// semanticsObject.element to communicate to the assistive technologies that /// the user can start editing by tapping on the element. Once a tap is detected, /// the editable element gets created and the role of textbox is removed from /// semanicsObject.element to avoid confusing VoiceOver. void _initializeForWebkit() { // Safari for desktop is also initialized as the other browsers. if (operatingSystem == OperatingSystem.macOs) { _initializeForBlink(); return; } setAttribute('role', 'textbox'); setAttribute('contenteditable', 'false'); setAttribute('tabindex', '0'); num? lastPointerDownOffsetX; num? lastPointerDownOffsetY; addEventListener('pointerdown', createDomEventListener((DomEvent event) { final DomPointerEvent pointerEvent = event as DomPointerEvent; lastPointerDownOffsetX = pointerEvent.clientX; lastPointerDownOffsetY = pointerEvent.clientY; }), true); addEventListener('pointerup', createDomEventListener((DomEvent event) { final DomPointerEvent pointerEvent = event as DomPointerEvent; if (lastPointerDownOffsetX != null) { assert(lastPointerDownOffsetY != null); final num deltaX = pointerEvent.clientX - lastPointerDownOffsetX!; final num deltaY = pointerEvent.clientY - lastPointerDownOffsetY!; // This should match the similar constant defined in: // // lib/src/gestures/constants.dart // // The value is pre-squared so we have to do less math at runtime. const double kTouchSlop = 18.0 * 18.0; // Logical pixels squared if (deltaX * deltaX + deltaY * deltaY < kTouchSlop) { // Recognize it as a tap that requires a keyboard. EnginePlatformDispatcher.instance.invokeOnSemanticsAction( semanticsObject.id, ui.SemanticsAction.tap, null); _invokeIosWorkaround(); } } else { assert(lastPointerDownOffsetY == null); } lastPointerDownOffsetX = null; lastPointerDownOffsetY = null; }), true); } void _invokeIosWorkaround() { if (editableElement != null) { return; } _initializeEditableElement(); activeEditableElement.style.transform = 'translate(${offScreenOffset}px, ${offScreenOffset}px)'; _positionInputElementTimer?.cancel(); _positionInputElementTimer = Timer(_delayBeforePlacement, () { editableElement?.style.transform = ''; _positionInputElementTimer = null; }); // Can not have both activeEditableElement and semanticsObject.element // represent the same text field. It will confuse VoiceOver, so `role` needs to // be assigned and removed, based on whether or not editableElement exists. activeEditableElement.focus(); removeAttribute('role'); activeEditableElement.addEventListener('blur', createDomEventListener((DomEvent event) { setAttribute('role', 'textbox'); activeEditableElement.remove(); SemanticsTextEditingStrategy._instance?.deactivate(this); // Focus on semantics element before removing the editable element, so that // the user can continue navigating the page with the assistive technology. element.focus(); editableElement = null; })); } @override void update() { super.update(); // Ignore the update if editableElement has not been created yet. // On iOS Safari, when the user dismisses the keyboard using the 'done' button, // we recieve a `blur` event from the browswer and a semantic update with // [hasFocus] set to true from the framework. In this case, we ignore the update // and wait for a tap event before invoking the iOS workaround and creating // the editable element. if (editableElement != null) { activeEditableElement.style ..width = '${semanticsObject.rect!.width}px' ..height = '${semanticsObject.rect!.height}px'; if (semanticsObject.hasFocus) { if (domDocument.activeElement != activeEditableElement) { semanticsObject.owner.addOneTimePostUpdateCallback(() { activeEditableElement.focus(); }); } SemanticsTextEditingStrategy._instance?.activate(this); } else if (domDocument.activeElement == activeEditableElement) { if (!isIosSafari) { SemanticsTextEditingStrategy._instance?.deactivate(this); // Only apply text, because this node is not focused. } activeEditableElement.blur(); } } final DomElement element = editableElement ?? this.element; if (semanticsObject.hasLabel) { element.setAttribute( 'aria-label', semanticsObject.label!, ); } else { element.removeAttribute('aria-label'); } } @override void dispose() { super.dispose(); _positionInputElementTimer?.cancel(); _positionInputElementTimer = null; // on iOS, the `blur` event listener callback will remove the element. if (!isIosSafari) { editableElement?.remove(); } SemanticsTextEditingStrategy._instance?.deactivate(this); } }
engine/lib/web_ui/lib/src/engine/semantics/text_field.dart/0
{'file_path': 'engine/lib/web_ui/lib/src/engine/semantics/text_field.dart', 'repo_id': 'engine', 'token_count': 5526}
// 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. @DefaultAsset('skwasm') library skwasm_impl; import 'dart:convert'; import 'dart:ffi'; final class RawSkString extends Opaque {} typedef SkStringHandle = Pointer<RawSkString>; final class RawSkString16 extends Opaque {} typedef SkString16Handle = Pointer<RawSkString16>; @Native<SkStringHandle Function(Size)>(symbol: 'skString_allocate', isLeaf: true) external SkStringHandle skStringAllocate(int size); @Native<Pointer<Int8> Function(SkStringHandle)>(symbol: 'skString_getData', isLeaf: true) external Pointer<Int8> skStringGetData(SkStringHandle handle); @Native<Void Function(SkStringHandle)>(symbol: 'skString_free', isLeaf: true) external void skStringFree(SkStringHandle handle); @Native<SkString16Handle Function(Size)>(symbol: 'skString16_allocate', isLeaf: true) external SkString16Handle skString16Allocate(int size); @Native<Pointer<Int16> Function(SkString16Handle)>(symbol: 'skString16_getData', isLeaf: true) external Pointer<Int16> skString16GetData(SkString16Handle handle); @Native<Void Function(SkString16Handle)>(symbol: 'skString16_free', isLeaf: true) external void skString16Free(SkString16Handle handle); SkStringHandle skStringFromDartString(String string) { final List<int> rawUtf8Bytes = utf8.encode(string); final SkStringHandle stringHandle = skStringAllocate(rawUtf8Bytes.length); final Pointer<Int8> stringDataPointer = skStringGetData(stringHandle); for (int i = 0; i < rawUtf8Bytes.length; i++) { stringDataPointer[i] = rawUtf8Bytes[i]; } return stringHandle; } SkString16Handle skString16FromDartString(String string) { final SkString16Handle stringHandle = skString16Allocate(string.length); final Pointer<Int16> stringDataPointer = skString16GetData(stringHandle); for (int i = 0; i < string.length; i++) { stringDataPointer[i] = string.codeUnitAt(i); } return stringHandle; }
engine/lib/web_ui/lib/src/engine/skwasm/skwasm_impl/raw/raw_skstring.dart/0
{'file_path': 'engine/lib/web_ui/lib/src/engine/skwasm/skwasm_impl/raw/raw_skstring.dart', 'repo_id': 'engine', 'token_count': 662}
// 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. import 'dart:js_interop'; import 'dom.dart'; @JS() @staticInterop class SVGElement extends DomElement {} SVGElement createSVGElement(String tag) => domDocument.createElementNS('http://www.w3.org/2000/svg', tag) as SVGElement; @JS() @staticInterop class SVGGraphicsElement extends SVGElement {} @JS() @staticInterop class SVGSVGElement extends SVGGraphicsElement {} SVGSVGElement createSVGSVGElement() { final SVGElement el = createSVGElement('svg'); el.setAttribute('version', '1.1'); return el as SVGSVGElement; } extension SVGSVGElementExtension on SVGSVGElement { external SVGNumber createSVGNumber(); external SVGAnimatedLength? get height; external SVGAnimatedLength? get width; } @JS() @staticInterop class SVGClipPathElement extends SVGGraphicsElement {} SVGClipPathElement createSVGClipPathElement() => domDocument.createElementNS('http://www.w3.org/2000/svg', 'clipPath') as SVGClipPathElement; @JS() @staticInterop class SVGDefsElement extends SVGGraphicsElement {} SVGDefsElement createSVGDefsElement() => domDocument.createElementNS('http://www.w3.org/2000/svg', 'defs') as SVGDefsElement; @JS() @staticInterop class SVGGeometryElement extends SVGGraphicsElement {} @JS() @staticInterop class SVGPathElement extends SVGGeometryElement {} SVGPathElement createSVGPathElement() => domDocument.createElementNS('http://www.w3.org/2000/svg', 'path') as SVGPathElement; @JS() @staticInterop class SVGFilterElement extends SVGElement {} extension SVGFilterElementExtension on SVGFilterElement { external SVGAnimatedEnumeration? get filterUnits; external SVGAnimatedLength? get height; external SVGAnimatedLength? get width; external SVGAnimatedLength? get x; external SVGAnimatedLength? get y; } SVGFilterElement createSVGFilterElement() => domDocument.createElementNS('http://www.w3.org/2000/svg', 'filter') as SVGFilterElement; @JS() @staticInterop class SVGAnimatedLength {} extension SVGAnimatedLengthExtension on SVGAnimatedLength { external SVGLength? get baseVal; } @JS() @staticInterop class SVGLength {} extension SVGLengthExtension on SVGLength { @JS('valueAsString') external set _valueAsString(JSString? value); set valueAsString(String? value) => _valueAsString = value?.toJS; @JS('newValueSpecifiedUnits') external JSVoid _newValueSpecifiedUnits(JSNumber unitType, JSNumber valueInSpecifiedUnits); void newValueSpecifiedUnits(int unitType, num valueInSpecifiedUnits) => _newValueSpecifiedUnits(unitType.toJS, valueInSpecifiedUnits.toJS); } const int svgLengthTypeNumber = 1; @JS() @staticInterop class SVGAnimatedEnumeration {} extension SVGAnimatedEnumerationExtenson on SVGAnimatedEnumeration { @JS('baseVal') external set _baseVal(JSNumber? value); set baseVal(int? value) => _baseVal = value?.toJS; } @JS() @staticInterop class SVGFEColorMatrixElement extends SVGElement {} extension SVGFEColorMatrixElementExtension on SVGFEColorMatrixElement { external SVGAnimatedEnumeration? get type; external SVGAnimatedString? get result; external SVGAnimatedNumberList? get values; } SVGFEColorMatrixElement createSVGFEColorMatrixElement() => domDocument.createElementNS('http://www.w3.org/2000/svg', 'feColorMatrix') as SVGFEColorMatrixElement; @JS() @staticInterop class SVGFEFloodElement extends SVGElement {} extension SVGFEFloodElementExtension on SVGFEFloodElement { external SVGAnimatedString? get result; } SVGFEFloodElement createSVGFEFloodElement() => domDocument.createElementNS('http://www.w3.org/2000/svg', 'feFlood') as SVGFEFloodElement; @JS() @staticInterop class SVGFEBlendElement extends SVGElement {} extension SVGFEBlendElementExtension on SVGFEBlendElement { external SVGAnimatedString? get in1; external SVGAnimatedString? get in2; external SVGAnimatedEnumeration? get mode; } SVGFEBlendElement createSVGFEBlendElement() => domDocument.createElementNS('http://www.w3.org/2000/svg', 'feBlend') as SVGFEBlendElement; @JS() @staticInterop class SVGFEImageElement extends SVGElement {} extension SVGFEImageElementExtension on SVGFEImageElement { external SVGAnimatedLength? get height; external SVGAnimatedLength? get width; external SVGAnimatedString? get result; external SVGAnimatedLength? get x; external SVGAnimatedLength? get y; external SVGAnimatedString? get href; } SVGFEImageElement createSVGFEImageElement() => domDocument.createElementNS('http://www.w3.org/2000/svg', 'feImage') as SVGFEImageElement; @JS() @staticInterop class SVGFECompositeElement extends SVGElement {} SVGFECompositeElement createSVGFECompositeElement() => domDocument.createElementNS('http://www.w3.org/2000/svg', 'feComposite') as SVGFECompositeElement; extension SVGFEBlendCompositeExtension on SVGFECompositeElement { external SVGAnimatedString? get in1; external SVGAnimatedString? get in2; external SVGAnimatedNumber? get k1; external SVGAnimatedNumber? get k2; external SVGAnimatedNumber? get k3; external SVGAnimatedNumber? get k4; external SVGAnimatedEnumeration? get operator; external SVGAnimatedString? get result; } @JS() @staticInterop class SVGAnimatedString {} extension SVGAnimatedStringExtension on SVGAnimatedString { @JS('baseVal') external set _baseVal(JSString? value); set baseVal(String? value) => _baseVal = value?.toJS; } @JS() @staticInterop class SVGAnimatedNumber {} extension SVGAnimatedNumberExtension on SVGAnimatedNumber { @JS('baseVal') external set _baseVal(JSNumber? value); set baseVal(num? value) => _baseVal = value?.toJS; } @JS() @staticInterop class SVGAnimatedNumberList {} extension SVGAnimatedNumberListExtension on SVGAnimatedNumberList { external SVGNumberList? get baseVal; } @JS() @staticInterop class SVGNumberList {} extension SVGNumberListExtension on SVGNumberList { external SVGNumber appendItem(SVGNumber newItem); } @JS() @staticInterop class SVGNumber {} extension SVGNumberExtension on SVGNumber { @JS('value') external set _value(JSNumber? value); set value(num? v) => _value = v?.toJS; }
engine/lib/web_ui/lib/src/engine/svg.dart/0
{'file_path': 'engine/lib/web_ui/lib/src/engine/svg.dart', 'repo_id': 'engine', 'token_count': 2110}
// 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. import '../util.dart'; import 'word_break_properties.dart'; enum _FindBreakDirection { forward(step: 1), backward(step: -1); const _FindBreakDirection({required this.step}); final int step; } /// [WordBreaker] exposes static methods to identify word boundaries. abstract final class WordBreaker { /// It starts from [index] and tries to find the next word boundary in [text]. static int nextBreakIndex(String text, int index) => _findBreakIndex(_FindBreakDirection.forward, text, index); /// It starts from [index] and tries to find the previous word boundary in /// [text]. static int prevBreakIndex(String text, int index) => _findBreakIndex(_FindBreakDirection.backward, text, index); static int _findBreakIndex( _FindBreakDirection direction, String text, int index, ) { int i = index; while (i >= 0 && i <= text.length) { i += direction.step; if (_isBreak(text, i)) { break; } } return clampInt(i, 0, text.length); } /// Find out if there's a word break between [index - 1] and [index]. /// http://unicode.org/reports/tr29/#Word_Boundary_Rules static bool _isBreak(String? text, int index) { // Break at the start and end of text. // WB1: sot ÷ Any // WB2: Any ÷ eot if (index <= 0 || index >= text!.length) { return true; } // Do not break inside surrogate pair if (_isUtf16Surrogate(text.codeUnitAt(index - 1))) { return false; } final WordCharProperty immediateRight = wordLookup.find(text, index); WordCharProperty immediateLeft = wordLookup.find(text, index - 1); // Do not break within CRLF. // WB3: CR × LF if (immediateLeft == WordCharProperty.CR && immediateRight == WordCharProperty.LF) { return false; } // Otherwise break before and after Newlines (including CR and LF) // WB3a: (Newline | CR | LF) ÷ if (_oneOf( immediateLeft, WordCharProperty.Newline, WordCharProperty.CR, WordCharProperty.LF, )) { return true; } // WB3b: ÷ (Newline | CR | LF) if (_oneOf( immediateRight, WordCharProperty.Newline, WordCharProperty.CR, WordCharProperty.LF, )) { return true; } // WB3c: ZWJ × \p{Extended_Pictographic} // TODO(mdebbar): What's the right way to implement this? // Keep horizontal whitespace together. // WB3d: WSegSpace × WSegSpace if (immediateLeft == WordCharProperty.WSegSpace && immediateRight == WordCharProperty.WSegSpace) { return false; } // Ignore Format and Extend characters, except after sot, CR, LF, and // Newline. // WB4: X (Extend | Format | ZWJ)* → X if (_oneOf( immediateRight, WordCharProperty.Extend, WordCharProperty.Format, WordCharProperty.ZWJ, )) { // The Extend|Format|ZWJ character is to the right, so it is attached // to a character to the left, don't split here return false; } // We've reached the end of an Extend|Format|ZWJ sequence, collapse it. int l = 0; while (_oneOf( immediateLeft, WordCharProperty.Extend, WordCharProperty.Format, WordCharProperty.ZWJ, )) { l++; if (index - l - 1 < 0) { // Reached the beginning of text. return true; } immediateLeft = wordLookup.find(text, index - l - 1); } // Do not break between most letters. // WB5: (ALetter | Hebrew_Letter) × (ALetter | Hebrew_Letter) if (_isAHLetter(immediateLeft) && _isAHLetter(immediateRight)) { return false; } // Some tests beyond this point require more context. We need to get that // context while also respecting rule WB4. So ignore Format, Extend and ZWJ. // Skip all Format, Extend and ZWJ to the right. int r = 0; WordCharProperty? nextRight; do { r++; nextRight = wordLookup.find(text, index + r); } while (_oneOf( nextRight, WordCharProperty.Extend, WordCharProperty.Format, WordCharProperty.ZWJ, )); // Skip all Format, Extend and ZWJ to the left. WordCharProperty? nextLeft; do { l++; nextLeft = wordLookup.find(text, index - l - 1); } while (_oneOf( nextLeft, WordCharProperty.Extend, WordCharProperty.Format, WordCharProperty.ZWJ, )); // Do not break letters across certain punctuation. // WB6: (AHLetter) × (MidLetter | MidNumLet | Single_Quote) (AHLetter) if (_isAHLetter(immediateLeft) && _oneOf( immediateRight, WordCharProperty.MidLetter, WordCharProperty.MidNumLet, WordCharProperty.SingleQuote, ) && _isAHLetter(nextRight)) { return false; } // WB7: (AHLetter) (MidLetter | MidNumLet | Single_Quote) × (AHLetter) if (_isAHLetter(nextLeft) && _oneOf( immediateLeft, WordCharProperty.MidLetter, WordCharProperty.MidNumLet, WordCharProperty.SingleQuote, ) && _isAHLetter(immediateRight)) { return false; } // WB7a: Hebrew_Letter × Single_Quote if (immediateLeft == WordCharProperty.HebrewLetter && immediateRight == WordCharProperty.SingleQuote) { return false; } // WB7b: Hebrew_Letter × Double_Quote Hebrew_Letter if (immediateLeft == WordCharProperty.HebrewLetter && immediateRight == WordCharProperty.DoubleQuote && nextRight == WordCharProperty.HebrewLetter) { return false; } // WB7c: Hebrew_Letter Double_Quote × Hebrew_Letter if (nextLeft == WordCharProperty.HebrewLetter && immediateLeft == WordCharProperty.DoubleQuote && immediateRight == WordCharProperty.HebrewLetter) { return false; } // Do not break within sequences of digits, or digits adjacent to letters // (“3a”, or “A3”). // WB8: Numeric × Numeric if (immediateLeft == WordCharProperty.Numeric && immediateRight == WordCharProperty.Numeric) { return false; } // WB9: AHLetter × Numeric if (_isAHLetter(immediateLeft) && immediateRight == WordCharProperty.Numeric) { return false; } // WB10: Numeric × AHLetter if (immediateLeft == WordCharProperty.Numeric && _isAHLetter(immediateRight)) { return false; } // Do not break within sequences, such as “3.2” or “3,456.789”. // WB11: Numeric (MidNum | MidNumLet | Single_Quote) × Numeric if (nextLeft == WordCharProperty.Numeric && _oneOf( immediateLeft, WordCharProperty.MidNum, WordCharProperty.MidNumLet, WordCharProperty.SingleQuote, ) && immediateRight == WordCharProperty.Numeric) { return false; } // WB12: Numeric × (MidNum | MidNumLet | Single_Quote) Numeric if (immediateLeft == WordCharProperty.Numeric && _oneOf( immediateRight, WordCharProperty.MidNum, WordCharProperty.MidNumLet, WordCharProperty.SingleQuote, ) && nextRight == WordCharProperty.Numeric) { return false; } // Do not break between Katakana. // WB13: Katakana × Katakana if (immediateLeft == WordCharProperty.Katakana && immediateRight == WordCharProperty.Katakana) { return false; } // Do not break from extenders. // WB13a: (AHLetter | Numeric | Katakana | ExtendNumLet) × ExtendNumLet if (_oneOf( immediateLeft, WordCharProperty.ALetter, WordCharProperty.HebrewLetter, WordCharProperty.Numeric, WordCharProperty.Katakana, WordCharProperty.ExtendNumLet, ) && immediateRight == WordCharProperty.ExtendNumLet) { return false; } // WB13b: ExtendNumLet × (AHLetter | Numeric | Katakana) if (immediateLeft == WordCharProperty.ExtendNumLet && _oneOf( immediateRight, WordCharProperty.ALetter, WordCharProperty.HebrewLetter, WordCharProperty.Numeric, WordCharProperty.Katakana, )) { return false; } // Do not break within emoji flag sequences. That is, do not break between // regional indicator (RI) symbols if there is an odd number of RI // characters before the break point. // WB15: sot (RI RI)* RI × RI // TODO(mdebbar): implement this. // WB16: [^RI] (RI RI)* RI × RI // TODO(mdebbar): implement this. // Otherwise, break everywhere (including around ideographs). // WB999: Any ÷ Any return true; } static bool _isUtf16Surrogate(int value) { return value & 0xF800 == 0xD800; } static bool _oneOf( WordCharProperty? value, WordCharProperty choice1, WordCharProperty choice2, [ WordCharProperty? choice3, WordCharProperty? choice4, WordCharProperty? choice5, ]) { if (value == choice1) { return true; } if (value == choice2) { return true; } if (choice3 != null && value == choice3) { return true; } if (choice4 != null && value == choice4) { return true; } if (choice5 != null && value == choice5) { return true; } return false; } static bool _isAHLetter(WordCharProperty? property) { return _oneOf(property, WordCharProperty.ALetter, WordCharProperty.HebrewLetter); } }
engine/lib/web_ui/lib/src/engine/text/word_breaker.dart/0
{'file_path': 'engine/lib/web_ui/lib/src/engine/text/word_breaker.dart', 'repo_id': 'engine', 'token_count': 3794}
// 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. import 'package:ui/src/engine/dom.dart'; import 'package:ui/src/engine/util.dart' show setElementStyle; import '../hot_restart_cache_handler.dart' show registerElementForCleanup; import 'embedding_strategy.dart'; /// An [EmbeddingStrategy] that takes over the whole web page. /// /// This strategy takes over the <body> element, modifies the viewport meta-tag, /// and ensures that the root Flutter view covers the whole screen. class FullPageEmbeddingStrategy implements EmbeddingStrategy { @override DomEventTarget get globalEventTarget => domWindow; @override void initialize({ Map<String, String>? hostElementAttributes, }) { // ignore:avoid_function_literals_in_foreach_calls hostElementAttributes?.entries.forEach((MapEntry<String, String> entry) { _setHostAttribute(entry.key, entry.value); }); _setHostAttribute('flt-embedding', 'full-page'); _applyViewportMeta(); _setHostStyles(); } @override void attachViewRoot(DomElement rootElement) { /// Tweaks style so the rootElement works well with the hostElement. rootElement.style ..position = 'absolute' ..top = '0' ..right = '0' ..bottom = '0' ..left = '0'; domDocument.body!.append(rootElement); registerElementForCleanup(rootElement); } @override void attachResourcesHost(DomElement resourceHost, {DomElement? nextTo}) { domDocument.body!.insertBefore(resourceHost, nextTo); registerElementForCleanup(resourceHost); } void _setHostAttribute(String name, String value) { domDocument.body!.setAttribute(name, value); } // Sets the global styles for a flutter app. void _setHostStyles() { final DomHTMLBodyElement bodyElement = domDocument.body!; setElementStyle(bodyElement, 'position', 'fixed'); setElementStyle(bodyElement, 'top', '0'); setElementStyle(bodyElement, 'right', '0'); setElementStyle(bodyElement, 'bottom', '0'); setElementStyle(bodyElement, 'left', '0'); setElementStyle(bodyElement, 'overflow', 'hidden'); setElementStyle(bodyElement, 'padding', '0'); setElementStyle(bodyElement, 'margin', '0'); setElementStyle(bodyElement, 'user-select', 'none'); setElementStyle(bodyElement, '-webkit-user-select', 'none'); // This is required to prevent the browser from doing any native touch // handling. If this is not done, the browser doesn't report 'pointermove' // events properly. setElementStyle(bodyElement, 'touch-action', 'none'); } // Sets a meta viewport tag appropriate for Flutter Web in full screen. void _applyViewportMeta() { for (final DomElement viewportMeta in domDocument.head!.querySelectorAll('meta[name="viewport"]')) { assert(() { // Filter out the meta tag that the engine placed on the page. This is // to avoid UI flicker during hot restart. Hot restart will clean up the // old meta tag synchronously with the first post-restart frame. if (!viewportMeta.hasAttribute('flt-viewport')) { print( 'WARNING: found an existing <meta name="viewport"> tag. Flutter ' 'Web uses its own viewport configuration for better compatibility ' 'with Flutter. This tag will be replaced.', ); } return true; }()); viewportMeta.remove(); } // The meta viewport is always removed by the for method above, so we don't // need to do anything else here, other than create it again. final DomHTMLMetaElement viewportMeta = createDomHTMLMetaElement() ..setAttribute('flt-viewport', '') ..name = 'viewport' ..content = 'width=device-width, initial-scale=1.0, ' 'maximum-scale=1.0, user-scalable=no'; domDocument.head!.append(viewportMeta); registerElementForCleanup(viewportMeta); } }
engine/lib/web_ui/lib/src/engine/view_embedder/embedding_strategy/full_page_embedding_strategy.dart/0
{'file_path': 'engine/lib/web_ui/lib/src/engine/view_embedder/embedding_strategy/full_page_embedding_strategy.dart', 'repo_id': 'engine', 'token_count': 1361}
// 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. import 'package:ui/src/engine.dart'; /// A function which takes a unique `id` and some `params` and creates an HTML /// element. typedef ParameterizedPlatformViewFactory = Object Function( int viewId, { Object? params, }); /// A function which takes a unique `id` and creates an HTML element. typedef PlatformViewFactory = Object Function(int viewId); /// The platform view registry for this app. final PlatformViewRegistry platformViewRegistry = PlatformViewRegistry(); /// A registry for factories that create platform views. class PlatformViewRegistry { /// The view type of the built-in factory that creates visible platform view /// DOM elements. /// /// There's no need to register this view type with [PlatformViewRegistry] /// because it is registered by default. static const String defaultVisibleViewType = '_default_document_create_element_visible'; /// The view type of the built-in factory that creates invisible platform view /// DOM elements. /// /// There's no need to register this view type with [PlatformViewRegistry] /// because it is registered by default. static const String defaultInvisibleViewType = '_default_document_create_element_invisible'; /// Register [viewType] as being created by the given [viewFactory]. /// /// [viewFactory] can be any function that takes an integer and optional /// `params` and returns an `HTMLElement` DOM object. bool registerViewFactory( String viewType, Function viewFactory, { bool isVisible = true, }) { return PlatformViewManager.instance.registerFactory( viewType, viewFactory, isVisible: isVisible, ); } /// Returns the view previously created for [viewId]. /// /// Throws if no view has been created for [viewId]. Object getViewById(int viewId) { return PlatformViewManager.instance.getViewById(viewId); } }
engine/lib/web_ui/lib/ui_web/src/ui_web/platform_view_registry.dart/0
{'file_path': 'engine/lib/web_ui/lib/ui_web/src/ui_web/platform_view_registry.dart', 'repo_id': 'engine', 'token_count': 562}
// 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. import 'package:test/bootstrap/browser.dart'; import 'package:test/test.dart'; import 'package:ui/src/engine.dart'; import 'package:ui/ui.dart' as ui; import 'common.dart'; void main() { internalBootstrapBrowserTest(() => testMain); } const ui.Rect region = ui.Rect.fromLTRB(0, 0, 500, 500); void testMain() { group('BackdropFilter', () { setUpCanvasKitTest(withImplicitView: true); EngineFlutterDisplay.instance.debugOverrideDevicePixelRatio(1.0); test('blur renders to the edges', () async { // Make a checkerboard picture so we can see the blur. final CkPictureRecorder recorder = CkPictureRecorder(); final CkCanvas canvas = recorder.beginRecording(region); canvas.drawColor(const ui.Color(0xffffffff), ui.BlendMode.srcOver); final double sideLength = region.width / 20; final int rows = (region.height / sideLength).ceil(); for (int row = 0; row < rows; row++) { for (int column = 0; column < 10; column++) { final ui.Rect rect = ui.Rect.fromLTWH( row.isEven ? (column * 2) * sideLength : (column * 2 + 1) * sideLength, row * sideLength, sideLength, sideLength, ); canvas.drawRect(rect, CkPaint()..color = const ui.Color(0xffff0000)); } } final CkPicture checkerboard = recorder.endRecording(); final LayerSceneBuilder builder = LayerSceneBuilder(); builder.pushOffset(0, 0); builder.addPicture(ui.Offset.zero, checkerboard); builder.pushBackdropFilter(ui.ImageFilter.blur(sigmaX: 10, sigmaY: 10)); await matchSceneGolden( 'canvaskit_backdropfilter_blur_edges.png', builder.build(), region: region); }); test('ImageFilter with ColorFilter as child', () async { final LayerSceneBuilder builder = LayerSceneBuilder(); const ui.Rect region = ui.Rect.fromLTRB(0, 0, 500, 250); builder.pushOffset(0, 0); final CkPictureRecorder recorder = CkPictureRecorder(); final CkCanvas canvas = recorder.beginRecording(region); final ui.ColorFilter colorFilter = ui.ColorFilter.mode( const ui.Color(0XFF00FF00).withOpacity(0.55), ui.BlendMode.darken); // using a colorFilter as an imageFilter for backDrop filter builder.pushBackdropFilter(colorFilter); canvas.drawCircle( const ui.Offset(75, 125), 50, CkPaint()..color = const ui.Color.fromARGB(255, 255, 0, 0), ); final CkPicture redCircle1 = recorder.endRecording(); builder.addPicture(ui.Offset.zero, redCircle1); await matchSceneGolden( 'canvaskit_red_circle_green_backdrop_colorFilter.png', builder.build(), region: region); }); // TODO(hterkelsen): https://github.com/flutter/flutter/issues/71520 }, skip: isSafari || isFirefox); }
engine/lib/web_ui/test/canvaskit/backdrop_filter_golden_test.dart/0
{'file_path': 'engine/lib/web_ui/test/canvaskit/backdrop_filter_golden_test.dart', 'repo_id': 'engine', 'token_count': 1237}
// 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. @TestOn('chrome || safari || firefox') library; import 'dart:async'; import 'package:test/bootstrap/browser.dart'; import 'package:test/test.dart'; import '../engine/semantics/semantics_test.dart'; import 'common.dart'; void main() { internalBootstrapBrowserTest(() => testMain); } // Run the same semantics tests in CanvasKit mode because as of today we do not // yet share platform view logic with the HTML renderer, which affects // semantics. Future<void> testMain() async { group('CanvasKit semantics', () { setUpCanvasKitTest(withImplicitView: true); runSemanticsTests(); }); }
engine/lib/web_ui/test/canvaskit/semantics_test.dart/0
{'file_path': 'engine/lib/web_ui/test/canvaskit/semantics_test.dart', 'repo_id': 'engine', 'token_count': 236}
// 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. import 'package:test/bootstrap/browser.dart'; import 'package:test/test.dart'; import 'package:ui/src/engine.dart'; const String _kDefaultCssFont = '14px monospace'; void main() { internalBootstrapBrowserTest(() => testMain); } void testMain() { late DomHTMLStyleElement styleElement; setUp(() { styleElement = createDomHTMLStyleElement(null); applyGlobalCssRulesToSheet( styleElement, defaultCssFont: _kDefaultCssFont, ); }); tearDown(() { styleElement.remove(); }); test('createDomHTMLStyleElement sets a nonce value, when passed', () { expect(styleElement.nonce, isEmpty); final DomHTMLStyleElement style = createDomHTMLStyleElement('a-nonce-value'); expect(style.nonce, 'a-nonce-value'); }); test('(Self-test) hasCssRule can extract rules', () { final bool hasRule = hasCssRule(styleElement, selector: '.flt-text-editing::placeholder', declaration: 'opacity: 0'); final bool hasFakeRule = hasCssRule(styleElement, selector: 'input::selection', declaration: 'color: #fabada;'); expect(hasRule, isTrue); expect(hasFakeRule, isFalse); }); test('Attaches styling to remove password reveal icons on Edge', () { // Check that style.sheet! contains input::-ms-reveal rule final bool hidesRevealIcons = hasCssRule(styleElement, selector: 'input::-ms-reveal', declaration: 'display: none'); final bool codeRanInFakeyBrowser = hasCssRule(styleElement, selector: 'input.fallback-for-fakey-browser-in-ci', declaration: 'display: none'); if (codeRanInFakeyBrowser) { print('Please, fix https://github.com/flutter/flutter/issues/116302'); } expect(hidesRevealIcons || codeRanInFakeyBrowser, isTrue, reason: 'In Edge, stylesheet must contain "input::-ms-reveal" rule.'); }, skip: !isEdge); test('Does not attach the Edge-specific style tag on non-Edge browsers', () { // Check that style.sheet! contains input::-ms-reveal rule final bool hidesRevealIcons = hasCssRule(styleElement, selector: 'input::-ms-reveal', declaration: 'display: none'); expect(hidesRevealIcons, isFalse); }, skip: isEdge); test( 'Attaches styles to hide the autofill overlay for browsers that support it', () { final String vendorPrefix = (isSafari || isFirefox) ? '' : '-webkit-'; final bool autofillOverlay = hasCssRule(styleElement, selector: '.transparentTextEditing:${vendorPrefix}autofill', declaration: 'opacity: 0 !important'); final bool autofillOverlayHovered = hasCssRule(styleElement, selector: '.transparentTextEditing:${vendorPrefix}autofill:hover', declaration: 'opacity: 0 !important'); final bool autofillOverlayFocused = hasCssRule(styleElement, selector: '.transparentTextEditing:${vendorPrefix}autofill:focus', declaration: 'opacity: 0 !important'); final bool autofillOverlayActive = hasCssRule(styleElement, selector: '.transparentTextEditing:${vendorPrefix}autofill:active', declaration: 'opacity: 0 !important'); expect(autofillOverlay, isTrue); expect(autofillOverlayHovered, isTrue); expect(autofillOverlayFocused, isTrue); expect(autofillOverlayActive, isTrue); }, skip: !browserHasAutofillOverlay()); } /// Finds out whether a given CSS Rule ([selector] { [declaration]; }) exists in a [styleElement]. bool hasCssRule( DomHTMLStyleElement styleElement, { required String selector, required String declaration, }) { domDocument.body!.append(styleElement); assert(styleElement.sheet != null); // regexr.com/740ff final RegExp ruleLike = RegExp('[^{]*(?:$selector)[^{]*{[^}]*(?:$declaration)[^}]*}'); final DomCSSStyleSheet sheet = styleElement.sheet! as DomCSSStyleSheet; // Check that the cssText of any rule matches the ruleLike RegExp. final bool result = sheet.cssRules .map((DomCSSRule rule) => rule.cssText) .any((String rule) => ruleLike.hasMatch(rule)); styleElement.remove(); return result; }
engine/lib/web_ui/test/engine/global_styles_test.dart/0
{'file_path': 'engine/lib/web_ui/test/engine/global_styles_test.dart', 'repo_id': 'engine', 'token_count': 1480}
// 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. import 'dart:async'; import 'dart:typed_data'; import 'package:test/bootstrap/browser.dart'; import 'package:test/test.dart'; import 'package:ui/src/engine.dart'; import 'package:ui/ui.dart' as ui; void main() { internalBootstrapBrowserTest(() => testMain); } void testMain() { ensureFlutterViewEmbedderInitialized(); group('PlatformDispatcher', () { test('reports at least one display', () { expect(ui.PlatformDispatcher.instance.displays.length, greaterThan(0)); }); test('high contrast in accessibilityFeatures has the correct value', () { final MockHighContrastSupport mockHighContrast = MockHighContrastSupport(); HighContrastSupport.instance = mockHighContrast; final EnginePlatformDispatcher engineDispatcher = EnginePlatformDispatcher(); expect(engineDispatcher.accessibilityFeatures.highContrast, isTrue); mockHighContrast.isEnabled = false; mockHighContrast.invokeListeners(mockHighContrast.isEnabled); expect(engineDispatcher.accessibilityFeatures.highContrast, isFalse); engineDispatcher.dispose(); }); test('AppLifecycleState transitions through all states', () { final List<ui.AppLifecycleState> states = <ui.AppLifecycleState>[]; void listener(ui.AppLifecycleState state) { states.add(state); } final MockAppLifecycleState mockAppLifecycleState = MockAppLifecycleState(); expect(mockAppLifecycleState.appLifecycleState, ui.AppLifecycleState.resumed); mockAppLifecycleState.addListener(listener); expect(mockAppLifecycleState.activeCallCount, 1); expect( states, equals(<ui.AppLifecycleState>[ui.AppLifecycleState.resumed])); mockAppLifecycleState.inactive(); expect(mockAppLifecycleState.appLifecycleState, ui.AppLifecycleState.inactive); expect( states, equals(<ui.AppLifecycleState>[ ui.AppLifecycleState.resumed, ui.AppLifecycleState.inactive ])); // consecutive same states are skipped mockAppLifecycleState.inactive(); expect( states, equals(<ui.AppLifecycleState>[ ui.AppLifecycleState.resumed, ui.AppLifecycleState.inactive ])); mockAppLifecycleState.hidden(); expect( mockAppLifecycleState.appLifecycleState, ui.AppLifecycleState.hidden); expect( states, equals(<ui.AppLifecycleState>[ ui.AppLifecycleState.resumed, ui.AppLifecycleState.inactive, ui.AppLifecycleState.hidden ])); mockAppLifecycleState.resume(); expect(mockAppLifecycleState.appLifecycleState, ui.AppLifecycleState.resumed); expect( states, equals(<ui.AppLifecycleState>[ ui.AppLifecycleState.resumed, ui.AppLifecycleState.inactive, ui.AppLifecycleState.hidden, ui.AppLifecycleState.resumed ])); mockAppLifecycleState.detach(); expect(mockAppLifecycleState.appLifecycleState, ui.AppLifecycleState.detached); expect( states, equals(<ui.AppLifecycleState>[ ui.AppLifecycleState.resumed, ui.AppLifecycleState.inactive, ui.AppLifecycleState.hidden, ui.AppLifecycleState.resumed, ui.AppLifecycleState.detached ])); mockAppLifecycleState.removeListener(listener); expect(mockAppLifecycleState.deactivateCallCount, 1); // No more states should be recorded after the listener is removed. mockAppLifecycleState.resume(); expect( states, equals(<ui.AppLifecycleState>[ ui.AppLifecycleState.resumed, ui.AppLifecycleState.inactive, ui.AppLifecycleState.hidden, ui.AppLifecycleState.resumed, ui.AppLifecycleState.detached ])); }); test('responds to flutter/skia Skia.setResourceCacheMaxBytes', () async { const MethodCodec codec = JSONMethodCodec(); final Completer<ByteData?> completer = Completer<ByteData?>(); ui.PlatformDispatcher.instance.sendPlatformMessage( 'flutter/skia', codec.encodeMethodCall(const MethodCall( 'Skia.setResourceCacheMaxBytes', 512 * 1000 * 1000, )), completer.complete, ); final ByteData? response = await completer.future; expect(response, isNotNull); expect( codec.decodeEnvelope(response!), <bool>[true], ); }); test('responds to flutter/platform HapticFeedback.vibrate', () async { const MethodCodec codec = JSONMethodCodec(); final Completer<ByteData?> completer = Completer<ByteData?>(); ui.PlatformDispatcher.instance.sendPlatformMessage( 'flutter/platform', codec.encodeMethodCall(const MethodCall( 'HapticFeedback.vibrate', )), completer.complete, ); final ByteData? response = await completer.future; expect(response, isNotNull); expect( codec.decodeEnvelope(response!), true, ); }); test('responds to flutter/platform SystemChrome.setSystemUIOverlayStyle', () async { const MethodCodec codec = JSONMethodCodec(); final Completer<ByteData?> completer = Completer<ByteData?>(); ui.PlatformDispatcher.instance.sendPlatformMessage( 'flutter/platform', codec.encodeMethodCall(const MethodCall( 'SystemChrome.setSystemUIOverlayStyle', <String, dynamic>{}, )), completer.complete, ); final ByteData? response = await completer.future; expect(response, isNotNull); expect( codec.decodeEnvelope(response!), true, ); }); test('responds to flutter/contextmenu enable', () async { const MethodCodec codec = JSONMethodCodec(); final Completer<ByteData?> completer = Completer<ByteData?>(); ui.PlatformDispatcher.instance.sendPlatformMessage( 'flutter/contextmenu', codec.encodeMethodCall(const MethodCall( 'enableContextMenu', )), completer.complete, ); final ByteData? response = await completer.future; expect(response, isNotNull); expect( codec.decodeEnvelope(response!), true, ); }); test('responds to flutter/contextmenu disable', () async { const MethodCodec codec = JSONMethodCodec(); final Completer<ByteData?> completer = Completer<ByteData?>(); ui.PlatformDispatcher.instance.sendPlatformMessage( 'flutter/contextmenu', codec.encodeMethodCall(const MethodCall( 'disableContextMenu', )), completer.complete, ); final ByteData? response = await completer.future; expect(response, isNotNull); expect( codec.decodeEnvelope(response!), true, ); }); test('can find text scale factor', () async { const double deltaTolerance = 1e-5; final DomElement root = domDocument.documentElement!; final String oldFontSize = root.style.fontSize; addTearDown(() { root.style.fontSize = oldFontSize; }); root.style.fontSize = '16px'; expect(findBrowserTextScaleFactor(), 1.0); root.style.fontSize = '20px'; expect(findBrowserTextScaleFactor(), 1.25); root.style.fontSize = '24px'; expect(findBrowserTextScaleFactor(), 1.5); root.style.fontSize = '14.4px'; expect(findBrowserTextScaleFactor(), closeTo(0.9, deltaTolerance)); root.style.fontSize = '12.8px'; expect(findBrowserTextScaleFactor(), closeTo(0.8, deltaTolerance)); root.style.fontSize = ''; expect(findBrowserTextScaleFactor(), 1.0); }); test( "calls onTextScaleFactorChanged when the <html> element's font-size changes", () async { final DomElement root = domDocument.documentElement!; final String oldFontSize = root.style.fontSize; final ui.VoidCallback? oldCallback = ui.PlatformDispatcher.instance.onTextScaleFactorChanged; addTearDown(() { root.style.fontSize = oldFontSize; ui.PlatformDispatcher.instance.onTextScaleFactorChanged = oldCallback; }); root.style.fontSize = '16px'; bool isCalled = false; ui.PlatformDispatcher.instance.onTextScaleFactorChanged = () { isCalled = true; }; root.style.fontSize = '20px'; await Future<void>.delayed(Duration.zero); expect(root.style.fontSize, '20px'); expect(isCalled, isTrue); expect(ui.PlatformDispatcher.instance.textScaleFactor, findBrowserTextScaleFactor()); isCalled = false; root.style.fontSize = '16px'; await Future<void>.delayed(Duration.zero); expect(root.style.fontSize, '16px'); expect(isCalled, isTrue); expect(ui.PlatformDispatcher.instance.textScaleFactor, findBrowserTextScaleFactor()); }); test('disposes all its views', () { final EnginePlatformDispatcher dispatcher = EnginePlatformDispatcher(); final EngineFlutterView view1 = EngineFlutterView(dispatcher, createDomHTMLDivElement()); final EngineFlutterView view2 = EngineFlutterView(dispatcher, createDomHTMLDivElement()); final EngineFlutterView view3 = EngineFlutterView(dispatcher, createDomHTMLDivElement()); dispatcher.viewManager ..registerView(view1) ..registerView(view2) ..registerView(view3); expect(view1.isDisposed, isFalse); expect(view2.isDisposed, isFalse); expect(view3.isDisposed, isFalse); dispatcher.dispose(); expect(view1.isDisposed, isTrue); expect(view2.isDisposed, isTrue); expect(view3.isDisposed, isTrue); }); test('connects view disposal to metrics changed event', () { final EnginePlatformDispatcher dispatcher = EnginePlatformDispatcher(); final EngineFlutterView view1 = EngineFlutterView(dispatcher, createDomHTMLDivElement()); final EngineFlutterView view2 = EngineFlutterView(dispatcher, createDomHTMLDivElement()); dispatcher.viewManager ..registerView(view1) ..registerView(view2); expect(view1.isDisposed, isFalse); expect(view2.isDisposed, isFalse); bool onMetricsChangedCalled = false; dispatcher.onMetricsChanged = () { onMetricsChangedCalled = true; }; expect(onMetricsChangedCalled, isFalse); dispatcher.viewManager.disposeAndUnregisterView(view2.viewId); expect(onMetricsChangedCalled, isTrue, reason: 'onMetricsChanged should have been called.'); dispatcher.dispose(); }); test('disconnects view disposal event on dispose', () { final EnginePlatformDispatcher dispatcher = EnginePlatformDispatcher(); final EngineFlutterView view1 = EngineFlutterView(dispatcher, createDomHTMLDivElement()); dispatcher.viewManager.registerView(view1); expect(view1.isDisposed, isFalse); bool onMetricsChangedCalled = false; dispatcher.onMetricsChanged = () { onMetricsChangedCalled = true; }; dispatcher.dispose(); expect(onMetricsChangedCalled, isFalse); expect(view1.isDisposed, isTrue); }); }); } class MockHighContrastSupport implements HighContrastSupport { bool isEnabled = true; final List<HighContrastListener> _listeners = <HighContrastListener>[]; @override bool get isHighContrastEnabled => isEnabled; void invokeListeners(bool val) { for (final HighContrastListener listener in _listeners) { listener(val); } } @override void addListener(HighContrastListener listener) { _listeners.add(listener); } @override void removeListener(HighContrastListener listener) { _listeners.remove(listener); } } class MockAppLifecycleState extends AppLifecycleState { int activeCallCount = 0; int deactivateCallCount = 0; void detach() { onAppLifecycleStateChange(ui.AppLifecycleState.detached); } void resume() { onAppLifecycleStateChange(ui.AppLifecycleState.resumed); } void inactive() { onAppLifecycleStateChange(ui.AppLifecycleState.inactive); } void hidden() { onAppLifecycleStateChange(ui.AppLifecycleState.hidden); } @override void activate() { activeCallCount++; } @override void deactivate() { deactivateCallCount++; } }
engine/lib/web_ui/test/engine/platform_dispatcher/platform_dispatcher_test.dart/0
{'file_path': 'engine/lib/web_ui/test/engine/platform_dispatcher/platform_dispatcher_test.dart', 'repo_id': 'engine', 'token_count': 5231}
// 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. import 'dart:async'; import 'package:test/bootstrap/browser.dart'; import 'package:test/test.dart'; import 'package:ui/src/engine.dart'; import '../../common/test_initialization.dart'; import 'semantics_tester.dart'; EngineSemantics semantics() => EngineSemantics.instance; EngineSemanticsOwner owner() => EnginePlatformDispatcher.instance.implicitView!.semantics; void main() { internalBootstrapBrowserTest(() { return testMain; }); } Future<void> testMain() async { await bootstrapAndRunApp(withImplicitView: true); test('EngineSemanticsOwner auto-enables semantics on update', () async { expect(semantics().semanticsEnabled, isFalse); expect( EnginePlatformDispatcher .instance.accessibilityFeatures.accessibleNavigation, isFalse); final DomShadowRoot renderingHost = EnginePlatformDispatcher.instance.implicitView!.dom.renderingHost; final DomElement placeholder = renderingHost.querySelector('flt-semantics-placeholder')!; expect(placeholder.isConnected, isTrue); // Sending a semantics update should auto-enable engine semantics. final SemanticsTester tester = SemanticsTester(owner()); tester.updateNode(id: 0); tester.apply(); expect(semantics().semanticsEnabled, isTrue); expect( EnginePlatformDispatcher.instance.accessibilityFeatures.accessibleNavigation, isTrue, ); // The placeholder should be removed expect(placeholder.isConnected, isFalse); }); }
engine/lib/web_ui/test/engine/semantics/semantics_auto_enable_test.dart/0
{'file_path': 'engine/lib/web_ui/test/engine/semantics/semantics_auto_enable_test.dart', 'repo_id': 'engine', 'token_count': 538}
// 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. import 'package:test/bootstrap/browser.dart'; import 'package:test/test.dart'; import 'package:ui/src/engine.dart'; import '../common/test_initialization.dart'; import '../ui/utils.dart'; void main() { internalBootstrapBrowserTest(() => testMain); } Future<void> testMain() async { setUpUnitTests( setUpTestViewDimensions: false, ); test('bootstrapper selects correct builds', () { if (browserEngine == BrowserEngine.blink) { expect(isWasm, isTrue); expect(isSkwasm, isTrue); } else { expect(isWasm, isFalse); expect(isCanvasKit, isTrue); } }); }
engine/lib/web_ui/test/fallbacks/fallbacks_test.dart/0
{'file_path': 'engine/lib/web_ui/test/fallbacks/fallbacks_test.dart', 'repo_id': 'engine', 'token_count': 273}
// 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. import 'package:test/bootstrap/browser.dart'; import 'package:test/test.dart'; import 'package:ui/src/engine.dart'; import 'package:ui/ui.dart'; void main() { internalBootstrapBrowserTest(() => testMain); } Future<void> testMain() async { group('$adjustRectForDom', () { test('does not change rect when not necessary', () async { const Rect rect = Rect.fromLTWH(10, 20, 140, 160); expect( adjustRectForDom(rect, SurfacePaintData()..style=PaintingStyle.fill), rect, ); expect( adjustRectForDom(rect, SurfacePaintData()..style=PaintingStyle.stroke..strokeWidth=0), rect, ); }); test('takes stroke width into consideration', () async { const Rect rect = Rect.fromLTWH(10, 20, 140, 160); expect( adjustRectForDom(rect, SurfacePaintData()..style=PaintingStyle.stroke..strokeWidth=1), const Rect.fromLTWH(9.5, 19.5, 139, 159), ); expect( adjustRectForDom(rect, SurfacePaintData()..style=PaintingStyle.stroke..strokeWidth=10), const Rect.fromLTWH(5, 15, 130, 150), ); expect( adjustRectForDom(rect, SurfacePaintData()..style=PaintingStyle.stroke..strokeWidth=15), const Rect.fromLTWH(2.5, 12.5, 125, 145), ); }); test('flips rect when necessary', () { Rect rect = const Rect.fromLTWH(100, 200, -40, -60); expect( adjustRectForDom(rect, SurfacePaintData()..style=PaintingStyle.fill), const Rect.fromLTWH(60, 140, 40, 60), ); rect = const Rect.fromLTWH(100, 200, 40, -60); expect( adjustRectForDom(rect, SurfacePaintData()..style=PaintingStyle.fill), const Rect.fromLTWH(100, 140, 40, 60), ); rect = const Rect.fromLTWH(100, 200, -40, 60); expect( adjustRectForDom(rect, SurfacePaintData()..style=PaintingStyle.fill), const Rect.fromLTWH(60, 200, 40, 60), ); }); test('handles stroke width greater than width or height', () { const Rect rect = Rect.fromLTWH(100, 200, 20, 70); expect( adjustRectForDom(rect, SurfacePaintData()..style=PaintingStyle.stroke..strokeWidth=50), const Rect.fromLTWH(75, 175, 0, 20), ); expect( adjustRectForDom(rect, SurfacePaintData()..style=PaintingStyle.stroke..strokeWidth=80), const Rect.fromLTWH(60, 160, 0, 0), ); }); }); }
engine/lib/web_ui/test/html/dom_canvas_test.dart/0
{'file_path': 'engine/lib/web_ui/test/html/dom_canvas_test.dart', 'repo_id': 'engine', 'token_count': 1057}
// 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. import 'dart:async'; import 'package:ui/src/engine.dart'; import 'package:ui/ui.dart'; import 'package:web_engine_tester/golden_tester.dart'; typedef CanvasTest = FutureOr<void> Function(EngineCanvas canvas); const LineBreakType prohibited = LineBreakType.prohibited; const LineBreakType opportunity = LineBreakType.opportunity; const LineBreakType mandatory = LineBreakType.mandatory; const LineBreakType endOfText = LineBreakType.endOfText; const TextDirection ltr = TextDirection.ltr; const TextDirection rtl = TextDirection.rtl; const FragmentFlow ffLtr = FragmentFlow.ltr; const FragmentFlow ffRtl = FragmentFlow.rtl; const FragmentFlow ffPrevious = FragmentFlow.previous; const FragmentFlow ffSandwich = FragmentFlow.sandwich; const String rtlWord1 = 'واحدة'; const String rtlWord2 = 'ثنتان'; const Color white = Color(0xFFFFFFFF); const Color black = Color(0xFF000000); const Color red = Color(0xFFFF0000); const Color lightGreen = Color(0xFFDCEDC8); const Color green = Color(0xFF00FF00); const Color lightBlue = Color(0xFFB3E5FC); const Color blue = Color(0xFF0000FF); const Color yellow = Color(0xFFFFEB3B); const Color lightPurple = Color(0xFFE1BEE7); final EngineParagraphStyle ahemStyle = EngineParagraphStyle( fontFamily: 'Ahem', fontSize: 10, ); ParagraphConstraints constrain(double width) { return ParagraphConstraints(width: width); } CanvasParagraph plain( EngineParagraphStyle style, String text, { EngineTextStyle? textStyle, }) { final CanvasParagraphBuilder builder = CanvasParagraphBuilder(style); if (textStyle != null) { builder.pushStyle(textStyle); } builder.addText(text); return builder.build(); } CanvasParagraph rich( EngineParagraphStyle style, void Function(CanvasParagraphBuilder) callback, ) { final CanvasParagraphBuilder builder = CanvasParagraphBuilder(style); callback(builder); return builder.build(); } Future<void> takeScreenshot( EngineCanvas canvas, Rect region, String fileName, ) async { final DomElement sceneElement = createDomElement('flt-scene'); if (isIosSafari) { // Shrink to fit on the iPhone screen. sceneElement.style.position = 'absolute'; sceneElement.style.transformOrigin = '0 0 0'; sceneElement.style.transform = 'scale(0.3)'; } try { sceneElement.append(canvas.rootElement); domDocument.body!.append(sceneElement); await matchGoldenFile('$fileName.png', region: region); } finally { // The page is reused across tests, so remove the element after taking the // screenshot. sceneElement.remove(); } } /// Fills the single placeholder in the given [paragraph] with a red rectangle. /// /// The placeholder is filled relative to [offset]. /// /// Throws if the paragraph contains more than one placeholder. void fillPlaceholder( EngineCanvas canvas, Offset offset, CanvasParagraph paragraph, ) { final TextBox placeholderBox = paragraph.getBoxesForPlaceholders().single; final SurfacePaint paint = SurfacePaint()..color = red; canvas.drawRect(placeholderBox.toRect().shift(offset), paint.paintData); } /// Fill the given [boxes] with rectangles of the given [color]. /// /// All rectangles are filled relative to [offset]. void fillBoxes(EngineCanvas canvas, Offset offset, List<TextBox> boxes, Color color) { for (final TextBox box in boxes) { final Rect rect = box.toRect().shift(offset); canvas.drawRect(rect, SurfacePaintData()..color = color.value); } } String getSpanText(CanvasParagraph paragraph, ParagraphSpan span) { return paragraph.plainText.substring(span.start, span.end); }
engine/lib/web_ui/test/html/paragraph/helper.dart/0
{'file_path': 'engine/lib/web_ui/test/html/paragraph/helper.dart', 'repo_id': 'engine', 'token_count': 1181}
// 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. import 'dart:async'; import 'package:ui/src/engine.dart'; import 'package:ui/ui.dart' as ui; import 'package:web_engine_tester/golden_tester.dart'; /// Commit a recording canvas to a bitmap, and compare with the expected. /// /// [region] specifies the area of the canvas that will be included in the /// golden. /// /// If [canvasRect] is omitted, it defaults to the value of [region]. Future<void> canvasScreenshot( RecordingCanvas rc, String fileName, { ui.Rect region = const ui.Rect.fromLTWH(0, 0, 500, 500), ui.Rect? canvasRect, bool setupPerspective = false, }) async { canvasRect ??= region; final EngineCanvas engineCanvas = BitmapCanvas(canvasRect, RenderStrategy()); rc.endRecording(); rc.apply(engineCanvas, region); // Wrap in <flt-scene> so that our CSS selectors kick in. final DomElement sceneElement = createDomElement('flt-scene'); if (isIosSafari) { // Shrink to fit on the iPhone screen. sceneElement.style.position = 'absolute'; sceneElement.style.transformOrigin = '0 0 0'; sceneElement.style.transform = 'scale(0.3)'; } try { if (setupPerspective) { // iFrame disables perspective, set it explicitly for test. engineCanvas.rootElement.style.perspective = '400px'; for (final DomElement element in engineCanvas.rootElement.querySelectorAll('div')) { element.style.perspective = '400px'; } } sceneElement.append(engineCanvas.rootElement); domDocument.body!.append(sceneElement); await matchGoldenFile('$fileName.png', region: region); } finally { // The page is reused across tests, so remove the element after taking the // screenshot. sceneElement.remove(); } } Future<void> sceneScreenshot(SurfaceSceneBuilder sceneBuilder, String fileName, {ui.Rect region = const ui.Rect.fromLTWH(0, 0, 600, 800)}) async { DomElement? sceneElement; try { sceneElement = sceneBuilder .build() .webOnlyRootElement; domDocument.body!.append(sceneElement!); await matchGoldenFile('$fileName.png', region: region); } finally { // The page is reused across tests, so remove the element after taking the // screenshot. sceneElement?.remove(); } }
engine/lib/web_ui/test/html/screenshot.dart/0
{'file_path': 'engine/lib/web_ui/test/html/screenshot.dart', 'repo_id': 'engine', 'token_count': 811}
// 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. library fuchsia_builtin; import 'dart:async'; import 'dart:io'; import 'dart:_internal' show VMLibraryHooks; // Corelib 'print' implementation. void _print(arg) { _Logger._printString(arg.toString()); try { // If stdout is connected, print to it as well. stdout.writeln(arg); } on FileSystemException catch (_) { // Some Fuchsia applications will not have stdout connected. } } class _Logger { @pragma('vm:external-name', 'Logger_PrintString') external static void _printString(String s); } @pragma('vm:entry-point') late String _rawScript; Uri _scriptUri() { if (_rawScript.startsWith('http:') || _rawScript.startsWith('https:') || _rawScript.startsWith('file:')) { return Uri.parse(_rawScript); } else { return Uri.base.resolveUri(Uri.file(_rawScript)); } } @pragma('vm:external-name', 'ScheduleMicrotask') external void _scheduleMicrotask(void callback()); @pragma('vm:entry-point') _getScheduleMicrotaskClosure() => _scheduleMicrotask; @pragma('vm:entry-point') _setupHooks() { VMLibraryHooks.platformScript = _scriptUri; } @pragma('vm:entry-point') _getPrintClosure() => _print; typedef EchoStringCallback = String? Function(String? str); late EchoStringCallback? receiveEchoStringCallback; @pragma('vm:entry-point') String? _receiveEchoString(String? str) { return receiveEchoStringCallback?.call(str); }
engine/shell/platform/fuchsia/dart_runner/embedder/builtin.dart/0
{'file_path': 'engine/shell/platform/fuchsia/dart_runner/embedder/builtin.dart', 'repo_id': 'engine', 'token_count': 543}
// 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. // On Fuchsia, in lieu of the ELF dynamic symbol table consumed through dladdr, // the Dart VM profiler consumes symbols produced by this tool, which have the // format // // struct { // uint32_t num_entries; // struct { // uint32_t offset; // uint32_t size; // uint32_t string_table_offset; // } entries[num_entries]; // const char* string_table; // } // // Entries are sorted by offset. String table entries are NUL-terminated. // // See also //third_party/dart/runtime/vm/native_symbol_fuchsia.cc import "dart:convert"; import "dart:io"; import "dart:typed_data"; import "package:args/args.dart"; import "package:path/path.dart" as path; Future<void> main(List<String> args) async { final parser = new ArgParser(); parser.addOption("nm", help: "Path to `nm` tool"); parser.addOption("binary", help: "Path to the ELF file to extract symbols from"); parser.addOption("output", help: "Path to output symbol table"); final usage = """ Usage: dart_profiler_symbols.dart [options] Options: ${parser.usage}; """; String? buildIdDir; String? buildIdScript; String? nm; String? binary; String? output; try { final options = parser.parse(args); nm = options["nm"]; if (nm == null) { throw "Must specify --nm"; } if (!FileSystemEntity.isFileSync(nm)) { throw "Cannot find $nm"; } binary = options["binary"]; if (binary == null) { throw "Must specify --binary"; } if (!FileSystemEntity.isFileSync(binary)) { throw "Cannot find $binary"; } output = options["output"]; if (output == null) { throw "Must specify --output"; } } catch (e) { print("ERROR: $e\n"); print(usage); exitCode = 1; return; } await run(buildIdDir, buildIdScript, nm, binary, output); } class Symbol { int offset; int size; String name; Symbol({required this.offset, required this.size, required this.name}); } Future<void> run(String? buildIdDir, String? buildIdScript, String nm, String binary, String output) async { final unstrippedFile = binary; final args = ["--demangle", "--numeric-sort", "--print-size", unstrippedFile]; final result = await Process.run(nm, args); if (result.exitCode != 0) { print(result.stdout); print(result.stderr); throw "Command failed: $nm $args"; } var symbols = []; var regex = new RegExp("([0-9A-Za-z]+) ([0-9A-Za-z]+) (t|T|w|W) (.*)"); for (final line in result.stdout.split("\n")) { var match = regex.firstMatch(line); if (match == null) { continue; // Ignore non-text symbols. } // Note that capture groups start at 1. final symbol = new Symbol(offset: int.parse(match[1]!, radix: 16), size: int.parse(match[2]!, radix: 16), name: match[4]!.split("(")[0]); if (symbol.name.startsWith("\$")) { continue; // Ignore compiler/assembler temps. } symbols.add(symbol); } if (symbols.isEmpty) { throw "$unstrippedFile has no symbols"; } var nameTable = new BytesBuilder(); var binarySearchTable = new Uint32List(symbols.length * 3 + 1); var binarySearchTableIndex = 0; binarySearchTable[binarySearchTableIndex++] = symbols.length; // Symbols are sorted by offset because of --numeric-sort. for (var symbol in symbols) { var nameOffset = nameTable.length; nameTable.add(utf8.encode(symbol.name)); nameTable.addByte(0); binarySearchTable[binarySearchTableIndex++] = symbol.offset; binarySearchTable[binarySearchTableIndex++] = symbol.size; binarySearchTable[binarySearchTableIndex++] = nameOffset; } var file = new File(output); await file.parent.create(recursive: true); var sink = file.openWrite(); sink.add(binarySearchTable.buffer.asUint8List()); sink.add(nameTable.takeBytes()); await sink.close(); }
engine/shell/platform/fuchsia/runtime/dart/profiler_symbols/dart_profiler_symbols.dart/0
{'file_path': 'engine/shell/platform/fuchsia/runtime/dart/profiler_symbols/dart_profiler_symbols.dart', 'repo_id': 'engine', 'token_count': 1497}
// 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. // This is a minimal dependency heart beat test for the Dart VM Service. import 'dart:async'; import 'dart:convert'; import 'dart:io'; import 'launcher.dart'; import 'service_client.dart'; class Expect { static void equals(dynamic actual, dynamic expected) { if (actual != expected) { throw 'Expected $actual == $expected'; } } static void contains(String needle, String haystack) { if (!haystack.contains(needle)) { throw 'Expected $haystack to contain $needle'; } } static void isTrue(bool tf) { if (tf != true) { throw 'Expected $tf to be true'; } } static void isFalse(bool tf) { if (tf != false) { throw 'Expected $tf to be false'; } } static void notExecuted() { throw 'Should not have hit'; } static void isNotNull(dynamic a) { if (a == null) { throw 'Expected $a to not be null'; } } } Future<String> readResponse(HttpClientResponse response) { final Completer<String> completer = Completer<String>(); final StringBuffer contents = StringBuffer(); response.transform(utf8.decoder).listen((String data) { contents.write(data); }, onDone: () => completer.complete(contents.toString())); return completer.future; } // Test accessing the service protocol over http. Future<Null> testHttpProtocolRequest(Uri uri) async { uri = uri.replace(path: 'getVM'); final HttpClient client = HttpClient(); final HttpClientRequest request = await client.getUrl(uri); final HttpClientResponse response = await request.close(); Expect.equals(response.statusCode, 200); final Map<String, dynamic> responseAsMap = json.decode(await readResponse(response)) as Map<String, dynamic>; Expect.equals(responseAsMap['jsonrpc'], '2.0'); client.close(); } // Test accessing the service protocol over ws. Future<Null> testWebSocketProtocolRequest(Uri uri) async { uri = uri.replace(scheme: 'ws', path: 'ws'); final WebSocket webSocketClient = await WebSocket.connect(uri.toString()); final ServiceClient serviceClient = ServiceClient(webSocketClient); final Map<String, dynamic> response = await serviceClient.invokeRPC('getVM'); Expect.equals(response['type'], 'VM'); try { await serviceClient.invokeRPC('BART_SIMPSON'); Expect.notExecuted(); } catch (e) { // Method not found. Expect.equals((e as Map<String, dynamic>)['code'], -32601); } } // Test accessing an Observatory UI asset. Future<Null> testHttpAssetRequest(Uri uri) async { uri = uri.replace(path: 'third_party/trace_viewer_full.html'); final HttpClient client = HttpClient(); final HttpClientRequest request = await client.getUrl(uri); final HttpClientResponse response = await request.close(); Expect.equals(response.statusCode, 200); await response.drain(); client.close(); } Future<Null> testStartPaused(Uri uri) async { uri = uri.replace(scheme: 'ws', path: 'ws'); final WebSocket webSocketClient = await WebSocket.connect(uri.toString()); final Completer<dynamic> isolateStartedId = Completer<dynamic>(); final Completer<dynamic> isolatePausedId = Completer<dynamic>(); final Completer<dynamic> isolateResumeId = Completer<dynamic>(); final ServiceClient serviceClient = ServiceClient(webSocketClient, isolateStartedId: isolateStartedId, isolatePausedId: isolatePausedId, isolateResumeId: isolateResumeId); await serviceClient .invokeRPC('streamListen', <String, String>{'streamId': 'Isolate'}); await serviceClient .invokeRPC('streamListen', <String, String>{'streamId': 'Debug'}); final Map<String, dynamic> response = await serviceClient.invokeRPC('getVM'); Expect.equals(response['type'], 'VM'); String isolateId; final List<dynamic> isolates = response['isolates'] as List<dynamic>; if (isolates.isNotEmpty) { isolateId = (isolates[0] as Map<String, String>)['id']!; } else { // Wait until isolate starts. isolateId = await isolateStartedId.future as String; } // Grab the isolate. Map<String, dynamic> isolate = await serviceClient.invokeRPC('getIsolate', <String, String>{ 'isolateId': isolateId, }); Expect.equals(isolate['type'], 'Isolate'); Expect.isNotNull(isolate['pauseEvent']); // If it is not runnable, wait until it becomes runnable. if (isolate['pauseEvent']['kind'] == 'None') { await isolatePausedId.future; isolate = await serviceClient.invokeRPC('getIsolate', <String, String>{ 'isolateId': isolateId, }); } // Verify that it is paused at start. Expect.equals(isolate['pauseEvent']['kind'], 'PauseStart'); // Resume the isolate. await serviceClient.invokeRPC('resume', <String, String>{ 'isolateId': isolateId, }); // Wait until the isolate has resumed. await isolateResumeId.future; final Map<String, dynamic> resumedResponse = await serviceClient .invokeRPC('getIsolate', <String, String>{'isolateId': isolateId}); Expect.equals(resumedResponse['type'], 'Isolate'); Expect.isNotNull(resumedResponse['pauseEvent']); Expect.equals(resumedResponse['pauseEvent']['kind'], 'Resume'); } typedef TestFunction = Future<Null> Function(Uri uri); final List<TestFunction> basicTests = <TestFunction>[ testHttpProtocolRequest, testWebSocketProtocolRequest, testHttpAssetRequest ]; final List<TestFunction> startPausedTests = <TestFunction>[ // TODO(engine): Investigate difference in lifecycle events. // testStartPaused, ]; Future<bool> runTests(ShellLauncher launcher, List<TestFunction> tests) async { final ShellProcess? process = await launcher.launch(); if (process == null) { return false; } final Uri uri = await process.waitForVMService(); try { for (int i = 0; i < tests.length; i++) { print('Executing test ${i + 1}/${tests.length}'); await tests[i](uri); } } catch (e, st) { print('Dart VM Service test failure: $e\n$st'); exitCode = -1; } await process.kill(); return exitCode == 0; } Future<Null> main(List<String> args) async { if (args.length < 2) { print('Usage: dart ${Platform.script} ' '<sky_shell_executable> <main_dart> ...'); return; } final String shellExecutablePath = args[0]; final String mainDartPath = args[1]; final List<String> extraArgs = args.length <= 2 ? <String>[] : args.sublist(2); final ShellLauncher launcher = ShellLauncher(shellExecutablePath, mainDartPath, false, extraArgs); final ShellLauncher startPausedlauncher = ShellLauncher(shellExecutablePath, mainDartPath, true, extraArgs); await runTests(launcher, basicTests); await runTests(startPausedlauncher, startPausedTests); }
engine/shell/testing/observatory/test.dart/0
{'file_path': 'engine/shell/testing/observatory/test.dart', 'repo_id': 'engine', 'token_count': 2308}
// 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. import 'dart:ui'; import 'package:litetest/litetest.dart'; class NotAColor extends Color { const NotAColor(super.value); } void main() { test('color accessors should work', () { const Color foo = Color(0x12345678); expect(foo.alpha, equals(0x12)); expect(foo.red, equals(0x34)); expect(foo.green, equals(0x56)); expect(foo.blue, equals(0x78)); }); test('paint set to black', () { const Color c = Color(0x00000000); final Paint p = Paint(); p.color = c; expect(c.toString(), equals('Color(0x00000000)')); }); test('color created with out of bounds value', () { const Color c = Color(0x100 << 24); final Paint p = Paint(); p.color = c; }); test('color created with wildly out of bounds value', () { const Color c = Color(1 << 1000000); final Paint p = Paint(); p.color = c; }); test('two colors are only == if they have the same runtime type', () { expect(const Color(0x12345678), equals(const Color(0x12345678))); expect(const Color(0x12345678), equals(Color(0x12345678))); // ignore: prefer_const_constructors expect(const Color(0x12345678), notEquals(const Color(0x87654321))); expect(const Color(0x12345678), notEquals(const NotAColor(0x12345678))); expect(const NotAColor(0x12345678), notEquals(const Color(0x12345678))); expect(const NotAColor(0x12345678), equals(const NotAColor(0x12345678))); }); test('Color.lerp', () { expect( Color.lerp(const Color(0x00000000), const Color(0xFFFFFFFF), 0.0), const Color(0x00000000), ); expect( Color.lerp(const Color(0x00000000), const Color(0xFFFFFFFF), 0.5), const Color(0x7F7F7F7F), ); expect( Color.lerp(const Color(0x00000000), const Color(0xFFFFFFFF), 1.0), const Color(0xFFFFFFFF), ); expect( Color.lerp(const Color(0x00000000), const Color(0xFFFFFFFF), -0.1), const Color(0x00000000), ); expect( Color.lerp(const Color(0x00000000), const Color(0xFFFFFFFF), 1.1), const Color(0xFFFFFFFF), ); // Prevent regression: https://github.com/flutter/flutter/issues/67423 expect( Color.lerp(const Color(0xFFFFFFFF), const Color(0xFFFFFFFF), 0.04), const Color(0xFFFFFFFF), ); }); test('Color.alphaBlend', () { expect( Color.alphaBlend(const Color(0x00000000), const Color(0x00000000)), const Color(0x00000000), ); expect( Color.alphaBlend(const Color(0x00000000), const Color(0xFFFFFFFF)), const Color(0xFFFFFFFF), ); expect( Color.alphaBlend(const Color(0xFFFFFFFF), const Color(0x00000000)), const Color(0xFFFFFFFF), ); expect( Color.alphaBlend(const Color(0xFFFFFFFF), const Color(0xFFFFFFFF)), const Color(0xFFFFFFFF), ); expect( Color.alphaBlend(const Color(0x80FFFFFF), const Color(0xFF000000)), const Color(0xFF808080), ); expect( Color.alphaBlend(const Color(0x80808080), const Color(0xFFFFFFFF)), const Color(0xFFBFBFBF), ); expect( Color.alphaBlend(const Color(0x80808080), const Color(0xFF000000)), const Color(0xFF404040), ); expect( Color.alphaBlend(const Color(0x01020304), const Color(0xFF000000)), const Color(0xFF000000), ); expect( Color.alphaBlend(const Color(0x11223344), const Color(0xFF000000)), const Color(0xFF020304), ); expect( Color.alphaBlend(const Color(0x11223344), const Color(0x80000000)), const Color(0x88040608), ); }); test('compute gray luminance', () { // Each color component is at 20%. const Color lightGray = Color(0xFF333333); // Relative luminance's formula is just the linearized color value for gray. // ((0.2 + 0.055) / 1.055) ^ 2.4. expect(lightGray.computeLuminance(), equals(0.033104766570885055)); }); test('compute color luminance', () { const Color brightRed = Color(0xFFFF3B30); // 0.2126 * ((1.0 + 0.055) / 1.055) ^ 2.4 + // 0.7152 * ((0.23137254902 +0.055) / 1.055) ^ 2.4 + // 0.0722 * ((0.18823529411 + 0.055) / 1.055) ^ 2.4 expect(brightRed.computeLuminance(), equals(0.24601329637099723)); }); }
engine/testing/dart/color_test.dart/0
{'file_path': 'engine/testing/dart/color_test.dart', 'repo_id': 'engine', 'token_count': 1775}
// 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. import 'dart:async'; import 'dart:io'; import 'dart:typed_data'; import 'dart:ui'; import 'package:litetest/litetest.dart'; import 'package:path/path.dart' as path; void main() { bool assertsEnabled = false; assert(() { assertsEnabled = true; return true; }()); test('no resize by default', () async { final Uint8List bytes = await readFile('2x2.png'); final Codec codec = await instantiateImageCodec(bytes); final FrameInfo frame = await codec.getNextFrame(); final int codecHeight = frame.image.height; final int codecWidth = frame.image.width; expect(codecHeight, 2); expect(codecWidth, 2); }); test('resize width with constrained height', () async { final Uint8List bytes = await readFile('2x2.png'); final Codec codec = await instantiateImageCodec(bytes, targetHeight: 1); final FrameInfo frame = await codec.getNextFrame(); final int codecHeight = frame.image.height; final int codecWidth = frame.image.width; expect(codecHeight, 1); expect(codecWidth, 1); }); test('resize height with constrained width', () async { final Uint8List bytes = await readFile('2x2.png'); final Codec codec = await instantiateImageCodec(bytes, targetWidth: 1); final FrameInfo frame = await codec.getNextFrame(); final int codecHeight = frame.image.height; final int codecWidth = frame.image.width; expect(codecHeight, 1); expect(codecWidth, 1); }); test('upscale image by 5x', () async { final Uint8List bytes = await readFile('2x2.png'); final Codec codec = await instantiateImageCodec(bytes, targetWidth: 10); final FrameInfo frame = await codec.getNextFrame(); final int codecHeight = frame.image.height; final int codecWidth = frame.image.width; expect(codecHeight, 10); expect(codecWidth, 10); }); test('upscale image by 5x - no upscaling', () async { final Uint8List bytes = await readFile('2x2.png'); final Codec codec = await instantiateImageCodec(bytes, targetWidth: 10, allowUpscaling: false); final FrameInfo frame = await codec.getNextFrame(); final int codecHeight = frame.image.height; final int codecWidth = frame.image.width; expect(codecHeight, 2); expect(codecWidth, 2); }); test('upscale image varying width and height', () async { final Uint8List bytes = await readFile('2x2.png'); final Codec codec = await instantiateImageCodec(bytes, targetWidth: 10, targetHeight: 1); final FrameInfo frame = await codec.getNextFrame(); final int codecHeight = frame.image.height; final int codecWidth = frame.image.width; expect(codecHeight, 1); expect(codecWidth, 10); }); test('upscale image varying width and height - no upscaling', () async { final Uint8List bytes = await readFile('2x2.png'); final Codec codec = await instantiateImageCodec(bytes, targetWidth: 10, targetHeight: 1, allowUpscaling: false); final FrameInfo frame = await codec.getNextFrame(); final int codecHeight = frame.image.height; final int codecWidth = frame.image.width; expect(codecHeight, 1); expect(codecWidth, 2); }); test('pixels: no resize by default', () async { final BlackSquare blackSquare = BlackSquare.create(); final Image resized = await blackSquare.resize(); expect(resized.height, blackSquare.height); expect(resized.width, blackSquare.width); }); test('pixels: resize width with constrained height', () async { final BlackSquare blackSquare = BlackSquare.create(); final Image resized = await blackSquare.resize(targetHeight: 1); expect(resized.height, 1); expect(resized.width, 1); }); test('pixels: resize height with constrained width', () async { final BlackSquare blackSquare = BlackSquare.create(); final Image resized = await blackSquare.resize(targetWidth: 1); expect(resized.height, 1); expect(resized.width, 1); }); test('pixels: upscale image by 5x', () async { final BlackSquare blackSquare = BlackSquare.create(); final Image resized = await blackSquare.resize(targetWidth: 10, allowUpscaling: true); expect(resized.height, 10); expect(resized.width, 10); }); test('pixels: upscale image by 5x - no upscaling', () async { final BlackSquare blackSquare = BlackSquare.create(); bool threw = false; try { decodeImageFromPixels( blackSquare.pixels, blackSquare.width, blackSquare.height, PixelFormat.rgba8888, (Image image) {}, targetHeight: 10, allowUpscaling: false, ); } catch (e) { expect(e is AssertionError, true); threw = true; } expect(threw, true); }, skip: !assertsEnabled); test('pixels: upscale image varying width and height', () async { final BlackSquare blackSquare = BlackSquare.create(); final Image resized = await blackSquare.resize(targetHeight: 1, targetWidth: 10, allowUpscaling: true); expect(resized.height, 1); expect(resized.width, 10); }); test('pixels: upscale image varying width and height - no upscaling', () async { final BlackSquare blackSquare = BlackSquare.create(); bool threw = false; try { decodeImageFromPixels( blackSquare.pixels, blackSquare.width, blackSquare.height, PixelFormat.rgba8888, (Image image) {}, targetHeight: 10, targetWidth: 1, allowUpscaling: false, ); } catch (e) { expect(e is AssertionError, true); threw = true; } expect(threw, true); }, skip: !assertsEnabled); test('pixels: large negative dimensions', () async { final BlackSquare blackSquare = BlackSquare.create(); final Image resized = await blackSquare.resize(targetHeight: -100, targetWidth: -99999); expect(resized.height, 2); expect(resized.width, 2); }); } class BlackSquare { BlackSquare._(this.width, this.height, this.pixels); factory BlackSquare.create({int width = 2, int height = 2}) { final Uint8List pixels = Uint8List.fromList(List<int>.filled(width * height * 4, 0)); return BlackSquare._(width, height, pixels); } Future<Image> resize({int? targetWidth, int? targetHeight, bool allowUpscaling = false}) async { final Completer<Image> imageCompleter = Completer<Image>(); decodeImageFromPixels( pixels, width, height, PixelFormat.rgba8888, (Image image) => imageCompleter.complete(image), targetHeight: targetHeight, targetWidth: targetWidth, allowUpscaling: allowUpscaling, ); return imageCompleter.future; } final int width; final int height; final Uint8List pixels; } Future<Uint8List> readFile(String fileName) async { final File file = File(path.join('flutter', 'testing', 'resources', fileName)); return file.readAsBytes(); }
engine/testing/dart/image_resize_test.dart/0
{'file_path': 'engine/testing/dart/image_resize_test.dart', 'repo_id': 'engine', 'token_count': 2467}
// 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. import 'dart:ui'; import 'package:litetest/litetest.dart'; void main() { test('Should be able to build and layout a paragraph', () { final ParagraphBuilder builder = ParagraphBuilder(ParagraphStyle()); builder.addText('Hello'); final Paragraph paragraph = builder.build(); expect(paragraph, isNotNull); paragraph.layout(const ParagraphConstraints(width: 800.0)); expect(paragraph.width, isNonZero); expect(paragraph.height, isNonZero); }); test('PushStyle should not segfault after build()', () { final ParagraphBuilder paragraphBuilder = ParagraphBuilder(ParagraphStyle()); paragraphBuilder.build(); expect(() { paragraphBuilder.pushStyle(TextStyle()); }, throwsStateError); }); test('GetRectsForRange smoke test', () { final ParagraphBuilder builder = ParagraphBuilder(ParagraphStyle()); builder.addText('Hello'); final Paragraph paragraph = builder.build(); expect(paragraph, isNotNull); paragraph.layout(const ParagraphConstraints(width: 800.0)); expect(paragraph.width, isNonZero); expect(paragraph.height, isNonZero); final List<TextBox> boxes = paragraph.getBoxesForRange(0, 3); expect(boxes.length, 1); expect(boxes.first.left, 0.0); expect(boxes.first.top, 0.0); expect(boxes.first.right, 42.0); expect(boxes.first.bottom, 14.0); expect(boxes.first.direction, TextDirection.ltr); }); test('LineMetrics smoke test', () { final ParagraphBuilder builder = ParagraphBuilder(ParagraphStyle()); builder.addText('Hello'); final Paragraph paragraph = builder.build(); expect(paragraph, isNotNull); paragraph.layout(const ParagraphConstraints(width: 800.0)); expect(paragraph.width, isNonZero); expect(paragraph.height, isNonZero); final List<LineMetrics> metrics = paragraph.computeLineMetrics(); expect(metrics.length, 1); expect(metrics.first.hardBreak, true); expect(metrics.first.ascent, 10.5); expect(metrics.first.descent, 3.5); expect(metrics.first.unscaledAscent, 10.5); expect(metrics.first.height, 14.0); expect(metrics.first.width, 70.0); expect(metrics.first.left, 0.0); expect(metrics.first.baseline, 10.5); expect(metrics.first.lineNumber, 0); }); }
engine/testing/dart/paragraph_builder_test.dart/0
{'file_path': 'engine/testing/dart/paragraph_builder_test.dart', 'repo_id': 'engine', 'token_count': 825}
// 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. import 'dart:async'; import 'dart:collection'; import 'dart:isolate'; import 'package:async_helper/async_helper.dart'; import 'package:async_helper/async_minitest.dart'; import 'package:litetest/src/test.dart'; import 'package:litetest/src/test_suite.dart'; Future<void> main() async { asyncStart(); test('skip', () async { final StringBuffer buffer = StringBuffer(); final TestLifecycle lifecycle = TestLifecycle(); final TestSuite ts = TestSuite( logger: buffer, lifecycle: lifecycle, ); ts.test('Test', () { expect(1, equals(1)); }, skip: true); final bool result = await lifecycle.result; expect(result, true); expect(buffer.toString(), equals( 'Test "Test": Skipped\nAll tests skipped.\n', )); }); test('test', () async { final StringBuffer buffer = StringBuffer(); final TestLifecycle lifecycle = TestLifecycle(); final TestSuite ts = TestSuite( logger: buffer, lifecycle: lifecycle, ); ts.test('Test', () { expect(1, equals(1)); }); final bool result = await lifecycle.result; expect(result, true); expect(buffer.toString(), equals( 'Test "Test": Started\nTest "Test": Passed\n', )); }); test('multiple tests', () async { final StringBuffer buffer = StringBuffer(); final TestLifecycle lifecycle = TestLifecycle(); final TestSuite ts = TestSuite( logger: buffer, lifecycle: lifecycle, ); ts.test('Test1', () { expect(1, equals(1)); }); ts.test('Test2', () { expect(2, equals(2)); }); ts.test('Test3', () { expect(3, equals(3)); }); final bool result = await lifecycle.result; expect(result, true); expect(buffer.toString(), equals(''' Test "Test1": Started Test "Test1": Passed Test "Test2": Started Test "Test2": Passed Test "Test3": Started Test "Test3": Passed ''', )); }); test('multiple tests with failure', () async { final StringBuffer buffer = StringBuffer(); final TestLifecycle lifecycle = TestLifecycle(); final TestSuite ts = TestSuite( logger: buffer, lifecycle: lifecycle, ); ts.test('Test1', () { expect(1, equals(1)); }); ts.test('Test2', () { expect(2, equals(3)); }); ts.test('Test3', () { expect(3, equals(3)); }); final bool result = await lifecycle.result; final String output = buffer.toString(); expect(result, false); expect(output.contains('Test "Test1": Started'), true); expect(output.contains('Test "Test1": Passed'), true); expect(output.contains('Test "Test2": Started'), true); expect(output.contains('Test "Test2": Failed'), true); expect(output.contains( 'In test "Test2" Expect.deepEquals(expected: <3>, actual: <2>) fails.', ), true); expect(output.contains('Test "Test3": Started'), true); expect(output.contains('Test "Test3": Passed'), true); }); test('test fail', () async { final StringBuffer buffer = StringBuffer(); final TestLifecycle lifecycle = TestLifecycle(); final TestSuite ts = TestSuite( logger: buffer, lifecycle: lifecycle, ); ts.test('Test', () { expect(1, equals(2)); }); final bool result = await lifecycle.result; final String output = buffer.toString(); expect(result, false); expect(output.contains('Test "Test": Started'), true); expect(output.contains('Test "Test": Failed'), true); expect( output.contains( 'In test "Test" Expect.deepEquals(expected: <2>, actual: <1>) fails.', ), true, ); }); test('async test', () async { final StringBuffer buffer = StringBuffer(); final TestLifecycle lifecycle = TestLifecycle(); final TestSuite ts = TestSuite( logger: buffer, lifecycle: lifecycle, ); ts.test('Test', () async { final Completer<void> completer = Completer<void>(); Timer.run(() { completer.complete(); }); await completer.future; expect(1, equals(1)); }); final bool result = await lifecycle.result; expect(result, true); expect(buffer.toString(), equals( 'Test "Test": Started\nTest "Test": Passed\n', )); }); test('async test fail', () async { final StringBuffer buffer = StringBuffer(); final TestLifecycle lifecycle = TestLifecycle(); final TestSuite ts = TestSuite( logger: buffer, lifecycle: lifecycle, ); ts.test('Test', () async { final Completer<void> completer = Completer<void>(); Timer.run(() { completer.complete(); }); await completer.future; expect(1, equals(2)); }); final bool result = await lifecycle.result; final String output = buffer.toString(); expect(result, false); expect(output.contains('Test "Test": Started'), true); expect(output.contains('Test "Test": Failed'), true); expect( output.contains( 'In test "Test" Expect.deepEquals(expected: <2>, actual: <1>) fails.', ), true, ); }); test('throws StateError on async test() call', () async { final StringBuffer buffer = StringBuffer(); final TestLifecycle lifecycle = TestLifecycle(); final TestSuite ts = TestSuite( logger: buffer, lifecycle: lifecycle, ); ts.test('Test', () { expect(1, equals(1)); }); bool caughtError = false; try { await Future<void>(() async { ts.test('Bad Test', () {}); }); } on StateError catch (e) { caughtError = true; expect(e.message.contains( 'Test "Bad Test" added after tests have started to run.', ), true); } expect(caughtError, true); final bool result = await lifecycle.result; expect(result, true); expect(buffer.toString(), equals( 'Test "Test": Started\nTest "Test": Passed\n', )); }); asyncEnd(); } class TestLifecycle implements Lifecycle { final ReceivePort port = ReceivePort(); final Completer<bool> _testCompleter = Completer<bool>(); Future<bool> get result => _testCompleter.future; @override void onStart() {} @override void onDone(Queue<Test> tests) { bool testsSucceeded = true; for (final Test t in tests) { testsSucceeded = testsSucceeded && (t.state == TestState.succeeded); } _testCompleter.complete(testsSucceeded); port.close(); } }
engine/testing/litetest/test/litetest_test.dart/0
{'file_path': 'engine/testing/litetest/test/litetest_test.dart', 'repo_id': 'engine', 'token_count': 2531}
// 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. import 'dart:ui'; import 'channel_util.dart'; import 'scenario.dart'; import 'scenarios.dart'; /// Displays a platform texture with the given width and height. class DisplayTexture extends Scenario { /// Creates the DisplayTexture scenario. DisplayTexture(super.view); int get _textureId => scenarioParams['texture_id'] as int; double get _textureWidth => (scenarioParams['texture_width'] as num).toDouble(); double get _textureHeight => (scenarioParams['texture_height'] as num).toDouble(); @override void onBeginFrame(Duration duration) { final SceneBuilder builder = SceneBuilder(); builder.addTexture( _textureId, offset: Offset( (view.physicalSize.width / 2.0) - (_textureWidth / 2.0), 0.0, ), width: _textureWidth, height: _textureHeight, ); final Scene scene = builder.build(); view.render(scene); scene.dispose(); sendJsonMessage( dispatcher: view.platformDispatcher, channel: 'display_data', json: <String, dynamic>{ 'data': 'ready', }, ); } }
engine/testing/scenario_app/lib/src/texture.dart/0
{'file_path': 'engine/testing/scenario_app/lib/src/texture.dart', 'repo_id': 'engine', 'token_count': 449}
// 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. import 'dart:io' as io; import 'package:path/path.dart' as pathlib; /// Contains various environment variables, such as common file paths and command-line options. Environment get environment { return _environment ??= Environment(); } Environment? _environment; /// Contains various environment variables, such as common file paths and command-line options. class Environment { /// Creates an environment deduced from the path of the main Dart script. factory Environment() { final io.File script = io.File.fromUri(io.Platform.script); io.Directory directory = script.parent; bool foundEngineRepoRoot = false; while (!foundEngineRepoRoot) { foundEngineRepoRoot = directory .listSync() .whereType<io.File>() .map((io.File file) => pathlib.basename(file.path)) .contains('DEPS'); final io.Directory parent = directory.parent; if (parent.path == directory.path) { throw Exception( 'Failed to locate the root of the engine repository starting from ${script.path}', ); } directory = parent; } return _prepareEnvironmentFromEngineDir(script, directory); } Environment._({ required this.self, required this.webUiRootDir, required this.engineSrcDir, required this.engineToolsDir, }); static Environment _prepareEnvironmentFromEngineDir( io.File self, io.Directory engineSrcDir) { final io.Directory engineToolsDir = io.Directory(pathlib.join(engineSrcDir.path, 'flutter', 'tools')); final io.Directory webUiRootDir = io.Directory( pathlib.join(engineSrcDir.path, 'flutter', 'lib', 'web_ui')); for (final io.Directory expectedDirectory in <io.Directory>[ engineSrcDir, webUiRootDir ]) { if (!expectedDirectory.existsSync()) { throw Exception('$expectedDirectory does not exist.'); } } return Environment._( self: self, webUiRootDir: webUiRootDir, engineSrcDir: engineSrcDir, engineToolsDir: engineToolsDir, ); } /// The Dart script that's currently running. final io.File self; /// Path to the "web_ui" package sources. final io.Directory webUiRootDir; /// Path to the engine's "src" directory. final io.Directory engineSrcDir; /// Path to the engine's "tools" directory. final io.Directory engineToolsDir; /// Path to where github.com/flutter/engine is checked out inside the engine workspace. io.Directory get flutterDirectory => io.Directory(pathlib.join(engineSrcDir.path, 'flutter')); /// Path to the "web_sdk" directory in the engine source tree. io.Directory get webSdkRootDir => io.Directory(pathlib.join( flutterDirectory.path, 'web_sdk', )); /// Path to the "web_engine_tester" package. io.Directory get webEngineTesterRootDir => io.Directory(pathlib.join( webSdkRootDir.path, 'web_engine_tester', )); /// Path to the "build" directory, generated by "package:build_runner". /// /// This is where compiled output goes. io.Directory get webUiBuildDir => io.Directory(pathlib.join( engineSrcDir.path, 'out', 'web_tests', )); /// Path to the ".dart_tool" directory, generated by various Dart tools. io.Directory get webUiDartToolDir => io.Directory(pathlib.join( webUiRootDir.path, '.dart_tool', )); /// Path to the ".dart_tool" directory living under `engine/src/flutter`. /// /// This is a designated area for tool downloads which can be used by /// multiple platforms. For exampe: Flutter repo for e2e tests. io.Directory get engineDartToolDir => io.Directory(pathlib.join( engineSrcDir.path, 'flutter', '.dart_tool', )); /// Path to the "dev" directory containing engine developer tools and /// configuration files. io.Directory get webUiDevDir => io.Directory(pathlib.join( webUiRootDir.path, 'dev', )); /// Path to the "test" directory containing web engine tests. io.Directory get webUiTestDir => io.Directory(pathlib.join( webUiRootDir.path, 'test', )); /// Path to the "lib" directory containing web engine code. io.Directory get webUiLibDir => io.Directory(pathlib.join( webUiRootDir.path, 'lib', )); /// Path to the base directory to be used by Skia Gold. io.Directory get webUiSkiaGoldDirectory => io.Directory(pathlib.join( webUiDartToolDir.path, 'skia_gold', )); /// Directory to add test results which would later be uploaded to a gcs /// bucket by LUCI. io.Directory get webUiTestResultsDirectory => io.Directory(pathlib.join( webUiDartToolDir.path, 'test_results', )); /// Path to the screenshots taken by iOS simulator. io.Directory get webUiSimulatorScreenshotsDirectory => io.Directory(pathlib.join( webUiDartToolDir.path, 'ios_screenshots', )); /// Path to the script that clones the Flutter repo. io.File get cloneFlutterScript => io.File(pathlib.join( engineToolsDir.path, 'clone_flutter.sh', )); /// Path to flutter. /// /// For example, this can be used to run `flutter pub get`. /// /// Only use [cloneFlutterScript] to clone flutter to the engine build. io.File get flutterCommand => io.File(pathlib.join( engineDartToolDir.path, 'flutter', 'bin', 'flutter', )); }
engine/web_sdk/web_test_utils/lib/environment.dart/0
{'file_path': 'engine/web_sdk/web_test_utils/lib/environment.dart', 'repo_id': 'engine', 'token_count': 2052}
/// A mixin that helps implement equality without needing to explicitly override /// `==` operators or `hashCode`s. library equatable; export './src/equatable.dart'; export './src/equatable_config.dart'; export './src/equatable_mixin.dart';
equatable/lib/equatable.dart/0
{'file_path': 'equatable/lib/equatable.dart', 'repo_id': 'equatable', 'token_count': 74}
targets: fast_noise: builders: build_web_compilers|entrypoint: generate_for: - test/**_test.dart - web/**.dart options: dart2js_args: - -O4
fast_noise/build.yaml/0
{'file_path': 'fast_noise/build.yaml', 'repo_id': 'fast_noise', 'token_count': 121}
/// This is a port of FastNoise, by Jordan Peck /// Please visit https://github.com/Auburns/FastNoise library fast_noise; export 'package:fast_noise/src/enums.dart'; export 'package:fast_noise/src/gradient_perturb.dart'; export 'package:fast_noise/src/noise_factory.dart'; export 'package:fast_noise/src/noise_helpers.dart'; export 'package:fast_noise/src/noises.dart'; export 'package:fast_noise/src/types.dart'; export 'package:fast_noise/src/utils.dart';
fast_noise/lib/fast_noise.dart/0
{'file_path': 'fast_noise/lib/fast_noise.dart', 'repo_id': 'fast_noise', 'token_count': 173}
library fast_noise; export 'package:fast_noise/src/noise/cellular.dart'; export 'package:fast_noise/src/noise/cubic.dart'; export 'package:fast_noise/src/noise/cubic_fractal.dart'; export 'package:fast_noise/src/noise/noise.dart'; export 'package:fast_noise/src/noise/perlin.dart'; export 'package:fast_noise/src/noise/perlin_fractal.dart'; export 'package:fast_noise/src/noise/simplex.dart'; export 'package:fast_noise/src/noise/simplex_fractal.dart'; export 'package:fast_noise/src/noise/value.dart'; export 'package:fast_noise/src/noise/value_fractal.dart'; export 'package:fast_noise/src/noise/white.dart';
fast_noise/lib/src/noises.dart/0
{'file_path': 'fast_noise/lib/src/noises.dart', 'repo_id': 'fast_noise', 'token_count': 254}
import 'package:favorite_country_sample/provider/favorite_provider.dart'; import 'package:favorite_country_sample/screens/countries_screen.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; class App extends StatelessWidget { const App({super.key}); // This widget is the root of your application. @override Widget build(BuildContext context) { return ListenableProvider( create: (context) => FavoriteProvider(), child: MaterialApp( debugShowCheckedModeBanner: false, title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: const CountriesScreen(), ), ); } }
favorite-countries-sample/lib/app.dart/0
{'file_path': 'favorite-countries-sample/lib/app.dart', 'repo_id': 'favorite-countries-sample', 'token_count': 256}
import 'package:flutter/material.dart'; class UIColors { static Color primaryColor = const Color(0xFFFF734A); static Color backagroundColor = const Color(0xFF1D1D35); }
finance-ui/lib/src/res/colors/ui_colors.dart/0
{'file_path': 'finance-ui/lib/src/res/colors/ui_colors.dart', 'repo_id': 'finance-ui', 'token_count': 61}
import 'package:equatable/equatable.dart'; import 'package:fire_atlas_editor/store/actions/editor_actions.dart'; import 'package:fire_atlas_editor/store/store.dart'; import 'package:fire_atlas_editor/widgets/color_badge.dart'; import 'package:fire_atlas_editor/widgets/slide_container.dart'; import 'package:flutter/material.dart'; import 'package:slices/slices.dart'; class _MessageBoardSlice extends Equatable { final List<Message> messages; _MessageBoardSlice.fromState(FireAtlasState state) : messages = state.messages.toList(); @override List<Object?> get props => [messages]; } class MessagesBoard extends StatelessWidget { const MessagesBoard({super.key}); @override Widget build(_) { return SliceWatcher<FireAtlasState, _MessageBoardSlice>( slicer: _MessageBoardSlice.fromState, builder: (ctx, store, slice) { return Column( children: slice.messages .map((message) { return _Message( key: Key(message.message), message: message, onVanish: () { store.dispatch(DismissMessageAction(message: message)); }, ); }) .toList() .cast(), ); }, ); } } class _Message extends StatelessWidget { final Message message; final VoidCallback onVanish; const _Message({ required this.message, required this.onVanish, super.key, }); @override Widget build(BuildContext ctx) { final color = message.type == MessageType.INFO ? const Color(0xFF34b4eb) : Theme.of(ctx).colorScheme.error; return SlideContainer( key: key, curve: Curves.easeOutQuad, onFinish: (controller) { Future<void>.delayed(const Duration(milliseconds: 2500)).then((_) { controller.reverse().whenComplete(onVanish); }); }, from: const Offset(1.2, 0.0), child: ColorBadge( color: color, label: message.message, ), ); } }
fire-atlas/fire_atlas_editor/lib/screens/widgets/messages_board.dart/0
{'file_path': 'fire-atlas/fire_atlas_editor/lib/screens/widgets/messages_board.dart', 'repo_id': 'fire-atlas', 'token_count': 905}
import 'package:flutter/material.dart'; class FContainer extends StatelessWidget { final double? width; final double? height; final Widget? child; final Color? color; final EdgeInsets margin; final EdgeInsets padding; const FContainer({ super.key, this.child, this.height, this.width, this.color, this.margin = const EdgeInsets.all(2.5), this.padding = EdgeInsets.zero, }); @override Widget build(BuildContext ctx) { final containerColor = color ?? Theme.of(ctx).dialogBackgroundColor; return Container( decoration: BoxDecoration( color: containerColor, border: Border.all( color: Theme.of(ctx).dividerColor, width: 2.5, ), borderRadius: BorderRadius.circular(5), ), padding: padding, margin: margin, width: width, height: height, child: child, ); } }
fire-atlas/fire_atlas_editor/lib/widgets/container.dart/0
{'file_path': 'fire-atlas/fire_atlas_editor/lib/widgets/container.dart', 'repo_id': 'fire-atlas', 'token_count': 369}
import 'package:flutter/material.dart'; class FadeRoute extends PageRouteBuilder { final Widget? page; FadeRoute({this.page}) : super( pageBuilder: ( BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, ) => page!, transitionsBuilder: ( BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child, ) => FadeTransition( opacity: animation, child: child, ), ); }
firebase-crud/lib/app/components/faderoute.dart/0
{'file_path': 'firebase-crud/lib/app/components/faderoute.dart', 'repo_id': 'firebase-crud', 'token_count': 326}
name: flare_rotation description: Flare example with rotation version: 1.0.0+1 environment: sdk: ">=2.1.0 <3.0.0" dependencies: flutter: sdk: flutter dev_dependencies: flutter_test: sdk: flutter flame: path: ../../flame flutter: assets: - assets/Bob_Minion.flr
flame-examples/flare_rotation/pubspec.yaml/0
{'file_path': 'flame-examples/flare_rotation/pubspec.yaml', 'repo_id': 'flame-examples', 'token_count': 128}
include: package:flame_lint/analysis_options.yaml
flame/doc/flame/examples/analysis_options.yaml/0
{'file_path': 'flame/doc/flame/examples/analysis_options.yaml', 'repo_id': 'flame', 'token_count': 16}
import 'package:flutter/material.dart' hide Image, Gradient; import 'package:padracing/menu_card.dart'; import 'package:padracing/padracing_game.dart'; class GameOver extends StatelessWidget { const GameOver(this.game, {super.key}); final PadRacingGame game; @override Widget build(BuildContext context) { final textTheme = Theme.of(context).textTheme; return Material( color: Colors.transparent, child: Center( child: Wrap( children: [ MenuCard( children: [ Text( 'Player ${game.winner!.playerNumber + 1} wins!', style: textTheme.headline1, ), const SizedBox(height: 10), Text( 'Time: ${game.timePassed}', style: textTheme.bodyText1, ), const SizedBox(height: 10), ElevatedButton( onPressed: game.reset, child: const Text('Restart'), ), ], ), ], ), ), ); } }
flame/examples/games/padracing/lib/game_over.dart/0
{'file_path': 'flame/examples/games/padracing/lib/game_over.dart', 'repo_id': 'flame', 'token_count': 597}
include: package:flame_lint/analysis_options.yaml
flame/examples/games/trex/analysis_options.yaml/0
{'file_path': 'flame/examples/games/trex/analysis_options.yaml', 'repo_id': 'flame', 'token_count': 16}
import 'package:flame/components.dart'; import 'package:flame/game.dart'; import 'package:meta/meta.dart'; class Ember<T extends FlameGame> extends SpriteAnimationComponent with HasGameRef<T> { Ember({super.position, Vector2? size, super.priority}) : super( size: size ?? Vector2.all(50), anchor: Anchor.center, ); @mustCallSuper @override Future<void> onLoad() async { animation = await gameRef.loadSpriteAnimation( 'animations/ember.png', SpriteAnimationData.sequenced( amount: 3, textureSize: Vector2.all(16), stepTime: 0.15, ), ); } }
flame/examples/lib/commons/ember.dart/0
{'file_path': 'flame/examples/lib/commons/ember.dart', 'repo_id': 'flame', 'token_count': 262}
// // Generated file. Do not edit. // // ignore_for_file: directives_ordering // ignore_for_file: lines_longer_than_80_chars import 'package:shared_preferences_web/shared_preferences_web.dart'; import 'package:url_launcher_web/url_launcher_web.dart'; import 'package:flutter_web_plugins/flutter_web_plugins.dart'; // ignore: public_member_api_docs void registerPlugins(Registrar registrar) { SharedPreferencesPlugin.registerWith(registrar); UrlLauncherPlugin.registerWith(registrar); registrar.registerMessageHandler(); }
flame/examples/lib/stories/bridge_libraries/forge2d/generated_plugin_registrant.dart/0
{'file_path': 'flame/examples/lib/stories/bridge_libraries/forge2d/generated_plugin_registrant.dart', 'repo_id': 'flame', 'token_count': 180}
import 'package:flame/components.dart'; import 'package:flame/game.dart'; import 'package:flame/input.dart'; class ZoomExample extends FlameGame with ScrollDetector, ScaleDetector { static const String description = ''' On web: use scroll to zoom in and out.\n On mobile: use scale gesture to zoom in and out. '''; final Vector2 viewportResolution; late SpriteComponent flame; ZoomExample({ required this.viewportResolution, }); @override Future<void> onLoad() async { final flameSprite = await loadSprite('flame.png'); camera.viewport = FixedResolutionViewport(viewportResolution); camera.setRelativeOffset(Anchor.center); camera.speed = 100; final flameSize = Vector2(149, 211); add( flame = SpriteComponent( sprite: flameSprite, size: flameSize, )..anchor = Anchor.center, ); } void clampZoom() { camera.zoom = camera.zoom.clamp(0.05, 3.0); } static const zoomPerScrollUnit = 0.02; @override void onScroll(PointerScrollInfo info) { camera.zoom += info.scrollDelta.game.y.sign * zoomPerScrollUnit; clampZoom(); } late double startZoom; @override void onScaleStart(_) { startZoom = camera.zoom; } @override void onScaleUpdate(ScaleUpdateInfo info) { final currentScale = info.scale.global; if (!currentScale.isIdentity()) { camera.zoom = startZoom * currentScale.y; clampZoom(); } else { camera.translateBy(-info.delta.game); camera.snap(); } } }
flame/examples/lib/stories/camera_and_viewport/zoom_example.dart/0
{'file_path': 'flame/examples/lib/stories/camera_and_viewport/zoom_example.dart', 'repo_id': 'flame', 'token_count': 564}
import 'dart:math'; import 'package:flame/components.dart'; import 'package:flame/effects.dart'; import 'package:flame/game.dart'; import 'package:flame/input.dart'; import 'package:flutter/material.dart'; class RemoveEffectExample extends FlameGame with HasTappables { static const description = ''' Click on any circle to apply a RemoveEffect, which will make the circle disappear after a 0.5 second delay. '''; @override void onMount() { super.onMount(); camera.viewport = FixedResolutionViewport(Vector2(400, 600)); final rng = Random(); for (var i = 0; i < 20; i++) { add(_RandomCircle.random(rng)); } } } class _RandomCircle extends CircleComponent with Tappable { _RandomCircle(double radius, {super.position, super.paint}) : super(radius: radius); factory _RandomCircle.random(Random rng) { final radius = rng.nextDouble() * 30 + 10; final position = Vector2( rng.nextDouble() * 320 + 40, rng.nextDouble() * 520 + 40, ); final paint = Paint() ..color = Colors.primaries[rng.nextInt(Colors.primaries.length)]; return _RandomCircle(radius, position: position, paint: paint); } @override bool onTapDown(TapDownInfo info) { add(RemoveEffect(delay: 0.5)); return false; } }
flame/examples/lib/stories/effects/remove_effect_example.dart/0
{'file_path': 'flame/examples/lib/stories/effects/remove_effect_example.dart', 'repo_id': 'flame', 'token_count': 464}
import 'package:examples/commons/ember.dart'; import 'package:flame/game.dart'; import 'package:flame/input.dart'; import 'package:flame/palette.dart'; import 'package:flutter/services.dart'; import 'package:flutter/widgets.dart'; class KeyboardExample extends FlameGame with KeyboardEvents { static const String description = ''' Example showcasing how to act on keyboard events. It also briefly showcases how to create a game without the FlameGame. Usage: Use A S D W to steer Ember. '''; static final Paint white = BasicPalette.white.paint(); static const int speed = 200; late final Ember ember; final Vector2 velocity = Vector2(0, 0); @override Future<void> onLoad() async { ember = Ember(position: size / 2, size: Vector2.all(100)); add(ember); } @override void update(double dt) { super.update(dt); final displacement = velocity * (speed * dt); ember.position.add(displacement); } @override KeyEventResult onKeyEvent( RawKeyEvent event, Set<LogicalKeyboardKey> keysPressed, ) { final isKeyDown = event is RawKeyDownEvent; if (event.logicalKey == LogicalKeyboardKey.keyA) { velocity.x = isKeyDown ? -1 : 0; } else if (event.logicalKey == LogicalKeyboardKey.keyD) { velocity.x = isKeyDown ? 1 : 0; } else if (event.logicalKey == LogicalKeyboardKey.keyW) { velocity.y = isKeyDown ? -1 : 0; } else if (event.logicalKey == LogicalKeyboardKey.keyS) { velocity.y = isKeyDown ? 1 : 0; } return super.onKeyEvent(event, keysPressed); } }
flame/examples/lib/stories/input/keyboard_example.dart/0
{'file_path': 'flame/examples/lib/stories/input/keyboard_example.dart', 'repo_id': 'flame', 'token_count': 561}
import 'package:flame/components.dart'; import 'package:flame/game.dart'; import 'package:flame/parallax.dart'; class SmallParallaxExample extends FlameGame { static const String description = ''' Shows how to create a smaller parallax in the center of the screen. '''; @override Future<void> onLoad() async { final component = await loadParallaxComponent( [ ParallaxImageData('parallax/bg.png'), ParallaxImageData('parallax/mountain-far.png'), ParallaxImageData('parallax/mountains.png'), ParallaxImageData('parallax/trees.png'), ParallaxImageData('parallax/foreground-trees.png'), ], size: Vector2.all(200), baseVelocity: Vector2(20, 0), velocityMultiplierDelta: Vector2(1.8, 1.0), ); component.position = size / 2; add(component); } }
flame/examples/lib/stories/parallax/small_parallax_example.dart/0
{'file_path': 'flame/examples/lib/stories/parallax/small_parallax_example.dart', 'repo_id': 'flame', 'token_count': 332}
import 'package:dashbook/dashbook.dart'; import 'package:examples/commons/commons.dart'; import 'package:examples/stories/svg/svg_component.dart'; import 'package:flame/game.dart'; void addSvgStories(Dashbook dashbook) { dashbook.storiesOf('Svg').add( 'Svg Component', (_) => GameWidget(game: SvgComponentExample()), codeLink: baseLink('svg/svg_component.dart'), info: SvgComponentExample.description, ); }
flame/examples/lib/stories/svg/svg.dart/0
{'file_path': 'flame/examples/lib/stories/svg/svg.dart', 'repo_id': 'flame', 'token_count': 178}
name: examples description: A set of small examples showcasing each feature provided by the Flame Engine. homepage: https://github.com/flame-engine/flame/tree/main/examples publish_to: 'none' version: 0.1.0 environment: sdk: ">=2.17.0 <3.0.0" flutter: ">=3.0.0" dependencies: dashbook: 0.1.6 flame: ^1.2.0 flame_audio: ^1.2.0 flame_forge2d: ^0.11.0 flame_svg: ^1.3.0 flutter: sdk: flutter google_fonts: ^2.3.2 padracing: path: games/padracing trex_game: path: games/trex dev_dependencies: flame_lint: ^0.0.1 flutter: uses-material-design: true assets: - assets/images/animations/ - assets/images/ - assets/images/tile_maps/ - assets/images/layers/ - assets/images/parallax/ - assets/svgs/ - assets/audio/music/ - assets/audio/sfx/
flame/examples/pubspec.yaml/0
{'file_path': 'flame/examples/pubspec.yaml', 'repo_id': 'flame', 'token_count': 354}
export 'src/collisions/broadphase.dart'; export 'src/collisions/collision_callbacks.dart'; export 'src/collisions/collision_detection.dart'; export 'src/collisions/collision_passthrough.dart'; export 'src/collisions/hitboxes/circle_hitbox.dart'; export 'src/collisions/hitboxes/composite_hitbox.dart'; export 'src/collisions/hitboxes/hitbox.dart'; export 'src/collisions/hitboxes/polygon_hitbox.dart'; export 'src/collisions/hitboxes/rectangle_hitbox.dart'; export 'src/collisions/hitboxes/screen_hitbox.dart'; export 'src/collisions/hitboxes/shape_hitbox.dart'; export 'src/collisions/sweep.dart';
flame/packages/flame/lib/collisions.dart/0
{'file_path': 'flame/packages/flame/lib/collisions.dart', 'repo_id': 'flame', 'token_count': 215}
import 'package:flame/src/extensions/vector2.dart'; import 'package:meta/meta.dart'; /// Represents a relative position inside some 2D object with a rectangular /// size or bounding box. /// /// Think of it as the place where you "grab" or "hold" the object. /// In Components, the Anchor is where the component position is measured from. /// For example, if a component position is (100, 100) the anchor reflects what /// exact point of the component that is positioned at (100, 100), as a relative /// fraction of the size of the object. /// /// The "default" anchor in most cases is topLeft. /// /// The Anchor is represented by a fraction of the size (in each axis), /// where 0 in x-axis means left, 0 in y-axis means top, 1 in x-axis means right /// and 1 in y-axis means bottom. @immutable class Anchor { static const Anchor topLeft = Anchor(0.0, 0.0); static const Anchor topCenter = Anchor(0.5, 0.0); static const Anchor topRight = Anchor(1.0, 0.0); static const Anchor centerLeft = Anchor(0.0, 0.5); static const Anchor center = Anchor(0.5, 0.5); static const Anchor centerRight = Anchor(1.0, 0.5); static const Anchor bottomLeft = Anchor(0.0, 1.0); static const Anchor bottomCenter = Anchor(0.5, 1.0); static const Anchor bottomRight = Anchor(1.0, 1.0); /// The relative x position with respect to the object's width; /// 0 means totally to the left (beginning) and 1 means totally to the /// right (end). final double x; /// The relative y position with respect to the object's height; /// 0 means totally to the top (beginning) and 1 means totally to the /// bottom (end). final double y; /// Returns [x] and [y] as a Vector2. Note that this is still a relative /// fractional representation. Vector2 toVector2() => Vector2(x, y); const Anchor(this.x, this.y); @Deprecated('Do not use; will be removed in 1.3.0') Vector2 translate(Vector2 p, Vector2 size) { return p - (toVector2()..multiply(size)); } /// Take your position [position] that is on this anchor and give back what /// that position it would be on in anchor [otherAnchor] with a size of /// [size]. Vector2 toOtherAnchorPosition( Vector2 position, Anchor otherAnchor, Vector2 size, ) { if (this == otherAnchor) { return position; } else { return position + ((otherAnchor.toVector2() - toVector2())..multiply(size)); } } /// Returns a string representation of this Anchor. /// /// This should only be used for serialization purposes. String get name { return _valueNames[this] ?? 'Anchor($x, $y)'; } /// Returns a string representation of this Anchor. /// /// This is the same as `name` and should be used only for debugging or /// serialization. @override String toString() => name; static final Map<Anchor, String> _valueNames = { topLeft: 'topLeft', topCenter: 'topCenter', topRight: 'topRight', centerLeft: 'centerLeft', center: 'center', centerRight: 'centerRight', bottomLeft: 'bottomLeft', bottomCenter: 'bottomCenter', bottomRight: 'bottomRight', }; /// List of all predefined anchor values. static final List<Anchor> values = _valueNames.keys.toList(); /// This should only be used for de-serialization purposes. /// /// If you need to convert anchors to serializable data (like JSON), /// use the `toString()` and `valueOf` methods. factory Anchor.valueOf(String name) { if (_valueNames.containsValue(name)) { return _valueNames.entries.singleWhere((e) => e.value == name).key; } else { final regexp = RegExp(r'^\Anchor\(([^,]+), ([^\)]+)\)'); final matches = regexp.firstMatch(name)?.groups([1, 2]); assert( matches != null && matches.length == 2, 'Bad anchor format: $name', ); return Anchor(double.parse(matches![0]!), double.parse(matches[1]!)); } } @override bool operator ==(Object other) { return other is Anchor && x == other.x && y == other.y; } @override int get hashCode => x.hashCode * 31 + y.hashCode; }
flame/packages/flame/lib/src/anchor.dart/0
{'file_path': 'flame/packages/flame/lib/src/anchor.dart', 'repo_id': 'flame', 'token_count': 1372}
import 'package:flame/collisions.dart'; import 'package:flame/components.dart'; import 'package:flame/game.dart'; import 'package:flame/src/geometry/shape_intersections.dart' as intersection_system; import 'package:meta/meta.dart'; /// A [ShapeHitbox] turns a [ShapeComponent] into a [Hitbox]. /// It is currently used by [CircleHitbox], [RectangleHitbox] and /// [PolygonHitbox]. mixin ShapeHitbox on ShapeComponent implements Hitbox<ShapeHitbox> { @override CollisionType collisionType = CollisionType.active; /// Whether the hitbox is allowed to collide with another hitbox that is /// added to the same parent. bool allowSiblingCollision = false; @override Aabb2 get aabb => _validAabb ? _aabb : _recalculateAabb(); final Aabb2 _aabb = Aabb2(); bool _validAabb = false; @override Set<ShapeHitbox> get activeCollisions => _activeCollisions ??= {}; Set<ShapeHitbox>? _activeCollisions; @override bool get isColliding { return _activeCollisions != null && _activeCollisions!.isNotEmpty; } @override bool collidingWith(Hitbox other) { return _activeCollisions != null && activeCollisions.contains(other); } CollisionDetection? _collisionDetection; final List<Transform2D> _transformAncestors = []; late Function() _transformListener; final Vector2 _halfExtents = Vector2.zero(); static const double _extentEpsilon = 0.000000000000001; final Matrix3 _rotationMatrix = Matrix3.zero(); @override bool renderShape = false; @protected late PositionComponent hitboxParent; void Function()? _parentSizeListener; @protected bool shouldFillParent = false; @override void onMount() { super.onMount(); hitboxParent = ancestors().firstWhere( (c) => c is PositionComponent, orElse: () { throw StateError('A ShapeHitbox needs a PositionComponent ancestor'); }, ) as PositionComponent; _transformListener = () => _validAabb = false; ancestors(includeSelf: true).whereType<PositionComponent>().forEach((c) { _transformAncestors.add(c.transform); c.transform.addListener(_transformListener); }); final parentGame = findParent<FlameGame>(); if (parentGame is HasCollisionDetection) { _collisionDetection = parentGame.collisionDetection; _collisionDetection?.add(this); } if (shouldFillParent) { _parentSizeListener = () { size = hitboxParent.size; fillParent(); }; _parentSizeListener?.call(); hitboxParent.size.addListener(_parentSizeListener!); } } @override void onRemove() { if (_parentSizeListener != null) { hitboxParent.size.removeListener(_parentSizeListener!); } _transformAncestors.forEach((t) => t.removeListener(_transformListener)); _collisionDetection?.remove(this); super.onRemove(); } /// Checks whether the [ShapeHitbox] contains the [point], where [point] is /// a position in the global coordinate system of your game. @override bool containsPoint(Vector2 point) { return _possiblyContainsPoint(point) && super.containsPoint(point); } /// Since this is a cheaper calculation than checking towards all shapes this /// check can be done first to see if it even is possible that the shapes can /// contain the point, since the shapes have to be within the size of the /// component. bool _possiblyContainsPoint(Vector2 point) { return aabb.containsVector2(point); } /// Where this [ShapeComponent] has intersection points with another shape @override Set<Vector2> intersections(Hitbox other) { assert( other is ShapeComponent, 'The intersection can only be performed between shapes', ); return intersection_system.intersections(this, other as ShapeComponent); } /// Since this is a cheaper calculation than checking towards all shapes, this /// check can be done first to see if it even is possible that the shapes can /// overlap, since the shapes have to be within the size of the component. @override bool possiblyIntersects(ShapeHitbox other) { final collisionAllowed = allowSiblingCollision || hitboxParent != other.hitboxParent; return collisionAllowed && aabb.intersectsWithAabb2(other.aabb); } /// This determines how the shape should scale if it should try to fill its /// parents boundaries. void fillParent(); Aabb2 _recalculateAabb() { final size = absoluteScaledSize; // This has double.minPositive since a point on the edge of the AABB is // currently counted as outside. _halfExtents.setValues( size.x / 2 + _extentEpsilon, size.y / 2 + _extentEpsilon, ); _rotationMatrix.setRotationZ(absoluteAngle); _validAabb = true; return _aabb ..setCenterAndHalfExtents(absoluteCenter, _halfExtents) ..rotate(_rotationMatrix); } //#region CollisionCallbacks methods @override @mustCallSuper void onCollision(Set<Vector2> intersectionPoints, ShapeHitbox other) { onCollisionCallback?.call(intersectionPoints, other); if (hitboxParent is CollisionCallbacks) { (hitboxParent as CollisionCallbacks).onCollision( intersectionPoints, other.hitboxParent, ); } } @override @mustCallSuper void onCollisionStart(Set<Vector2> intersectionPoints, ShapeHitbox other) { activeCollisions.add(other); onCollisionStartCallback?.call(intersectionPoints, other); if (hitboxParent is CollisionCallbacks) { (hitboxParent as CollisionCallbacks).onCollisionStart( intersectionPoints, other.hitboxParent, ); } } @override @mustCallSuper void onCollisionEnd(ShapeHitbox other) { activeCollisions.remove(other); onCollisionEndCallback?.call(other); if (hitboxParent is CollisionCallbacks) { (hitboxParent as CollisionCallbacks).onCollisionEnd(other.hitboxParent); } } @override CollisionCallback<ShapeHitbox>? onCollisionCallback; @override CollisionCallback<ShapeHitbox>? onCollisionStartCallback; @override CollisionEndCallback<ShapeHitbox>? onCollisionEndCallback; //#endregion }
flame/packages/flame/lib/src/collisions/hitboxes/shape_hitbox.dart/0
{'file_path': 'flame/packages/flame/lib/src/collisions/hitboxes/shape_hitbox.dart', 'repo_id': 'flame', 'token_count': 2030}
import 'package:flame/components.dart'; import 'package:flame/src/events/flame_game_mixins/has_draggables_bridge.dart'; import 'package:flame/src/game/mixins/has_draggables.dart'; import 'package:flame/src/gestures/events.dart'; import 'package:flutter/material.dart'; mixin Draggable on Component { bool _isDragged = false; bool get isDragged => _isDragged; /// Override this to handle the start of a drag/pan gesture that is within the /// boundaries (determined by [Component.containsPoint]) of the component that /// this mixin is used on. /// Return `true` if you want this event to continue to be passed on to /// components underneath (lower priority) this component. bool onDragStart(DragStartInfo info) { return true; } /// Override this to handle the update of a drag/pan gesture that is within /// the boundaries (determined by [Component.containsPoint]) of the component /// that this mixin is used on. /// Return `true` if you want this event to continue to be passed on to /// components underneath (lower priority) this component. bool onDragUpdate(DragUpdateInfo info) { return true; } /// Override this to handle the end of a drag/pan gesture that is within /// the boundaries (determined by [Component.containsPoint]) of the component /// that this mixin is used on. /// Return `true` if you want this event to continue to be passed on to /// components underneath (lower priority) this component. bool onDragEnd(DragEndInfo info) { return true; } /// Override this to handle if a drag/pan gesture is cancelled that was /// previously started on the component that this mixin is used on. /// Return `true` if you want this event to continue to be passed on to /// components underneath (lower priority) this component. /// /// This event is not that common, it can happen for example when the user /// is interrupted by a system-modal dialog in the middle of the drag. bool onDragCancel() { return true; } final List<int> _currentPointerIds = []; bool _checkPointerId(int pointerId) => _currentPointerIds.contains(pointerId); bool handleDragStart(int pointerId, DragStartInfo info) { if (containsPoint(eventPosition(info))) { _isDragged = true; _currentPointerIds.add(pointerId); return onDragStart(info); } return true; } bool handleDragUpdated(int pointerId, DragUpdateInfo info) { if (_checkPointerId(pointerId)) { return onDragUpdate(info); } return true; } bool handleDragEnded(int pointerId, DragEndInfo info) { if (_checkPointerId(pointerId)) { _isDragged = false; _currentPointerIds.remove(pointerId); return onDragEnd(info); } return true; } bool handleDragCanceled(int pointerId) { if (_checkPointerId(pointerId)) { _isDragged = false; _currentPointerIds.remove(pointerId); return onDragCancel(); } return true; } @override @mustCallSuper void onMount() { super.onMount(); assert( (() { final game = findGame()!; return game is HasDraggables || game is HasDraggablesBridge; })(), 'Draggable Components can only be added to a FlameGame with ' 'HasDraggables or HasDraggablesBridge', ); } }
flame/packages/flame/lib/src/components/mixins/draggable.dart/0
{'file_path': 'flame/packages/flame/lib/src/components/mixins/draggable.dart', 'repo_id': 'flame', 'token_count': 1074}
import 'dart:ui'; import 'package:flame/components.dart'; import 'package:flame/src/effects/provider_interfaces.dart'; import 'package:meta/meta.dart'; export '../sprite_animation.dart'; class SpriteAnimationGroupComponent<T> extends PositionComponent with HasPaint implements SizeProvider { /// Key with the current playing animation T? current; /// Map with the mapping each state to the flag removeOnFinish final Map<T, bool> removeOnFinish; /// Map with the available states for this animation group Map<T, SpriteAnimation>? animations; /// Creates a component with an empty animation which can be set later SpriteAnimationGroupComponent({ this.animations, this.current, Map<T, bool>? removeOnFinish, Paint? paint, super.position, super.size, super.scale, super.angle, super.anchor, super.children, super.priority, }) : removeOnFinish = removeOnFinish ?? const {} { if (paint != null) { this.paint = paint; } } /// Creates a SpriteAnimationGroupComponent from a [size], an [image] and /// [data]. /// Check [SpriteAnimationData] for more info on the available options. /// /// Optionally [removeOnFinish] can be mapped to true to have this component /// be auto removed from the FlameGame when the animation is finished. SpriteAnimationGroupComponent.fromFrameData( Image image, Map<T, SpriteAnimationData> data, { T? current, Map<T, bool>? removeOnFinish, Paint? paint, Vector2? position, Vector2? size, Vector2? scale, double? angle, Anchor? anchor, int? priority, }) : this( animations: data.map((key, value) { return MapEntry( key, SpriteAnimation.fromFrameData( image, value, ), ); }), current: current, removeOnFinish: removeOnFinish, paint: paint, position: position, size: size, scale: scale, angle: angle, anchor: anchor, priority: priority, ); SpriteAnimation? get animation => animations?[current]; @mustCallSuper @override void render(Canvas canvas) { animation?.getSprite().render( canvas, size: size, overridePaint: paint, ); } @mustCallSuper @override void update(double dt) { animation?.update(dt); if ((removeOnFinish[current] ?? false) && (animation?.done() ?? false)) { removeFromParent(); } } }
flame/packages/flame/lib/src/components/sprite_animation_group_component.dart/0
{'file_path': 'flame/packages/flame/lib/src/components/sprite_animation_group_component.dart', 'repo_id': 'flame', 'token_count': 1005}
import 'package:flame/src/effects/controllers/curved_effect_controller.dart'; import 'package:flame/src/effects/controllers/delayed_effect_controller.dart'; import 'package:flame/src/effects/controllers/infinite_effect_controller.dart'; import 'package:flame/src/effects/controllers/linear_effect_controller.dart'; import 'package:flame/src/effects/controllers/pause_effect_controller.dart'; import 'package:flame/src/effects/controllers/repeated_effect_controller.dart'; import 'package:flame/src/effects/controllers/reverse_curved_effect_controller.dart'; import 'package:flame/src/effects/controllers/reverse_linear_effect_controller.dart'; import 'package:flame/src/effects/controllers/sequence_effect_controller.dart'; import 'package:flame/src/effects/controllers/speed_effect_controller.dart'; import 'package:flame/src/effects/effect.dart' show Effect; import 'package:flutter/animation.dart' show Curve, Curves; /// Base "controller" class to facilitate animation of effects. /// /// The purpose of an effect controller is to define how an [Effect] or an /// animation should progress over time. To facilitate that, this class provides /// variable [progress], which will grow from 0.0 to 1.0. The value of 0 /// corresponds to the beginning of an animation, and the value of 1.0 is /// the end of the animation. /// /// The [progress] variable can best be thought of as a "logical time". For /// example, if you want to animate a certain property from value A to value B, /// then you can use [progress] to linearly interpolate between these two /// extremes and obtain variable `x = A*(1 - progress) + B*progress`. /// /// The exact behavior of [progress] is determined by subclasses, but the /// following general considerations apply: /// - the progress can also go in negative direction (i.e. from 1 to 0); /// - the progress may oscillate, going from 0 to 1, then back to 0, etc; /// - the progress may change over a finite or infinite period of time; /// - the value of 0 corresponds to the logical start of an animation; /// - the value of 1 is either the end or the "peak" of an animation; /// - the progress may briefly attain values outside of `[0; 1]` range (for /// example if a "bouncy" easing curve is applied). /// /// An [EffectController] can be made to run forward in time (`advance()`), or /// backward in time (`recede()`). /// /// Unlike the `dart.ui.AnimationController`, this class does not use a `Ticker` /// to keep track of time. Instead, it must be pushed through time manually, by /// calling the `update()` method within the game loop. abstract class EffectController { /// Factory function for producing common [EffectController]s. /// /// In the simplest case, when only `duration` is provided, this will return /// a [LinearEffectController] that grows linearly from 0 to 1 over the period /// of that duration. /// /// More generally, the produced effect controller allows to add a delay /// before the beginning of the animation, to animate both forward and in /// reverse, to iterate several times (or infinitely), to apply an arbitrary /// [curve] making the effect progression non-linear, etc. /// /// In the most general case, the animation proceeds through the following /// steps: /// 1. wait for [startDelay] seconds, /// 2. repeat the following steps [repeatCount] times (or [infinite]ly): /// a. progress from 0 to 1 over the [duration] seconds, /// b. wait for [atMaxDuration] seconds, /// c. progress from 1 to 0 over the [reverseDuration] seconds, /// d. wait for [atMinDuration] seconds. /// /// Setting parameter [alternate] to true is another way to create a /// controller whose [reverseDuration] is the same as the forward [duration]. /// /// As an alternative to specifying durations, you can also provide [speed] /// and [reverseSpeed] parameters, but only for effects where the notion of /// a speed is well-defined (`MeasurableEffect`s). /// /// If the animation is finite and there are no "backward" or "atMin" stages /// then the animation will complete at `progress == 1`, otherwise it will /// complete at `progress == 0`. factory EffectController({ double? duration, double? speed, Curve curve = Curves.linear, double? reverseDuration, double? reverseSpeed, Curve? reverseCurve, bool infinite = false, bool alternate = false, int? repeatCount, double startDelay = 0.0, double atMaxDuration = 0.0, double atMinDuration = 0.0, }) { assert( (duration ?? 1) >= 0, 'Duration cannot be negative: $duration', ); assert( (reverseDuration ?? 1) >= 0, 'Reverse duration cannot be negative: $reverseDuration', ); assert( (duration != null) || (speed != null), 'Either duration or speed must be specified', ); assert( !(duration != null && speed != null), 'Both duration and speed cannot be specified at the same time', ); assert( !(reverseDuration != null && reverseSpeed != null), 'Both reverseDuration and reverseSpeed cannot be specified at the ' 'same time', ); assert( (speed ?? 1) > 0, 'Speed must be positive: $speed', ); assert( (reverseSpeed ?? 1) > 0, 'Reverse speed must be positive: $reverseSpeed', ); assert( !(infinite && repeatCount != null), 'An infinite effect cannot have a repeat count', ); assert( (repeatCount ?? 1) > 0, 'Repeat count must be positive: $repeatCount', ); assert( startDelay >= 0, 'Start delay cannot be negative: $startDelay', ); assert( atMaxDuration >= 0, 'At-max duration cannot be negative: $atMaxDuration', ); assert( atMinDuration >= 0, 'At-min duration cannot be negative: $atMinDuration', ); final items = <EffectController>[]; // FORWARD final isLinear = curve == Curves.linear; if (isLinear) { items.add( duration != null ? LinearEffectController(duration) : SpeedEffectController(LinearEffectController(0), speed: speed!), ); } else { items.add( duration != null ? CurvedEffectController(duration, curve) : SpeedEffectController( CurvedEffectController(1, curve), speed: speed!, ), ); } // AT-MAX if (atMaxDuration != 0) { items.add(PauseEffectController(atMaxDuration, progress: 1.0)); } // REVERSE final hasReverse = alternate || (reverseDuration != null) || (reverseSpeed != null); if (hasReverse) { final reverseIsLinear = reverseCurve == Curves.linear || ((reverseCurve == null) && isLinear); final reverseHasDuration = (reverseDuration != null) || (reverseSpeed == null && duration != null); if (reverseIsLinear) { items.add( reverseHasDuration ? ReverseLinearEffectController(reverseDuration ?? duration!) : SpeedEffectController( ReverseLinearEffectController(0), speed: reverseSpeed ?? speed!, ), ); } else { reverseCurve ??= curve.flipped; items.add( reverseHasDuration ? ReverseCurvedEffectController( reverseDuration ?? duration!, reverseCurve, ) : SpeedEffectController( ReverseCurvedEffectController(1, reverseCurve), speed: reverseSpeed ?? speed!, ), ); } } // AT-MIN if (atMinDuration != 0) { items.add(PauseEffectController(atMinDuration, progress: 0.0)); } assert(items.isNotEmpty); var controller = items.length == 1 ? items[0] : SequenceEffectController(items); if (infinite) { controller = InfiniteEffectController(controller); } if (repeatCount != null && repeatCount != 1) { controller = RepeatedEffectController(controller, repeatCount); } if (startDelay != 0) { controller = DelayedEffectController(controller, delay: startDelay); } return controller; } EffectController.empty(); /// Will the effect continue to run forever (never completes)? bool get isInfinite => duration == double.infinity; /// Is the effect's duration random or fixed? bool get isRandom => false; /// Total duration of the effect. If the duration cannot be determined, this /// will return `null`. For an infinite effect the duration is infinity. double? get duration; /// Has the effect started running? Some effects use a "delay" parameter to /// postpone the start of an animation. This property then tells you whether /// this delay period has already passed. bool get started => true; /// Has the effect already finished? /// /// For a finite animation, this property will turn `true` once the animation /// has finished running and the [progress] variable will no longer change /// in the future. For an infinite animation this should always return /// `false`. bool get completed; /// The current progress of the effect, a value between 0 and 1. double get progress; /// Advances this controller's internal clock by [dt] seconds. /// /// If the controller is still running, the return value will be 0. If it /// already finished, then the return value will be the "leftover" part of /// the [dt]. That is, the amount of time [dt] that remains after the /// controller has finished. In all cases, the return value can be positive /// only when `completed == true`. /// /// Normally, this method will be called by the owner of the controller class. /// For example, if the controller is passed to an [Effect] class, then that /// class will take care of calling this method as necessary. double advance(double dt); /// Similar to `advance()`, but makes the effect controller move back in time. /// /// If the supplied amount of time [dt] would push the effect past its /// starting point, then the effect stops at the start and the "leftover" /// portion of [dt] is returned. double recede(double dt); /// Reverts the controller to its initial state, as it was before the start /// of the animation. void setToStart(); /// Puts the controller into its final "completed" state. void setToEnd(); /// This is called by the [Effect] class when the controller is attached to /// that effect. Controllers with children should propagate this to their /// children. void onMount(Effect parent) {} }
flame/packages/flame/lib/src/effects/controllers/effect_controller.dart/0
{'file_path': 'flame/packages/flame/lib/src/effects/controllers/effect_controller.dart', 'repo_id': 'flame', 'token_count': 3488}
import 'dart:ui'; import 'package:flame/src/effects/controllers/effect_controller.dart'; import 'package:flame/src/effects/move_effect.dart'; import 'package:flame/src/effects/provider_interfaces.dart'; import 'package:vector_math/vector_math_64.dart'; /// This effect will move the target along the specified path, which may /// contain curved segments, but must be simply-connected. /// /// If `absolute` is false (default), the `path` argument will be taken as /// relative to the target's position at the start of the effect. It is /// recommended in this case to have a path that starts at the origin in order /// to avoid sudden jumps in the target's position. /// /// If `absolute` flag is true, then the `path` will be assumed to be given in /// absolute coordinate space and the target will be placed at the beginning of /// the path when the effect starts. /// /// The `oriented` flag controls the direction of the target as it follows the /// path. If this flag is false (default), the target keeps its original /// orientation. If the flag is true, the target is automatically rotated as it /// follows the path so that it is always oriented tangent to the path. When /// using this flag, make sure that the effect is applied to a target that /// actually supports rotations. class MoveAlongPathEffect extends MoveEffect { MoveAlongPathEffect( Path path, EffectController controller, { bool absolute = false, bool oriented = false, PositionProvider? target, void Function()? onComplete, }) : _isAbsolute = absolute, _followDirection = oriented, super( controller, target, onComplete: onComplete, ) { final metrics = path.computeMetrics().toList(); if (metrics.length != 1) { throw ArgumentError( 'Only single-contour paths are allowed in MoveAlongPathEffect', ); } _pathMetric = metrics[0]; _pathLength = _pathMetric.length; assert(_pathLength > 0); } /// If true, the path is considered _absolute_, i.e. the component will be /// put onto the start of the path and then follow that path. If false, the /// path is considered _relative_, i.e. this path is added as an offset to /// the current position of the target. final bool _isAbsolute; /// If true, then not only the target's position will follow the path, but /// also the target's angle of rotation. final bool _followDirection; /// The path that the target will follow. late final PathMetric _pathMetric; /// Pre-computed length of the path. late final double _pathLength; /// Position offset that was applied to the target on the previous iteration. /// This is needed in order to make updates to `target.position` incremental /// (which in turn is necessary in order to allow multiple effects to be able /// to apply to the same target simultaneously). late Vector2 _lastOffset; /// Target's angle of rotation on the previous iteration. late double _lastAngle; @override void onStart() { _lastOffset = Vector2.zero(); _lastAngle = 0; if (_followDirection) { assert( target is AngleProvider, 'An `oriented` MoveAlongPathEffect cannot be applied to a target that ' 'does not support rotation', ); } if (_isAbsolute) { final start = _pathMetric.getTangentForOffset(0)!; target.position.x = _lastOffset.x = start.position.dx; target.position.y = _lastOffset.y = start.position.dy; if (_followDirection) { (target as AngleProvider).angle = _lastAngle = -start.angle; } } } @override void apply(double progress) { final distance = progress * _pathLength; final tangent = _pathMetric.getTangentForOffset(distance)!; final offset = tangent.position; target.position.x += offset.dx - _lastOffset.x; target.position.y += offset.dy - _lastOffset.y; _lastOffset.x = offset.dx; _lastOffset.y = offset.dy; if (_followDirection) { (target as AngleProvider).angle += -tangent.angle - _lastAngle; _lastAngle = -tangent.angle; } } @override double measure() => _pathLength; }
flame/packages/flame/lib/src/effects/move_along_path_effect.dart/0
{'file_path': 'flame/packages/flame/lib/src/effects/move_along_path_effect.dart', 'repo_id': 'flame', 'token_count': 1326}
import 'package:flame/src/components/mixins/draggable.dart'; import 'package:flame/src/events/component_mixins/drag_callbacks.dart'; import 'package:flame/src/events/flame_game_mixins/has_draggable_components.dart'; /// Mixin that can be added to a game to indicate that is has [Draggable] /// components (in addition to components with [DragCallbacks]). /// /// This is a temporary mixin to facilitate the transition between the old and /// the new event system. In the future it will be deprecated. mixin HasDraggablesBridge on HasDraggableComponents {}
flame/packages/flame/lib/src/events/flame_game_mixins/has_draggables_bridge.dart/0
{'file_path': 'flame/packages/flame/lib/src/events/flame_game_mixins/has_draggables_bridge.dart', 'repo_id': 'flame', 'token_count': 162}
import 'package:flame/src/components/component.dart'; import 'package:flame/src/events/flame_game_mixins/has_draggable_components.dart'; import 'package:flame/src/events/flame_game_mixins/has_tappable_components.dart'; import 'package:meta/meta.dart'; /// [TaggedComponent] is a utility class that represents a pair of a component /// and a pointer id. /// /// This class is used by [HasTappableComponents] and [HasDraggableComponents] /// to store information about which components were affected by which pointer /// event, so that subsequent events can be reliably delivered to the same /// components. @internal @immutable class TaggedComponent<T extends Component> { const TaggedComponent(this.pointerId, this.component); final int pointerId; final T component; @override int get hashCode => Object.hash(pointerId, component); @override bool operator ==(Object other) { return other is TaggedComponent<T> && other.pointerId == pointerId && other.component == component; } }
flame/packages/flame/lib/src/events/tagged_component.dart/0
{'file_path': 'flame/packages/flame/lib/src/events/tagged_component.dart', 'repo_id': 'flame', 'token_count': 305}
import 'dart:ui'; import 'package:flame/palette.dart'; import 'package:flame/src/extensions/vector2.dart'; export 'dart:ui' show Canvas; extension CanvasExtension on Canvas { void scaleVector(Vector2 vector) { scale(vector.x, vector.y); } void translateVector(Vector2 vector) { translate(vector.x, vector.y); } /// Renders a point as a square of size [size] (default 1 logical pixel) using /// the provided [paint] (default solid magenta). /// /// This is mostly useful for debugging. void renderPoint( Vector2 point, { double size = 1.0, Paint? paint, }) { final rect = (point - Vector2.all(size / 2)) & Vector2.all(size); drawRect(rect, paint ?? BasicPalette.magenta.paint()); } /// Utility method to render stuff on a specific place in an isolated way. /// /// Some render methods don't allow to pass a vector. /// This method translate the canvas before rendering your fn. /// The changes are reset after the fn is run. void renderAt(Vector2 p, void Function(Canvas) fn) { save(); translateVector(p); fn(this); restore(); } /// Utility method to render stuff rotated at specific angle. /// /// It rotates the canvas around the center of rotation. /// The changes are reset after the fn is run. void renderRotated( double angle, Vector2 rotationCenter, void Function(Canvas) fn, ) { save(); translateVector(rotationCenter); rotate(angle); translateVector(-rotationCenter); fn(this); restore(); } }
flame/packages/flame/lib/src/extensions/canvas.dart/0
{'file_path': 'flame/packages/flame/lib/src/extensions/canvas.dart', 'repo_id': 'flame', 'token_count': 508}
import 'package:flutter/scheduler.dart'; /// Internal class that drives the game loop by calling the provided [callback] /// function on every Flutter animation frame. /// /// After creating a GameLoop, call `start()` in order to make it actually run. /// When a GameLoop object is no longer needed, it must be `dispose()`d. /// /// For example: /// ```dart /// final gameLoop = GameLoop(onGameLoopTick); /// gameLoop.start(); /// ... /// gameLoop.dispose(); /// ``` class GameLoop { GameLoop(this.callback) { _ticker = Ticker(_tick); } /// Function to be called on every Flutter rendering frame. /// /// This function takes a single parameter `dt`, which is the amount of time /// passed since the previous invocation of this function. The time is /// measured in seconds, with microsecond precision. The argument will be /// equal to 0 on first invocation of the callback. void Function(double dt) callback; /// Total amount of time passed since the game loop was started. /// /// This variable is updated on every rendering frame, just before the /// [callback] is invoked. It will be equal to zero while the game loop is /// stopped. It is also guaranteed to be equal to zero on the first invocation /// of the callback. Duration _previous = Duration.zero; /// Internal object responsible for periodically calling the [callback] /// function. late final Ticker _ticker; /// This method is periodically invoked by the [_ticker]. void _tick(Duration timestamp) { final durationDelta = timestamp - _previous; final dt = durationDelta.inMicroseconds / Duration.microsecondsPerSecond; _previous = timestamp; callback(dt); } /// Start running the game loop. The game loop is created in a paused state, /// so this must be called once in order to make the loop running. Calling /// this method again when the game loop already runs is a noop. void start() { if (!_ticker.isActive) { _ticker.start(); } } /// Stop the game loop. While it is stopped, the time "freezes". When the /// game loop is started again, the [callback] will NOT be made aware that /// any amount of time has passed. void stop() { _ticker.stop(); _previous = Duration.zero; } /// Call this before deleting the [GameLoop] object. /// /// The [GameLoop] will no longer be usable after this method is called. You /// do not have to stop the game loop before disposing of it. void dispose() { _ticker.dispose(); } }
flame/packages/flame/lib/src/game/game_loop.dart/0
{'file_path': 'flame/packages/flame/lib/src/game/game_loop.dart', 'repo_id': 'flame', 'token_count': 708}
import 'package:flame/extensions.dart'; import 'package:flame/src/geometry/line.dart'; /// A [LineSegment] represent a segment of an infinitely long line, it is the /// segment between the [from] and [to] vectors (inclusive). class LineSegment { final Vector2 from; final Vector2 to; LineSegment(this.from, this.to); factory LineSegment.zero() => LineSegment(Vector2.zero(), Vector2.zero()); /// Returns an empty list if there are no intersections between the segments /// If the segments are concurrent, the intersecting point is returned as a /// list with a single point List<Vector2> intersections(LineSegment otherSegment) { final result = toLine().intersections(otherSegment.toLine()); if (result.isNotEmpty) { // The lines are not parallel final intersection = result.first; if (containsPoint(intersection) && otherSegment.containsPoint(intersection)) { // The intersection point is on both line segments return result; } } else { // In here we know that the lines are parallel final overlaps = { if (otherSegment.containsPoint(from)) from, if (otherSegment.containsPoint(to)) to, if (containsPoint(otherSegment.from)) otherSegment.from, if (containsPoint(otherSegment.to)) otherSegment.to, }; if (overlaps.isNotEmpty) { final sum = Vector2.zero(); overlaps.forEach(sum.add); return [sum..scale(1 / overlaps.length)]; } } return []; } bool containsPoint(Vector2 point, {double epsilon = 0.000001}) { final delta = to - from; final crossProduct = (point.y - from.y) * delta.x - (point.x - from.x) * delta.y; // compare versus epsilon for floating point values if (crossProduct.abs() > epsilon) { return false; } final dotProduct = (point.x - from.x) * delta.x + (point.y - from.y) * delta.y; if (dotProduct < 0) { return false; } final squaredLength = from.distanceToSquared(to); if (dotProduct > squaredLength) { return false; } return true; } bool pointsAt(Line line) { final result = toLine().intersections(line); if (result.isNotEmpty) { final delta = to - from; final intersection = result.first; final intersectionDelta = intersection - to; // Whether the two points [from] and [through] forms a ray that points on // the line represented by this object if (delta.x.sign == intersectionDelta.x.sign && delta.y.sign == intersectionDelta.y.sign) { return true; } } return false; } Line toLine() => Line.fromPoints(from, to); @override String toString() { return '[$from, $to]'; } }
flame/packages/flame/lib/src/geometry/line_segment.dart/0
{'file_path': 'flame/packages/flame/lib/src/geometry/line_segment.dart', 'repo_id': 'flame', 'token_count': 1031}
import 'dart:ui'; import 'package:flame/src/components/component.dart'; import 'package:flame/src/extensions/vector2.dart'; import 'package:flame/src/particles/particle.dart'; class ComponentParticle extends Particle { final Component component; final Vector2? size; final Paint? overridePaint; ComponentParticle({ required this.component, this.size, this.overridePaint, super.lifespan, }); @override void render(Canvas canvas) { component.render(canvas); } @override void update(double dt) { super.update(dt); component.update(dt); } }
flame/packages/flame/lib/src/particles/component_particle.dart/0
{'file_path': 'flame/packages/flame/lib/src/particles/component_particle.dart', 'repo_id': 'flame', 'token_count': 211}
import 'dart:typed_data'; import 'dart:ui'; import 'package:flame/src/anchor.dart'; import 'package:flame/src/text/text_renderer.dart'; import 'package:vector_math/vector_math_64.dart'; /// [TextRenderer] implementation that uses a spritesheet of various font glyphs /// to render text. /// /// For example, suppose there is a spritesheet with sprites for characters from /// A to Z. Mapping these sprites into a [SpriteFontRenderer] allows then to /// write text using these sprite images as the font. /// /// Currently, this class supports monospace fonts only -- the widths and the /// heights of all characters must be the same. /// Extra space between letters can be added via the [letterSpacing] parameter /// (it can also be negative to "squish" characters together). Finally, the /// [scale] parameter allows scaling the font to be bigger/smaller relative to /// its size in the source image. /// /// The [paint] parameter is used to composite the character images onto the /// canvas. Its default value will draw the character images as-is. Changing /// the opacity of the paint's color will make the text semi-transparent. class SpriteFontRenderer extends TextRenderer { SpriteFontRenderer({ required this.source, required double charWidth, required double charHeight, required Map<String, GlyphData> glyphs, this.scale = 1, this.letterSpacing = 0, }) : scaledCharWidth = charWidth * scale, scaledCharHeight = charHeight * scale, _glyphs = glyphs.map((char, rect) { assert( char.length == 1, 'A glyph must have a single character: "$char"', ); final info = _GlyphInfo(); info.srcLeft = rect.left; info.srcTop = rect.top; info.srcRight = rect.right ?? rect.left + charWidth; info.srcBottom = rect.bottom ?? rect.top + charHeight; info.rstSCos = scale; info.rstTy = (charHeight - (info.srcBottom - info.srcTop)) * scale; info.width = charWidth * scale; info.height = charHeight * scale; return MapEntry(char.codeUnitAt(0), info); }); final Image source; final Map<int, _GlyphInfo> _glyphs; final double letterSpacing; final double scale; final double scaledCharWidth; final double scaledCharHeight; bool get isMonospace => true; Paint paint = Paint()..color = const Color(0xFFFFFFFF); @override double measureTextHeight(String text) => scaledCharHeight; @override double measureTextWidth(String text) { final n = text.length; return n > 0 ? scaledCharWidth * n + letterSpacing * (n - 1) : 0; } @override Vector2 measureText(String text) { return Vector2(measureTextWidth(text), measureTextHeight(text)); } @override void render( Canvas canvas, String text, Vector2 position, { Anchor anchor = Anchor.topLeft, }) { final rstTransforms = Float32List(4 * text.length); final rects = Float32List(4 * text.length); var j = 0; var x0 = position.x; final y0 = position.y; for (final glyph in _textToGlyphs(text)) { rects[j + 0] = glyph.srcLeft; rects[j + 1] = glyph.srcTop; rects[j + 2] = glyph.srcRight; rects[j + 3] = glyph.srcBottom; rstTransforms[j + 0] = glyph.rstSCos; rstTransforms[j + 1] = glyph.rstSSin; rstTransforms[j + 2] = x0 + glyph.rstTx; rstTransforms[j + 3] = y0 + glyph.rstTy; x0 += glyph.width + letterSpacing; j += 4; } canvas.drawRawAtlas(source, rstTransforms, rects, null, null, null, paint); } Iterable<_GlyphInfo> _textToGlyphs(String text) { return text.codeUnits.map(_getGlyphFromCodeUnit); } _GlyphInfo _getGlyphFromCodeUnit(int i) { final glyph = _glyphs[i]; if (glyph == null) { throw ArgumentError('No glyph for character "${String.fromCharCode(i)}"'); } return glyph; } } class GlyphData { const GlyphData({ required this.left, required this.top, this.right, this.bottom, }); const GlyphData.fromLTWH(this.left, this.top, double width, double height) : right = left + width, bottom = top + height; const GlyphData.fromLTRB(this.left, this.top, this.right, this.bottom); final double left; final double top; final double? right; final double? bottom; } class _GlyphInfo { double srcLeft = 0; double srcTop = 0; double srcRight = 0; double srcBottom = 0; double rstSCos = 1; double rstSSin = 0; double rstTx = 0; double rstTy = 0; double width = 0; double height = 0; }
flame/packages/flame/lib/src/text/sprite_font_renderer.dart/0
{'file_path': 'flame/packages/flame/lib/src/text/sprite_font_renderer.dart', 'repo_id': 'flame', 'token_count': 1705}
import 'package:flame/components.dart'; import 'package:flame/input.dart'; import 'package:flame/src/game/game_widget/game_widget.dart'; import 'package:flame_test/flame_test.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import '../game/flame_game_test.dart'; void main() { group('ButtonComponent', () { testWithGame<GameWithTappables>( 'correctly registers taps', GameWithTappables.new, (game) async { var pressedTimes = 0; var releasedTimes = 0; final initialGameSize = Vector2.all(100); final componentSize = Vector2.all(10); final buttonPosition = Vector2.all(100); late final ButtonComponent button; game.onGameResize(initialGameSize); await game.ensureAdd( button = ButtonComponent( button: RectangleComponent(size: componentSize), onPressed: () => pressedTimes++, onReleased: () => releasedTimes++, position: buttonPosition, size: componentSize, ), ); expect(pressedTimes, 0); expect(releasedTimes, 0); game.onTapDown(1, createTapDownEvent(game)); expect(pressedTimes, 0); expect(releasedTimes, 0); game.onTapUp( 1, createTapUpEvent( game, globalPosition: button.positionOfAnchor(Anchor.center).toOffset(), ), ); expect(pressedTimes, 0); expect(releasedTimes, 0); game.onTapDown( 1, createTapDownEvent( game, globalPosition: buttonPosition.toOffset(), ), ); expect(pressedTimes, 1); expect(releasedTimes, 0); game.onTapUp( 1, createTapUpEvent( game, globalPosition: buttonPosition.toOffset(), ), ); expect(pressedTimes, 1); expect(releasedTimes, 1); }); testWithGame<GameWithTappables>( 'correctly registers taps onGameResize', GameWithTappables.new, (game) async { var pressedTimes = 0; var releasedTimes = 0; final initialGameSize = Vector2.all(100); final componentSize = Vector2.all(10); final buttonPosition = Vector2.all(100); late final ButtonComponent button; game.onGameResize(initialGameSize); await game.ensureAdd( button = ButtonComponent( button: RectangleComponent(size: componentSize), onPressed: () => pressedTimes++, onReleased: () => releasedTimes++, position: buttonPosition, size: componentSize, ), ); final previousPosition = button.positionOfAnchor(Anchor.center).toOffset(); game.onGameResize(initialGameSize * 2); game.onTapDown( 1, createTapDownEvent( game, globalPosition: previousPosition, ), ); expect(pressedTimes, 1); expect(releasedTimes, 0); game.onTapUp( 1, createTapUpEvent( game, globalPosition: previousPosition, ), ); expect(pressedTimes, 1); expect(releasedTimes, 1); }); testWidgets( '[#1723] can be pressed while the engine is paused', (tester) async { final game = GameWithTappables(); game.add( ButtonComponent( button: CircleComponent(radius: 40), position: Vector2(400, 300), anchor: Anchor.center, onPressed: () { game.pauseEngine(); game.overlays.add('pause-menu'); }, ), ); await tester.pumpWidget( GameWidget( game: game, overlayBuilderMap: { 'pause-menu': (context, _) { return SimpleStatelessWidget( build: (context) { return Center( child: OutlinedButton( onPressed: () { game.overlays.remove('pause-menu'); game.resumeEngine(); }, child: const Text('Resume'), ), ); }, ); }, }, ), ); await tester.pump(); await tester.pump(); await tester.tapAt(const Offset(400, 300)); await tester.pump(const Duration(seconds: 1)); expect(game.paused, true); await tester.tapAt(const Offset(400, 300)); await tester.pump(const Duration(seconds: 1)); expect(game.paused, false); }, ); }); } class SimpleStatelessWidget extends StatelessWidget { const SimpleStatelessWidget({ required Widget Function(BuildContext) build, super.key, }) : _build = build; final Widget Function(BuildContext) _build; @override Widget build(BuildContext context) => _build(context); }
flame/packages/flame/test/components/button_component_test.dart/0
{'file_path': 'flame/packages/flame/test/components/button_component_test.dart', 'repo_id': 'flame', 'token_count': 2344}
import 'package:flame/components.dart'; import 'package:flame_test/flame_test.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { group('ParentIsA', () { testWithFlameGame('successfully sets the parent link', (game) async { final parent = _ParentComponent()..addToParent(game); final component = _TestComponent()..addToParent(parent); await game.ready(); expect(component.isMounted, true); expect(component.parent, isA<_ParentComponent>()); }); testWithFlameGame( 'throws assertion error if the wrong parent is used', (game) async { final parent = _DifferentComponent()..addToParent(game); await game.ready(); expect( () { parent.add(_TestComponent()); game.update(0); }, failsAssert('Parent must be of type _ParentComponent'), ); }, ); }); } class _ParentComponent extends Component {} class _DifferentComponent extends Component {} class _TestComponent extends Component with ParentIsA<_ParentComponent> {}
flame/packages/flame/test/components/mixins/parent_is_a_test.dart/0
{'file_path': 'flame/packages/flame/test/components/mixins/parent_is_a_test.dart', 'repo_id': 'flame', 'token_count': 405}
import 'package:flame/components.dart'; import 'package:flame/effects.dart'; import 'package:flame/experimental.dart'; import 'package:flame_test/flame_test.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { group('AnchorToEffect', () { testWithFlameGame('simple anchor movement', (game) async { final object = PositionComponent() ..position = Vector2(3, 4) ..anchor = Anchor.bottomRight; game.add(object); await game.ready(); object.add( AnchorToEffect(Anchor.center, EffectController(duration: 1)), ); game.update(0.5); expect(object.position, Vector2(3, 4)); expect(object.anchor.x, closeTo(0.75, 1e-15)); expect(object.anchor.y, closeTo(0.75, 1e-15)); game.update(0.5); expect(object.anchor.x, closeTo(0.5, 1e-15)); expect(object.anchor.y, closeTo(0.5, 1e-15)); }); testWithFlameGame('viewfinder move anchor', (game) async { final world = World()..addToParent(game); final camera = CameraComponent(world: world)..addToParent(game); await game.ready(); expect(camera.viewfinder.anchor, Anchor.center); camera.viewfinder.add( AnchorToEffect(const Anchor(0.2, 0.6), EffectController(duration: 1)), ); for (var t = 0.0; t <= 1.0; t += 0.1) { expect(camera.viewfinder.anchor.x, closeTo(0.5 - 0.3 * t, 1e-15)); expect(camera.viewfinder.anchor.y, closeTo(0.5 + 0.1 * t, 1e-15)); game.update(0.1); } }); }); }
flame/packages/flame/test/effects/anchor_to_effect_test.dart/0
{'file_path': 'flame/packages/flame/test/effects/anchor_to_effect_test.dart', 'repo_id': 'flame', 'token_count': 665}
import 'dart:ui'; import 'package:flame/components.dart'; import 'package:flame/effects.dart'; import 'package:flame/game.dart'; import 'package:flame_test/flame_test.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { group('MoveByEffect', () { test('simple linear motion', () { final game = FlameGame(); game.onGameResize(Vector2(100, 100)); final object = PositionComponent()..position = Vector2(3, 4); game.add(object); game.update(0); object.add( MoveByEffect(Vector2(5, -1), EffectController(duration: 1)), ); game.update(0.5); expect(object.position.x, closeTo(3 + 2.5, 1e-15)); expect(object.position.y, closeTo(4 + -0.5, 1e-15)); game.update(0.5); expect(object.position.x, closeTo(3 + 5, 1e-15)); expect(object.position.y, closeTo(4 + -1, 1e-15)); }); test('#to', () { final game = FlameGame(); game.onGameResize(Vector2(100, 100)); final object = PositionComponent()..position = Vector2(3, 4); game.add(object); game.update(0); object.add( MoveEffect.to(Vector2(5, -1), LinearEffectController(1)), ); game.update(0.5); expect(object.position.x, closeTo(3 * 0.5 + 5 * 0.5, 1e-15)); expect(object.position.y, closeTo(4 * 0.5 + -1 * 0.5, 1e-15)); game.update(0.5); expect(object.position.x, closeTo(5, 1e-15)); expect(object.position.y, closeTo(-1, 1e-15)); }); testWithFlameGame('custom target', (game) async { final rectComponent = _RectComponent() ..rect = const Rect.fromLTRB(10, 20, 50, 40) ..addToParent(game); rectComponent.add( MoveEffect.by( Vector2(3, -3), EffectController(duration: 1), target: _TopLeftCorner(rectComponent), ), ); await game.ready(); expect(rectComponent.rect, const Rect.fromLTRB(10, 20, 50, 40)); game.update(0.5); expect(rectComponent.rect, const Rect.fromLTRB(11.5, 18.5, 50, 40)); game.update(0.5); expect(rectComponent.rect, const Rect.fromLTRB(13, 17, 50, 40)); }); }); } class _RectComponent extends Component { Rect rect = Rect.zero; } class _TopLeftCorner implements PositionProvider { _TopLeftCorner(this.target); _RectComponent target; @override Vector2 get position => Vector2(target.rect.left, target.rect.top); @override set position(Vector2 value) { final rect = target.rect; target.rect = Rect.fromLTRB(value.x, value.y, rect.right, rect.bottom); } }
flame/packages/flame/test/effects/move_by_effect_test.dart/0
{'file_path': 'flame/packages/flame/test/effects/move_by_effect_test.dart', 'repo_id': 'flame', 'token_count': 1106}
import 'dart:math'; import 'package:flame/experimental.dart'; import 'package:flame/game.dart'; import 'package:flame_test/flame_test.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { group('Polygon', () { test('invalid polygon', () { expect( () => Polygon([]), failsAssert('At least 3 vertices are required'), ); expect( () => Polygon([Vector2(1, 5), Vector2.zero()]), failsAssert('At least 3 vertices are required'), ); }); test('simple triangle', () { final polygon = Polygon( [Vector2.zero(), Vector2(0, 60), Vector2(80, 60)], ); expect(polygon.vertices.length, 3); expect(polygon.vertices[0], Vector2(0, 0)); expect(polygon.vertices[1], Vector2(0, 60)); expect(polygon.vertices[2], Vector2(80, 60)); expect(polygon.edges.length, 3); expect(polygon.edges[0], Vector2(-80, -60)); expect(polygon.edges[1], Vector2(0, 60)); expect(polygon.edges[2], Vector2(80, 0)); expect(polygon.perimeter, 100 + 60 + 80); expect(polygon.isConvex, true); expect(polygon.isClosed, true); expect( polygon.aabb, closeToAabb(Aabb2.minMax(Vector2.zero(), Vector2(80, 60))), ); expect(polygon.center, closeToVector(80 / 3, 60 * 2 / 3, epsilon: 1e-14)); expect('$polygon', 'Polygon([[0.0,0.0], [0.0,60.0], [80.0,60.0]])'); }); test('triangle with edges in a wrong order', () { final polygon1 = Polygon( [Vector2(0, 60), Vector2.zero(), Vector2(80, 60)], ); final polygon2 = Polygon( [Vector2(80, 60), Vector2.zero(), Vector2(0, 60)], ); expect(polygon1.vertices, polygon2.vertices); expect(polygon1.edges, polygon2.edges); expect(polygon1.isConvex, true); expect(polygon2.isConvex, true); }); test('explicit `convex` flag', () { final polygon = Polygon( [Vector2(0, 60), Vector2.zero(), Vector2(80, 60)], convex: true, ); // The polygon is marked as "convex", but the vertices are in the wrong // order. As a result, all points will be detected as being "outside". expect(polygon.isConvex, true); expect(polygon.vertices[0], Vector2(0, 60)); expect(polygon.vertices[1], Vector2(0, 0)); expect(polygon.vertices[2], Vector2(80, 60)); expect(polygon.containsPoint(Vector2(0, 0)), false); expect(polygon.containsPoint(Vector2(10, 30)), false); expect(polygon.containsPoint(Vector2(-10, 30)), false); expect(polygon.containsPoint(Vector2(100, 30)), false); expect(polygon.containsPoint(Vector2(100, 100)), false); }); test('asPath', () { final polygon = Polygon( [Vector2.zero(), Vector2(0, 60), Vector2(80, 60)], ); final path = polygon.asPath(); final metrics = path.computeMetrics().toList(); expect(metrics.length, 1); expect(metrics[0].isClosed, true); expect(metrics[0].length, 60 + 80 + 100); }); test('containsPoint', () { final polygon = Polygon( [Vector2.zero(), Vector2(0, 60), Vector2(80, 60)], ); expect(polygon.containsPoint(Vector2(0, 0)), true); expect(polygon.containsPoint(Vector2(1, 0)), false); expect(polygon.containsPoint(Vector2(0, 10)), true); expect(polygon.containsPoint(Vector2(0, 60)), true); expect(polygon.containsPoint(Vector2(20, 30)), true); expect(polygon.containsPoint(Vector2(40, 30)), true); expect(polygon.containsPoint(Vector2(40, 29)), false); expect(polygon.containsPoint(Vector2(41, 30)), false); expect(polygon.containsPoint(Vector2(41, 31)), true); expect(polygon.containsPoint(Vector2(80, 60)), true); expect(polygon.containsPoint(Vector2(70, 55)), true); expect(polygon.containsPoint(Vector2(80, 61)), false); }); test('move', () { final polygon = Polygon( [Vector2.zero(), Vector2(0, 60), Vector2(80, 60)], ); // Force computing (and caching) the aabb and the center expect(polygon.aabb.min, Vector2.zero()); expect(polygon.center, closeToVector(80 / 3, 40, epsilon: 1e-14)); polygon.move(Vector2(5, -10)); expect( polygon.vertices, [Vector2(5, -10), Vector2(5, 50), Vector2(85, 50)], ); expect( polygon.edges, [Vector2(-80, -60), Vector2(0, 60), Vector2(80, 0)], ); expect( polygon.aabb, closeToAabb(Aabb2.minMax(Vector2(5, -10), Vector2(85, 50))), ); expect(polygon.center, closeToVector(95 / 3, 30, epsilon: 1e-14)); }); test('support', () { final polygon = Polygon([ Vector2(10, 0), Vector2(0, 30), Vector2(30, 70), Vector2(80, 40), ]); expect(polygon.isConvex, true); expect(polygon.support(Vector2(1, 0)), Vector2(80, 40)); expect(polygon.support(Vector2(-1, 0)), Vector2(0, 30)); expect(polygon.support(Vector2(0, 1)), Vector2(30, 70)); expect(polygon.support(Vector2(0, -1)), Vector2(10, 0)); expect(polygon.support(Vector2(-1, -1)), Vector2(10, 0)); expect(polygon.support(Vector2(1, 1)), Vector2(80, 40)); }); test('weird-shape polygon', () { final polygon = Polygon([ Vector2(20, 40), Vector2(50, 30), Vector2(70, 60), Vector2(50, 40), Vector2(40, 60), Vector2(90, 80), Vector2(100, 20), Vector2(90, 50), Vector2(60, 10), Vector2(40, 25), ]); expect(polygon.edges.length, 10); expect(polygon.isConvex, false); expect(polygon.vertices[0], Vector2(20, 40)); expect( polygon.center.x, (20 + 50 + 70 + 50 + 40 + 90 + 100 + 90 + 60 + 40) / 10, ); expect( polygon.center.y, (40 + 30 + 60 + 40 + 60 + 80 + 20 + 50 + 10 + 25) / 10, ); expect(polygon.aabb.min, Vector2(20, 10)); expect(polygon.aabb.max, Vector2(100, 80)); // containsPoint expect(polygon.containsPoint(Vector2(40, 25)), true); expect(polygon.containsPoint(Vector2(40, 30)), true); expect(polygon.containsPoint(Vector2(40, 60)), true); expect(polygon.containsPoint(Vector2(60, 20)), true); expect(polygon.containsPoint(Vector2(60, 30)), true); expect(polygon.containsPoint(Vector2(65, 25)), true); expect(polygon.containsPoint(Vector2(60, 40)), true); expect(polygon.containsPoint(Vector2(50, 50)), true); expect(polygon.containsPoint(Vector2(60, 60)), true); expect(polygon.containsPoint(Vector2(80, 40)), true); expect(polygon.containsPoint(Vector2(80, 70)), true); expect(polygon.containsPoint(Vector2(90, 80)), true); expect(polygon.containsPoint(Vector2(90, 50)), true); expect(polygon.containsPoint(Vector2(95, 50)), true); expect(polygon.containsPoint(Vector2(97, 30)), true); expect(polygon.containsPoint(Vector2(40, 40)), false); expect(polygon.containsPoint(Vector2(40, 50)), false); expect(polygon.containsPoint(Vector2(50, 35)), false); expect(polygon.containsPoint(Vector2(60, 49)), false); expect(polygon.containsPoint(Vector2(90, 40)), false); expect(polygon.containsPoint(Vector2(100, 40)), false); }); test('project', () { final polygon = Polygon([ Vector2(0, 20), Vector2(20, 40), Vector2(40, 20), Vector2(20, 0), ]); expect(polygon.isConvex, true); final transform = Transform2D() ..angle = pi / 4 ..offset = Vector2(-20, -20); final result = polygon.project(transform); final a = 10 * sqrt(2); expect(result, isA<Polygon>()); expect((result as Polygon).edges.length, 4); expect(result.vertices[0], closeToVector(-a, -a, epsilon: 1e-14)); expect(result.vertices[1], closeToVector(-a, a, epsilon: 1e-14)); expect(result.vertices[2], closeToVector(a, a, epsilon: 1e-14)); expect(result.vertices[3], closeToVector(a, -a, epsilon: 1e-14)); }); test('project with target', () { final polygon = Polygon([ Vector2(0, 20), Vector2(20, 40), Vector2(40, 20), Vector2(20, 0), ]); final transform = Transform2D() ..position = Vector2(10, 10) ..scale = Vector2(2, 1); final target = Polygon(List.generate(4, (_) => Vector2.zero())); final result = polygon.project(transform, target); expect(result, isA<Polygon>()); expect(result, target); expect((result as Polygon).edges.length, 4); expect(result.vertices[0], Vector2(10, 30)); expect(result.vertices[1], Vector2(50, 50)); expect(result.vertices[2], Vector2(90, 30)); expect(result.vertices[3], Vector2(50, 10)); }); test('project with target and reflection transform', () { final polygon = Polygon([ Vector2(0, 20), Vector2(20, 40), Vector2(40, 20), Vector2(20, 0), ]); final transform = Transform2D() ..position = Vector2(10, 10) ..scale = Vector2(-2, 1); final target = Polygon(List.generate(4, (_) => Vector2.zero())); final result = polygon.project(transform, target); expect(result, isA<Polygon>()); expect(result, target); expect((result as Polygon).edges.length, 4); expect(result.isConvex, true); expect(result.vertices[0], Vector2(-30, 10)); expect(result.vertices[1], Vector2(-70, 30)); expect(result.vertices[2], Vector2(-30, 50)); expect(result.vertices[3], Vector2(10, 30)); }); test('project with wrong-shape target', () { final z = Vector2.zero(); final polygon = Polygon([z, z, z, z, z]); final target = Polygon([z, z, z]); final transform = Transform2D()..angle = 1; final result = polygon.project(transform, target); expect(result == target, false); expect(result, isA<Polygon>()); expect((result as Polygon).edges.length, 5); expect(target.edges.length, 3); expect(result.vertices, [z, z, z, z, z]); expect(result.edges, [z, z, z, z, z]); expect(result.isConvex, true); }); }); }
flame/packages/flame/test/experimental/geometry/shapes/polygon_test.dart/0
{'file_path': 'flame/packages/flame/test/experimental/geometry/shapes/polygon_test.dart', 'repo_id': 'flame', 'token_count': 4575}
import 'package:flame/game.dart'; import 'package:flame/input.dart'; import 'package:flame_test/flame_test.dart'; import 'package:flutter_test/flutter_test.dart'; class _HorizontalDragGame extends FlameGame with HorizontalDragDetector { bool horizontalDragStarted = false; bool horizontalDragEnded = false; @override void onHorizontalDragStart(_) { horizontalDragStarted = true; } @override void onHorizontalDragEnd(_) { horizontalDragEnded = true; } } class _VerticalDragGame extends FlameGame with VerticalDragDetector { bool verticalDragStarted = false; bool verticalDragEnded = false; @override void onVerticalDragStart(_) { verticalDragStarted = true; } @override void onVerticalDragEnd(_) { verticalDragEnded = true; } } class _PanGame extends FlameGame with PanDetector { bool panStarted = false; bool panEnded = false; @override void onPanStart(_) { panStarted = true; } @override void onPanEnd(_) { panEnded = true; } } void main() { final horizontalGame = FlameTester(_HorizontalDragGame.new); final verticalGame = FlameTester(_VerticalDragGame.new); final panGame = FlameTester(_PanGame.new); group('GameWidget - HorizontalDragDetector', () { horizontalGame.testGameWidget( 'register drags', verify: (game, tester) async { await tester.drag( find.byGame<_HorizontalDragGame>(), const Offset(50, 0), ); expect(game.horizontalDragStarted, isTrue); expect(game.horizontalDragEnded, isTrue); }, ); }); group('GameWidget - VerticalDragDetector', () { verticalGame.testGameWidget( 'register drags', verify: (game, tester) async { await tester.drag( find.byGame<_VerticalDragGame>(), const Offset(50, 0), ); expect(game.verticalDragStarted, isTrue); expect(game.verticalDragEnded, isTrue); }, ); }); group('GameWidget - PanDetector', () { panGame.testGameWidget( 'register drags', verify: (game, tester) async { await tester.drag( find.byGame<_PanGame>(), const Offset(50, 0), ); expect(game.panStarted, isTrue); expect(game.panEnded, isTrue); }, ); }); }
flame/packages/flame/test/game/game_widget/game_widget_drag_test.dart/0
{'file_path': 'flame/packages/flame/test/game/game_widget/game_widget_drag_test.dart', 'repo_id': 'flame', 'token_count': 915}
import 'package:flame/extensions.dart'; import 'package:flame/src/sprite_animation.dart'; import 'package:flame_test/flame_test.dart'; import 'package:mocktail/mocktail.dart'; import 'package:test/test.dart'; void main() { group('SpriteAnimation', () { test('Throw assertion error on empty list of frames', () { expect( () => SpriteAnimation.spriteList([], stepTime: 1), failsAssert('There must be at least one animation frame'), ); }); test('Throw assertion error on non-positive step time', () { final sprite = MockSprite(); expect( () => SpriteAnimation.spriteList([sprite], stepTime: 0), failsAssert('All frames must have positive durations'), ); expect( () => SpriteAnimation.variableSpriteList( [sprite, sprite, sprite], stepTimes: [1, -1, 0], ), failsAssert('All frames must have positive durations'), ); }); test('Throw assertion error when setting non-positive step time', () { final sprite = MockSprite(); final animation = SpriteAnimation.spriteList([sprite, sprite, sprite], stepTime: 1); expect( () => animation.stepTime = 0, failsAssert('Step time must be positive'), ); expect( () => animation.variableStepTimes = [3, 2, 0], failsAssert('All step times must be positive'), ); }); test('onStart called for single-frame animation', () { var counter = 0; final sprite = MockSprite(); final animation = SpriteAnimation.spriteList([sprite], stepTime: 1, loop: false) ..onStart = () => counter++; expect(counter, 0); animation.update(0.5); expect(counter, 1); animation.update(1); expect(counter, 1); }); test('onComplete called for single-frame animation', () { var counter = 0; final sprite = MockSprite(); final animation = SpriteAnimation.spriteList([sprite], stepTime: 1, loop: false) ..onComplete = () => counter++; expect(counter, 0); animation.update(0.5); expect(counter, 0); animation.update(0.5); expect(counter, 1); animation.update(1); expect(counter, 1); }); test( 'verify call is being made at first of frame for multi-frame animation', () { var timePassed = 0.0; const dt = 0.03; var timesCalled = 0; final sprite = MockSprite(); final spriteList = [sprite, sprite, sprite]; final animation = SpriteAnimation.spriteList(spriteList, stepTime: 1, loop: false); animation.onFrame = (index) { expect(timePassed, closeTo(index * 1.0, dt)); timesCalled++; }; while (timePassed <= spriteList.length) { timePassed += dt; animation.update(dt); } expect(timesCalled, spriteList.length); }); test('test sequence of event lifecycle for an animation', () { var animationStarted = false; var animationRunning = false; var animationComplete = false; final sprite = MockSprite(); final animation = SpriteAnimation.spriteList([sprite], stepTime: 1, loop: false); animation.onStart = () { expect(animationStarted, false); expect(animationRunning, false); expect(animationComplete, false); animationStarted = true; animationRunning = true; }; animation.onFrame = (index) { expect(animationStarted, true); expect(animationRunning, true); expect(animationComplete, false); }; animation.onComplete = () { expect(animationStarted, true); expect(animationRunning, true); expect(animationComplete, false); animationComplete = true; }; animation.update(1); expect(animationComplete, true); }); test('completed completes', () { final sprite = MockSprite(); final animation = SpriteAnimation.spriteList( [sprite], stepTime: 1, loop: false, ); expectLater(animation.completed, completes); animation.update(1); }); test( 'completed completes when the animation has already completed', () async { final sprite = MockSprite(); final animation = SpriteAnimation.spriteList( [sprite], stepTime: 1, loop: false, ); animation.update(1); expectLater(animation.completed, completes); }, ); test( "completed doesn't complete when the animation is yet to complete", () async { final sprite = MockSprite(); final animation = SpriteAnimation.spriteList( [sprite], stepTime: 1, loop: false, ); expectLater(animation.completed, doesNotComplete); }, ); test( "completed doesn't complete when animation is looping", () async { final sprite = MockSprite(); final animation = SpriteAnimation.spriteList([sprite], stepTime: 1); expectLater(animation.completed, doesNotComplete); }, ); test( "completed doesn't complete when animation is looping and on last frame", () async { final sprite = MockSprite(); final animation = SpriteAnimation.spriteList([sprite], stepTime: 1); animation.update(1); expectLater(animation.completed, doesNotComplete); }, ); }); group('SpriteAnimationData', () { test( 'throws assertion error when amountPerRow is greater than amount', () { expect( () => SpriteAnimationData.variable( amount: 5, stepTimes: List.filled(5, 0.1), textureSize: Vector2(50, 50), amountPerRow: 10, ), failsAssert(), ); }, ); test('creates a new SpriteAnimationData using the range constructor', () { final animationData = SpriteAnimationData.range( start: 6, end: 11, amount: 18, stepTimes: [0.1, 0.2, 0.3, 0.4, 0.5, 0.6], amountPerRow: 6, textureSize: Vector2(1, 1), ); expect(animationData.frames.length, 6); expect( animationData.frames.map((f) => f.stepTime), [0.1, 0.2, 0.3, 0.4, 0.5, 0.6], ); expect(animationData.frames.map((f) => f.srcPosition), [ Vector2(0, 1), Vector2(1, 1), Vector2(2, 1), Vector2(3, 1), Vector2(4, 1), Vector2(5, 1), ]); }); }); } class MockSprite extends Mock implements Sprite {}
flame/packages/flame/test/sprite_animation_test.dart/0
{'file_path': 'flame/packages/flame/test/sprite_animation_test.dart', 'repo_id': 'flame', 'token_count': 2833}
part of 'inventory_bloc.dart'; abstract class InventoryEvent extends Equatable { const InventoryEvent(); } class WeaponEquipped extends InventoryEvent { final Weapon weapon; const WeaponEquipped(this.weapon); @override List<Object?> get props => [weapon]; } class NextWeaponEquipped extends InventoryEvent { const NextWeaponEquipped(); @override List<Object?> get props => []; }
flame/packages/flame_bloc/example/lib/src/inventory/bloc/inventory_event.dart/0
{'file_path': 'flame/packages/flame_bloc/example/lib/src/inventory/bloc/inventory_event.dart', 'repo_id': 'flame', 'token_count': 115}
import 'package:flame_bloc/flame_bloc.dart'; import 'package:flame_test/flame_test.dart'; import 'package:flutter_test/flutter_test.dart'; import '../player_cubit.dart'; void main() { group('FlameBlocListener', () { testWithFlameGame( 'onNewsState is called when state changes', (game) async { final bloc = PlayerCubit(); final provider = FlameBlocProvider<PlayerCubit, PlayerState>.value( value: bloc, ); final states = <PlayerState>[]; await game.ensureAdd(provider); final component = FlameBlocListener<PlayerCubit, PlayerState>( onNewState: states.add, ); await provider.ensureAdd(component); bloc.kill(); await Future.microtask(() {}); expect(states, equals([PlayerState.dead])); }, ); testWithFlameGame( 'onNewsState is not called when listenWhen returns false', (game) async { final bloc = PlayerCubit(); final provider = FlameBlocProvider<PlayerCubit, PlayerState>.value( value: bloc, ); final states = <PlayerState>[]; await game.ensureAdd(provider); final component = FlameBlocListener<PlayerCubit, PlayerState>( onNewState: states.add, listenWhen: (_, __) => false, ); await provider.ensureAdd(component); bloc.kill(); await Future.microtask(() {}); expect(states, isEmpty); }, ); testWithFlameGame( 'a bloc can be explicitly passed', (game) async { final bloc = PlayerCubit(); final states = <PlayerState>[]; final component = FlameBlocListener<PlayerCubit, PlayerState>( bloc: bloc, onNewState: states.add, ); await game.ensureAdd(component); bloc.kill(); await Future.microtask(() {}); expect(states, equals([PlayerState.dead])); }, ); }); }
flame/packages/flame_bloc/test/src/flame_bloc_listener_test.dart/0
{'file_path': 'flame/packages/flame_bloc/test/src/flame_bloc_listener_test.dart', 'repo_id': 'flame', 'token_count': 839}
import 'package:flame/components.dart'; import 'package:flame/game.dart'; import 'package:flame/input.dart'; import 'package:flame_fire_atlas/flame_fire_atlas.dart'; import 'package:flutter/material.dart'; void main() { WidgetsFlutterBinding.ensureInitialized(); final game = ExampleGame(); runApp(GameWidget(game: game)); } class ExampleGame extends FlameGame with TapDetector { late FireAtlas _atlas; @override Future<void> onLoad() async { _atlas = await loadFireAtlas('caveace.fa'); add( SpriteAnimationComponent( size: Vector2(150, 100), animation: _atlas.getAnimation('shooting_ptero'), )..y = 50, ); add( SpriteAnimationComponent( size: Vector2(150, 100), animation: _atlas.getAnimation('bomb_ptero'), ) ..y = 50 ..x = 200, ); add( SpriteComponent(size: Vector2(50, 50), sprite: _atlas.getSprite('bullet')) ..y = 200, ); add( SpriteComponent(size: Vector2(50, 50), sprite: _atlas.getSprite('shield')) ..x = 100 ..y = 200, ); add( SpriteComponent(size: Vector2(50, 50), sprite: _atlas.getSprite('ham')) ..x = 200 ..y = 200, ); } @override void onTapUp(TapUpInfo details) { add( SpriteAnimationComponent( size: Vector2(100, 100), animation: _atlas.getAnimation('explosion'), removeOnFinish: true, ) ..anchor = Anchor.center ..position = details.eventPosition.game, ); } }
flame/packages/flame_fire_atlas/example/lib/main.dart/0
{'file_path': 'flame/packages/flame_fire_atlas/example/lib/main.dart', 'repo_id': 'flame', 'token_count': 666}
name: flame_flare_example description: Flame sample for using Flare animations publish_to: 'none' version: 0.1.0 environment: sdk: ">=2.17.0 <3.0.0" flutter: ">=3.0.0" dependencies: flame: ^1.2.0 flame_flare: ^1.2.0 flutter: sdk: flutter dev_dependencies: flame_lint: ^0.1.0 flutter: assets: - assets/Bob_Minion.flr
flame/packages/flame_flare/example/pubspec.yaml/0
{'file_path': 'flame/packages/flame_flare/example/pubspec.yaml', 'repo_id': 'flame', 'token_count': 158}
name: flame_forge2d_example description: Flame Forge2D (box2d) samples publish_to: 'none' version: 1.0.0+1 environment: sdk: ">=2.17.0 <3.0.0" flutter: ">=3.0.0" dependencies: dashbook: ^0.1.6 flame_forge2d: ^0.11.0 flutter: sdk: flutter dev_dependencies: flame_lint: ^0.0.1 flutter_test: sdk: flutter flutter: uses-material-design: true
flame/packages/flame_forge2d/example/pubspec.yaml/0
{'file_path': 'flame/packages/flame_forge2d/example/pubspec.yaml', 'repo_id': 'flame', 'token_count': 176}
import 'package:flame/extensions.dart'; import 'package:flame_oxygen/flame_oxygen.dart'; import 'package:flame_oxygen_example/component/timer_component.dart'; import 'package:flame_oxygen_example/component/velocity_component.dart'; import 'package:flame_oxygen_example/main.dart'; import 'package:flutter/material.dart'; class MoveSystem extends System with UpdateSystem, GameRef<ExampleGame> { Query? _query; @override void init() { _query = createQuery([ Has<PositionComponent>(), Has<VelocityComponent>(), ]); } @override void dispose() { _query = null; super.dispose(); } @override void update(double delta) { for (final entity in _query?.entities ?? <Entity>[]) { final velocity = entity.get<VelocityComponent>()!.velocity; final size = entity.get<SizeComponent>()!.size; final position = entity.get<PositionComponent>()!.position ..add(velocity * delta); final screenSize = Vector2.zero() & game!.size; if (!screenSize.containsPoint(position) || !screenSize.containsPoint(position + size)) { velocity.setFrom(-velocity); game!.createEntity( name: '${entity.name} says', position: position + size / 2, size: Vector2.zero(), anchor: Anchor.topCenter, ) ..add<TextComponent, TextInit>( TextInit( 'Kawabunga', style: const TextStyle(color: Colors.blue, fontSize: 12), ), ) ..add<TimerComponent, double>(3); } } } }
flame/packages/flame_oxygen/example/lib/system/move_system.dart/0
{'file_path': 'flame/packages/flame_oxygen/example/lib/system/move_system.dart', 'repo_id': 'flame', 'token_count': 647}
import 'package:flame/extensions.dart'; import 'package:flame/sprite.dart'; import 'package:oxygen/oxygen.dart'; export 'package:flame/sprite.dart'; class SpriteInit { final Sprite sprite; const SpriteInit(this.sprite); factory SpriteInit.fromImage( Image image, { Vector2? srcPosition, Vector2? srcSize, }) { return SpriteInit( Sprite( image, srcPosition: srcPosition, srcSize: srcSize, ), ); } } class SpriteComponent extends Component<SpriteInit> { Sprite? sprite; @override void init([SpriteInit? initValue]) => sprite = initValue?.sprite; @override void reset() => sprite = null; }
flame/packages/flame_oxygen/lib/src/component/sprite_component.dart/0
{'file_path': 'flame/packages/flame_oxygen/lib/src/component/sprite_component.dart', 'repo_id': 'flame', 'token_count': 252}
import 'package:test/test.dart'; void expectDouble( double d1, double d2, { double epsilon = 0.01, String? reason, }) { expect(d1, closeTo(d2, epsilon), reason: reason); }
flame/packages/flame_test/lib/src/expect_double.dart/0
{'file_path': 'flame/packages/flame_test/lib/src/expect_double.dart', 'repo_id': 'flame', 'token_count': 74}
import 'dart:math'; import 'package:flame_test/flame_test.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { group('testRandom', () { // The primary difficulty with testing `testRandom` is that it is a *test* // and tests cannot be invoked within other tests. So, instead we will // invoke `testRandom` in the main body, and then hope that all these tests // will be invoked in order. group('Uses different seed each time', () { final seeds = <int>[]; for (var i = 0; i < 50; i++) { testRandom('a', (Random rnd) => seeds.add(rnd.nextInt(1000000))); } test('verify', () { final nTotal = seeds.length; // Allow some seeds to coincide by pure luck expect(seeds.toSet().length, greaterThanOrEqualTo(nTotal - 2)); }); }); group('Uses specific seed', () { final seeds = <int>[]; testRandom( 'b', (Random rnd) => seeds.add(rnd.nextInt(1000000)), seed: 123456, ); test('verify', () { expect(seeds[0], 778213); }); }); group('Repeat count works', () { final seeds = <int>[]; testRandom( 'c', (Random rnd) => seeds.add(rnd.nextInt(1000000)), repeatCount: 20, ); test('verify', () { expect(seeds.length, 20); expect(seeds.toSet().length, greaterThanOrEqualTo(18)); }); }); }); }
flame/packages/flame_test/test/random_test_test.dart/0
{'file_path': 'flame/packages/flame_test/test/random_test_test.dart', 'repo_id': 'flame', 'token_count': 613}
import 'package:flame/components.dart'; import 'package:flame/flame.dart'; import 'package:flame/game.dart'; import 'package:flame_tiled/flame_tiled.dart'; import 'package:flutter/widgets.dart' hide Animation, Image; import 'package:tiled/tiled.dart'; void main() { runApp(GameWidget(game: TiledGame())); } class TiledGame extends FlameGame { @override Future<void> onLoad() async { await super.onLoad(); final tiledMap = await TiledComponent.load('map.tmx', Vector2.all(16)); add(tiledMap); final objGroup = tiledMap.tileMap.getLayer<ObjectGroup>('AnimatedCoins'); final coins = await Flame.images.load('coins.png'); // We are 100% sure that an object layer named `AnimatedCoins` // exists in the example `map.tmx`. for (final obj in objGroup!.objects) { add( SpriteAnimationComponent( size: Vector2.all(20.0), position: Vector2(obj.x, obj.y), animation: SpriteAnimation.fromFrameData( coins, SpriteAnimationData.sequenced( amount: 8, stepTime: .15, textureSize: Vector2.all(20), ), ), ), ); } } }
flame/packages/flame_tiled/example/lib/main.dart/0
{'file_path': 'flame/packages/flame_tiled/example/lib/main.dart', 'repo_id': 'flame', 'token_count': 509}
import 'package:flutter/material.dart'; import 'package:tutorials_space_shooter/steps/1_getting_started/1_flame_game/code.dart'; import 'package:tutorials_space_shooter/steps/1_getting_started/1_flame_game/tutorial.dart'; import 'package:tutorials_space_shooter/widgets/step_scaffold.dart'; class RunningFlameStep extends StatelessWidget { const RunningFlameStep({super.key}); @override Widget build(BuildContext context) { return const StepScaffold( tutorial: tutorial, game: MyGame(), ); } }
flame/tutorials/space_shooter/lib/steps/1_getting_started/1_flame_game/step.dart/0
{'file_path': 'flame/tutorials/space_shooter/lib/steps/1_getting_started/1_flame_game/step.dart', 'repo_id': 'flame', 'token_count': 188}
import 'package:flame_and_watch/widgets/console/console.dart'; import 'package:flutter/material.dart'; class FlameAndWatchScreen extends StatelessWidget { @override Widget build(_) { return MaterialApp( home: Scaffold( body: Center( child: Console(), ), ), ); } }
flame_and_watch/lib/flame_and_watch.dart/0
{'file_path': 'flame_and_watch/lib/flame_and_watch.dart', 'repo_id': 'flame_and_watch', 'token_count': 131}
export 'moving_behavior.dart'; export 'rotating_behavior.dart'; export 'screen_colliding_behavior.dart';
flame_behaviors/packages/flame_behaviors/example/lib/entities/behaviors/behaviors.dart/0
{'file_path': 'flame_behaviors/packages/flame_behaviors/example/lib/entities/behaviors/behaviors.dart', 'repo_id': 'flame_behaviors', 'token_count': 34}
import 'package:example/behaviors/behaviors.dart'; import 'package:flame/components.dart'; import 'package:flame/game.dart'; import 'package:flame_behaviors/flame_behaviors.dart'; import 'package:flutter/material.dart'; class ExampleGame extends FlameGame with EntityMixin, HasCollisionDetection { @override Future<void> onLoad() async { await add(FpsTextComponent(position: Vector2.zero())); await add(ScreenHitbox()); // Game-specific behaviors await add(SpawningBehavior()); return super.onLoad(); } } void main() { runApp(GameWidget(game: ExampleGame())); }
flame_behaviors/packages/flame_behaviors/example/lib/main.dart/0
{'file_path': 'flame_behaviors/packages/flame_behaviors/example/lib/main.dart', 'repo_id': 'flame_behaviors', 'token_count': 200}
import 'package:flame_behaviors/flame_behaviors.dart'; import 'package:flutter_test/flutter_test.dart'; class _TestBehavior extends HoverableBehavior {} void main() { group('$HoverableBehavior', () { test('can be instantiated', () { expect(_TestBehavior(), isNotNull); }); }); }
flame_behaviors/packages/flame_behaviors/test/src/behaviors/events/hoverable_behavior_test.dart/0
{'file_path': 'flame_behaviors/packages/flame_behaviors/test/src/behaviors/events/hoverable_behavior_test.dart', 'repo_id': 'flame_behaviors', 'token_count': 109}
import 'package:flame/collisions.dart'; import 'package:flame_behaviors/flame_behaviors.dart'; /// Simplified "screen wrapping" behavior, while not perfect it does showcase /// the possibility of acting on collision with non-entities. class ScreenCollisionBehavior extends CollisionBehavior<ScreenHitbox, PositionedEntity> { @override void onCollisionEnd(ScreenHitbox other) { if (parent.position.x < other.position.x) { parent.position.x = other.position.x + other.scaledSize.x; } else if (parent.position.x > other.position.x + other.scaledSize.x) { parent.position.x = other.position.x; } if (parent.position.y < other.position.y) { parent.position.y = other.position.y + other.scaledSize.y; } else if (parent.position.y > other.position.y + other.scaledSize.y) { parent.position.y = other.position.y; } } }
flame_behaviors/packages/flame_steering_behaviors/example/lib/src/behaviors/screen_collision_behavior.dart/0
{'file_path': 'flame_behaviors/packages/flame_steering_behaviors/example/lib/src/behaviors/screen_collision_behavior.dart', 'repo_id': 'flame_behaviors', 'token_count': 308}
import 'dart:math'; import 'package:flame_steering_behaviors/flame_steering_behaviors.dart'; /// {@template wander_behavior} /// Wander steering behavior. /// {@endtemplate} class WanderBehavior<Parent extends Steerable> extends SteeringBehavior<Parent> { /// {@macro wander_behavior} WanderBehavior({ required this.circleDistance, required this.maximumAngle, required double startingAngle, Random? random, }) : _angle = startingAngle, random = random ?? Random(); /// The distance to the circle center of the next target. final double circleDistance; /// The rate at which the wander angle can change in radians. final double maximumAngle; /// The current wander angle in radians. double get angle => _angle; double _angle; /// The random number generator used to calculate the next wander [angle]. final Random random; @override void update(double dt) { steer( Wander( circleDistance: circleDistance, maximumAngle: maximumAngle, angle: _angle, onNewAngle: (angle) => _angle = angle, random: random, ), dt, ); } }
flame_behaviors/packages/flame_steering_behaviors/lib/src/behaviors/wander_behavior.dart/0
{'file_path': 'flame_behaviors/packages/flame_steering_behaviors/lib/src/behaviors/wander_behavior.dart', 'repo_id': 'flame_behaviors', 'token_count': 390}
# Source of linter options: # http://dart-lang.github.io/linter/lints/options/options.html analyzer: strong-mode: implicit-casts: false implicit-dynamic: false plugins: - dart_code_metrics linter: rules: - always_declare_return_types - always_put_control_body_on_new_line - always_require_non_null_named_parameters - annotate_overrides - avoid_double_and_int_checks - avoid_dynamic_calls - avoid_empty_else - avoid_equals_and_hash_code_on_mutable_classes - avoid_escaping_inner_quotes - avoid_field_initializers_in_const_classes - avoid_init_to_null - avoid_js_rounded_ints - avoid_null_checks_in_equality_operators - avoid_private_typedef_functions - avoid_redundant_argument_values - avoid_relative_lib_imports - avoid_return_types_on_setters - avoid_shadowing_type_parameters - avoid_slow_async_io - avoid_type_to_string - avoid_types_as_parameter_names - avoid_unused_constructor_parameters - await_only_futures - camel_case_extensions - camel_case_types - cancel_subscriptions - cast_nullable_to_non_nullable - close_sinks - comment_references - constant_identifier_names - control_flow_in_finally - curly_braces_in_flow_control_structures - directives_ordering - do_not_use_environment - empty_catches - empty_constructor_bodies - empty_statements - exhaustive_cases - file_names - hash_and_equals - implementation_imports - invariant_booleans - iterable_contains_unrelated_type - join_return_with_assignment - library_names - library_prefixes - list_remove_unrelated_type - literal_only_boolean_expressions - missing_whitespace_between_adjacent_strings - no_adjacent_strings_in_list - no_duplicate_case_values - no_runtimeType_toString - omit_local_variable_types - package_api_docs - package_names - package_prefixed_library_names - parameter_assignments - prefer_adjacent_string_concatenation - prefer_asserts_in_initializer_lists - prefer_collection_literals - prefer_conditional_assignment - prefer_const_constructors - prefer_const_constructors_in_immutables - prefer_const_declarations - prefer_const_literals_to_create_immutables - prefer_contains - prefer_equal_for_default_values - prefer_final_fields - prefer_final_in_for_each - prefer_final_locals - prefer_for_elements_to_map_fromIterable - prefer_foreach - prefer_function_declarations_over_variables - prefer_generic_function_type_aliases - prefer_if_elements_to_conditional_expressions - prefer_if_null_operators - prefer_initializing_formals - prefer_inlined_adds - prefer_interpolation_to_compose_strings - prefer_is_empty - prefer_is_not_empty - prefer_is_not_operator - prefer_iterable_whereType - prefer_mixin - prefer_null_aware_operators - prefer_single_quotes - prefer_spread_collections - prefer_relative_imports - prefer_typing_uninitialized_variables - prefer_void_to_null - provide_deprecation_message - recursive_getters - slash_for_doc_comments - sort_unnamed_constructors_first - test_types_in_equals - throw_in_finally - type_annotate_public_apis - type_init_formals - unnecessary_await_in_return - unnecessary_brace_in_string_interps - unnecessary_const - unnecessary_getters_setters - unnecessary_lambdas - unnecessary_new - unnecessary_null_aware_assignments - unnecessary_null_in_if_null_operators - unnecessary_overrides - unnecessary_parenthesis - unnecessary_raw_strings - unnecessary_statements - unnecessary_string_escapes - unnecessary_string_interpolations - unnecessary_this - use_full_hex_values_for_flutter_colors - use_function_type_syntax_for_parameters - use_is_even_rather_than_modulo - use_rethrow_when_possible - unrelated_type_equality_checks - unsafe_html - void_checks dart_code_metrics: rules: - prefer-trailing-comma - prefer-trailing-comma-for-collection - no-equal-then-else - no-object-declaration - potential-null-dereference metrics-exclude: - test/** metrics: number-of-arguments: 8 number-of-methods: 28 lines-of-executable-code: 200 cyclomatic-complexity: 36
flame_example/analysis_options.yaml/0
{'file_path': 'flame_example/analysis_options.yaml', 'repo_id': 'flame_example', 'token_count': 1735}
String baseLink(String path) { const _basePath = 'https://github.com/flame-engine/flame_example/blob/master/lib/stories/'; return '$_basePath$path'; }
flame_example/lib/commons/commons.dart/0
{'file_path': 'flame_example/lib/commons/commons.dart', 'repo_id': 'flame_example', 'token_count': 60}
import 'package:flame/extensions.dart'; import 'package:flame/game.dart'; import 'package:flame/gestures.dart'; import 'package:flame/palette.dart'; import 'package:flutter/material.dart'; /// Includes an example including advanced detectors class MultitapGame extends BaseGame with MultiTouchTapDetector { static final _whitePaint = BasicPalette.white.paint; static final _size = Vector2.all(50); final Map<int, Rect> _taps = {}; @override void onTapDown(int pointerId, TapDownDetails details) { _taps[pointerId] = details.globalPosition.toVector2().toPositionedRect(_size); } @override void onTapUp(int pointerId, _) { _taps.remove(pointerId); } @override void onTapCancel(int pointerId) { _taps.remove(pointerId); } @override void render(Canvas canvas) { super.render(canvas); _taps.values.forEach((rect) { canvas.drawRect(rect, _whitePaint); }); } }
flame_example/lib/stories/controls/multitap.dart/0
{'file_path': 'flame_example/lib/stories/controls/multitap.dart', 'repo_id': 'flame_example', 'token_count': 336}
import 'package:dashbook/dashbook.dart'; import 'package:flame/game.dart'; import '../../commons/commons.dart'; import 'advanced.dart'; import 'basic.dart'; import 'component.dart'; import 'no_fcs.dart'; void addParallaxStories(Dashbook dashbook) { dashbook.storiesOf('Parallax') ..add( 'Basic', (_) => GameWidget(game: BasicParallaxGame()), codeLink: baseLink('parallax/basic.dart'), ) ..add( 'Component', (_) => GameWidget(game: ComponentParallaxGame()), codeLink: baseLink('parallax/component.dart'), ) ..add( 'No FCS', (_) => GameWidget(game: NoFCSParallaxGame()), codeLink: baseLink('parallax/no_fcs.dart'), ) ..add( 'Advanced', (_) => GameWidget(game: AdvancedParallaxGame()), codeLink: baseLink('parallax/advanced.dart'), ); }
flame_example/lib/stories/parallax/parallax.dart/0
{'file_path': 'flame_example/lib/stories/parallax/parallax.dart', 'repo_id': 'flame_example', 'token_count': 367}
import 'package:flutter/material.dart'; import 'package:flame/game.dart'; import 'package:flame/timer.dart'; import 'package:flame/gestures.dart'; class TimerGame extends Game with TapDetector { final TextConfig textConfig = TextConfig(color: const Color(0xFFFFFFFF)); Timer countdown; Timer interval; int elapsedSecs = 0; TimerGame() { countdown = Timer(2); interval = Timer( 1, callback: () => elapsedSecs += 1, repeat: true, ); interval.start(); } @override void onTapDown(_) { countdown.start(); } @override void update(double dt) { countdown.update(dt); interval.update(dt); } @override void render(Canvas canvas) { textConfig.render( canvas, 'Countdown: ${countdown.current}', Vector2(10, 100), ); textConfig.render(canvas, 'Elapsed time: $elapsedSecs', Vector2(10, 150)); } }
flame_example/lib/stories/utils/timer.dart/0
{'file_path': 'flame_example/lib/stories/utils/timer.dart', 'repo_id': 'flame_example', 'token_count': 347}
import 'dart:ui'; import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:flame_forge2d/forge2d_game.dart'; import 'package:forge2d/forge2d.dart'; import 'package:flame/palette.dart'; import 'package:flame/game.dart'; import 'package:flame_forge2d/body_component.dart'; List<Wall> createBoundaries(Forge2DGame game) { final Vector2 topLeft = Vector2.zero(); final Vector2 bottomRight = game.screenToWorld(game.viewport.effectiveSize); final Vector2 topRight = Vector2(bottomRight.x, topLeft.y); final Vector2 bottomLeft = Vector2(topLeft.x, bottomRight.y); return [ Wall(topLeft, topRight), Wall(topRight, bottomRight), Wall(bottomRight, bottomLeft), Wall(bottomLeft, topLeft), ]; } class Wall extends BodyComponent { Paint paint = BasicPalette.white.paint(); final Vector2 start; final Vector2 end; Wall(this.start, this.end); @override Body createBody() { final shape = EdgeShape()..set(start, end); final fixtureDef = FixtureDef(shape) ..restitution = 0.0 ..friction = 0.3; final bodyDef = BodyDef() ..userData = this // To be able to determine object in collision ..position = Vector2.zero() ..type = BodyType.static; return world.createBody(bodyDef)..createFixture(fixtureDef); } }
flame_forge2d/example/lib/boundaries.dart/0
{'file_path': 'flame_forge2d/example/lib/boundaries.dart', 'repo_id': 'flame_forge2d', 'token_count': 463}
import 'dart:ui'; mixin Renderable { void render(Canvas c, Paint paint); }
flame_geom/lib/renderable.dart/0
{'file_path': 'flame_geom/lib/renderable.dart', 'repo_id': 'flame_geom', 'token_count': 29}
import 'package:collision_detection_performance/components/bullet_component.dart'; import 'package:collision_detection_performance/components/enemy_component.dart'; import 'package:collision_detection_performance/components/explosion_component.dart'; import 'package:collision_detection_performance/game.dart'; import 'package:flame/collisions.dart'; import 'package:flame/components.dart'; class PlayerComponent extends SpriteAnimationComponent with HasGameRef<SpaceShooterGame>, CollisionCallbacks { late TimerComponent bulletCreator; PlayerComponent() : super( size: Vector2(50, 75), position: Vector2(100, 500), anchor: Anchor.center, ); @override Future<void> onLoad() async { add(CircleHitbox()); add( bulletCreator = TimerComponent( period: 0.05, repeat: true, autoStart: false, onTick: _createBullet, ), ); animation = await gameRef.loadSpriteAnimation( 'player.png', SpriteAnimationData.sequenced( stepTime: 0.2, amount: 4, textureSize: Vector2(32, 39), ), ); } final _bulletAngles = [0.5, 0.3, 0.0, -0.5, -0.3]; void _createBullet() { gameRef.addAll( _bulletAngles.map( (angle) => BulletComponent( position: position + Vector2(0, -size.y / 2), angle: angle, ), ), ); } void beginFire() { bulletCreator.timer.start(); } void stopFire() { bulletCreator.timer.pause(); } void takeHit() { gameRef.add(ExplosionComponent(position: position)); } @override void onCollisionStart(Set<Vector2> points, PositionComponent other) { super.onCollisionStart(points, other); if (other is EnemyComponent) { other.takeHit(); } } }
flame_perfomance_test_game/collision_detection/lib/components/player_component.dart/0
{'file_path': 'flame_perfomance_test_game/collision_detection/lib/components/player_component.dart', 'repo_id': 'flame_perfomance_test_game', 'token_count': 733}
import 'package:flutter/material.dart'; import 'package:flame/game.dart'; import 'package:flame/flame.dart'; import 'package:flame_shells/flame_shells.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); await Flame.util.fullScreen(); final game = MyGame(); final shell = FlameShell(game: game); runApp(shell); } class MyGame extends Game with HasShellControls { Rect _rect = const Rect.fromLTWH(10, 10, 50, 50); Paint _paint = Paint()..color = const Color(0xFFFFFFFF); double _xVelocity = 0.0; double _yVelocity = 0.0; @override void update(double dt) { _rect = _rect.translate(_xVelocity * 100 * dt, _yVelocity * 100 * dt); } @override void render(Canvas canvas) { canvas.drawRect(_rect, _paint); } @override void onShellButtonTapDown(button) { if (button == FlameShellButton.DPAD_UP) { _yVelocity = -1; } else if (button == FlameShellButton.DPAD_DOWN) { _yVelocity = 1; } if (button == FlameShellButton.DPAD_LEFT) { _xVelocity = -1; } else if (button == FlameShellButton.DPAD_RIGHT) { _xVelocity = 1; } if (button == FlameShellButton.ACTION_B) { _paint = Paint()..color = const Color(0xFF00FF00); } if (button == FlameShellButton.ACTION_A) { _paint = Paint()..color = const Color(0xFF0000FF); } } @override void onShellButtonTapUp(button) { if (button == FlameShellButton.DPAD_UP || button == FlameShellButton.DPAD_DOWN) { _yVelocity = 0; } if (button == FlameShellButton.DPAD_LEFT || button == FlameShellButton.DPAD_RIGHT) { _xVelocity = 0; } if (button == FlameShellButton.ACTION_B || button == FlameShellButton.ACTION_A) { _paint = Paint()..color = const Color(0xFFFFFFFF); } } }
flame_shells/example/lib/main.dart/0
{'file_path': 'flame_shells/example/lib/main.dart', 'repo_id': 'flame_shells', 'token_count': 728}
part of flame_splash_screen; /// This widget builds up the Flame logo composed of 3 layers, /// that are rendered via separate PNG files under the assets directory. class AnimatedLogo extends AnimatedWidget { /// Create this widget providing the animation parameter to control /// the opacity of the flame. const AnimatedLogo({ Key? key, required Animation<double> animation, }) : super( key: key, listenable: animation, ); @override Widget build(BuildContext context) { final animation = listenable as Animation<double>; return Stack( fit: StackFit.expand, alignment: Alignment.center, children: [ Image.asset( 'assets/layer1.png', package: 'flame_splash_screen', ), Opacity( opacity: animation.value, child: Image.asset( 'assets/layer2.png', package: 'flame_splash_screen', ), ), Image.asset( 'assets/layer3.png', package: 'flame_splash_screen', ), ], ); } } /// Creates and controls an [AnimatedLogo], making sure to provide the required /// animation and to properly dispose of itself after usage. class LogoComposite extends StatefulWidget { /// Creates a [LogoComposite]. const LogoComposite({Key? key}) : super(key: key); @override _LogoCompositeState createState() => _LogoCompositeState(); } class _LogoCompositeState extends State<LogoComposite> with SingleTickerProviderStateMixin { late Animation<double> animation; late AnimationController controller; @override void initState() { super.initState(); controller = AnimationController( duration: const Duration(milliseconds: 500), vsync: this, ); animation = Tween<double>(begin: 0.0, end: 1.0).animate(controller); controller.addStatusListener((status) { if (status == AnimationStatus.completed) { controller.reverse(); } else if (status == AnimationStatus.dismissed) { controller.forward(); } }); controller.forward(); } @override void dispose() { controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) => AnimatedLogo(animation: animation); } Widget _logoBuilder(BuildContext context) { return LayoutBuilder( builder: (context, constraints) { return FractionalTranslation( translation: const Offset(0, -0.25), child: ConstrainedBox( constraints: BoxConstraints.loose(const Size(300, 300)), child: const LogoComposite(), ), ); }, ); } /// Wraps the splash screen layout options /// There is two predefined themes [FlameSplashTheme.dark] and [FlameSplashTheme.white] class FlameSplashTheme { /// Creates a customized theme. [logoBuilder] returns the widget that will be /// rendered in place of main step of the animation. const FlameSplashTheme({ required this.backgroundDecoration, required this.logoBuilder, this.constraints = const BoxConstraints.expand(), }); /// Decoration to be applied to the widget underneath the Flame logo. /// It can be used to set the background colour, among other parameters. final BoxDecoration backgroundDecoration; /// A lambda to build the widget representing the logo itself. /// By default this will be wired to use the [LogoComposite] widget. final WidgetBuilder logoBuilder; /// Th constraints of the outside box, defaults to [BoxConstraints.expand]. final BoxConstraints constraints; /// One of the two default themes provided; this is optimal of light mode /// apps. static FlameSplashTheme white = const FlameSplashTheme( backgroundDecoration: BoxDecoration(color: Color(0xFFFFFFFF)), logoBuilder: _logoBuilder, ); /// One of the two default themes provided; this is optimal of dark mode apps. static FlameSplashTheme dark = const FlameSplashTheme( backgroundDecoration: BoxDecoration(color: Color(0xFF000000)), logoBuilder: _logoBuilder, ); }
flame_splash_screen/lib/src/theme.dart/0
{'file_path': 'flame_splash_screen/lib/src/theme.dart', 'repo_id': 'flame_splash_screen', 'token_count': 1395}
import 'package:flame/game.dart'; import 'package:flutter/material.dart'; import 'game.dart'; void main() { final game = FlappyEmber(); runApp(GameWidget(game: game)); }
flappy_ember/lib/main.dart/0
{'file_path': 'flappy_ember/lib/main.dart', 'repo_id': 'flappy_ember', 'token_count': 64}
import 'package:example/location_flow/location_flow.dart'; import 'package:example/location_flow/pages/state_selection/state_selection_cubit.dart'; import 'package:flow_builder/flow_builder.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; class StateSelection extends StatelessWidget { const StateSelection({super.key, required this.country}); static MaterialPage<void> page({required String country}) { return MaterialPage<void>(child: StateSelection(country: country)); } final String country; @override Widget build(BuildContext context) { return BlocProvider( create: (_) { return StateSelectionCubit(context.read<LocationRepository>()) ..statesRequested(country); }, child: const StateSelectionForm(), ); } } class StateSelectionForm extends StatelessWidget { const StateSelectionForm({super.key}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('State')), body: Center( child: Column( mainAxisSize: MainAxisSize.min, children: [ BlocBuilder<StateSelectionCubit, LocationState>( builder: (context, state) { switch (state.status) { case LocationStatus.initial: case LocationStatus.loading: return const LoadingIndicator(); case LocationStatus.success: return Dropdown( hint: const Text('Select a State'), items: state.locations, value: state.selectedLocation, onChanged: (value) => context .read<StateSelectionCubit>() .stateSelected(value), ); case LocationStatus.failure: return const LocationError(); } }, ), BlocBuilder<StateSelectionCubit, LocationState>( builder: (context, state) { return TextButton( onPressed: state.selectedLocation != null ? () => context.flow<Location>().update( (s) => s.copyWith(state: state.selectedLocation), ) : null, child: const Text('Submit'), ); }, ), ], ), ), ); } }
flow_builder/example/lib/location_flow/pages/state_selection/state_selection.dart/0
{'file_path': 'flow_builder/example/lib/location_flow/pages/state_selection/state_selection.dart', 'repo_id': 'flow_builder', 'token_count': 1228}
blank_issues_enabled: false
flutter-bloc-widget/.github/ISSUE_TEMPLATE/config.yml/0
{'file_path': 'flutter-bloc-widget/.github/ISSUE_TEMPLATE/config.yml', 'repo_id': 'flutter-bloc-widget', 'token_count': 7}
include: package:very_good_analysis/analysis_options.3.1.0.yaml
flutter-bloc-widget/analysis_options.yaml/0
{'file_path': 'flutter-bloc-widget/analysis_options.yaml', 'repo_id': 'flutter-bloc-widget', 'token_count': 23}
import '../iwidgets_factory.dart'; import '../widgets/activity_indicators/android_activity_indicator.dart'; import '../widgets/iactivity_indicator.dart'; import '../widgets/islider.dart'; import '../widgets/iswitch.dart'; import '../widgets/sliders/android_slider.dart'; import '../widgets/switches/android_switch.dart'; class MaterialWidgetsFactory implements IWidgetsFactory { const MaterialWidgetsFactory(); @override String getTitle() => 'Android widgets'; @override IActivityIndicator createActivityIndicator() => const AndroidActivityIndicator(); @override ISlider createSlider() => const AndroidSlider(); @override ISwitch createSwitch() => const AndroidSwitch(); }
flutter-design-patterns/lib/design_patterns/abstract_factory/factories/material_widgets_factory.dart/0
{'file_path': 'flutter-design-patterns/lib/design_patterns/abstract_factory/factories/material_widgets_factory.dart', 'repo_id': 'flutter-design-patterns', 'token_count': 221}
class Contact { final String fullName; final String email; final bool favourite; const Contact({ required this.fullName, required this.email, required this.favourite, }); }
flutter-design-patterns/lib/design_patterns/adapter/contact.dart/0
{'file_path': 'flutter-design-patterns/lib/design_patterns/adapter/contact.dart', 'repo_id': 'flutter-design-patterns', 'token_count': 63}
import '../burger_builder_base.dart'; import '../ingredients/index.dart'; class BigMacBuilder extends BurgerBuilderBase { BigMacBuilder() { price = 3.99; } @override void addBuns() { burger.addIngredient(BigMacBun()); } @override void addCheese() { burger.addIngredient(Cheese()); } @override void addPatties() { burger.addIngredient(BeefPatty()); } @override void addSauces() { burger.addIngredient(BigMacSauce()); } @override void addSeasoning() { burger.addIngredient(GrillSeasoning()); } @override void addVegetables() { burger.addIngredient(Onions()); burger.addIngredient(PickleSlices()); burger.addIngredient(ShreddedLettuce()); } }
flutter-design-patterns/lib/design_patterns/builder/burger_builders/big_mac_builder.dart/0
{'file_path': 'flutter-design-patterns/lib/design_patterns/builder/burger_builders/big_mac_builder.dart', 'repo_id': 'flutter-design-patterns', 'token_count': 286}