浏览代码

Merge branch 'dev_1.17.5' into zgh/devtools

/zgh-devtools
guanghuispark 4 年前
当前提交
755bb996
共有 60 个文件被更改,包括 1871 次插入551 次删除
  1. 2
      Samples/UIWidgetsSamples_2019_4/Assets/UIWidgetsGallery/demo/cupertino/cupertino_switch_demo.cs
  2. 4
      Samples/UIWidgetsSamples_2019_4/Assets/UIWidgetsGallery/demo/material/backdrop_demo.cs
  3. 3
      Samples/UIWidgetsSamples_2019_4/Assets/UIWidgetsSample.asmdef
  4. 2
      com.unity.uiwidgets/Editor/UIWidgetsPanelEditor.cs
  5. 12
      com.unity.uiwidgets/Runtime/cupertino/date_picker.cs
  6. 384
      com.unity.uiwidgets/Runtime/engine2/UIWidgetsPanel.cs
  7. 5
      com.unity.uiwidgets/Runtime/gestures/binding.cs
  8. 8
      com.unity.uiwidgets/Runtime/material/app.cs
  9. 5
      com.unity.uiwidgets/Runtime/material/pickers/date_picker_head.cs
  10. 7
      com.unity.uiwidgets/Runtime/painting/image_provider.cs
  11. 6
      com.unity.uiwidgets/Runtime/rendering/list_wheel_viewport.cs
  12. 7
      com.unity.uiwidgets/Runtime/services/asset_bundle.cs
  13. 27
      com.unity.uiwidgets/Runtime/ui2/window.cs
  14. 138
      com.unity.uiwidgets/Runtime/widgets/app.cs
  15. 6
      com.unity.uiwidgets/Runtime/widgets/focus_manager.cs
  16. 8
      com.unity.uiwidgets/Runtime/widgets/image.cs
  17. 14
      com.unity.uiwidgets/Runtime/widgets/navigator.cs
  18. 19
      com.unity.uiwidgets/Runtime/widgets/nested_scroll_view.cs
  19. 15
      com.unity.uiwidgets/Runtime/widgets/routes.cs
  20. 19
      com.unity.uiwidgets/Runtime/widgets/scrollable.cs
  21. 19
      com.unity.uiwidgets/Runtime/widgets/text.cs
  22. 2
      engine/src/lib/ui/window/window.cc
  23. 21
      engine/src/shell/platform/unity/darwin/macos/uiwidgets_panel.h
  24. 64
      engine/src/shell/platform/unity/darwin/macos/uiwidgets_panel.mm
  25. 3
      engine/src/shell/platform/unity/darwin/macos/uiwidgets_system.h
  26. 20
      engine/src/shell/platform/unity/darwin/macos/uiwidgets_system.mm
  27. 33
      engine/src/shell/platform/unity/darwin/macos/unity_surface_manager.mm
  28. 81
      engine/src/shell/platform/unity/windows/uiwidgets_panel.cc
  29. 21
      engine/src/shell/platform/unity/windows/uiwidgets_panel.h
  30. 19
      engine/src/shell/platform/unity/windows/uiwidgets_system.cc
  31. 3
      engine/src/shell/platform/unity/windows/uiwidgets_system.h
  32. 27
      engine/src/shell/platform/unity/windows/unity_surface_manager.cc
  33. 3
      Samples/UIWidgetsSamples_2019_4/Assets/Editor.meta
  34. 14
      Samples/UIWidgetsSamples_2019_4/Assets/UIWidgetsGallery/UIWidgetsGallery.asmdef
  35. 135
      com.unity.uiwidgets/Editor/UIWidgetsEditorPanel.cs
  36. 8
      com.unity.uiwidgets/Editor/third_parties.meta
  37. 377
      com.unity.uiwidgets/Runtime/engine2/UIWidgetsPanelWrapper.cs
  38. 8
      com.unity.uiwidgets/Runtime/redux.meta
  39. 3
      Samples/UIWidgetsSamples_2019_4/Assets/Editor/EditorWindowSample.meta
  40. 7
      Samples/UIWidgetsSamples_2019_4/Assets/Editor/EditorWindowSample/UIWidgetsEditorWindowSample.asmdef.meta
  41. 21
      Samples/UIWidgetsSamples_2019_4/Assets/Editor/EditorWindowSample/GalleryMain.cs
  42. 16
      Samples/UIWidgetsSamples_2019_4/Assets/Editor/EditorWindowSample/UIWidgetsEditorWindowSample.asmdef
  43. 3
      Samples/UIWidgetsSamples_2019_4/Assets/Editor/EditorWindowSample/GalleryMain.cs.meta
  44. 39
      com.unity.uiwidgets/Editor/third_parties/EditorCoroutines.cs
  45. 8
      com.unity.uiwidgets/Editor/third_parties/editor_coroutines.meta
  46. 407
      com.unity.uiwidgets/Editor/third_parties/editor_coroutines/EditorCoroutines.cs
  47. 21
      com.unity.uiwidgets/Editor/third_parties/editor_coroutines/LICENSE
  48. 19
      com.unity.uiwidgets/Runtime/redux/redux_logging.cs
  49. 11
      com.unity.uiwidgets/Runtime/redux/redux_logging.cs.meta
  50. 32
      com.unity.uiwidgets/Runtime/redux/redux_thunk.cs
  51. 11
      com.unity.uiwidgets/Runtime/redux/redux_thunk.cs.meta
  52. 81
      com.unity.uiwidgets/Runtime/redux/store.cs
  53. 11
      com.unity.uiwidgets/Runtime/redux/store.cs.meta
  54. 172
      com.unity.uiwidgets/Runtime/redux/widget_redux.cs
  55. 11
      com.unity.uiwidgets/Runtime/redux/widget_redux.cs.meta

2
Samples/UIWidgetsSamples_2019_4/Assets/UIWidgetsGallery/demo/cupertino/cupertino_switch_demo.cs


using Unity.UIWidgets.widgets;
namespace UIWidgetsGallery.gallery {
class CupertinoSwitchDemo : StatefulWidget {
public class CupertinoSwitchDemo : StatefulWidget {
public static string routeName = "/cupertino/switch";
public override State createState() => new _CupertinoSwitchDemoState();

4
Samples/UIWidgetsSamples_2019_4/Assets/UIWidgetsGallery/demo/material/backdrop_demo.cs


onTap: () => { this.onTap?.Invoke(); },
child: new Container(
height: 48.0f,
//TODO: uncomment this when fixes on EdgeInsetsDirectional lands
//padding: EdgeInsetsDirectional.only(start: 16.0f),
padding: EdgeInsets.only(left: 16.0f),
padding: EdgeInsetsDirectional.only(start: 16.0f),
alignment: AlignmentDirectional.centerStart,
child: new DefaultTextStyle(
style: theme.textTheme.subtitle1,

3
Samples/UIWidgetsSamples_2019_4/Assets/UIWidgetsSample.asmdef


{
"name": "UIWidgetsSample",
"references": [
"Unity.UIWidgets"
"Unity.UIWidgets",
"UIWidgetsGallery"
],
"optionalUnityReferences": [],
"includePlatforms": [],

2
com.unity.uiwidgets/Editor/UIWidgetsPanelEditor.cs


public class UIWidgetsPanelEditor : RawImageEditor {
public override void OnInspectorGUI() {
base.OnInspectorGUI();
base.OnInspectorGUI();
var pixelRatioProperty = serializedObject.FindProperty("devicePixelRatioOverride");
var antiAliasingProperty = serializedObject.FindProperty("hardwareAntiAliasing");
var ShowDebugLog = serializedObject.FindProperty("m_ShowDebugLog");

12
com.unity.uiwidgets/Runtime/cupertino/date_picker.cs


offAxisFraction = -0.5f * textDirectionFactor;
break;
}
}
return new CupertinoPicker(
scrollController: new FixedExtentScrollController(
initialItem: (int)selectedMinute / widget.minuteInterval

},
children: CupertinoDatePickerUtils.listGenerate((int)(60 / widget.minuteInterval), (int index) => {
int minute = index * widget.minuteInterval;
return _buildPickerNumberLabel(localizations.timerPickerMinute(minute), additionalPadding);
return _buildPickerNumberLabel(localizations.timerPickerMinute(minute), additionalPadding);
})
);
}

string semanticsLabel = textDirectionFactor == 1
? localizations.timerPickerSecond(second) + localizations.timerPickerSecondLabel(second)
: localizations.timerPickerSecondLabel(second) + localizations.timerPickerSecond(second);
return _buildPickerNumberLabel(localizations.timerPickerSecond(second), additionalPadding);
return _buildPickerNumberLabel(localizations.timerPickerSecond(second), additionalPadding);
})
);
}

384
com.unity.uiwidgets/Runtime/engine2/UIWidgetsPanel.cs


using System;
using System.Collections;
using System.Runtime.InteropServices;
using AOT;
using Unity.UIWidgets.editor2;
using Unity.UIWidgets.gestures;
using Unity.UIWidgets.services;
using NativeBindings = Unity.UIWidgets.ui.NativeBindings;
#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN
public partial class UIWidgetsPanel {
RenderTexture _renderTexture;
void _createRenderTexture(int width, int height, float devicePixelRatio) {
D.assert(_renderTexture == null);
var desc = new RenderTextureDescriptor(
width, height, RenderTextureFormat.ARGB32, 0) {
useMipMap = false,
autoGenerateMips = false,
};
_renderTexture = new RenderTexture(desc) {hideFlags = HideFlags.HideAndDontSave};
_renderTexture.Create();
_width = width;
_height = height;
_devicePixelRatio = devicePixelRatio;
public enum UIWidgetsWindowType {
InvalidPanel = 0,
GameObjectPanel = 1,
EditorWindowPanel = 2
}
public interface IUIWidgetsWindow {
Offset windowPosToScreenPos(Offset offset);
texture = _renderTexture;
}
void startCoroutine(IEnumerator routing);
void _destroyRenderTexture() {
D.assert(_renderTexture != null);
texture = null;
ObjectUtils.SafeDestroy(_renderTexture);
_renderTexture = null;
}
bool isActive();
void _enableUIWidgetsPanel(string font_settings) {
UIWidgetsPanel_onEnable(_ptr, _renderTexture.GetNativeTexturePtr(),
_width, _height, _devicePixelRatio, Application.streamingAssetsPath, font_settings);
}
void mainEntry();
void _resizeUIWidgetsPanel() {
UIWidgetsPanel_onRenderTexture(_ptr,
_renderTexture.GetNativeTexturePtr(),
_width, _height, _devicePixelRatio);
}
void onNewFrameScheduled();
void _disableUIWidgetsPanel() {
_renderTexture = null;
texture = null;
}
UIWidgetsWindowType getWindowType();
}
public partial class UIWidgetsPanel : RawImage, IUIWidgetsWindow {
UIWidgetsPanelWrapper _wrapper;
[DllImport(NativeBindings.dllName)]
static extern void UIWidgetsPanel_onEnable(IntPtr ptr,
IntPtr nativeTexturePtr, int width, int height, float dpi, string streamingAssetsPath,
string font_settings);
public float devicePixelRatioOverride;
[DllImport(NativeBindings.dllName)]
static extern void UIWidgetsPanel_onRenderTexture(
IntPtr ptr, IntPtr nativeTexturePtr, int width, int height, float dpi);
}
public bool hardwareAntiAliasing;
#elif UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX
public partial class UIWidgetsPanel {
Texture _renderTexture;
void _createRenderTexture(int width, int height, float devicePixelRatio) {
D.assert(_renderTexture == null);
_width = width;
_height = height;
_devicePixelRatio = devicePixelRatio;
public UIWidgetsWindowType getWindowType() {
return UIWidgetsWindowType.GameObjectPanel;
void _destroyRenderTexture() {
D.assert(_renderTexture != null);
var releaseOK = UIWidgetsPanel_releaseNativeTexture(_ptr);
D.assert(releaseOK);
_renderTexture = null;
texture = null;
public bool isActive() {
return IsActive();
void _enableUIWidgetsPanel(string font_settings) {
D.assert(_renderTexture == null);
IntPtr native_tex_ptr = UIWidgetsPanel_onEnable(_ptr, _width, _height, _devicePixelRatio,
Application.streamingAssetsPath, font_settings);
D.assert(native_tex_ptr != IntPtr.Zero);
_renderTexture =
Texture2D.CreateExternalTexture(_width, _height, TextureFormat.BGRA32, false, true, native_tex_ptr);
texture = _renderTexture;
public void startCoroutine(IEnumerator routing) {
StartCoroutine(routing);
void _disableUIWidgetsPanel() {
_renderTexture = null;
texture = null;
}
void _resizeUIWidgetsPanel()
{
D.assert(_renderTexture == null);
IntPtr native_tex_ptr = UIWidgetsPanel_onRenderTexture(_ptr, _width, _height, _devicePixelRatio);
D.assert(native_tex_ptr != IntPtr.Zero);
public void onNewFrameScheduled() {
_renderTexture =
Texture2D.CreateExternalTexture(_width, _height, TextureFormat.BGRA32, false, true, native_tex_ptr);
}
texture = _renderTexture;
public Offset windowPosToScreenPos(Offset offset) {
Camera camera = null;
if (canvas.renderMode != RenderMode.ScreenSpaceCamera) {
camera = canvas.GetComponent<GraphicRaycaster>().eventCamera;
}
var pos = new Vector2(offset.dx, offset.dy);
pos = pos * _currentDevicePixelRatio / canvas.scaleFactor;
var rect = rectTransform.rect;
pos.x += rect.min.x;
pos.y = rect.max.y - pos.y;
var worldPos = rectTransform.TransformPoint(new Vector2(pos.x, pos.y));
var screenPos = RectTransformUtility.WorldToScreenPoint(camera, worldPos);
return new Offset(screenPos.x, Screen.height - screenPos.y);
[DllImport(NativeBindings.dllName)]
static extern IntPtr UIWidgetsPanel_onEnable(IntPtr ptr,
int width, int height, float dpi, string streamingAssetsPath, string font_settings);
[DllImport(NativeBindings.dllName)]
static extern bool UIWidgetsPanel_releaseNativeTexture(IntPtr ptr);
[DllImport(NativeBindings.dllName)]
static extern IntPtr UIWidgetsPanel_onRenderTexture(
IntPtr ptr, int width, int height, float dpi);
}
#endif
public partial class UIWidgetsPanel : RawImage {
[Serializable]
public struct Font {
public string asset;

return result;
}
public float devicePixelRatioOverride = 1;
public float hardwareAntiAliasing;
// RectTransform rectTransform {
// get { return rectTransform; }
// }
// Canvas canvas {
// get { return canvas; }
// }
// Texture texture {
// set { texture = value; }
// }
public static UIWidgetsPanel current {
get { return Window.instance._panel; }
}
public Isolate isolate { get; private set; }
IntPtr _ptr;
GCHandle _handle;
int _width;
int _height;
float _devicePixelRatio;
int _currentWidth {
get { return Mathf.RoundToInt(rectTransform.rect.width * canvas.scaleFactor); }
}

protected void OnEnable() {
base.OnEnable();
D.assert(_renderTexture == null);
_recreateRenderTexture(_currentWidth, _currentHeight, _currentDevicePixelRatio);
_handle = GCHandle.Alloc(this);
_ptr = UIWidgetsPanel_constructor((IntPtr) _handle, UIWidgetsPanel_entrypoint);
panels.Add(this);
_ShowDebugLog = m_ShowDebugLog;
_enableUIWidgetsPanel(JSONMessageCodec.instance.toJson(settings));
D.assert(_wrapper == null);
_wrapper = new UIWidgetsPanelWrapper();
_wrapper.Initiate(this, _currentWidth, _currentHeight, _currentDevicePixelRatio, settings);
texture = _wrapper.renderTexture;
NativeConsole.OnEnable();
panels.Add(this);
_ShowDebugLog = m_ShowDebugLog;
protected virtual void main() {
public void mainEntry() {
main();
void _entryPoint() {
try {
isolate = Isolate.current;
Window.instance._panel = this;
main();
}
catch (Exception ex) {
Debug.LogException(new Exception("exception in main", ex));
}
protected virtual void main() {
if (_ptr != IntPtr.Zero && _renderTexture) {
if (_recreateRenderTexture(_currentWidth, _currentHeight, _currentDevicePixelRatio)) {
_resizeUIWidgetsPanel();
}
if (_wrapper != null && _wrapper.didDisplayMetricsChanged(_currentWidth, _currentHeight, _currentDevicePixelRatio)) {
_wrapper.OnDisplayMetricsChanged(_currentWidth, _currentHeight, _currentDevicePixelRatio);
texture = _wrapper.renderTexture;
Input_OnDisable();
UIWidgetsPanel_onDisable(_ptr);
UIWidgetsPanel_dispose(_ptr);
_ptr = IntPtr.Zero;
_handle.Free();
_handle = default;
_disableUIWidgetsPanel();
panels.Remove(this);
D.assert(_wrapper != null);
_wrapper?.Destroy();
_wrapper = null;
texture = null;
D.assert(!isolate.isValid);
Input_OnDisable();
}
bool _recreateRenderTexture(int width, int height, float devicePixelRatio) {
if (_renderTexture != null && _width == width && _height == height &&
_devicePixelRatio == devicePixelRatio) {
return false;
}
if (_renderTexture) {
_destroyRenderTexture();
}
_createRenderTexture(width, height, devicePixelRatio);
return true;
panels.Remove(this);
}
protected virtual void Update() {

protected virtual void OnGUI() {
Input_OnGUI();
}
public int registerTexture(Texture texture) {
return UIWidgetsPanel_registerTexture(_ptr, texture.GetNativeTexturePtr());
}
public void unregisterTexture(int textureId) {
UIWidgetsPanel_unregisterTexture(_ptr, textureId);
}
public void markNewFrameAvailable(int textureId) {
UIWidgetsPanel_markNewFrameAvailable(_ptr, textureId);
}
delegate void UIWidgetsPanel_EntrypointCallback(IntPtr handle);
[MonoPInvokeCallback(typeof(UIWidgetsPanel_EntrypointCallback))]
static void UIWidgetsPanel_entrypoint(IntPtr handle) {
GCHandle gcHandle = (GCHandle) handle;
UIWidgetsPanel panel = (UIWidgetsPanel) gcHandle.Target;
panel._entryPoint();
}
[DllImport(NativeBindings.dllName)]
static extern IntPtr UIWidgetsPanel_constructor(IntPtr handle,
UIWidgetsPanel_EntrypointCallback entrypointCallback);
[DllImport(NativeBindings.dllName)]
static extern void UIWidgetsPanel_dispose(IntPtr ptr);
[DllImport(NativeBindings.dllName)]
static extern void UIWidgetsPanel_onDisable(IntPtr ptr);
[DllImport(NativeBindings.dllName)]
static extern int UIWidgetsPanel_registerTexture(IntPtr ptr, IntPtr nativeTexturePtr);
[DllImport(NativeBindings.dllName)]
static extern void UIWidgetsPanel_unregisterTexture(IntPtr ptr, int textureId);
[DllImport(NativeBindings.dllName)]
static extern void UIWidgetsPanel_markNewFrameAvailable(IntPtr ptr, int textureId);
}
public partial class UIWidgetsPanel : IPointerDownHandler, IPointerUpHandler,

Vector2? _getPointerPosition(Vector2 position) {
Camera worldCamera = canvas.worldCamera;
if (RectTransformUtility.ScreenPointToLocalPointInRectangle(
rectTransform, position, worldCamera, out var localPoint)) {
var scaleFactor = canvas.scaleFactor;
localPoint.x = (localPoint.x - rectTransform.rect.min.x) * scaleFactor;
localPoint.y = (rectTransform.rect.max.y - localPoint.y) * scaleFactor;
return localPoint;
}
return null;
}
void Input_OnEnable() {
}

else {
_lastMousePosition = Input.mousePosition;
}
if (Input.mouseScrollDelta.magnitude != 0) {
_onScroll();
}
}
}
}

if (e.isKey) {
UIWidgetsPanel_onKey(_ptr, e.keyCode, e.type == EventType.KeyDown);
if (e.character != 0 || e.keyCode == KeyCode.Backspace) {
PointerEventConverter.KeyEvent.Enqueue(new Event(e));
// TODO: add on char
// UIWidgetsPanel_onChar(_ptr, e.character);
}
}
}
Vector2? _getPointerPosition(Vector2 position) {
Camera worldCamera = canvas.worldCamera;
if (RectTransformUtility.ScreenPointToLocalPointInRectangle(
rectTransform, position, worldCamera, out var localPoint)) {
var scaleFactor = canvas.scaleFactor;
localPoint.x = (localPoint.x - rectTransform.rect.min.x) * scaleFactor;
localPoint.y = (rectTransform.rect.max.y - localPoint.y) * scaleFactor;
return localPoint;
_wrapper.OnKeyDown(e);
return null;
if (pos == null) {
return;
}
_wrapper.OnMouseMove(pos);
}
UIWidgetsPanel_onMouseMove(_ptr, pos.Value.x, pos.Value.y);
void _onScroll() {
var pos = _getPointerPosition(Input.mousePosition);
_wrapper.OnMouseScroll(Input.mouseScrollDelta, pos);
if (pos == null) {
return;
}
// mouse event
if (eventData.pointerId < 0) {
UIWidgetsPanel_onMouseDown(_ptr, pos.Value.x, pos.Value.y, eventData.pointerId);
}
_wrapper.OnPointerDown(pos, eventData.pointerId);
if (pos == null) {
return;
}
// mouse event
if (eventData.pointerId < 0) {
UIWidgetsPanel_onMouseUp(_ptr, pos.Value.x, pos.Value.y, eventData.pointerId);
}
_wrapper.OnPointerUp(pos, eventData.pointerId);
}
public void OnPointerEnter(PointerEventData eventData) {

public void OnPointerExit(PointerEventData eventData) {
D.assert(eventData.pointerId < 0);
_isEntered = false;
UIWidgetsPanel_onMouseLeave(_ptr);
_wrapper.OnPointerLeave();
if (pos == null) {
return;
}
// mouse event
if (eventData.pointerId < 0) {
UIWidgetsPanel_onMouseMove(_ptr, pos.Value.x, pos.Value.y);
}
_wrapper.OnDrag(pos, eventData.pointerId);
[DllImport(NativeBindings.dllName)]
static extern void UIWidgetsPanel_onChar(IntPtr ptr, char c);
[DllImport(NativeBindings.dllName)]
static extern void UIWidgetsPanel_onKey(IntPtr ptr, KeyCode keyCode, bool isKeyDown);
[DllImport(NativeBindings.dllName)]
static extern void UIWidgetsPanel_onMouseDown(IntPtr ptr, float x, float y, int button);
[DllImport(NativeBindings.dllName)]
static extern void UIWidgetsPanel_onMouseUp(IntPtr ptr, float x, float y, int button);
[DllImport(NativeBindings.dllName)]
static extern void UIWidgetsPanel_onMouseMove(IntPtr ptr, float x, float y);
[DllImport(NativeBindings.dllName)]
static extern void UIWidgetsPanel_onMouseLeave(IntPtr ptr);
}
}

5
com.unity.uiwidgets/Runtime/gestures/binding.cs


readonly HashSet<HitTestEntry> _enteredTargets = new HashSet<HitTestEntry>();
void _handlePointerEvent(PointerEvent evt) {
if (evt is PointerScrollEvent) {
_handlePointerScrollEvent(evt);
return;
}
HitTestResult hitTestResult = null;
if (evt is PointerDownEvent || evt is PointerSignalEvent) {
D.assert(!_hitTests.ContainsKey(evt.pointer));

8
com.unity.uiwidgets/Runtime/material/app.cs


using System.Collections.Generic;
using uiwidgets;
using Unity.UIWidgets.animation;
using Unity.UIWidgets.cupertino;
using Unity.UIWidgets.foundation;

List<NavigatorObserver> navigatorObservers = null,
TransitionBuilder builder = null,
string title = "",
GenerateAppTitle onGenerateTitle = null,
Color color = null,
ThemeData theme = null,
ThemeData darkTheme = null,

this.navigatorObservers = navigatorObservers ?? new List<NavigatorObserver>();
this.builder = builder;
this.title = title;
this.onGenerateTitle = onGenerateTitle;
this.color = color;
this.theme = theme;
this.darkTheme = darkTheme;

public readonly string title;
public readonly GenerateAppTitle onGenerateTitle;
public readonly ThemeData theme;
public readonly ThemeData darkTheme;

);
},
textStyle: material_._errorTextStyle,
title: widget.title,
onGenerateTitle: widget.onGenerateTitle,
color: widget.color ?? widget.theme?.primaryColor ?? Colors.blue,
locale: widget.locale,
localizationsDelegates: _localizationsDelegates,
localeResolutionCallback: widget.localeResolutionCallback,

5
com.unity.uiwidgets/Runtime/material/pickers/date_picker_head.cs


new Container(
height: DatePickerHeaderUtils._datePickerHeaderPortraitHeight,
color: primarySurfaceColor,
//FixMe: uncomment this after EdgeInsetsGeometry is ready for use
/*padding: EdgeInsetsDirectional.only(
padding: EdgeInsetsDirectional.only(
),*/
),
child: new Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: new List<Widget> {

7
com.unity.uiwidgets/Runtime/painting/image_provider.cs


using System.IO;
using System.Text;
using Unity.UIWidgets.async2;
using Unity.UIWidgets.editor2;
using Unity.UIWidgets.engine2;
using Unity.UIWidgets.foundation;
using Unity.UIWidgets.ui;

Future<Codec> _loadAsync(NetworkImage key, DecoderCallback decode) {
var completer = Completer.create();
var isolate = Isolate.current;
var panel = UIWidgetsPanel.current;
if (panel.IsActive()) {
panel.StartCoroutine(_loadCoroutine(key.url, completer, isolate));
var panel = UIWidgetsPanelWrapper.current.window;
if (panel.isActive()) {
panel.startCoroutine(_loadCoroutine(key.url, completer, isolate));
return completer.future.to<byte[]>().then_<byte[]>(data => {
if (data != null && data.Length > 0) {
return decode(data);

6
com.unity.uiwidgets/Runtime/rendering/list_wheel_viewport.cs


untransformedPaintingCoordinates.dx,
-_topScrollMarginExtent
);
bool shouldApplyOffCenterDim = overAndUnderCenterOpacity < 1;
if (useMagnifier || shouldApplyOffCenterDim) {
_paintChildWithMagnifier(context, offset, child, transform, offsetToCenter, untransformedPaintingCoordinates);

context1.pushTransform(
needsCompositing,
offset1,
cylindricalTransform,
// this._centerOriginTransform(cylindricalTransform),
_magnifyTransform(),
(PaintingContext context2, Offset offset2) => {
context2.paintChild(child, offset2 + untransformedPaintingCoordinates);
});

7
com.unity.uiwidgets/Runtime/services/asset_bundle.cs


using System.Collections.Generic;
using System.Text;
using Unity.UIWidgets.async2;
using Unity.UIWidgets.editor2;
using Unity.UIWidgets.engine2;
using Unity.UIWidgets.foundation;
using Unity.UIWidgets.ui;

public override Future<byte[]> load(string key) {
var completer = Completer.create();
var isolate = Isolate.current;
var panel = UIWidgetsPanel.current;
panel.StartCoroutine(_loadCoroutine(key, completer, isolate));
var panel =UIWidgetsPanelWrapper.current.window;
if (panel.isActive()) {
panel.startCoroutine(_loadCoroutine(key, completer, isolate));
}
return completer.future.to<byte[]>();
}

27
com.unity.uiwidgets/Runtime/ui2/window.cs


using System.Runtime.InteropServices;
using AOT;
using Unity.UIWidgets.async2;
using Unity.UIWidgets.editor2;
using Unity.UIWidgets.engine2;
using Unity.UIWidgets.foundation;
using Unity.UIWidgets.ui;

public class Window {
internal IntPtr _ptr;
internal object _binding;
internal UIWidgetsPanel _panel;
internal UIWidgetsPanelWrapper _panel;
internal _AsyncCallbackState _asyncCallbackState;
internal Window() {

}
protected float queryDevicePixelRatio() {
return _panel.devicePixelRatioOverride;
return _panel.devicePixelRatio;
Camera camera = null;
var canvas = _panel.canvas;
if (canvas.renderMode != RenderMode.ScreenSpaceCamera) {
camera = canvas.GetComponent<GraphicRaycaster>().eventCamera;
}
var pos = new Vector2(offset.dx, offset.dy);
pos = pos * queryDevicePixelRatio() / _panel.canvas.scaleFactor;
var rectTransform = _panel.rectTransform;
var rect = rectTransform.rect;
pos.x += rect.min.x;
pos.y = rect.max.y - pos.y;
var worldPos = rectTransform.TransformPoint(new Vector2(pos.x, pos.y));
var screenPos = RectTransformUtility.WorldToScreenPoint(camera, worldPos);
return new Offset(screenPos.x, Screen.height - screenPos.y);
}
public void run(Action callback) {
//Fixme: do nothing now
D.assert(false, () => "window.run is not implemented yet!");
return _panel.window.windowPosToScreenPos(offset);
}
public PointerDataPacketCallback onPointerDataPacket {

public void scheduleFrame() {
Window_scheduleFrame(_ptr);
_panel.window.onNewFrameScheduled();
}
public void scheduleMicrotask(Action callback) {

138
com.unity.uiwidgets/Runtime/widgets/app.cs


supportedLocales = supportedLocales ?? new List<Locale> {new Locale("en", "US")};
window = Window.instance;
D.assert(routes != null);
D.assert(color != null);
D.assert(supportedLocales != null && supportedLocales.isNotEmpty());
this.home = home;
this.navigatorKey = navigatorKey;
this.onGenerateRoute = onGenerateRoute;

}
}
public class WindowProvider : InheritedWidget {
public readonly Window window;
public WindowProvider(Key key = null, Window window = null, Widget child = null) :
base(key, child) {
D.assert(window != null);
this.window = window;
}
public static Window of(BuildContext context) {
var provider = (WindowProvider) context.inheritFromWidgetOfExactType(typeof(WindowProvider));
if (provider == null) {
throw new UIWidgetsError("WindowProvider is missing");
}
return provider.window;
}
public static Window of(GameObject gameObject) {
D.assert(false, () => "window.Of is not implemented yet!");
return null;
/*
var panel = gameObject.GetComponent<UIWidgetsPanel>();
return panel == null ? null : panel.window;
*/
}
public override bool updateShouldNotify(InheritedWidget oldWidget) {
D.assert(window == ((WindowProvider) oldWidget).window);
return false;
}
}
class _WidgetsAppState : State<WidgetsApp>, WidgetsBindingObserver {
public void didChangeMetrics() {
setState();

public override void initState() {
base.initState();
_updateNavigator();
//todo: xingwei.zhu: change the default locale to ui.Window.locale
/*D.assert(() => {
WidgetInspectorService.instance.inspectorShowCallback += inspectorShowChanged;
return true;
});*/
WidgetsBinding.instance.addObserver(this);
}

public override void dispose() {
WidgetsBinding.instance.removeObserver(this);
/*D.assert(() => {
WidgetInspectorService.instance.inspectorShowCallback -= inspectorShowChanged;
return true;
});*/
base.dispose();
}

}
/*bool _debugCheckLocalizations(Locale appLocale) {
bool _debugCheckLocalizations(Locale appLocale) {
foreach ( LocalizationsDelegate<dynamic> _delegate in _localizationsDelegates) {
foreach ( LocalizationsDelegate _delegate in _localizationsDelegates) {
if (!unsupportedTypes.Contains(_delegate.type))
continue;
if (_delegate.isSupported(appLocale))

if (unsupportedTypesList.SequenceEqual(list))
return true;
StringBuffer message = new StringBuffer();
message.writeln('\u2550' * 8);
message.writeln(
StringBuilder message = new StringBuilder();
message.Append('\u2550' * 8);
message.Append(
// Currently the Cupertino library only provides english localizations.
// Remove this when https://github.com/flutter/flutter/issues/23847
// is fixed.
message.writeln(
message.Append(
message.writeln(
message.Append(
message.writeln('\u2550' * 8);
//Debug.Log(message.toString());
message.Append('\u2550' * 8);
}*/
}
public override Widget build(BuildContext context) {
Widget navigator = null;

key: _navigator,
initialRoute: widget.initialRoute ?? Navigator.defaultRouteName,
/*WidgetsBinding.instance.window.defaultRouteName != Navigator.defaultRouteName
initialRoute:
WidgetsBinding.instance.window.defaultRouteName != Navigator.defaultRouteName
: widget.initialRoute ?? WidgetsBinding.instance.window.defaultRouteName,*/
: widget.initialRoute ?? WidgetsBinding.instance.window.defaultRouteName,
onGenerateRoute: _onGenerateRoute,
onGenerateInitialRoutes: widget.onGenerateInitialRoutes == null
? Navigator.defaultGenerateInitialRoutes

}
PerformanceOverlay performanceOverlay = null;
if (widget.showPerformanceOverlay) {
performanceOverlay = PerformanceOverlay.allEnabled();
}
/*if (widget.showPerformanceOverlay || WidgetsApp.showPerformanceOverlayOverride) {
if (widget.showPerformanceOverlay || WidgetsApp.showPerformanceOverlayOverride) {
performanceOverlay = PerformanceOverlay.allEnabled(
checkerboardRasterCacheImages: widget.checkerboardRasterCacheImages,
checkerboardOffscreenLayers: widget.checkerboardOffscreenLayers

checkerboardRasterCacheImages: widget.checkerboardRasterCacheImages,
checkerboardOffscreenLayers: widget.checkerboardOffscreenLayers
);
}*/
}
if (performanceOverlay != null) {
result = new Stack(

});
}
/*if (widget.showSemanticsDebugger) {
result = SemanticsDebugger(
child: result,
);
}*/
D.assert(() => {
if (widget.debugShowWidgetInspector || WidgetsApp.debugShowWidgetInspectorOverride) {
result = new WidgetInspector(

);
}
return true;
/*if (widget.debugShowWidgetInspector || WidgetsApp.debugShowWidgetInspectorOverride) {
result = new WidgetInspector(
child: result,
selectButtonBuilder: widget.inspectorSelectButtonBuilder
);
}
if (widget.debugShowCheckedModeBanner && WidgetsApp.debugAllowBannerOverride) {
result = new CheckedModeBanner(
child: result
);
}*/
return true;
result = new Directionality(child: result, TextDirection.ltr);
result = new WindowProvider(
window: widget.window,
child: result
);
/*Widget title = null;
Widget title = null;
if (widget.onGenerateTitle != null) {
title = new Builder(
builder: (BuildContext context1)=> {

color: widget.color,
child: result
);
}*/
}
//D.assert(_debugCheckLocalizations(appLocale));
result = new MediaQuery(
data: MediaQueryData.fromWindow(widget.window),
child: new Localizations(
locale: appLocale,
delegates: _localizationsDelegates,
child: result)
);
/////todo
///
/*result = new Shortcuts(
D.assert(_debugCheckLocalizations(appLocale));
result = new Shortcuts(
child: FocusTraversalGroup(
policy: ReadingOrderTraversalPolicy(),
child: _MediaQueryFromWindow(
child: new FocusTraversalGroup(
policy: new ReadingOrderTraversalPolicy(),
child: new _MediaQueryFromWindow(
delegates: _localizationsDelegates,
delegates: _localizationsDelegates.ToList(),
);*/
);
return result;
}

6
com.unity.uiwidgets/Runtime/widgets/focus_manager.cs


public void _setAsFocusedChildForScope() {
FocusNode scopeFocus = this;
foreach (FocusScopeNode ancestor in ancestors) {
foreach ( var ancestor in ancestors) {
ancestor._focusedChildren.Remove(scopeFocus);
((FocusScopeNode)ancestor)._focusedChildren.Remove(scopeFocus);
ancestor._focusedChildren.Add(scopeFocus);
((FocusScopeNode)ancestor)._focusedChildren.Add(scopeFocus);
scopeFocus = ancestor;
}
}

8
com.unity.uiwidgets/Runtime/widgets/image.cs


}
void _resolveImage() {
/*ScrollAwareImageProvider<object> provider = new ScrollAwareImageProvider<object>(
ScrollAwareImageProvider<object> provider = new ScrollAwareImageProvider<object>(
);*/
);
widget.image.resolve(ImageUtils.createLocalImageConfiguration(
provider.resolve(ImageUtils.createLocalImageConfiguration(
context,
size: widget.width != null && widget.height != null
? new Size(widget.width.Value, widget.height.Value)

base.debugFillProperties(description);
description.add(new DiagnosticsProperty<ImageStream>("stream", _imageStream));
description.add(new DiagnosticsProperty<ImageInfo>("pixels", _imageInfo));
//description.add(new DiagnosticsProperty<ImageChunkEvent>("loadingProgress", _loadingProgress));
description.add(new DiagnosticsProperty<ImageChunkEvent>("loadingProgress", _loadingProgress));
description.add(new DiagnosticsProperty<int>("frameNumber", _frameNumber));
description.add(new DiagnosticsProperty<bool>("wasSynchronouslyLoaded", _wasSynchronouslyLoaded));
}

14
com.unity.uiwidgets/Runtime/widgets/navigator.cs


using Unity.UIWidgets.gestures;
using Unity.UIWidgets.rendering;
using Unity.UIWidgets.scheduler2;
using Unity.UIWidgets.services;
using SchedulerBinding = Unity.UIWidgets.scheduler2.SchedulerBinding;
using SchedulerPhase = Unity.UIWidgets.scheduler2.SchedulerPhase;

public delegate Route<T> RouteBuilder<T>(BuildContext context, RouteSettings settings);
public delegate List<Route> RouteListFactory(NavigatorState navigator, string initialRoute);
//public delegate bool RoutePredicate(Route route);
public delegate bool RoutePredicate(Route route);

string description;
if (route is TransitionRoute ){
//TransitionRoute transitionRoute = route;
description = ((TransitionRoute)route).debugLabel;
}
else {

Dictionary<string, object> settingsJsonable = new Dictionary<string, object> {
{"name", settings.name}
};
/*if (settings.arguments != null) {
settingsJsonable["arguments"] = jsonEncode(
settings.arguments,
toEncodable: (object _object) => $"{_object}"
);
}*/
if (settings.arguments != null) {
settingsJsonable["arguments"] = JSONMessageCodec.instance.toJson(
settings.arguments);
}
routeJsonable["settings"] = settingsJsonable;
}

19
com.unity.uiwidgets/Runtime/widgets/nested_scroll_view.cs


return 0.0f;
}
public float applyClampedPointerSignalUpdate(float delta) {
D.assert(delta != 0.0f);
float min = delta > 0.0f
? float.NegativeInfinity
: Mathf.Min(minScrollExtent, pixels);
// The logic for max is equivalent but on the other side.
float max = delta < 0.0f
? float.PositiveInfinity
: Mathf.Max(maxScrollExtent, pixels);
float newPixels = (pixels + delta).clamp(min, max);
float clampedDelta = newPixels - pixels;
if (clampedDelta == 0.0f)
return delta;
forcePixels(newPixels);
didUpdateScrollPositionBy(clampedDelta);
return delta - clampedDelta;
}
public override ScrollDirection userScrollDirection {
get { return coordinator.userScrollDirection; }
}

15
com.unity.uiwidgets/Runtime/widgets/routes.cs


D.assert(!_transitionCompleter.isCompleted, () => $"Cannot reuse a {GetType()} after disposing it.");
_didPushOrReplace();
base.didAdd();
_controller.setValue(_controller.upperBound); //_controller.upperBound;
_controller.setValue(_controller.upperBound);
}
protected internal override void didReplace(Route oldRoute) {
D.assert(_controller != null,

entry._owner = null;
entry._notifyRemoved();
if (_localHistory.isEmpty()) {
//changedInternalState();
if (SchedulerBinding.instance.schedulerPhase == SchedulerPhase.persistentCallbacks) {
SchedulerBinding.instance.addPostFrameCallback((TimeSpan timestamp) =>{
changedInternalState();

animation: widget.route.navigator?.userGestureInProgressNotifier ?? new ValueNotifier<bool>(false),
builder: (BuildContext context1, Widget child1) =>{
bool ignoreEvents = _shouldIgnoreFocusRequest;
focusScopeNode.canRequestFocus = !ignoreEvents; // todo
focusScopeNode.canRequestFocus = !ignoreEvents;
return new IgnorePointer(
ignoring: ignoreEvents,
child: child1

animation.drive(new ColorTween(
begin: _kTransparent,
end: barrierColor // changedInternalState is called if this updates
).chain(new CurveTween(curve: barrierCurve)));//.animate(animation);
).chain(new CurveTween(curve: barrierCurve)));
//,semanticsLabel: barrierLabel, // changedInternalState is called if barrierLabel updates
//barrierSemanticsDismissible: semanticsDismissible
//semanticsLabel: barrierLabel, // changedInternalState is called if barrierLabel updates
//barrierSemanticsDismissible: semanticsDismissible,
);
}
if (_filter != null) {

BuildContext context,
Animation<float> animation,
Animation<float> secondaryAnimation) {
//TODO SEMANTICS
return _pageBuilder(context, animation, secondaryAnimation);
}

19
com.unity.uiwidgets/Runtime/widgets/scrollable.cs


}
float _targetScrollOffsetForPointerScroll(PointerScrollEvent e) {
float delta = widget.axis == Axis.horizontal ? e.delta.dx : e.delta.dy;
float delta = widget.axis == Axis.horizontal
? e.scrollDelta.dx
: e.scrollDelta.dy;
delta += -1;
delta *= -1;
}
float _pointerSignalEventDelta(PointerScrollEvent evt) {
float delta = widget.axis == Axis.horizontal
? evt.scrollDelta.dx
: evt.scrollDelta.dy;
if (AxisUtils.axisDirectionIsReversed(widget.axisDirection)) {
delta *= -1;
}
return delta;
}
void _receivedPointerSignal(PointerSignalEvent e) {

19
com.unity.uiwidgets/Runtime/widgets/text.cs


public static DefaultTextStyle of(BuildContext context) {
return context.dependOnInheritedWidgetOfExactType<DefaultTextStyle>() ?? new DefaultTextStyle();
}
public override bool updateShouldNotify(InheritedWidget oldWidget) {
oldWidget = (DefaultTextStyle) oldWidget;
return style != ((DefaultTextStyle)oldWidget).style ||
textAlign != ((DefaultTextStyle)oldWidget).textAlign ||
softWrap != ((DefaultTextStyle)oldWidget).softWrap ||
overflow != ((DefaultTextStyle)oldWidget).overflow ||
maxLines != ((DefaultTextStyle)oldWidget).maxLines ||
textWidthBasis != ((DefaultTextStyle)oldWidget).textWidthBasis ||
textHeightBehavior != ((DefaultTextStyle)oldWidget).textHeightBehavior;
public override bool updateShouldNotify(InheritedWidget oldWidget) {
DefaultTextStyle _oldWidget = (DefaultTextStyle) oldWidget;
return style != _oldWidget.style ||
textAlign != _oldWidget.textAlign ||
softWrap != _oldWidget.softWrap ||
overflow != _oldWidget.overflow ||
maxLines != _oldWidget.maxLines ||
textWidthBasis != _oldWidget.textWidthBasis ||
textHeightBehavior != _oldWidget.textHeightBehavior;
}
public override Widget wrap(BuildContext context, Widget child) {

2
engine/src/lib/ui/window/window.cc


const std::string routeName = ptr->client()->DefaultRouteName();
size_t size = routeName.length() + 1;
char* result = static_cast<char*>(malloc(size));
routeName.copy(result, size);
strcpy(result, routeName.c_str());
return result;
}

21
engine/src/shell/platform/unity/darwin/macos/uiwidgets_panel.h


namespace uiwidgets {
enum UIWidgetsWindowType {
InvalidPanel = 0,
GameObjectPanel = 1,
EditorWindowPanel = 2
};
struct MouseState {
bool state_is_down = false;
bool state_is_added = false;

typedef void (*EntrypointCallback)(Mono_Handle handle);
static fml::RefPtr<UIWidgetsPanel> Create(
Mono_Handle handle, EntrypointCallback entrypoint_callback);
Mono_Handle handle, UIWidgetsWindowType window_type, EntrypointCallback entrypoint_callback);
~UIWidgetsPanel();

void VSyncCallback(intptr_t baton);
void SetEventLocationFromCursorPosition(UIWidgetsPointerEvent* event_data);
void OnScroll(float x, float y, float px, float py);
void OnMouseDown(float x, float y, int button);
void OnMouseUp(float x, float y, int button);

bool NeedUpdateByPlayerLoop();
bool NeedUpdateByEditorLoop();
UIWidgetsPanel(Mono_Handle handle, EntrypointCallback entrypoint_callback);
UIWidgetsPanel(Mono_Handle handle, UIWidgetsWindowType window_type, EntrypointCallback entrypoint_callback);
void CreateInternalUIWidgetsEngine(size_t width, size_t height, float device_pixel_ratio, const char* streaming_assets_path, const char* settings);

void SendMouseLeave();
void SendScroll(float delta_x, float delta_y, float px, float py);
void SetEventPhaseFromCursorButtonState(UIWidgetsPointerEvent* event_data);
void SendPointerEventWithData(const UIWidgetsPointerEvent& event_data);

UIWidgetsWindowType window_type_;
std::unique_ptr<UnitySurfaceManager> surface_manager_;

64
engine/src/shell/platform/unity/darwin/macos/uiwidgets_panel.mm


namespace uiwidgets {
fml::RefPtr<UIWidgetsPanel> UIWidgetsPanel::Create(
Mono_Handle handle, EntrypointCallback entrypoint_callback) {
return fml::MakeRefCounted<UIWidgetsPanel>(handle, entrypoint_callback);
Mono_Handle handle, UIWidgetsWindowType window_type, EntrypointCallback entrypoint_callback) {
return fml::MakeRefCounted<UIWidgetsPanel>(handle, window_type, entrypoint_callback);
UIWidgetsWindowType window_type,
: handle_(handle), entrypoint_callback_(entrypoint_callback) {}
: handle_(handle), window_type_(window_type), entrypoint_callback_(entrypoint_callback) {}
bool UIWidgetsPanel::NeedUpdateByPlayerLoop() {
return window_type_ == GameObjectPanel;
}
bool UIWidgetsPanel::NeedUpdateByEditorLoop() {
return window_type_ == EditorWindowPanel;
}
void* UIWidgetsPanel::OnEnable(size_t width, size_t height, float device_pixel_ratio,
const char* streaming_assets_path, const char* settings)

SendPointerEventWithData(event);
}
void UIWidgetsPanel::SendScroll(float delta_x, float delta_y, float px, float py) {
UIWidgetsPointerEvent event = {};
// TODO: this is a native method, use unity position instead.
event.x = px;
event.y = py;
SetEventPhaseFromCursorButtonState(&event);
event.signal_kind = UIWidgetsPointerSignalKind::kUIWidgetsPointerSignalKindScroll;
// TODO: See if this can be queried from the OS; this value is chosen
// arbitrarily to get something that feels reasonable.
const int kScrollOffsetMultiplier = 20;
event.scroll_delta_x = delta_x * kScrollOffsetMultiplier;
event.scroll_delta_y = delta_y * kScrollOffsetMultiplier;
SendPointerEventWithData(event);
}
void UIWidgetsPanel::SendPointerEventWithData(
const UIWidgetsPointerEvent& event_data) {
MouseState mouse_state = GetMouseState();

}
}
void UIWidgetsPanel::OnMouseMove(float x, float y) {
if (process_events_) {
SendMouseMove(x, y);

void UIWidgetsPanel::OnScroll(float x, float y, float px, float py) {
if (process_events_) {
SendScroll(x, y, px, py);
}
}
static uint64_t ConvertToUIWidgetsButton(int button) {
switch (button) {
case -1:

UIWIDGETS_API(UIWidgetsPanel*)
UIWidgetsPanel_constructor(
Mono_Handle handle,
Mono_Handle handle, int windowType,
const auto panel = UIWidgetsPanel::Create(handle, entrypoint_callback);
UIWidgetsWindowType window_type = static_cast<UIWidgetsWindowType>(windowType);
const auto panel = UIWidgetsPanel::Create(handle, window_type, entrypoint_callback);
panel->AddRef();
return panel.get();
}

UIWIDGETS_API(void)
UIWidgetsPanel_onMouseLeave(UIWidgetsPanel* panel) { panel->OnMouseLeave(); }
UIWIDGETS_API(void)
UIWidgetsPanel_onEditorUpdate(UIWidgetsPanel* panel) {
if (!panel->NeedUpdateByEditorLoop()) {
std::cerr << "only EditorWindowPanel can be updated using onEditorUpdate" << std::endl;
return;
}
//_Update
panel->ProcessMessages();
//_ProcessVSync
panel->ProcessVSync();
//_Wait
panel->ProcessMessages();
}
UIWIDGETS_API(void)
UIWidgetsPanel_onScroll(UIWidgetsPanel* panel, float x, float y, float px, float py) {
panel->OnScroll(x, y, px, py);
}
} // namespace uiwidgets

3
engine/src/shell/platform/unity/darwin/macos/uiwidgets_system.h


#include <cstdarg>
#include <set>
#include <unordered_map>
#include <mutex>
#include "Unity/IUnityInterface.h"
#include "Unity/IUnityUIWidgets.h"

TimePoint next_uiwidgets_event_time_ = TimePoint::clock::now();
std::set<UIWidgetsPanel*> uiwidgets_panels_;
std::mutex task_mutex_;
};
} // namespace uiwidgets

20
engine/src/shell/platform/unity/darwin/macos/uiwidgets_system.mm


void UIWidgetsSystem::Update() {
TimePoint next_event_time = TimePoint::max();
for (auto* uiwidgets_panel : uiwidgets_panels_) {
if (!uiwidgets_panel->NeedUpdateByPlayerLoop()) {
continue;
}
std::chrono::nanoseconds wait_duration = uiwidgets_panel->ProcessMessages();
if (wait_duration != std::chrono::nanoseconds::max()) {
next_event_time =

void UIWidgetsSystem::VSync() {
for (auto* uiwidgets_panel : uiwidgets_panels_) {
if (!uiwidgets_panel->NeedUpdateByPlayerLoop()) {
continue;
}
uiwidgets_panel->ProcessVSync();
}
}

void UIWidgetsSystem::GfxWorkerCallback(int eventId, void* data) {
const fml::closure task(std::move(gfx_worker_tasks_[eventId]));
gfx_worker_tasks_.erase(eventId);
{
std::scoped_lock lock(task_mutex_);
gfx_worker_tasks_.erase(eventId);
}
last_task_id_++;
gfx_worker_tasks_[last_task_id_] = task;
{
std::scoped_lock lock(task_mutex_);
last_task_id_++;
gfx_worker_tasks_[last_task_id_] = task;
}
unity_uiwidgets_->IssuePluginEventAndData(&_GfxWorkerCallback, last_task_id_,
nullptr);
}

33
engine/src/shell/platform/unity/darwin/macos/unity_surface_manager.mm


};
NSOpenGLPixelFormat *pixelFormat = [[NSOpenGLPixelFormat alloc] initWithAttributes:attrs];
gl_context_ = [[NSOpenGLContext alloc] initWithFormat:pixelFormat shareContext:nil];
gl_resource_context_ = [[NSOpenGLContext alloc] initWithFormat:pixelFormat shareContext:gl_context_];
//gl_context_ may be created unproperly, we can check this using the relevant gl_resource_context_
//loop until the created gl_context_ is ok, otherwise the program will crash anyway
while(gl_resource_context_ == nil) {
gl_context_ = [[NSOpenGLContext alloc] initWithFormat:pixelFormat shareContext:nil];
gl_resource_context_ = [[NSOpenGLContext alloc] initWithFormat:pixelFormat shareContext:gl_context_];
if (gl_resource_context_ == nil) {
CGLReleaseContext(gl_context_.CGLContextObj);
gl_context_ = nullptr;
}
}
FML_DCHECK(gl_context_ != nullptr);
FML_DCHECK(gl_context_ != nullptr && gl_resource_context_ != nullptr);
}
UnitySurfaceManager::~UnitySurfaceManager() { ReleaseNativeRenderContext(); }

bool UnitySurfaceManager::MakeCurrentResourceContext()
{
if (gl_resource_context_ == nullptr)
{
[gl_context_ makeCurrentContext];
}
else
{
[gl_resource_context_ makeCurrentContext];
}
[gl_resource_context_ makeCurrentContext];
return true;
}

void UnitySurfaceManager::ReleaseNativeRenderContext()
{
if (gl_resource_context_ != nullptr)
{
CGLReleaseContext(gl_resource_context_.CGLContextObj);
gl_resource_context_ = nullptr;
}
FML_DCHECK(gl_resource_context_);
CGLReleaseContext(gl_resource_context_.CGLContextObj);
gl_resource_context_ = nullptr;
FML_DCHECK(gl_context_);
CGLReleaseContext(gl_context_.CGLContextObj);

81
engine/src/shell/platform/unity/windows/uiwidgets_panel.cc


namespace uiwidgets {
fml::RefPtr<UIWidgetsPanel> UIWidgetsPanel::Create(
Mono_Handle handle, EntrypointCallback entrypoint_callback) {
return fml::MakeRefCounted<UIWidgetsPanel>(handle, entrypoint_callback);
Mono_Handle handle, UIWidgetsWindowType window_type, EntrypointCallback entrypoint_callback) {
return fml::MakeRefCounted<UIWidgetsPanel>(handle, window_type, entrypoint_callback);
UIWidgetsWindowType window_type,
: handle_(handle), entrypoint_callback_(entrypoint_callback) {}
: handle_(handle), window_type_(window_type), entrypoint_callback_(entrypoint_callback) {}
bool UIWidgetsPanel::NeedUpdateByPlayerLoop() {
return window_type_ == GameObjectPanel;
}
bool UIWidgetsPanel::NeedUpdateByEditorLoop() {
return window_type_ == EditorWindowPanel;
}
void UIWidgetsPanel::OnEnable(void* native_texture_ptr, size_t width,
size_t height, float device_pixel_ratio,

void UIWidgetsPanel::OnRenderTexture(void* native_texture_ptr, size_t width,
size_t height, float device_pixel_ratio) {
fml::AutoResetWaitableEvent latch;
[this, native_texture_ptr]() -> void {
[&latch, this, native_texture_ptr]() -> void {
surface_manager_->MakeCurrent(EGL_NO_DISPLAY);
if (fbo_) {

fbo_ = surface_manager_->CreateRenderSurface(native_texture_ptr);
surface_manager_->ClearCurrent();
latch.Signal();
latch.Wait();
ViewportMetrics metrics;
metrics.physical_width = static_cast<float>(width);

vsync_batons_.push_back(baton);
}
void UIWidgetsPanel::SetEventLocationFromCursorPosition(
UIWidgetsPointerEvent* event_data) {
POINT point;
GetCursorPos(&point);
// TODO: this is a native method, use unity position instead.
// ScreenToClient(GetWindowHandle(), &point);
event_data->x = point.x;
event_data->y = point.y;
}
void UIWidgetsPanel::SetEventPhaseFromCursorButtonState(
UIWidgetsPointerEvent* event_data) {
MouseState state = GetMouseState();

SendPointerEventWithData(event);
}
void UIWidgetsPanel::SendScroll(float delta_x, float delta_y, float px, float py) {
UIWidgetsPointerEvent event = {};
// TODO: this is a native method, use unity position instead.
event.x = px;
event.y = py;
//SetEventLocationFromCursorPosition(&event);
SetEventPhaseFromCursorButtonState(&event);
event.signal_kind = UIWidgetsPointerSignalKind::kUIWidgetsPointerSignalKindScroll;
// TODO: See if this can be queried from the OS; this value is chosen
// arbitrarily to get something that feels reasonable.
const int kScrollOffsetMultiplier = 20;
event.scroll_delta_x = delta_x * kScrollOffsetMultiplier;
event.scroll_delta_y = delta_y * kScrollOffsetMultiplier;
SendPointerEventWithData(event);
}
void UIWidgetsPanel::SendPointerEventWithData(
const UIWidgetsPointerEvent& event_data) {
MouseState mouse_state = GetMouseState();

}
}
void UIWidgetsPanel::OnScroll(float x, float y, float px, float py) {
if (process_events_) {
SendScroll(x, y, px, py);
}
}
static uint64_t ConvertToUIWidgetsButton(int button) {
switch (button) {
case -1:

UIWIDGETS_API(UIWidgetsPanel*)
UIWidgetsPanel_constructor(
Mono_Handle handle,
Mono_Handle handle, int windowType,
const auto panel = UIWidgetsPanel::Create(handle, entrypoint_callback);
UIWidgetsWindowType window_type = static_cast<UIWidgetsWindowType>(windowType);
const auto panel = UIWidgetsPanel::Create(handle, window_type, entrypoint_callback);
panel->AddRef();
return panel.get();
}

UIWIDGETS_API(void)
UIWidgetsPanel_onMouseLeave(UIWidgetsPanel* panel) { panel->OnMouseLeave(); }
UIWIDGETS_API(void)
UIWidgetsPanel_onEditorUpdate(UIWidgetsPanel* panel) {
if (!panel->NeedUpdateByEditorLoop()) {
std::cerr << "only EditorWindowPanel can be updated using onEditorUpdate" << std::endl;
return;
}
//_Update
panel->ProcessMessages();
//_ProcessVSync
panel->ProcessVSync();
//_Wait
panel->ProcessMessages();
}
UIWIDGETS_API(void)
UIWidgetsPanel_onScroll(UIWidgetsPanel* panel, float x, float y, float px, float py) {
panel->OnScroll(x, y, px, py);
}
} // namespace uiwidgets

21
engine/src/shell/platform/unity/windows/uiwidgets_panel.h


namespace uiwidgets {
enum UIWidgetsWindowType {
InvalidPanel = 0,
GameObjectPanel = 1,
EditorWindowPanel = 2
};
struct MouseState {
bool state_is_down = false;
bool state_is_added = false;

typedef void (*EntrypointCallback)(Mono_Handle handle);
static fml::RefPtr<UIWidgetsPanel> Create(
Mono_Handle handle, EntrypointCallback entrypoint_callback);
Mono_Handle handle, UIWidgetsWindowType window_type, EntrypointCallback entrypoint_callback);
~UIWidgetsPanel();

void VSyncCallback(intptr_t baton);
void SetEventLocationFromCursorPosition(UIWidgetsPointerEvent* event_data);
void OnScroll(float x, float y, float px, float py);
bool NeedUpdateByPlayerLoop();
bool NeedUpdateByEditorLoop();
UIWidgetsPanel(Mono_Handle handle, EntrypointCallback entrypoint_callback);
UIWidgetsPanel(Mono_Handle handle, UIWidgetsWindowType window_type, EntrypointCallback entrypoint_callback);
MouseState GetMouseState() { return mouse_state_; }

void SendMouseLeave();
void SendScroll(float delta_x, float delta_y, float px, float py);
void SetEventPhaseFromCursorButtonState(UIWidgetsPointerEvent* event_data);
void SendPointerEventWithData(const UIWidgetsPointerEvent& event_data);

UIWidgetsWindowType window_type_;
std::unique_ptr<UnitySurfaceManager> surface_manager_;
GLuint fbo_ = 0;

19
engine/src/shell/platform/unity/windows/uiwidgets_system.cc


void UIWidgetsSystem::Update() {
TimePoint next_event_time = TimePoint::max();
for (auto* uiwidgets_panel : uiwidgets_panels_) {
if (!uiwidgets_panel->NeedUpdateByPlayerLoop()) {
continue;
}
std::chrono::nanoseconds wait_duration = uiwidgets_panel->ProcessMessages();
if (wait_duration != std::chrono::nanoseconds::max()) {
next_event_time =

void UIWidgetsSystem::VSync() {
for (auto* uiwidgets_panel : uiwidgets_panels_) {
if (!uiwidgets_panel->NeedUpdateByPlayerLoop()) {
continue;
}
uiwidgets_panel->ProcessVSync();
}
}

void UIWidgetsSystem::GfxWorkerCallback(int eventId, void* data) {
const fml::closure task(std::move(gfx_worker_tasks_[eventId]));
gfx_worker_tasks_.erase(eventId);
{
std::scoped_lock lock(task_mutex_);
gfx_worker_tasks_.erase(eventId);
}
last_task_id_++;
gfx_worker_tasks_[last_task_id_] = task;
{
std::scoped_lock lock(task_mutex_);
last_task_id_++;
gfx_worker_tasks_[last_task_id_] = task;
}
unity_uiwidgets_->IssuePluginEventAndData(&_GfxWorkerCallback, last_task_id_,
nullptr);
}

3
engine/src/shell/platform/unity/windows/uiwidgets_system.h


#include <cstdarg>
#include <set>
#include <unordered_map>
#include <mutex>
#include "Unity/IUnityInterface.h"
#include "Unity/IUnityUIWidgets.h"

TimePoint next_uiwidgets_event_time_ = TimePoint::clock::now();
std::set<UIWidgetsPanel*> uiwidgets_panels_;
std::mutex task_mutex_;
};
} // namespace uiwidgets

27
engine/src/shell/platform/unity/windows/unity_surface_manager.cc


void UnitySurfaceManager::CleanUp() {
EGLBoolean result = EGL_FALSE;
if (egl_display_ != EGL_NO_DISPLAY && egl_context_ != EGL_NO_CONTEXT) {
result = eglDestroyContext(egl_display_, egl_context_);
egl_context_ = EGL_NO_CONTEXT;
if (result == EGL_FALSE) {
FML_LOG(ERROR) << "EGL: Failed to destroy context";
}
}
d3d11_device_ = nullptr;
if (egl_display_ != EGL_NO_DISPLAY &&
egl_resource_context_ != EGL_NO_CONTEXT) {
result = eglDestroyContext(egl_display_, egl_resource_context_);

}
}
if (egl_display_ != EGL_NO_DISPLAY) {
result = eglTerminate(egl_display_);
egl_display_ = EGL_NO_DISPLAY;
if (egl_display_ != EGL_NO_DISPLAY && egl_context_ != EGL_NO_CONTEXT) {
result = eglDestroyContext(egl_display_, egl_context_);
egl_context_ = EGL_NO_CONTEXT;
FML_LOG(ERROR) << "EGL : Failed to terminate EGL";
FML_LOG(ERROR) << "EGL: Failed to destroy context";
//TODO: investigate a bit more on the possible memory leak here since egl_display_ will never be released
//refer to the commit log (9b39afd879d06626f5049cfae2a9cb852044c518) for the details
if (egl_display_ != EGL_NO_DISPLAY) {
egl_display_ = EGL_NO_DISPLAY;
}
d3d11_device_ = nullptr;
}
} // namespace uiwidgets

3
Samples/UIWidgetsSamples_2019_4/Assets/Editor.meta


fileFormatVersion: 2
guid: fbf4348f25a14fb7a48fd287e0d01b88
timeCreated: 1614220178

14
Samples/UIWidgetsSamples_2019_4/Assets/UIWidgetsGallery/UIWidgetsGallery.asmdef


{
"name": "UIWidgetsGallery",
"references": [
"Unity.UIWidgets"
],
"optionalUnityReferences": [],
"includePlatforms": [],
"excludePlatforms": [],
"allowUnsafeCode": false,
"overrideReferences": false,
"precompiledReferences": [],
"autoReferenced": true,
"defineConstraints": []
}

135
com.unity.uiwidgets/Editor/UIWidgetsEditorPanel.cs


using System.Collections;
using System.Collections.Generic;
using Unity.UIWidgets.editor2;
using Unity.UIWidgets.engine2;
using Unity.UIWidgets.foundation;
using Unity.UIWidgets.ui;
using UnityEditor;
using UnityEngine;
using Rect = UnityEngine.Rect;
namespace Unity.UIWidgets.Editor {
public class UIWidgetsEditorPanel : EditorWindow, IUIWidgetsWindow {
UIWidgetsPanelWrapper _wrapper;
public UIWidgetsWindowType getWindowType() {
return UIWidgetsWindowType.EditorWindowPanel;
}
public bool isActive() {
return true;
}
public void startCoroutine(IEnumerator routing) {
this.StartCoroutine(routing);
}
public void onNewFrameScheduled() {
Repaint();
}
public Offset windowPosToScreenPos(Offset offset) {
return offset;
}
int _currentWidth {
get { return Mathf.RoundToInt(position.size.x); }
}
int _currentHeight {
get { return Mathf.RoundToInt(position.size.y); }
}
float _currentDevicePixelRatio {
get { return EditorGUIUtility.pixelsPerPoint; }
}
void OnDestroy() {
D.assert(_wrapper != null);
_wrapper?.Destroy();
_wrapper = null;
Input_OnDisable();
}
void OnEnable() {
D.assert(_wrapper == null);
_wrapper = new UIWidgetsPanelWrapper();
_wrapper.Initiate(this, _currentWidth, _currentHeight, _currentDevicePixelRatio, new Dictionary<string, object>());
Input_OnEnable();
}
void Update() {
_wrapper.onEditorUpdate();
}
void OnGUI()
{
if (_wrapper != null) {
if (_wrapper.didDisplayMetricsChanged(_currentWidth, _currentHeight, _currentDevicePixelRatio)) {
_wrapper.OnDisplayMetricsChanged(_currentWidth, _currentHeight, _currentDevicePixelRatio);
}
GUI.DrawTexture(new Rect(0.0f, 0.0f, position.width, position.height), _wrapper.renderTexture);
Input_OnGUIEvent(Event.current);
}
}
Vector2? _getPointerPosition(Vector2 position) {
return new Vector2(position.x, position.y);
}
int _buttonToPointerId(int buttonId) {
if (buttonId == 0) {
return -1;
}
else if (buttonId == 1) {
return -2;
}
return 0;
}
void Input_OnGUIEvent(Event evt) {
if (evt.type == EventType.MouseDown) {
var pos = _getPointerPosition(evt.mousePosition);
_wrapper.OnPointerDown(pos, _buttonToPointerId(evt.button));
}
else if (evt.type == EventType.MouseUp || evt.rawType == EventType.MouseUp) {
var pos = _getPointerPosition(evt.mousePosition);
_wrapper.OnPointerUp(pos, _buttonToPointerId(evt.button));
}
else if (evt.type == EventType.MouseDrag) {
var pos = _getPointerPosition(evt.mousePosition);
_wrapper.OnMouseMove(pos);
}
else if (evt.type == EventType.MouseMove) {
var pos = _getPointerPosition(evt.mousePosition);
_wrapper.OnMouseMove(pos);
}
else if (evt.type == EventType.ScrollWheel && evt.delta.magnitude != 0) {
var delta = evt.delta;
delta.y /= 3f;
var pos = _getPointerPosition(evt.mousePosition);
_wrapper.OnMouseScroll(delta, pos);
}
}
public void mainEntry() {
main();
}
protected virtual void main() {
}
void Input_OnDisable() {
}
void Input_OnEnable() {
}
}
}

8
com.unity.uiwidgets/Editor/third_parties.meta


fileFormatVersion: 2
guid: 41a89d8cd28257149b9e6d7116b7d598
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

377
com.unity.uiwidgets/Runtime/engine2/UIWidgetsPanelWrapper.cs


using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using AOT;
using Unity.UIWidgets.engine2;
using Unity.UIWidgets.foundation;
using Unity.UIWidgets.gestures;
using Unity.UIWidgets.services;
using Unity.UIWidgets.ui;
using UnityEngine;
namespace Unity.UIWidgets.editor2 {
#region Platform: Windows Specific Functionalities
#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN
public partial class UIWidgetsPanelWrapper {
RenderTexture _renderTexture;
public RenderTexture renderTexture {
get { return _renderTexture; }
}
void _createRenderTexture(int width, int height, float devicePixelRatio) {
D.assert(_renderTexture == null);
var desc = new RenderTextureDescriptor(
width, height, RenderTextureFormat.ARGB32, 0) {
useMipMap = false,
autoGenerateMips = false,
};
_renderTexture = new RenderTexture(desc) {hideFlags = HideFlags.HideAndDontSave};
_renderTexture.Create();
_width = width;
_height = height;
_devicePixelRatio = devicePixelRatio;
}
void _destroyRenderTexture() {
D.assert(_renderTexture != null);
ObjectUtils.SafeDestroy(_renderTexture);
_renderTexture = null;
}
void _enableUIWidgetsPanel(string font_settings) {
UIWidgetsPanel_onEnable(_ptr, _renderTexture.GetNativeTexturePtr(),
_width, _height, _devicePixelRatio, Application.streamingAssetsPath, font_settings);
}
void _resizeUIWidgetsPanel() {
UIWidgetsPanel_onRenderTexture(_ptr,
_renderTexture.GetNativeTexturePtr(),
_width, _height, _devicePixelRatio);
}
void _disableUIWidgetsPanel() {
_renderTexture = null;
}
[DllImport(NativeBindings.dllName)]
static extern void UIWidgetsPanel_onEnable(IntPtr ptr,
IntPtr nativeTexturePtr, int width, int height, float dpi, string streamingAssetsPath,
string font_settings);
[DllImport(NativeBindings.dllName)]
static extern void UIWidgetsPanel_onRenderTexture(
IntPtr ptr, IntPtr nativeTexturePtr, int width, int height, float dpi);
}
#endif
#endregion
#region Platform: MacOs Specific Functionalities
#if UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX
public partial class UIWidgetsPanelWrapper {
Texture _renderTexture;
public Texture renderTexture {
get { return _renderTexture; }
}
void _createRenderTexture(int width, int height, float devicePixelRatio) {
D.assert(_renderTexture == null);
_width = width;
_height = height;
_devicePixelRatio = devicePixelRatio;
}
void _destroyRenderTexture() {
D.assert(_renderTexture != null);
var releaseOK = UIWidgetsPanel_releaseNativeTexture(_ptr);
D.assert(releaseOK);
_renderTexture = null;
}
void _enableUIWidgetsPanel(string font_settings) {
D.assert(_renderTexture == null);
IntPtr native_tex_ptr = UIWidgetsPanel_onEnable(_ptr, _width, _height, _devicePixelRatio,
Application.streamingAssetsPath, font_settings);
D.assert(native_tex_ptr != IntPtr.Zero);
_renderTexture =
Texture2D.CreateExternalTexture(_width, _height, TextureFormat.BGRA32, false, true, native_tex_ptr);
}
void _disableUIWidgetsPanel() {
_renderTexture = null;
}
void _resizeUIWidgetsPanel() {
D.assert(_renderTexture == null);
IntPtr native_tex_ptr = UIWidgetsPanel_onRenderTexture(_ptr, _width, _height, _devicePixelRatio);
D.assert(native_tex_ptr != IntPtr.Zero);
_renderTexture =
Texture2D.CreateExternalTexture(_width, _height, TextureFormat.BGRA32, false, true, native_tex_ptr);
}
[DllImport(NativeBindings.dllName)]
static extern IntPtr UIWidgetsPanel_onEnable(IntPtr ptr,
int width, int height, float dpi, string streamingAssetsPath, string font_settings);
[DllImport(NativeBindings.dllName)]
static extern bool UIWidgetsPanel_releaseNativeTexture(IntPtr ptr);
[DllImport(NativeBindings.dllName)]
static extern IntPtr UIWidgetsPanel_onRenderTexture(
IntPtr ptr, int width, int height, float dpi);
}
#endif
#endregion
#region Window Common Properties and Functions
public partial class UIWidgetsPanelWrapper {
public static UIWidgetsPanelWrapper current {
get { return Window.instance._panel; }
}
IntPtr _ptr;
GCHandle _handle;
int _width;
int _height;
float _devicePixelRatio;
IUIWidgetsWindow _host;
public IUIWidgetsWindow window {
get { return _host; }
}
public Isolate isolate { get; private set; }
public float devicePixelRatio {
get { return _devicePixelRatio; }
}
public void Initiate(IUIWidgetsWindow host, int width, int height, float dpr,
Dictionary<string, object> settings) {
D.assert(_renderTexture == null);
_recreateRenderTexture(width, height, dpr);
_handle = GCHandle.Alloc(this);
_ptr = UIWidgetsPanel_constructor((IntPtr) _handle, (int) host.getWindowType(), UIWidgetsPanel_entrypoint);
_host = host;
_enableUIWidgetsPanel(JSONMessageCodec.instance.toJson(settings));
NativeConsole.OnEnable();
}
public void _entryPoint() {
try {
isolate = Isolate.current;
Window.instance._panel = this;
_host.mainEntry();
}
catch (Exception ex) {
Debug.LogException(new Exception("exception in main", ex));
}
}
public bool didDisplayMetricsChanged(int width, int height, float dpr) {
return width != _width || height != _height || dpr != _devicePixelRatio;
}
public void OnDisplayMetricsChanged(int width, int height, float dpr) {
if (_ptr != IntPtr.Zero && _renderTexture) {
if (_recreateRenderTexture(width, height, dpr)) {
_resizeUIWidgetsPanel();
}
}
}
public void Destroy() {
UIWidgetsPanel_onDisable(_ptr);
UIWidgetsPanel_dispose(_ptr);
_ptr = IntPtr.Zero;
_handle.Free();
_handle = default;
_disableUIWidgetsPanel();
D.assert(!isolate.isValid);
}
bool _recreateRenderTexture(int width, int height, float devicePixelRatio) {
if (_renderTexture != null && _width == width && _height == height &&
_devicePixelRatio == devicePixelRatio) {
return false;
}
if (_renderTexture) {
_destroyRenderTexture();
}
_createRenderTexture(width, height, devicePixelRatio);
return true;
}
public int registerTexture(Texture texture) {
return UIWidgetsPanel_registerTexture(_ptr, texture.GetNativeTexturePtr());
}
public void unregisterTexture(int textureId) {
UIWidgetsPanel_unregisterTexture(_ptr, textureId);
}
public void markNewFrameAvailable(int textureId) {
UIWidgetsPanel_markNewFrameAvailable(_ptr, textureId);
}
public void onEditorUpdate() {
UIWidgetsPanel_onEditorUpdate(_ptr);
}
delegate void UIWidgetsPanel_EntrypointCallback(IntPtr handle);
[MonoPInvokeCallback(typeof(UIWidgetsPanel_EntrypointCallback))]
static void UIWidgetsPanel_entrypoint(IntPtr handle) {
GCHandle gcHandle = (GCHandle) handle;
UIWidgetsPanelWrapper panel = (UIWidgetsPanelWrapper) gcHandle.Target;
panel._entryPoint();
}
[DllImport(NativeBindings.dllName)]
static extern IntPtr UIWidgetsPanel_constructor(IntPtr handle, int windowType,
UIWidgetsPanel_EntrypointCallback entrypointCallback);
[DllImport(NativeBindings.dllName)]
static extern void UIWidgetsPanel_dispose(IntPtr ptr);
[DllImport(NativeBindings.dllName)]
static extern void UIWidgetsPanel_onDisable(IntPtr ptr);
[DllImport(NativeBindings.dllName)]
static extern int UIWidgetsPanel_registerTexture(IntPtr ptr, IntPtr nativeTexturePtr);
[DllImport(NativeBindings.dllName)]
static extern void UIWidgetsPanel_unregisterTexture(IntPtr ptr, int textureId);
[DllImport(NativeBindings.dllName)]
static extern void UIWidgetsPanel_markNewFrameAvailable(IntPtr ptr, int textureId);
#if UNITY_EDITOR
[DllImport(NativeBindings.dllName)]
static extern void UIWidgetsPanel_onEditorUpdate(IntPtr ptr);
#else
static void UIWidgetsPanel_onEditorUpdate(IntPtr ptr) { throw new NotImplementedException(); }
#endif
}
#endregion
#region Input Events Handles
public partial class UIWidgetsPanelWrapper {
public void OnMouseMove(Vector2? pos) {
if (pos == null) {
return;
}
UIWidgetsPanel_onMouseMove(_ptr, pos.Value.x, pos.Value.y);
}
public void OnMouseScroll(Vector2 delta, Vector2? pos) {
if (pos == null) {
return;
}
UIWidgetsPanel_onScroll(_ptr, delta.x, delta.y, pos.Value.x, pos.Value.y);
}
public void OnPointerDown(Vector2? pos, int pointerId) {
if (pos == null) {
return;
}
// mouse event
if (pointerId < 0) {
UIWidgetsPanel_onMouseDown(_ptr, pos.Value.x, pos.Value.y, pointerId);
}
}
public void OnPointerUp(Vector2? pos, int pointerId) {
if (pos == null) {
return;
}
// mouse event
if (pointerId < 0) {
UIWidgetsPanel_onMouseUp(_ptr, pos.Value.x, pos.Value.y, pointerId);
}
}
public void OnDrag(Vector2? pos, int pointerId) {
if (pos == null) {
return;
}
// mouse event
if (pointerId < 0) {
UIWidgetsPanel_onMouseMove(_ptr, pos.Value.x, pos.Value.y);
}
}
public void OnPointerLeave() {
UIWidgetsPanel_onMouseLeave(_ptr);
}
public void OnKeyDown(Event e) {
UIWidgetsPanel_onKey(_ptr, e.keyCode, e.type == EventType.KeyDown);
if (e.character != 0 || e.keyCode == KeyCode.Backspace) {
PointerEventConverter.KeyEvent.Enqueue(new Event(e));
// TODO: add on char
// UIWidgetsPanel_onChar(_ptr, e.character);
}
}
[DllImport(NativeBindings.dllName)]
static extern void UIWidgetsPanel_onChar(IntPtr ptr, char c);
[DllImport(NativeBindings.dllName)]
static extern void UIWidgetsPanel_onKey(IntPtr ptr, KeyCode keyCode, bool isKeyDown);
[DllImport(NativeBindings.dllName)]
static extern void UIWidgetsPanel_onMouseDown(IntPtr ptr, float x, float y, int button);
[DllImport(NativeBindings.dllName)]
static extern void UIWidgetsPanel_onMouseUp(IntPtr ptr, float x, float y, int button);
[DllImport(NativeBindings.dllName)]
static extern void UIWidgetsPanel_onMouseMove(IntPtr ptr, float x, float y);
[DllImport(NativeBindings.dllName)]
static extern void UIWidgetsPanel_onMouseLeave(IntPtr ptr);
[DllImport(NativeBindings.dllName)]
static extern void UIWidgetsPanel_onScroll(IntPtr ptr, float x, float y, float px, float py);
}
#endregion
}

8
com.unity.uiwidgets/Runtime/redux.meta


fileFormatVersion: 2
guid: a074d5db1a47743f19fc0f9ac709e173
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

3
Samples/UIWidgetsSamples_2019_4/Assets/Editor/EditorWindowSample.meta


fileFormatVersion: 2
guid: 67e95d5f76f549d4ad7bfdeda34a9e75
timeCreated: 1614132309

7
Samples/UIWidgetsSamples_2019_4/Assets/Editor/EditorWindowSample/UIWidgetsEditorWindowSample.asmdef.meta


fileFormatVersion: 2
guid: 0ee4c4c70c305834389c168df0125409
AssemblyDefinitionImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

21
Samples/UIWidgetsSamples_2019_4/Assets/Editor/EditorWindowSample/GalleryMain.cs


using UIWidgetsGallery.gallery;
using Unity.UIWidgets.Editor;
using UnityEditor;
using ui_ = Unity.UIWidgets.widgets.ui_;
namespace UIWidgetsEditorWindowSample
{
public class EditorWindowGallery : UIWidgetsEditorPanel
{
[MenuItem("UIWidgets/EditorSample")]
public static void CountDemo()
{
CreateWindow<EditorWindowGallery>();
}
protected override void main()
{
ui_.runApp(new GalleryApp());
}
}
}

16
Samples/UIWidgetsSamples_2019_4/Assets/Editor/EditorWindowSample/UIWidgetsEditorWindowSample.asmdef


{
"name": "UIWidgetsEditorWindowSample",
"references": [
"Unity.UIWidgets",
"Unity.UIWidgets.Editor",
"UIWidgetsGallery"
],
"optionalUnityReferences": [],
"includePlatforms": [],
"excludePlatforms": [],
"allowUnsafeCode": false,
"overrideReferences": false,
"precompiledReferences": [],
"autoReferenced": true,
"defineConstraints": []
}

3
Samples/UIWidgetsSamples_2019_4/Assets/Editor/EditorWindowSample/GalleryMain.cs.meta


fileFormatVersion: 2
guid: 5e098e276aca4edf89cd58abb8af51b0
timeCreated: 1614132321

39
com.unity.uiwidgets/Editor/third_parties/EditorCoroutines.cs


using System.Collections;
using UnityEditor;
using marijnz.EditorCoroutines;
namespace Unity.UIWidgets.Editor {
public static class UIWidgetsEditorCoroutineExtensions
{
public static EditorCoroutines.EditorCoroutine StartCoroutine(this EditorWindow thisRef, IEnumerator coroutine)
{
return EditorCoroutines.StartCoroutine(coroutine, thisRef);
}
public static EditorCoroutines.EditorCoroutine StartCoroutine(this EditorWindow thisRef, string methodName)
{
return EditorCoroutines.StartCoroutine(methodName, thisRef);
}
public static EditorCoroutines.EditorCoroutine StartCoroutine(this EditorWindow thisRef, string methodName, object value)
{
return EditorCoroutines.StartCoroutine(methodName, value, thisRef);
}
public static void StopCoroutine(this EditorWindow thisRef, IEnumerator coroutine)
{
EditorCoroutines.StopCoroutine(coroutine, thisRef);
}
public static void StopCoroutine(this EditorWindow thisRef, string methodName)
{
EditorCoroutines.StopCoroutine(methodName, thisRef);
}
public static void StopAllCoroutines(this EditorWindow thisRef)
{
EditorCoroutines.StopAllCoroutines(thisRef);
}
}
}

8
com.unity.uiwidgets/Editor/third_parties/editor_coroutines.meta


fileFormatVersion: 2
guid: d2360e9d4e895a442a14215d1d4953f7
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

407
com.unity.uiwidgets/Editor/third_parties/editor_coroutines/EditorCoroutines.cs


using UnityEngine;
using System.Collections;
using UnityEditor;
using System.Collections.Generic;
using System;
using System.Reflection;
namespace marijnz.EditorCoroutines
{
public class EditorCoroutines
{
public class EditorCoroutine
{
public ICoroutineYield currentYield = new YieldDefault();
public IEnumerator routine;
public string routineUniqueHash;
public string ownerUniqueHash;
public string MethodName = "";
public int ownerHash;
public string ownerType;
public bool finished = false;
public EditorCoroutine(IEnumerator routine, int ownerHash, string ownerType)
{
this.routine = routine;
this.ownerHash = ownerHash;
this.ownerType = ownerType;
ownerUniqueHash = ownerHash + "_" + ownerType;
if (routine != null)
{
string[] split = routine.ToString().Split('<', '>');
if (split.Length == 3)
{
MethodName = split[1];
}
}
routineUniqueHash = ownerHash + "_" + ownerType + "_" + MethodName;
}
public EditorCoroutine(string methodName, int ownerHash, string ownerType)
{
MethodName = methodName;
this.ownerHash = ownerHash;
this.ownerType = ownerType;
ownerUniqueHash = ownerHash + "_" + ownerType;
routineUniqueHash = ownerHash + "_" + ownerType + "_" + MethodName;
}
}
public interface ICoroutineYield
{
bool IsDone(float deltaTime);
}
struct YieldDefault : ICoroutineYield
{
public bool IsDone(float deltaTime)
{
return true;
}
}
struct YieldWaitForSeconds : ICoroutineYield
{
public float timeLeft;
public bool IsDone(float deltaTime)
{
timeLeft -= deltaTime;
return timeLeft < 0;
}
}
struct YieldCustomYieldInstruction : ICoroutineYield
{
public CustomYieldInstruction customYield;
public bool IsDone(float deltaTime)
{
return !customYield.keepWaiting;
}
}
struct YieldWWW : ICoroutineYield
{
public WWW Www;
public bool IsDone(float deltaTime)
{
return Www.isDone;
}
}
struct YieldAsync : ICoroutineYield
{
public AsyncOperation asyncOperation;
public bool IsDone(float deltaTime)
{
return asyncOperation.isDone;
}
}
struct YieldNestedCoroutine : ICoroutineYield
{
public EditorCoroutine coroutine;
public bool IsDone(float deltaTime)
{
return coroutine.finished;
}
}
static EditorCoroutines instance = null;
Dictionary<string, List<EditorCoroutine>> coroutineDict = new Dictionary<string, List<EditorCoroutine>>();
List<List<EditorCoroutine>> tempCoroutineList = new List<List<EditorCoroutine>>();
Dictionary<string, Dictionary<string, EditorCoroutine>> coroutineOwnerDict =
new Dictionary<string, Dictionary<string, EditorCoroutine>>();
DateTime previousTimeSinceStartup;
/// <summary>Starts a coroutine.</summary>
/// <param name="routine">The coroutine to start.</param>
/// <param name="thisReference">Reference to the instance of the class containing the method.</param>
public static EditorCoroutine StartCoroutine(IEnumerator routine, object thisReference)
{
CreateInstanceIfNeeded();
return instance.GoStartCoroutine(routine, thisReference);
}
/// <summary>Starts a coroutine.</summary>
/// <param name="methodName">The name of the coroutine method to start.</param>
/// <param name="thisReference">Reference to the instance of the class containing the method.</param>
public static EditorCoroutine StartCoroutine(string methodName, object thisReference)
{
return StartCoroutine(methodName, null, thisReference);
}
/// <summary>Starts a coroutine.</summary>
/// <param name="methodName">The name of the coroutine method to start.</param>
/// <param name="value">The parameter to pass to the coroutine.</param>
/// <param name="thisReference">Reference to the instance of the class containing the method.</param>
public static EditorCoroutine StartCoroutine(string methodName, object value, object thisReference)
{
MethodInfo methodInfo = thisReference.GetType()
.GetMethod(methodName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
if (methodInfo == null)
{
Debug.LogError("Coroutine '" + methodName + "' couldn't be started, the method doesn't exist!");
}
object returnValue;
if (value == null)
{
returnValue = methodInfo.Invoke(thisReference, null);
}
else
{
returnValue = methodInfo.Invoke(thisReference, new object[] {value});
}
if (returnValue is IEnumerator)
{
CreateInstanceIfNeeded();
return instance.GoStartCoroutine((IEnumerator) returnValue, thisReference);
}
else
{
Debug.LogError("Coroutine '" + methodName + "' couldn't be started, the method doesn't return an IEnumerator!");
}
return null;
}
/// <summary>Stops all coroutines being the routine running on the passed instance.</summary>
/// <param name="routine"> The coroutine to stop.</param>
/// <param name="thisReference">Reference to the instance of the class containing the method.</param>
public static void StopCoroutine(IEnumerator routine, object thisReference)
{
CreateInstanceIfNeeded();
instance.GoStopCoroutine(routine, thisReference);
}
/// <summary>
/// Stops all coroutines named methodName running on the passed instance.</summary>
/// <param name="methodName"> The name of the coroutine method to stop.</param>
/// <param name="thisReference">Reference to the instance of the class containing the method.</param>
public static void StopCoroutine(string methodName, object thisReference)
{
CreateInstanceIfNeeded();
instance.GoStopCoroutine(methodName, thisReference);
}
/// <summary>
/// Stops all coroutines running on the passed instance.</summary>
/// <param name="thisReference">Reference to the instance of the class containing the method.</param>
public static void StopAllCoroutines(object thisReference)
{
CreateInstanceIfNeeded();
instance.GoStopAllCoroutines(thisReference);
}
static void CreateInstanceIfNeeded()
{
if (instance == null)
{
instance = new EditorCoroutines();
instance.Initialize();
}
}
void Initialize()
{
previousTimeSinceStartup = DateTime.Now;
EditorApplication.update += OnUpdate;
}
void GoStopCoroutine(IEnumerator routine, object thisReference)
{
GoStopActualRoutine(CreateCoroutine(routine, thisReference));
}
void GoStopCoroutine(string methodName, object thisReference)
{
GoStopActualRoutine(CreateCoroutineFromString(methodName, thisReference));
}
void GoStopActualRoutine(EditorCoroutine routine)
{
if (coroutineDict.ContainsKey(routine.routineUniqueHash))
{
coroutineOwnerDict[routine.ownerUniqueHash].Remove(routine.routineUniqueHash);
coroutineDict.Remove(routine.routineUniqueHash);
}
}
void GoStopAllCoroutines(object thisReference)
{
EditorCoroutine coroutine = CreateCoroutine(null, thisReference);
if (coroutineOwnerDict.ContainsKey(coroutine.ownerUniqueHash))
{
foreach (var couple in coroutineOwnerDict[coroutine.ownerUniqueHash])
{
coroutineDict.Remove(couple.Value.routineUniqueHash);
}
coroutineOwnerDict.Remove(coroutine.ownerUniqueHash);
}
}
EditorCoroutine GoStartCoroutine(IEnumerator routine, object thisReference)
{
if (routine == null)
{
Debug.LogException(new Exception("IEnumerator is null!"), null);
}
EditorCoroutine coroutine = CreateCoroutine(routine, thisReference);
GoStartCoroutine(coroutine);
return coroutine;
}
void GoStartCoroutine(EditorCoroutine coroutine)
{
if (!coroutineDict.ContainsKey(coroutine.routineUniqueHash))
{
List<EditorCoroutine> newCoroutineList = new List<EditorCoroutine>();
coroutineDict.Add(coroutine.routineUniqueHash, newCoroutineList);
}
coroutineDict[coroutine.routineUniqueHash].Add(coroutine);
if (!coroutineOwnerDict.ContainsKey(coroutine.ownerUniqueHash))
{
Dictionary<string, EditorCoroutine> newCoroutineDict = new Dictionary<string, EditorCoroutine>();
coroutineOwnerDict.Add(coroutine.ownerUniqueHash, newCoroutineDict);
}
// If the method from the same owner has been stored before, it doesn't have to be stored anymore,
// One reference is enough in order for "StopAllCoroutines" to work
if (!coroutineOwnerDict[coroutine.ownerUniqueHash].ContainsKey(coroutine.routineUniqueHash))
{
coroutineOwnerDict[coroutine.ownerUniqueHash].Add(coroutine.routineUniqueHash, coroutine);
}
MoveNext(coroutine);
}
EditorCoroutine CreateCoroutine(IEnumerator routine, object thisReference)
{
return new EditorCoroutine(routine, thisReference.GetHashCode(), thisReference.GetType().ToString());
}
EditorCoroutine CreateCoroutineFromString(string methodName, object thisReference)
{
return new EditorCoroutine(methodName, thisReference.GetHashCode(), thisReference.GetType().ToString());
}
void OnUpdate()
{
float deltaTime = (float) (DateTime.Now.Subtract(previousTimeSinceStartup).TotalMilliseconds / 1000.0f);
previousTimeSinceStartup = DateTime.Now;
if (coroutineDict.Count == 0)
{
return;
}
tempCoroutineList.Clear();
foreach (var pair in coroutineDict)
tempCoroutineList.Add(pair.Value);
for (var i = tempCoroutineList.Count - 1; i >= 0; i--)
{
List<EditorCoroutine> coroutines = tempCoroutineList[i];
for (int j = coroutines.Count - 1; j >= 0; j--)
{
EditorCoroutine coroutine = coroutines[j];
if (!coroutine.currentYield.IsDone(deltaTime))
{
continue;
}
if (!MoveNext(coroutine))
{
coroutines.RemoveAt(j);
coroutine.currentYield = null;
coroutine.finished = true;
}
if (coroutines.Count == 0)
{
coroutineDict.Remove(coroutine.routineUniqueHash);
}
}
}
}
static bool MoveNext(EditorCoroutine coroutine)
{
if (coroutine.routine.MoveNext())
{
return Process(coroutine);
}
return false;
}
// returns false if no next, returns true if OK
static bool Process(EditorCoroutine coroutine)
{
object current = coroutine.routine.Current;
if (current == null)
{
coroutine.currentYield = new YieldDefault();
}
else if (current is WaitForSeconds)
{
float seconds = float.Parse(GetInstanceField(typeof(WaitForSeconds), current, "m_Seconds").ToString());
coroutine.currentYield = new YieldWaitForSeconds() {timeLeft = seconds};
}
else if (current is CustomYieldInstruction)
{
coroutine.currentYield = new YieldCustomYieldInstruction()
{
customYield = current as CustomYieldInstruction
};
}
else if (current is WWW)
{
coroutine.currentYield = new YieldWWW {Www = (WWW) current};
}
else if (current is WaitForFixedUpdate || current is WaitForEndOfFrame)
{
coroutine.currentYield = new YieldDefault();
}
else if (current is AsyncOperation)
{
coroutine.currentYield = new YieldAsync {asyncOperation = (AsyncOperation) current};
}
else if (current is EditorCoroutine)
{
coroutine.currentYield = new YieldNestedCoroutine { coroutine= (EditorCoroutine) current};
}
else
{
Debug.LogException(
new Exception("<" + coroutine.MethodName + "> yielded an unknown or unsupported type! (" + current.GetType() + ")"),
null);
coroutine.currentYield = new YieldDefault();
}
return true;
}
static object GetInstanceField(Type type, object instance, string fieldName)
{
BindingFlags bindFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static;
FieldInfo field = type.GetField(fieldName, bindFlags);
return field.GetValue(instance);
}
}
}

21
com.unity.uiwidgets/Editor/third_parties/editor_coroutines/LICENSE


MIT License
Copyright (c) 2017 Marijn Zwemmer
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

19
com.unity.uiwidgets/Runtime/redux/redux_logging.cs


using UnityEngine;
namespace Unity.UIWidgets.Redux {
public static class ReduxLogging {
public static Middleware<State> create<State>() {
return (store) => (next) => new DispatcherImpl((action) => {
var previousState = store.getState();
var previousStateDump = JsonUtility.ToJson(previousState);
var result = next.dispatch(action);
var afterState = store.getState();
var afterStateDump = JsonUtility.ToJson(afterState);
Debug.LogFormat("Action name={0} data={1}", action.ToString(), JsonUtility.ToJson(action));
Debug.LogFormat("previousState=\n{0}", previousStateDump);
Debug.LogFormat("afterState=\n{0}", afterStateDump);
return result;
});
}
}
}

11
com.unity.uiwidgets/Runtime/redux/redux_logging.cs.meta


fileFormatVersion: 2
guid: 66d5d5237e5f84f7f870b6e8d2b87815
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

32
com.unity.uiwidgets/Runtime/redux/redux_thunk.cs


using System;
namespace Unity.UIWidgets.Redux {
public static class ReduxThunk {
public static Middleware<State> create<State>() {
return store => next => new DispatcherImpl(action => {
var thunkAction = action as ThunkAction<State>;
if (thunkAction != null && thunkAction.action != null) {
return thunkAction.action(store.dispatcher, store.getState);
}
return next.dispatch(action);
});
}
}
public sealed class ThunkAction<State> {
public readonly Func<Dispatcher, Func<State>, object> action;
public readonly string displayName;
public ThunkAction(
Func<Dispatcher, Func<State>, object> action = null,
string displayName = null) {
this.action = action;
this.displayName = displayName ?? "";
}
public override string ToString() {
return "ThunkAction(" + displayName + ")";
}
}
}

11
com.unity.uiwidgets/Runtime/redux/redux_thunk.cs.meta


fileFormatVersion: 2
guid: f837de040a3fa4a3fb3e6c344153e1eb
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

81
com.unity.uiwidgets/Runtime/redux/store.cs


using System;
using System.Linq;
namespace Unity.UIWidgets {
public interface Dispatcher {
T dispatch<T>(object action);
object dispatch(object action);
}
public class DispatcherImpl : Dispatcher {
readonly Func<object, object> _impl;
public DispatcherImpl(Func<object, object> impl) {
_impl = impl;
}
public T dispatch<T>(object action) {
if (_impl == null) {
return default;
}
return (T) _impl(action);
}
public object dispatch(object action) {
if (_impl == null) {
return default;
}
return _impl(action);
}
}
public delegate State Reducer<State>(State previousState, object action);
public delegate Func<Dispatcher, Dispatcher> Middleware<State>(Store<State> store);
public delegate void StateChangedHandler<State>(State action);
public class Store<State> {
public StateChangedHandler<State> stateChanged;
readonly Dispatcher _dispatcher;
readonly Reducer<State> _reducer;
State _state;
public Store(
Reducer<State> reducer,
State initialState = default,
params Middleware<State>[] middleware) {
_reducer = reducer;
_dispatcher = _applyMiddleware(middleware);
_state = initialState;
}
public Dispatcher dispatcher {
get { return _dispatcher; }
}
public State getState() {
return _state;
}
Dispatcher _applyMiddleware(params Middleware<State>[] middleware) {
return middleware.Reverse().Aggregate<Middleware<State>, Dispatcher>(
new DispatcherImpl(_innerDispatch),
(current, middlewareItem) => middlewareItem(this)(current));
}
object _innerDispatch(object action) {
_state = _reducer(_state, action);
if (stateChanged != null) {
stateChanged(_state);
}
return action;
}
}
}

11
com.unity.uiwidgets/Runtime/redux/store.cs.meta


fileFormatVersion: 2
guid: 14bfb41ffcfd144f1b32a04eff5f93d0
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

172
com.unity.uiwidgets/Runtime/redux/widget_redux.cs


using System;
using Unity.UIWidgets.foundation;
using Unity.UIWidgets.ui;
using Unity.UIWidgets.widgets;
namespace Unity.UIWidgets.Redux {
public class StoreProvider<State> : InheritedWidget {
readonly Store<State> _store;
public StoreProvider(
Store<State> store = null,
Widget child = null,
Key key = null) : base(key: key, child: child) {
D.assert(store != null);
D.assert(child != null);
_store = store;
}
public static Store<State> of(BuildContext context) {
var type = _typeOf<StoreProvider<State>>();
StoreProvider<State> provider = context.inheritFromWidgetOfExactType(type) as StoreProvider<State>;
if (provider == null) {
throw new UIWidgetsError("StoreProvider is missing");
}
return provider._store;
}
static Type _typeOf<T>() {
return typeof(T);
}
public override bool updateShouldNotify(InheritedWidget old) {
return !Equals(objA: _store, objB: ((StoreProvider<State>) old)._store);
}
}
public delegate Widget ViewModelBuilder<in ViewModel>(BuildContext context, ViewModel viewModel, Dispatcher dispatcher);
public delegate ViewModel StoreConverter<in State, out ViewModel>(State state);
public delegate bool ShouldRebuildCallback<in ViewModel>(ViewModel previous, ViewModel current);
public class StoreConnector<State, ViewModel> : StatelessWidget {
public readonly ViewModelBuilder<ViewModel> builder;
public readonly StoreConverter<State, ViewModel> converter;
public readonly ShouldRebuildCallback<ViewModel> shouldRebuild;
public readonly bool pure;
public StoreConnector(
ViewModelBuilder<ViewModel> builder = null,
StoreConverter<State, ViewModel> converter = null,
bool pure = false,
ShouldRebuildCallback<ViewModel> shouldRebuild = null,
Key key = null) : base(key) {
D.assert(builder != null);
D.assert(converter != null);
this.pure = pure;
this.builder = builder;
this.converter = converter;
this.shouldRebuild = shouldRebuild;
}
public override Widget build(BuildContext context) {
return new _StoreListener<State, ViewModel>(
store: StoreProvider<State>.of(context),
builder: builder,
converter: converter,
pure: pure,
shouldRebuild: shouldRebuild
);
}
}
public class _StoreListener<State, ViewModel> : StatefulWidget {
public readonly ViewModelBuilder<ViewModel> builder;
public readonly StoreConverter<State, ViewModel> converter;
public readonly Store<State> store;
public readonly ShouldRebuildCallback<ViewModel> shouldRebuild;
public readonly bool pure;
public _StoreListener(
ViewModelBuilder<ViewModel> builder = null,
StoreConverter<State, ViewModel> converter = null,
Store<State> store = null,
bool pure = false,
ShouldRebuildCallback<ViewModel> shouldRebuild = null,
Key key = null) : base(key) {
D.assert(builder != null);
D.assert(converter != null);
D.assert(store != null);
this.store = store;
this.builder = builder;
this.converter = converter;
this.pure = pure;
this.shouldRebuild = shouldRebuild;
}
public override widgets.State createState() {
return new _StoreListenerState<State, ViewModel>();
}
}
class _StoreListenerState<State, ViewModel> : State<_StoreListener<State, ViewModel>> {
ViewModel latestValue;
public override void initState() {
base.initState();
_init();
}
public override void dispose() {
widget.store.stateChanged -= _handleStateChanged;
base.dispose();
}
public override void didUpdateWidget(StatefulWidget oldWidget) {
var oldStore = ((_StoreListener<State, ViewModel>) oldWidget).store;
if (widget.store != oldStore) {
oldStore.stateChanged -= _handleStateChanged;
_init();
}
base.didUpdateWidget(oldWidget);
}
void _init() {
widget.store.stateChanged += _handleStateChanged;
latestValue = widget.converter(widget.store.getState());
}
void _handleStateChanged(State state) {
if (Window.instance._panel != null) {
_innerStateChanged(state: state);
}
else {
var isolate = Isolate.current;
using (Isolate.getScope(isolate: isolate)) {
_innerStateChanged(state: state);
}
}
}
void _innerStateChanged(State state) {
var preValue = latestValue;
latestValue = widget.converter(widget.store.getState());
if (widget.shouldRebuild != null) {
if (!widget.shouldRebuild(preValue, latestValue)) {
return;
}
}
else if (widget.pure) {
if (Equals(preValue, latestValue)) {
return;
}
}
setState();
}
public override Widget build(BuildContext context) {
return widget.builder(context, latestValue, widget.store.dispatcher);
}
}
}

11
com.unity.uiwidgets/Runtime/redux/widget_redux.cs.meta


fileFormatVersion: 2
guid: a1765e003a4744e39b381a0bd927735a
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
正在加载...
取消
保存