浏览代码

Merge branch 'dev_1.17.5' into siyaoH/1.17/android

/siyaoH-1.17-PlatformMessage
siyao 4 年前
当前提交
1378fd2d
共有 100 个文件被更改,包括 2634 次插入1794 次删除
  1. 2
      Samples/UIWidgetsSamples_2019_4/Assets/UIWidgetsGallery/demo/cupertino/cupertino_alert_demo.cs
  2. 384
      Samples/UIWidgetsSamples_2019_4/Assets/UIWidgetsGallery/demo/cupertino/cupertino_picker_demo.cs
  3. 2
      Samples/UIWidgetsSamples_2019_4/Assets/UIWidgetsGallery/demo/cupertino/cupertino_switch_demo.cs
  4. 4
      Samples/UIWidgetsSamples_2019_4/Assets/UIWidgetsGallery/demo/material/backdrop_demo.cs
  5. 4
      Samples/UIWidgetsSamples_2019_4/Assets/UIWidgetsGallery/demo/material/selection_controls_demo.cs
  6. 57
      Samples/UIWidgetsSamples_2019_4/Assets/UIWidgetsGallery/demo/shrine/expanding_bottom_sheet.cs
  7. 28
      Samples/UIWidgetsSamples_2019_4/Assets/UIWidgetsGallery/demo/shrine/shopping_cart.cs
  8. 3
      Samples/UIWidgetsSamples_2019_4/Assets/UIWidgetsGallery/demo/shrine/supplemental/product_card.cs
  9. 7
      Samples/UIWidgetsSamples_2019_4/Assets/UIWidgetsGallery/gallery/app.cs
  10. 3
      Samples/UIWidgetsSamples_2019_4/Assets/UIWidgetsSample.asmdef
  11. 2
      com.unity.uiwidgets/Editor/UIWidgetsPanelEditor.cs
  12. 4
      com.unity.uiwidgets/Runtime/animation/animation_controller.cs
  13. 36
      com.unity.uiwidgets/Runtime/cupertino/context_menu.cs
  14. 536
      com.unity.uiwidgets/Runtime/cupertino/date_picker.cs
  15. 10
      com.unity.uiwidgets/Runtime/cupertino/dialog.cs
  16. 14
      com.unity.uiwidgets/Runtime/cupertino/picker.cs
  17. 22
      com.unity.uiwidgets/Runtime/cupertino/route.cs
  18. 7
      com.unity.uiwidgets/Runtime/cupertino/segmented_control.cs
  19. 2
      com.unity.uiwidgets/Runtime/cupertino/switch.cs
  20. 384
      com.unity.uiwidgets/Runtime/engine2/UIWidgetsPanel.cs
  21. 4
      com.unity.uiwidgets/Runtime/foundation/diagnostics.cs
  22. 5
      com.unity.uiwidgets/Runtime/gestures/binding.cs
  23. 8
      com.unity.uiwidgets/Runtime/material/app.cs
  24. 2
      com.unity.uiwidgets/Runtime/material/app_bar.cs
  25. 2
      com.unity.uiwidgets/Runtime/material/app_bar_theme.cs
  26. 4
      com.unity.uiwidgets/Runtime/material/divider.cs
  27. 2
      com.unity.uiwidgets/Runtime/material/navigation_rail_theme.cs
  28. 5
      com.unity.uiwidgets/Runtime/material/pickers/date_picker_head.cs
  29. 69
      com.unity.uiwidgets/Runtime/material/theme_data.cs
  30. 4
      com.unity.uiwidgets/Runtime/painting/basic_types.cs
  31. 9
      com.unity.uiwidgets/Runtime/painting/image_provider.cs
  32. 2
      com.unity.uiwidgets/Runtime/painting/image_stream.cs
  33. 2
      com.unity.uiwidgets/Runtime/painting/matrix_utils.cs
  34. 9
      com.unity.uiwidgets/Runtime/rendering/binding.cs
  35. 56
      com.unity.uiwidgets/Runtime/rendering/layer.cs
  36. 25
      com.unity.uiwidgets/Runtime/rendering/list_wheel_viewport.cs
  37. 46
      com.unity.uiwidgets/Runtime/rendering/paragraph.cs
  38. 311
      com.unity.uiwidgets/Runtime/rendering/proxy_box.cs
  39. 16
      com.unity.uiwidgets/Runtime/rendering/proxy_sliver.cs
  40. 2
      com.unity.uiwidgets/Runtime/scheduler2/binding.cs
  41. 7
      com.unity.uiwidgets/Runtime/services/asset_bundle.cs
  42. 2
      com.unity.uiwidgets/Runtime/ui2/Matrix4.cs
  43. 43
      com.unity.uiwidgets/Runtime/ui2/painting.cs
  44. 27
      com.unity.uiwidgets/Runtime/ui2/window.cs
  45. 138
      com.unity.uiwidgets/Runtime/widgets/app.cs
  46. 26
      com.unity.uiwidgets/Runtime/widgets/editable_text.cs
  47. 6
      com.unity.uiwidgets/Runtime/widgets/focus_manager.cs
  48. 4
      com.unity.uiwidgets/Runtime/widgets/focus_traversal.cs
  49. 2
      com.unity.uiwidgets/Runtime/widgets/framework.cs
  50. 8
      com.unity.uiwidgets/Runtime/widgets/image.cs
  51. 68
      com.unity.uiwidgets/Runtime/widgets/list_wheel_scroll_view.cs
  52. 1
      com.unity.uiwidgets/Runtime/widgets/localizations.cs
  53. 41
      com.unity.uiwidgets/Runtime/widgets/navigator.cs
  54. 19
      com.unity.uiwidgets/Runtime/widgets/nested_scroll_view.cs
  55. 17
      com.unity.uiwidgets/Runtime/widgets/routes.cs
  56. 9
      com.unity.uiwidgets/Runtime/widgets/scroll_position.cs
  57. 35
      com.unity.uiwidgets/Runtime/widgets/scrollable.cs
  58. 31
      com.unity.uiwidgets/Runtime/widgets/sliver.cs
  59. 121
      com.unity.uiwidgets/Runtime/widgets/text.cs
  60. 8
      com.unity.uiwidgets/Runtime/widgets/text_selection.cs
  61. 9
      com.unity.uiwidgets/Runtime/widgets/texture.cs
  62. 2
      engine/src/lib/ui/window/window.cc
  63. 21
      engine/src/shell/platform/unity/darwin/macos/uiwidgets_panel.h
  64. 64
      engine/src/shell/platform/unity/darwin/macos/uiwidgets_panel.mm
  65. 3
      engine/src/shell/platform/unity/darwin/macos/uiwidgets_system.h
  66. 20
      engine/src/shell/platform/unity/darwin/macos/uiwidgets_system.mm
  67. 33
      engine/src/shell/platform/unity/darwin/macos/unity_surface_manager.mm
  68. 81
      engine/src/shell/platform/unity/windows/uiwidgets_panel.cc
  69. 21
      engine/src/shell/platform/unity/windows/uiwidgets_panel.h
  70. 19
      engine/src/shell/platform/unity/windows/uiwidgets_system.cc
  71. 3
      engine/src/shell/platform/unity/windows/uiwidgets_system.h
  72. 27
      engine/src/shell/platform/unity/windows/unity_surface_manager.cc
  73. 3
      Samples/UIWidgetsSamples_2019_4/Assets/Editor.meta
  74. 14
      Samples/UIWidgetsSamples_2019_4/Assets/UIWidgetsGallery/UIWidgetsGallery.asmdef
  75. 135
      com.unity.uiwidgets/Editor/UIWidgetsEditorPanel.cs
  76. 8
      com.unity.uiwidgets/Editor/third_parties.meta
  77. 377
      com.unity.uiwidgets/Runtime/engine2/UIWidgetsPanelWrapper.cs
  78. 8
      com.unity.uiwidgets/Runtime/redux.meta
  79. 3
      Samples/UIWidgetsSamples_2019_4/Assets/Editor/EditorWindowSample.meta
  80. 7
      Samples/UIWidgetsSamples_2019_4/Assets/Editor/EditorWindowSample/UIWidgetsEditorWindowSample.asmdef.meta
  81. 21
      Samples/UIWidgetsSamples_2019_4/Assets/Editor/EditorWindowSample/GalleryMain.cs
  82. 16
      Samples/UIWidgetsSamples_2019_4/Assets/Editor/EditorWindowSample/UIWidgetsEditorWindowSample.asmdef
  83. 3
      Samples/UIWidgetsSamples_2019_4/Assets/Editor/EditorWindowSample/GalleryMain.cs.meta
  84. 39
      com.unity.uiwidgets/Editor/third_parties/EditorCoroutines.cs
  85. 8
      com.unity.uiwidgets/Editor/third_parties/editor_coroutines.meta
  86. 407
      com.unity.uiwidgets/Editor/third_parties/editor_coroutines/EditorCoroutines.cs
  87. 21
      com.unity.uiwidgets/Editor/third_parties/editor_coroutines/LICENSE
  88. 19
      com.unity.uiwidgets/Runtime/redux/redux_logging.cs
  89. 11
      com.unity.uiwidgets/Runtime/redux/redux_logging.cs.meta
  90. 32
      com.unity.uiwidgets/Runtime/redux/redux_thunk.cs
  91. 11
      com.unity.uiwidgets/Runtime/redux/redux_thunk.cs.meta
  92. 81
      com.unity.uiwidgets/Runtime/redux/store.cs
  93. 11
      com.unity.uiwidgets/Runtime/redux/store.cs.meta
  94. 172
      com.unity.uiwidgets/Runtime/redux/widget_redux.cs
  95. 11
      com.unity.uiwidgets/Runtime/redux/widget_redux.cs.meta

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


navigationBar: new CupertinoNavigationBar(
middle: new Text("Alerts"),
previousPageTitle: "Cupertino"
//trailing: CupertinoDemoDocumentationButton(CupertinoAlertDemo.routeName)
//,trailing: CupertinoDemoDocumentationButton(CupertinoAlertDemo.routeName)
),
child: new DefaultTextStyle(
style: CupertinoTheme.of(context).textTheme.textStyle,

384
Samples/UIWidgetsSamples_2019_4/Assets/UIWidgetsGallery/demo/cupertino/cupertino_picker_demo.cs


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

using Unity.UIWidgets.widgets;
using UnityEngine;
using TextStyle = Unity.UIWidgets.painting.TextStyle;
using Brightness = Unity.UIWidgets.ui.Brightness;

return new GestureDetector(
onTap: () => {
CupertinoRouteUtils.showCupertinoModalPopup(
context: context,
semanticsDismissible: true,
builder: (BuildContext context1) =>{
return new _BottomPicker(
child: new CupertinoPicker(
scrollController: scrollController,
itemExtent: CupertinoPickerDemoUtils._kPickerItemHeight,
backgroundColor: CupertinoColors.systemBackground.resolveFrom(context1),
onSelectedItemChanged: (int index)=> {
setState(() => _selectedColorIndex = index);
},
children: widgets
)
CupertinoRouteUtils.showCupertinoModalPopup(
context: context,
semanticsDismissible: true,
builder: (BuildContext context1) =>{
return new _BottomPicker(
child: new CupertinoPicker(
scrollController: scrollController,
itemExtent: CupertinoPickerDemoUtils._kPickerItemHeight,
backgroundColor: CupertinoColors.systemBackground.resolveFrom(context1),
onSelectedItemChanged: (int index)=> {
setState(() => _selectedColorIndex = index);
},
children: widgets
)
);
}
}
);
},
child: new _Menu(
children: new List<Widget>{
new Text("Favorite Color"),
new Text(
CupertinoPickerDemoUtils.coolColorNames[_selectedColorIndex],
style: new TextStyle(color: CupertinoDynamicColor.resolve(CupertinoColors.inactiveGray, context))
)
}
)
);
}
Widget _buildCountdownTimerPicker(BuildContext context) {
return new GestureDetector(
onTap: () =>{
CupertinoRouteUtils.showCupertinoModalPopup(
context: context,
semanticsDismissible: true,
builder: (BuildContext context1) =>{
return new _BottomPicker(
child: new CupertinoTimerPicker(
backgroundColor: CupertinoColors.systemBackground.resolveFrom(context1),
initialTimerDuration: timer,
onTimerDurationChanged: (newTimer) =>{
setState(() => timer = newTimer);
}
},
child: new _Menu(
children: new List<Widget>{
new Text("Favorite Color"),
new Text(
CupertinoPickerDemoUtils.coolColorNames[_selectedColorIndex],
style: new TextStyle(color: CupertinoDynamicColor.resolve(CupertinoColors.inactiveGray, context))
}
)
);
}
Widget _buildCountdownTimerPicker(BuildContext context) {
return new GestureDetector(
onTap: () =>
{
CupertinoRouteUtils.showCupertinoModalPopup(
context: context,
semanticsDismissible: true,
builder: (BuildContext context1) =>
{
return new _BottomPicker(
child: new CupertinoTimerPicker(
backgroundColor: CupertinoColors.systemBackground.resolveFrom(context1),
initialTimerDuration: timer,
onTimerDurationChanged: (TimeSpan newTimer) =>{
setState(() => timer = newTimer);
}
)
);
}
}
},
child: new _Menu(
children: new List<Widget>{
new Text("Countdown Timer"),
new Text(
$"{timer.Hours}:" +
$"{(timer.Minutes % 60).ToString("00")}:" +
$"{(timer.Seconds % 60).ToString("00")}",
style: new TextStyle(color: CupertinoDynamicColor.resolve(CupertinoColors.inactiveGray, context))
),
}
)
},
child: new _Menu(
children: new List<Widget>{
new Text("Countdown Timer"),
new Text(
$"{timer.Hours}:" +
$"{(timer.Minutes % 60).ToString("00")}:" +
$"{(timer.Seconds % 60).ToString("00")}",
style: new TextStyle(color: CupertinoDynamicColor.resolve(CupertinoColors.inactiveGray, context))
),
}
)
);
}
}
Widget _buildDatePicker(BuildContext context)
{
return new GestureDetector(
onTap: () =>
Widget _buildDatePicker(BuildContext context)
CupertinoRouteUtils.showCupertinoModalPopup(
context: context,
semanticsDismissible: true,
builder: (BuildContext context1) =>
return new GestureDetector(
onTap: () =>
return new _BottomPicker(
child: new CupertinoDatePicker(
backgroundColor: CupertinoColors.systemBackground.resolveFrom(context1),
mode: CupertinoDatePickerMode.date,
initialDateTime: date,
onDateTimeChanged: (newDateTime) => { setState(() => date = newDateTime); }
)
CupertinoRouteUtils.showCupertinoModalPopup(
context: context,
semanticsDismissible: true,
builder: (BuildContext context1) =>
{
return new _BottomPicker(
child: new CupertinoDatePicker(
backgroundColor: CupertinoColors.systemBackground.resolveFrom(context1),
mode: CupertinoDatePickerMode.date,
initialDateTime: date,
onDateTimeChanged: (DateTime newDateTime) =>{
setState(() => date = newDateTime);
}
)
);
}
}
},
child: new _Menu(
children: new List<Widget>{
new Text("Date"),
new Text(
date.ToString("MMMM dd, yyyy"),
style: new TextStyle(color: CupertinoDynamicColor.resolve(CupertinoColors.inactiveGray, context))
),
}
)
},
child: new _Menu(
children: new List<Widget>{
new Text("Date"),
new Text(
date.ToString("MMMM dd, yyyy"),
style: new TextStyle(color: CupertinoDynamicColor.resolve(CupertinoColors.inactiveGray, context))
),
}
)
);
}
}
Widget _buildTimePicker(BuildContext context) {
return new GestureDetector(
onTap: () =>{
CupertinoRouteUtils.showCupertinoModalPopup(
context: context,
semanticsDismissible: true,
builder: (BuildContext context1) =>{
return new _BottomPicker(
child: new CupertinoDatePicker(
backgroundColor: CupertinoColors.systemBackground.resolveFrom(context1),
mode: CupertinoDatePickerMode.time,
initialDateTime: time,
onDateTimeChanged: (newDateTime) => {
setState(() => time = newDateTime);
}
)
Widget _buildTimePicker(BuildContext context) {
return new GestureDetector(
onTap: () =>{
CupertinoRouteUtils.showCupertinoModalPopup(
context: context,
semanticsDismissible: true,
builder: (BuildContext context1) =>{
return new _BottomPicker(
child: new CupertinoDatePicker(
backgroundColor: CupertinoColors.systemBackground.resolveFrom(context1),
mode: CupertinoDatePickerMode.time,
initialDateTime: time,
onDateTimeChanged: (newDateTime) => {
setState(() => time = newDateTime);
}
)
);
}
}
},
child:new _Menu(
children: new List<Widget>{
new Text("Time"),
new Text(
time.ToString("h:mm tt"),
style: new TextStyle(color: CupertinoDynamicColor.resolve(CupertinoColors.inactiveGray, context))
),
}
)
},
child:new _Menu(
children: new List<Widget>{
new Text("Time"),
new Text(
time.ToString("h:mm tt"),
style: new TextStyle(color: CupertinoDynamicColor.resolve(CupertinoColors.inactiveGray, context))
),
}
)
);
}
}
Widget _buildDateAndTimePicker(BuildContext context) {
return new GestureDetector(
onTap: ()=> {
CupertinoRouteUtils.showCupertinoModalPopup(
context: context,
semanticsDismissible: true,
builder: (BuildContext context1) =>{
return new _BottomPicker(
child: new CupertinoDatePicker(
backgroundColor: CupertinoColors.systemBackground.resolveFrom(context1),
mode: CupertinoDatePickerMode.dateAndTime,
initialDateTime: dateTime,
onDateTimeChanged: (newDateTime) => {
setState(() => dateTime = newDateTime);
}
)
Widget _buildDateAndTimePicker(BuildContext context) {
return new GestureDetector(
onTap: ()=> {
CupertinoRouteUtils.showCupertinoModalPopup(
context: context,
semanticsDismissible: true,
builder: (BuildContext context1) =>{
return new _BottomPicker(
child: new CupertinoDatePicker(
backgroundColor: CupertinoColors.systemBackground.resolveFrom(context1),
mode: CupertinoDatePickerMode.dateAndTime,
initialDateTime: dateTime,
onDateTimeChanged: (newDateTime) => {
setState(() => dateTime = newDateTime);
}
)
);
}
}
},
child: new _Menu(
children:new List<Widget>{
new Text("Date and Time"),
new Text(
dateTime.ToString("MMMM dd, yyyy") + " " + dateTime.ToString("HH:mm tt"),
style: new TextStyle(color: CupertinoDynamicColor.resolve(CupertinoColors.inactiveGray, context))
),
}
)
},
child: new _Menu(
children:new List<Widget>{
new Text("Date and Time"),
new Text(
dateTime.ToString("MMMM dd, yyyy h:mm tt"),
style: new TextStyle(color: CupertinoDynamicColor.resolve(CupertinoColors.inactiveGray, context))
),
}
)
);
}
public override Widget build(BuildContext context) {
return new CupertinoPageScaffold(
navigationBar: new CupertinoNavigationBar(
middle: new Text("Picker"),
// We're specifying a back label here because the previous page is a
// Material page. CupertinoPageRoutes could auto-populate these back
// labels.
previousPageTitle: "Cupertino"
//trailing: CupertinoDemoDocumentationButton(CupertinoPickerDemo.routeName)
),
child: new DefaultTextStyle(
style: CupertinoTheme.of(context).textTheme.textStyle,
child: new ListView(
children: new List<Widget>{
new Padding(padding: EdgeInsets.only(top: 32.0f)),
_buildColorPicker(context),
//_buildCountdownTimerPicker(context),
//_buildDatePicker(context),
//_buildTimePicker(context),
//_buildDateAndTimePicker(context),
}
)
)
);
}
}
}
}
public override Widget build(BuildContext context) {
return new CupertinoPageScaffold(
navigationBar: new CupertinoNavigationBar(
middle: new Text("Picker"),
// We're specifying a back label here because the previous page is a
// Material page. CupertinoPageRoutes could auto-populate these back
// labels.
previousPageTitle: "Cupertino"
//trailing: CupertinoDemoDocumentationButton(CupertinoPickerDemo.routeName)
),
child: new DefaultTextStyle(
style: CupertinoTheme.of(context).textTheme.textStyle,
child: new ListView(
children: new List<Widget>{
new Padding(padding: EdgeInsets.only(top: 32.0f)),
_buildColorPicker(context),
_buildCountdownTimerPicker(context),
_buildDatePicker(context),
_buildTimePicker(context),
_buildDateAndTimePicker(context),
}
)
)
);
}
}
D.assert(child != null);
this.child = child;
D.assert(child != null);
this.child = child;
public override Widget build(BuildContext context) {
public override Widget build(BuildContext context)
{
height: 216,
padding: EdgeInsets.only(top: 6),
margin: EdgeInsets.only(
bottom: MediaQuery.of(context).viewInsets.bottom
),
color: CupertinoColors.systemBackground.resolveFrom(context),
height: CupertinoPickerDemoUtils._kPickerSheetHeight,
padding: EdgeInsets.only(top: 6.0f),
color: CupertinoColors.label.resolveFrom(context).darkColor,
fontSize: 22
fontSize: 22.0f
// Blocks taps from propagating to the modal sheet and popping.
onTap: ()=> {},
child: new SafeArea(
top: false,
child: child
)
onTap: () =>{ },
child: new SafeArea(
top: false,
child: child
)
}
public class _Menu : StatelessWidget {

);
}
}
}

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,

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


private bool checkboxValueA = true;
private bool checkboxValueB = false;
private bool checkboxValueC;
private bool? checkboxValueC;
private int radioValue = 0;
private bool switchValue = false;

new Checkbox(
value: checkboxValueC,
tristate: true,
onChanged: (bool? value) => { setState(() => { checkboxValueC = value.Value; }); }
onChanged: (bool? value) => { setState(() => { checkboxValueC = value; }); }
)
}
),

57
Samples/UIWidgetsSamples_2019_4/Assets/UIWidgetsGallery/demo/shrine/expanding_bottom_sheet.cs


public class ExpandingBottomSheet : StatefulWidget {
public ExpandingBottomSheet(Key key = null, AnimationController hideController = null)
public ExpandingBottomSheet(
Key key = null,
AnimationController hideController = null)
: base(key: key)
{
D.assert(hideController != null);

}
}
Widget _buildThumbnails(int numProducts) {
return new Container(
child: new Opacity(
opacity: _thumbnailOpacityAnimation.value,
child: new Column(
children: new List<Widget>{
new Row(
children: new List<Widget>{
new AnimatedPadding(
padding: _cartPaddingFor(numProducts),
child: new Icon(Icons.shopping_cart),
duration: TimeSpan.FromMilliseconds(225)
),
new Container(
// Accounts for the overflow number
width: numProducts > 3 ? _width - 94.0f: _width - 64.0f,
height: expanding_buttom_sheetUtils._kCartHeight,
padding: EdgeInsets.symmetric(vertical: 8.0f),
child: new ProductThumbnailRow()
),
new ExtraProductsNumber(),
}
),
}
)
Widget _buildThumbnails(int numProducts)
{
return new Opacity(
opacity: _thumbnailOpacityAnimation.value,
child: new Column(
children: new List<Widget>
{
new Row(
children: new List<Widget>
{
new AnimatedPadding(
padding: _cartPaddingFor(numProducts),
child: new Icon(Icons.shopping_cart),
duration: TimeSpan.FromMilliseconds(225)
),
new Container(
// Accounts for the overflow number
width: numProducts > 3 ? _width - 94.0f : _width - 64.0f,
height: expanding_buttom_sheetUtils._kCartHeight,
padding: EdgeInsets.symmetric(vertical: 8.0f),
child: new ProductThumbnailRow()
),
new ExtraProductsNumber(),
}
),
}
)
);
}

}
public readonly GlobalKey<AnimatedListState> listKey;
//public readonly Delegate removedItemBuilder;
public RemovedItemBuilder removedItemBuilder;
public readonly List<int> _items;

28
Samples/UIWidgetsSamples_2019_4/Assets/UIWidgetsGallery/demo/shrine/shopping_cart.cs


using Unity.UIWidgets.rendering;
using Unity.UIWidgets.ui;
using Unity.UIWidgets.widgets;
using UnityEngine;
using Image = Unity.UIWidgets.widgets.Image;
using TextStyle = Unity.UIWidgets.painting.TextStyle;

List<Widget> _createShoppingCartRows(AppStateModel model)
{
List<Widget> widgets = new List<Widget>();
for (int id = 0; id < model.productsInCart.Count; id++)
foreach (var product in model.productsInCart.Keys)
widgets.Add(new ShoppingCartRow(
product: model.getProductById(id),
quantity: model.productsInCart[id],
onPressed: ()=> {
model.removeItemFromCart(id);
}
));
int id = product;
widgets.Add(new ShoppingCartRow(
product: model.getProductById(id),
quantity: model.productsInCart[id],
onPressed: ()=> {
model.removeItemFromCart(id);
}
));
}
return widgets;

public class ShoppingCartRow : StatelessWidget {
public ShoppingCartRow(
Product product = null,
int? quantity = null,
int quantity = 1,
this.quantity = quantity?? 0;
this.quantity = quantity;
this.onPressed = onPressed;
}

new Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: new List<Widget>{
Image.asset(
Image.file(
package: product.assetPackage,
//package: product.assetPackage,
fit: BoxFit.cover,
width: 75.0f,
height: 75.0f

new Expanded(
child: new Text($"Quantity: {quantity}")
),
new Text($"x $ {product.price : D} ")
new Text($"x $ {product.price :F} ")
}
),
new Text(

3
Samples/UIWidgetsSamples_2019_4/Assets/UIWidgetsGallery/demo/shrine/supplemental/product_card.cs


using Unity.UIWidgets.painting;
using Unity.UIWidgets.rendering;
using Unity.UIWidgets.widgets;
using UnityEngine;
namespace UIWidgetsGallery.demo.shrine.supplemental
{

),
new SizedBox(height: 4.0f),
new Text(
$" $ { product.price:D}",
$" $ { product.price:F}",
style: theme.textTheme.caption
),
}

7
Samples/UIWidgetsSamples_2019_4/Assets/UIWidgetsGallery/gallery/app.cs


namespace UIWidgetsGallery.gallery
{
public class GalleryApp : StatefulWidget
{
public GalleryApp(
{ public GalleryApp(
Key key = null,
UpdateUrlFetcher updateUrlFetcher = null,
bool enablePerformanceOverlay = true,

// Specifically use a blank Cupertino theme here and do not transfer
// over the Material primary color etc except the brightness to
// showcase standard iOS looks.
new Builder(builder: (BuildContext subsubContext) =>
new Builder(builder: (BuildContext context1) =>
brightness: Theme.of(context).brightness
brightness: Theme.of(context1).brightness
),
child: child
);

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");

4
com.unity.uiwidgets/Runtime/animation/animation_controller.cs


void _internalSetValue(float newValue) {
_value = newValue.clamp(lowerBound, upperBound);
if (_value == lowerBound) {
if (foundation_.FloatEqual(_value, lowerBound)) {
else if (_value == upperBound) {
else if (foundation_.FloatEqual(_value, upperBound)) {
_status = AnimationStatus.completed;
}
else {

36
com.unity.uiwidgets/Runtime/cupertino/context_menu.cs


public class _CupertinoContextMenuState : TickerProviderStateMixin<CupertinoContextMenu> {
public readonly GlobalKey _childGlobalKey = GlobalKey<State<StatefulWidget>>.key();
static readonly TimeSpan kLongPressTimeout = TimeSpan.FromMilliseconds(500);//new TimeSpan(0, 0, 0, 0, 500);
static readonly TimeSpan kLongPressTimeout = TimeSpan.FromMilliseconds(500);
public bool _childHidden = false;
public AnimationController _openController;
public Rect _decoyChildEndRect;

public Orientation _lastOrientation;
public readonly Rect _previousChildRect;
public float _scale = 1.0f;
public readonly GlobalKey _sheetGlobalKey = new LabeledGlobalKey<State<StatefulWidget>>();//GlobalKey();
public readonly GlobalKey _sheetGlobalKey = new LabeledGlobalKey<State<StatefulWidget>>();
public readonly static CurveTween _curve = new CurveTween(
curve: Curves.easeOutBack
);

public readonly Tween< float> _opacityTween = new FloatTween(begin: 0.0f, end: 1.0f);
public Animation< float> _sheetOpacity;
public readonly string barrierLabel;
//public override string barrierLabel;
public Color barrierColor {
//public readonly string barrierLabel;
public override string barrierLabel { get; }
public override Color barrierColor {
public bool barrierDismissible{
public override bool barrierDismissible{
public bool semanticsDismissible {
public override bool semanticsDismissible {
public TimeSpan transitionDuration {
public override TimeSpan transitionDuration {
/*public static AlignmentDirectional getSheetAlignment(_ContextMenuLocation contextMenuLocation) {
public static AlignmentDirectional getSheetAlignment(_ContextMenuLocation contextMenuLocation) {
switch (contextMenuLocation) {
case _ContextMenuLocation.center:
return AlignmentDirectional.topCenter;

return AlignmentDirectional.topStart;
}
}*/
}
public static Rect _getScaledRect(GlobalKey globalKey, float scale) {
Rect childRect = CupertinoContextMenuUtils._getRect(globalKey);
Size sizeScaled = childRect.size * scale;

base.offstage = _externalOffstage || _internalOffstage;
changedInternalState();
}
public bool didPop(object result) {
protected internal override bool didPop(object result) {
public bool offstage{
public override bool offstage{
set{
_externalOffstage = value;
_setOffstageInternally();

public TickerFuture didPush() {
protected internal override TickerFuture didPush() {
_internalOffstage = true;
_setOffstageInternally();
SchedulerBinding.instance.addPostFrameCallback((TimeSpan timeSpan)=>{

});
return base.didPush();
}
public Animation<float> createAnimation() {
public override Animation<float> createAnimation() {
Animation< float> animation = base.createAnimation();
_sheetOpacity = _opacityTween.animate(new CurvedAnimation(
parent: animation,

child: new Opacity(
opacity: _sheetOpacity.value,
child: Transform.scale(
//alignment: getSheetAlignment(_contextMenuLocation),
alignment: getSheetAlignment(_contextMenuLocation),
scale: sheetScale,
child: new _ContextMenuSheet(
key: _sheetGlobalKey,

// Build the animation for the _ContextMenuSheet.
Widget _buildSheetAnimation(BuildContext context, Widget child) {
return Transform.scale(
//alignment: _ContextMenuRoute.getSheetAlignment(widget.contextMenuLocation),
alignment: _ContextMenuRoute.getSheetAlignment(widget.contextMenuLocation),
scale: _sheetScaleAnimation.value,
child: new Opacity(
opacity: _sheetOpacityAnimation.value,

);
_sheetController = new AnimationController(
duration: TimeSpan.FromMilliseconds(100),
reverseDuration: TimeSpan.FromMilliseconds(300),/// TBC ???
reverseDuration: TimeSpan.FromMilliseconds(300),
vsync: this
);
_sheetScaleAnimation = new FloatTween(

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


letterSpacing: -0.83f
);
public const float _kTimerPickerHalfColumnPadding = 2f;
public const float _kTimerPickerLabelPadSize = 4.5f;
public const float _kTimerPickerLabelFontSize = 17.0f;
public const float _kTimerPickerColumnIntrinsicWidth = 106f;

_onSelectedItemChange(index);
},
itemBuilder: (BuildContext context, int index) => {
rangeStart.AddDays(index);
rangeStart = rangeStart.AddDays(index);
var rangeEnd = rangeStart.AddDays(1);

return null;
if (widget.maximumDate?.CompareTo(rangeStart) > 0)
if (widget.maximumDate?.CompareTo(rangeStart) < 0)
return null;
string dateText = rangeStart == new DateTime(now.Year, now.Month, now.Day)

DateTime _lastDayInMonth(int year, int month) {
//new DateTime(year, month + 1, 0);
var date = new DateTime(year,month,1);
date.AddMonths(1);
date.Subtract(new TimeSpan(1, 0, 0, 0));
date = date.AddMonths(1);
date = date.Subtract(new TimeSpan(1, 0, 0, 0));
return date;
}

context,
new Text(
localizations.datePickerYear(year),
style: CupertinoDatePickerUtils._themeTextStyle(context, isValid: isValidYear))
style: CupertinoDatePickerUtils._themeTextStyle(_context, isValid: isValidYear))
);
}

// The current date selection represents a range [minSelectedData, maxSelectDate].
get {
DateTime minSelectedDate = new DateTime(selectedYear, selectedMonth, selectedDay);
DateTime maxSelectedDate = new DateTime(selectedYear, selectedMonth, selectedDay + 1);
DateTime maxSelectedDate = new DateTime(selectedYear, selectedMonth, selectedDay);
maxSelectedDate = maxSelectedDate.AddDays(1);
bool minCheck = widget.minimumDate?.CompareTo(maxSelectedDate) < 0;
bool maxCheck = widget.maximumDate?.CompareTo(minSelectedDate) > 0;
bool minCheck = widget.minimumDate == null ? true : widget.minimumDate?.CompareTo(maxSelectedDate) < 0;
bool maxCheck = widget.maximumDate == null ? false : widget.maximumDate?.CompareTo(minSelectedDate) > 0;
return minCheck && !maxCheck && minSelectedDate.Day == selectedDay;
}

DateTime minSelectDate = new DateTime(selectedYear, selectedMonth, selectedDay);
DateTime maxSelectDate = new DateTime(selectedYear, selectedMonth, selectedDay + 1);
bool minCheck = widget.minimumDate?.CompareTo(maxSelectDate) < 0;
bool maxCheck = widget.maximumDate?.CompareTo(minSelectDate) > 0;
bool minCheck = widget.minimumDate == null ? true : widget.minimumDate?.CompareTo(maxSelectDate) < 0 ;
bool maxCheck = widget.maximumDate == null ? false :widget.maximumDate?.CompareTo(minSelectDate) > 0;
DateTime targetDate = minCheck ? (DateTime) widget.maximumDate : (DateTime) widget.minimumDate;
_scrollToDate(targetDate);
return;

List<Widget> pickers = new List<Widget>();
for (int i = 0; i < columnWidths.Count; i++) {
float offAxisFraction = (i - 1) * 0.3f * textDirectionFactor;
int index = i;
float offAxisFraction = (index - 1) * 0.3f * textDirectionFactor;
Widget transitionBuilder(BuildContext _context, Widget child) {
var columnWidth = columnWidths.Count == 0 ? 0 : columnWidths[index];
var result = new Container(
alignment: index == (columnWidths.Count - 1)
? alignCenterLeft
: alignCenterRight,
padding: index == 0 ? null : padding,
child: new Container(
alignment: index == 0 ? alignCenterLeft : alignCenterRight,
width: columnWidth + CupertinoDatePickerUtils._kDatePickerPadSize,
child: child
)
);
return result;
}
TransitionBuilder builder = transitionBuilder;
Widget childWidget = pickerBuilders[index](
offAxisFraction: offAxisFraction,
itemPositioningBuilder : builder
);
id: i,
child: pickerBuilders[i](
offAxisFraction,
(BuildContext _context, Widget child) => {
return new Container(
alignment: i == columnWidths.Count - 1
? alignCenterLeft
: alignCenterRight,
padding: i == 0 ? null : padding,
child: new Container(
alignment: i == 0 ? alignCenterLeft : alignCenterRight,
width: columnWidths[i] + CupertinoDatePickerUtils._kDatePickerPadSize,
child: child
)
);
}
id: index,
child: childWidget
));
);
}
return new MediaQuery(

Color backgroundColor = null,
ValueChanged<TimeSpan> onTimerDurationChanged = null
):base(key : key) {
alignment = alignment ?? Alignment.center ;
alignment = alignment ?? Alignment.center;
//D.assert(((TimeSpan)initialTimerDuration)/TimeSpan. % minuteInterval == 0);
//D.assert(((TimeSpan)initialTimerDuration).% secondInterval == 0);
this.mode = mode;
this.initialTimerDuration = initialTimerDuration ?? TimeSpan.Zero;
this.minuteInterval = minuteInterval;

this.onTimerDurationChanged = onTimerDurationChanged;
public readonly CupertinoTimerPickerMode mode;
public readonly TimeSpan initialTimerDuration;
public readonly int minuteInterval;

Alignment alignCenterLeft;
Alignment alignCenterRight;
int selectedHour = 0;
int selectedMinute = 0;
int selectedSecond = 0;
int selectedHour;
int selectedMinute;
int selectedSecond;
int lastSelectedHour = 0;
int lastSelectedMinute = 0;
int lastSelectedSecond = 0;
int lastSelectedHour;
int lastSelectedMinute;
int lastSelectedSecond;
float numberLabelWidth = 0f;
float numberLabelHeight = 0f;
float numberLabelBaseline = 0f;
float numberLabelWidth;
float numberLabelHeight;
float numberLabelBaseline;
if (widget.mode != CupertinoTimerPickerMode.ms) {
selectedHour = (int) widget.initialTimerDuration.TotalHours;
}

}
PaintingBinding.instance.systemFonts.addListener(_handleSystemFontsChange);
}
void _handleSystemFontsChange() {
setState(() =>{

numberLabelWidth = textPainter.maxIntrinsicWidth;
numberLabelHeight = textPainter.height;
numberLabelBaseline = textPainter.computeDistanceToActualBaseline(TextBaseline.alphabetic);
}
}
EdgeInsetsDirectional padding = EdgeInsetsDirectional.only(
start: numberLabelWidth
+ CupertinoDatePickerUtils._kTimerPickerLabelPadSize
+ pickerPadding.start
EdgeInsetsDirectional padding = EdgeInsetsDirectional.only(
start: numberLabelWidth
+ CupertinoDatePickerUtils._kTimerPickerLabelPadSize
+ pickerPadding.start
child: new Container(
//alignment: AlignmentDirectional.centerStart.resolve(textDirection),
padding: padding.resolve(textDirection),
child: new SizedBox(
height: numberLabelHeight,
child: new Baseline(
baseline: numberLabelBaseline,
baselineType: TextBaseline.alphabetic,
child: new Text(
text,
style: new TextStyle(
fontSize: CupertinoDatePickerUtils._kTimerPickerLabelFontSize,
fontWeight: FontWeight.w600),
maxLines: 1,
softWrap: false)))
));
}
Widget _buildPickerNumberLabel(string text, EdgeInsetsDirectional padding) {
return new Container(
width: CupertinoDatePickerUtils._kTimerPickerColumnIntrinsicWidth + padding.horizontal,
child: new Container(
alignment: AlignmentDirectional.centerStart.resolve(textDirection),
//alignment: AlignmentDirectional.centerStart.resolve(textDirection),
child: new Container(
width: numberLabelWidth,
// alignment: AlignmentDirectional.centerEnd.resolve(textDirection),
child: new Text(text, softWrap: false, maxLines: 1, overflow: TextOverflow.visible)
child: new SizedBox(
height: numberLabelHeight,
child: new Baseline(
baseline: numberLabelBaseline,
baselineType: TextBaseline.alphabetic,
child: new Text(
text,
style: new TextStyle(
fontSize: CupertinoDatePickerUtils._kTimerPickerLabelFontSize,
fontWeight: FontWeight.w600
),
maxLines: 1,
softWrap: false
)
)
)
}
Widget _buildHourPicker(EdgeInsetsDirectional additionalPadding) {
List<Widget> widgets = new List<Widget>();
for (int index = 0; index < 24; index++) {
string semanticsLabel = textDirectionFactor == 1
? localizations.timerPickerHour(index) + localizations.timerPickerHourLabel(index)
: localizations.timerPickerHourLabel(index) + localizations.timerPickerHour(index);
}
widgets.Add( _buildPickerNumberLabel(localizations.timerPickerHour(index), additionalPadding));
}
Widget _buildPickerNumberLabel(string text, EdgeInsetsDirectional padding) {
return new Container(
width: CupertinoDatePickerUtils._kTimerPickerColumnIntrinsicWidth + padding.horizontal,
padding: padding.resolve(textDirection),
alignment: AlignmentDirectional.centerStart.resolve(textDirection),
child: new Container(
width: numberLabelWidth,
alignment: AlignmentDirectional.centerEnd.resolve(textDirection),
child: new Text(text, softWrap: false, maxLines: 1, overflow: TextOverflow.visible)
)
);
}
Widget _buildHourPicker(EdgeInsetsDirectional additionalPadding) {
scrollController: new FixedExtentScrollController(initialItem: selectedHour),
offAxisFraction: -0.5f * textDirectionFactor,
itemExtent: CupertinoDatePickerUtils._kItemExtent,
backgroundColor: ((CupertinoTimerPicker)widget).backgroundColor,
squeeze: CupertinoDatePickerUtils._kSqueeze,
onSelectedItemChanged: (int index)=> {
setState(()=> {
selectedHour = index;
widget.onTimerDurationChanged(
new TimeSpan(
hours: selectedHour,
minutes: selectedMinute,
seconds: selectedSecond != 0 ? selectedSecond : 0));
scrollController: new FixedExtentScrollController(initialItem: selectedHour),
offAxisFraction: -0.5f * textDirectionFactor,
itemExtent: CupertinoDatePickerUtils._kItemExtent,
backgroundColor: widget.backgroundColor,
squeeze: CupertinoDatePickerUtils._kSqueeze,
onSelectedItemChanged: (int index)=> {
setState(() =>{
selectedHour = index;
widget.onTimerDurationChanged(
new TimeSpan(
hours: selectedHour,
minutes: selectedMinute,
seconds: selectedSecond == 0 ? 0 : selectedHour));
},
children: widgets
},
children: CupertinoDatePickerUtils.listGenerate(24, (int index) => {
string semanticsLabel = textDirectionFactor == 1
? localizations.timerPickerHour(index) + localizations.timerPickerHourLabel(index)
: localizations.timerPickerHourLabel(index) + localizations.timerPickerHour(index);
return _buildPickerNumberLabel(localizations.timerPickerHour(index), additionalPadding);
})
}
}
Widget _buildHourColumn(EdgeInsetsDirectional additionalPadding) {
Widget _buildHourColumn(EdgeInsetsDirectional additionalPadding) {
children: new List<Widget>{
new NotificationListener<ScrollEndNotification>(
onNotification: (ScrollEndNotification notification)=> {
setState(()=> { lastSelectedHour = selectedHour; });
return false;
},
child: _buildHourPicker(additionalPadding)
),
_buildLabel(
localizations.timerPickerHourLabel(lastSelectedHour == 0 ? selectedHour : lastSelectedHour),
additionalPadding
),
});
}
Widget _buildMinutePicker(EdgeInsetsDirectional additionalPadding) {
List<Widget> widgets = new List<Widget>();
for (int index = 0; index < (int)(60 / widget.minuteInterval); index++) {
int minute = index * widget.minuteInterval;
children: new List<Widget>{
new NotificationListener<ScrollEndNotification>(
onNotification: (ScrollEndNotification notification)=> {
setState(()=> { lastSelectedHour = selectedHour; });
return false;
},
child: _buildHourPicker(additionalPadding)
),
_buildLabel(
localizations.timerPickerHourLabel(lastSelectedHour == 0 ? selectedHour : lastSelectedHour),
additionalPadding
),
}
);
}
string semanticsLabel = textDirectionFactor == 1
? localizations.timerPickerMinute(minute) + localizations.timerPickerMinuteLabel(minute)
: localizations.timerPickerMinuteLabel(minute) + localizations.timerPickerMinute(minute);
widgets.Add(_buildPickerNumberLabel(localizations.timerPickerMinute(minute), additionalPadding)
);
}
Widget _buildMinutePicker(EdgeInsetsDirectional additionalPadding) {
switch (widget.mode) {
case CupertinoTimerPickerMode.hm:
offAxisFraction = 0.5f * textDirectionFactor;
switch (widget.mode) {
case CupertinoTimerPickerMode.hm:
offAxisFraction = 0.5f * textDirectionFactor;
case CupertinoTimerPickerMode.hms:
case CupertinoTimerPickerMode.hms:
case CupertinoTimerPickerMode.ms:
case CupertinoTimerPickerMode.ms:
break;
}
break;
}
scrollController: new FixedExtentScrollController(
initialItem: (int) (selectedMinute / widget.minuteInterval)
),
offAxisFraction: offAxisFraction,
itemExtent: CupertinoDatePickerUtils._kItemExtent,
backgroundColor: widget.backgroundColor,
squeeze: CupertinoDatePickerUtils._kSqueeze,
looping: true,
onSelectedItemChanged: (int index) => {
setState(() => {
selectedMinute = index * widget.minuteInterval;
widget.onTimerDurationChanged(
new TimeSpan(
hours: selectedHour == 0 ? 0 : selectedHour,
minutes: selectedMinute,
seconds: selectedSecond == 0 ? 0 : selectedSecond));
});
},
children: widgets
);
scrollController: new FixedExtentScrollController(
initialItem: (int)selectedMinute / widget.minuteInterval
),
offAxisFraction: offAxisFraction,
itemExtent: CupertinoDatePickerUtils._kItemExtent,
backgroundColor: widget.backgroundColor,
squeeze: CupertinoDatePickerUtils._kSqueeze,
looping: true,
onSelectedItemChanged: (int index) => {
setState(() =>{
selectedMinute = index * widget.minuteInterval;
widget.onTimerDurationChanged(
new TimeSpan(
hours: selectedHour == 0 ? 0 : selectedHour,
minutes: selectedMinute,
seconds: selectedSecond == 0 ? 0 : selectedSecond ));
});
},
children: CupertinoDatePickerUtils.listGenerate((int)(60 / widget.minuteInterval), (int index) => {
int minute = index * widget.minuteInterval;
string semanticsLabel = textDirectionFactor == 1
? localizations.timerPickerMinute(minute) + localizations.timerPickerMinuteLabel(minute)
: localizations.timerPickerMinuteLabel(minute) + localizations.timerPickerMinute(minute);
return _buildPickerNumberLabel(localizations.timerPickerMinute(minute), additionalPadding);
})
);
}
}
Widget _buildMinuteColumn(EdgeInsetsDirectional additionalPadding) {
Widget _buildMinuteColumn(EdgeInsetsDirectional additionalPadding) {
setState(()=> { lastSelectedMinute = selectedMinute; });
setState(() => { lastSelectedMinute = selectedMinute; });
return false;
},
child: _buildMinutePicker(additionalPadding)

),
}
);
}
Widget _buildSecondPicker(EdgeInsetsDirectional additionalPadding) {
float offAxisFraction = 0.5f * textDirectionFactor;
}
Widget _buildSecondPicker(EdgeInsetsDirectional additionalPadding) {
float offAxisFraction = 0.5f * textDirectionFactor;
scrollController: new FixedExtentScrollController(
initialItem: (int)(selectedSecond / widget.secondInterval)
),
offAxisFraction: offAxisFraction,
itemExtent: CupertinoDatePickerUtils._kItemExtent,
backgroundColor: widget.backgroundColor,
squeeze: CupertinoDatePickerUtils._kSqueeze,
looping: true,
onSelectedItemChanged: (int index) =>{
setState(()=> {
selectedSecond = index * widget.secondInterval;
widget.onTimerDurationChanged(
new TimeSpan(
hours: selectedHour == 0 ? 0 : selectedHour,
minutes: selectedMinute,
seconds: selectedSecond));
});
},
children: CupertinoDatePickerUtils.listGenerate((int)60 / widget.secondInterval, (int index)=> {
int second = index * widget.secondInterval;
string semanticsLabel = textDirectionFactor == 1
? localizations.timerPickerSecond(second) + localizations.timerPickerSecondLabel(second)
: localizations.timerPickerSecondLabel(second) + localizations.timerPickerSecond(second);
scrollController: new FixedExtentScrollController(
initialItem: (int) selectedSecond / widget.secondInterval
),
offAxisFraction: offAxisFraction,
itemExtent: CupertinoDatePickerUtils._kItemExtent,
backgroundColor: widget.backgroundColor,
squeeze: CupertinoDatePickerUtils._kSqueeze,
looping: true,
onSelectedItemChanged: (int index)=> {
setState(() => {
selectedSecond = index * widget.secondInterval;
widget.onTimerDurationChanged(
new TimeSpan(
hours: selectedHour == 0 ? 0 : selectedHour,
minutes: selectedMinute,
seconds: selectedSecond));
});
},
children: CupertinoDatePickerUtils.listGenerate((int) (60 / widget.secondInterval), (int index)=> {
int second = index * widget.secondInterval;
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);
})
);
}
Widget _buildSecondColumn(EdgeInsetsDirectional additionalPadding) {
Widget _buildSecondColumn(EdgeInsetsDirectional additionalPadding) {
children: new List<Widget>{
new NotificationListener<ScrollEndNotification>(
onNotification: (ScrollEndNotification notification)=> {
setState(()=> { lastSelectedSecond = selectedSecond; });
return false;
children: new List<Widget>{
new NotificationListener<ScrollEndNotification>(
onNotification: (ScrollEndNotification notification)=> {
setState(() => { lastSelectedSecond = selectedSecond; });
return false;
},
child: _buildSecondPicker(additionalPadding)
),

)
}
);
}
TextStyle _textStyleFrom(BuildContext context) {
}
TextStyle _textStyleFrom(BuildContext context) {
.pickerTextStyle.merge(
new TextStyle(
fontSize: CupertinoDatePickerUtils._kTimerPickerNumberLabelFontSize
)
);
}
.pickerTextStyle.merge(
new TextStyle(
fontSize: CupertinoDatePickerUtils._kTimerPickerNumberLabelFontSize
)
);
}
public override Widget build(BuildContext context) {
List<Widget> columns = new List<Widget>();
float paddingValue = CupertinoDatePickerUtils._kPickerWidth - 2 * CupertinoDatePickerUtils._kTimerPickerColumnIntrinsicWidth - 2 * CupertinoDatePickerUtils._kTimerPickerHalfColumnPadding;
float totalWidth = CupertinoDatePickerUtils._kPickerWidth;
D.assert(paddingValue >= 0);
public override Widget build(BuildContext context) {
List<Widget> columns = new List<Widget>();
float paddingValue = CupertinoDatePickerUtils._kPickerWidth -
2 * CupertinoDatePickerUtils._kTimerPickerColumnIntrinsicWidth - 2 * CupertinoDatePickerUtils._kTimerPickerHalfColumnPadding;
float totalWidth = CupertinoDatePickerUtils._kPickerWidth;
D.assert(paddingValue >= 0);
switch (widget.mode) {
case CupertinoTimerPickerMode.hm:
columns = new List<Widget>{
_buildHourColumn(EdgeInsetsDirectional.only(start: paddingValue / 2, end: CupertinoDatePickerUtils._kTimerPickerHalfColumnPadding)),
_buildMinuteColumn(EdgeInsetsDirectional.only(start:CupertinoDatePickerUtils. _kTimerPickerHalfColumnPadding, end: paddingValue / 2)),};
break;
case CupertinoTimerPickerMode.ms:
columns = new List<Widget>{
_buildMinuteColumn(EdgeInsetsDirectional.only(start: paddingValue / 2, end: CupertinoDatePickerUtils._kTimerPickerHalfColumnPadding)),
_buildSecondColumn(EdgeInsetsDirectional.only(start: CupertinoDatePickerUtils._kTimerPickerHalfColumnPadding, end: paddingValue / 2)),
};
break;
case CupertinoTimerPickerMode.hms:
float _paddingValue = CupertinoDatePickerUtils._kTimerPickerHalfColumnPadding * 2;
totalWidth = CupertinoDatePickerUtils._kTimerPickerColumnIntrinsicWidth * 3 + 4 * CupertinoDatePickerUtils._kTimerPickerHalfColumnPadding + _paddingValue;
columns = new List<Widget>{
_buildHourColumn(EdgeInsetsDirectional.only(start: _paddingValue / 2, end: CupertinoDatePickerUtils._kTimerPickerHalfColumnPadding)),
_buildMinuteColumn(EdgeInsetsDirectional.only(start: CupertinoDatePickerUtils._kTimerPickerHalfColumnPadding, end: CupertinoDatePickerUtils._kTimerPickerHalfColumnPadding)),
_buildSecondColumn(EdgeInsetsDirectional.only(start: CupertinoDatePickerUtils._kTimerPickerHalfColumnPadding, end: _paddingValue / 2)),
switch (widget.mode) {
case CupertinoTimerPickerMode.hm:
// Pad the widget to make it as wide as `_kPickerWidth`.
columns = new List<Widget>{
_buildHourColumn( EdgeInsetsDirectional.only(start: paddingValue / 2, end: CupertinoDatePickerUtils._kTimerPickerHalfColumnPadding)),
_buildMinuteColumn( EdgeInsetsDirectional.only(start: CupertinoDatePickerUtils._kTimerPickerHalfColumnPadding, end: paddingValue / 2)),
break;
}
CupertinoThemeData themeData = CupertinoTheme.of(context);
List<Widget> results = new List<Widget>();
foreach (var result in columns.Select((Widget child) => new Expanded(child: child)).ToList()) {
results.Add((Widget)result);
break;
case CupertinoTimerPickerMode.ms:
// Pad the widget to make it as wide as `_kPickerWidth`.
columns = new List<Widget>{
_buildMinuteColumn( EdgeInsetsDirectional.only(start: paddingValue / 2, end: CupertinoDatePickerUtils._kTimerPickerHalfColumnPadding)),
_buildSecondColumn( EdgeInsetsDirectional.only(start: CupertinoDatePickerUtils._kTimerPickerHalfColumnPadding, end: paddingValue / 2)),
};
break;
case CupertinoTimerPickerMode.hms:
float _paddingValue = CupertinoDatePickerUtils._kTimerPickerHalfColumnPadding * 2;
totalWidth = CupertinoDatePickerUtils._kTimerPickerColumnIntrinsicWidth * 3 + 4 * CupertinoDatePickerUtils._kTimerPickerHalfColumnPadding + _paddingValue;
columns = new List<Widget>{
_buildHourColumn( EdgeInsetsDirectional.only(start: _paddingValue / 2, end: CupertinoDatePickerUtils._kTimerPickerHalfColumnPadding)),
_buildMinuteColumn( EdgeInsetsDirectional.only(start: CupertinoDatePickerUtils._kTimerPickerHalfColumnPadding, end: CupertinoDatePickerUtils._kTimerPickerHalfColumnPadding)),
_buildSecondColumn( EdgeInsetsDirectional.only(start: CupertinoDatePickerUtils._kTimerPickerHalfColumnPadding, end: _paddingValue / 2)),
};
break;
CupertinoThemeData themeData = CupertinoTheme.of(context);
data: MediaQuery.of(context).copyWith(textScaleFactor: 1.0f),
child: new CupertinoTheme(
data: themeData.copyWith(
textTheme: themeData.textTheme.copyWith(pickerTextStyle: _textStyleFrom(context))
),
child: new Align(
alignment: widget.alignment,
child: new Container(
color: CupertinoDynamicColor.resolve(widget.backgroundColor, context),
width: totalWidth,
height: CupertinoDatePickerUtils._kPickerHeight,
child: new DefaultTextStyle(
style: _textStyleFrom(context),
child: new Row(children: results
)
)
)
// The native iOS picker's text scaling is fixed, so we will also fix it
// as well in our picker.
data: MediaQuery.of(context).copyWith(textScaleFactor: 1.0f),
child: new CupertinoTheme(
data: themeData.copyWith(
textTheme: themeData.textTheme.copyWith(
pickerTextStyle: _textStyleFrom(context)
)
),
child: new Align(
alignment: widget.alignment,
child: new Container(
color: CupertinoDynamicColor.resolve(widget.backgroundColor, context),
width: totalWidth,
height: CupertinoDatePickerUtils._kPickerHeight,
child: new DefaultTextStyle(
style: _textStyleFrom(context),
child: new Row(
children:
columns.Select((Widget child) => {
var result = new Expanded(child: child);
return (Widget) result;
}).ToList()
)
)
)
}
}
}
}

10
com.unity.uiwidgets/Runtime/cupertino/dialog.cs


}
}
/*class _DialogActionButtonParentData : MultiChildLayoutParentData {
public _DialogActionButtonParentData(
bool isPressed = false
) {
this.isPressed = isPressed;
}
public bool isPressed;
}*/
public class CupertinoDialogAction : StatelessWidget {
public CupertinoDialogAction(
Key key = null,

14
com.unity.uiwidgets/Runtime/cupertino/picker.cs


public class CupertinoPicker : StatefulWidget {
public CupertinoPicker(
List<Widget> children,
float itemExtent,
Key key = null,
float? diameterRatio = null,
Color backgroundColor = null,

FixedExtentScrollController scrollController = null,
float? squeeze = null,
float? itemExtent = null,
ValueChanged<int> onSelectedItemChanged = null,
bool looping = false
) : base(key: key) {

D.assert(diameterRatio > 0.0f, ()=>RenderListWheelViewport.diameterRatioZeroMessage);
D.assert(magnification > 0);
D.assert(itemExtent != null);
D.assert(itemExtent > 0);
D.assert(squeeze > 0);
this.diameterRatio = diameterRatio;

}
public CupertinoPicker(
float itemExtent,
Key key = null,
float? diameterRatio = null,
Color backgroundColor = null,

FixedExtentScrollController scrollController = null,
float? squeeze = null,
float? itemExtent = null,
ValueChanged<int> onSelectedItemChanged = null,
IndexedWidgetBuilder itemBuilder = null,
int? childCount = null

D.assert(itemBuilder != null);
D.assert(diameterRatio > 0.0f,()=> RenderListWheelViewport.diameterRatioZeroMessage);
D.assert(magnification > 0);
D.assert(itemExtent != null);
D.assert(itemExtent > 0);
D.assert(squeeze > 0);
this.diameterRatio = diameterRatio;

public readonly bool useMagnifier;
public readonly float magnification;
public readonly FixedExtentScrollController scrollController;
public readonly float? itemExtent;
public readonly float itemExtent;
public readonly ValueChanged<int> onSelectedItemChanged;
public ListWheelChildDelegate childDelegate;
public readonly float? squeeze;

}
public override void didUpdateWidget(StatefulWidget oldWidget) {
oldWidget = (CupertinoPicker) oldWidget;
if (widget.scrollController != null && ((CupertinoPicker) oldWidget).scrollController == null) {
_controller = null;
}

child: new ListWheelScrollView(
controller: widget.scrollController ?? _controller,
physics: new FixedExtentScrollPhysics(),
diameterRatio: widget.diameterRatio ?? CupertinoPickerUtils._kDefaultDiameterRatio,
diameterRatio: widget.diameterRatio ?? RenderListWheelViewport.defaultDiameterRatio ,
itemExtent: widget.itemExtent ?? 1f,
itemExtent: widget.itemExtent ,
squeeze: widget.squeeze ?? CupertinoPickerUtils._kSqueeze,
onSelectedItemChanged: _handleSelectedItemChanged,
childDelegate: widget.childDelegate

22
com.unity.uiwidgets/Runtime/cupertino/route.cs


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

public readonly WidgetBuilder builder;
public readonly string title;
ValueNotifier<string> _previousTitle;
public ValueListenable<string> previousTitle {

public override Widget buildPage(BuildContext context, Animation<float> animation, Animation<float> secondaryAnimation) {
Widget result = builder(context);
D.assert(() =>{
if (result == null) {

}
public new string debugLabel {
get { return $"{base.debugLabel}(${settings.name})"; }
get { return $"{base.debugLabel}({settings.name})"; }
}
}

}
public readonly Animation<Offset> _primaryPositionAnimation;
public readonly Widget child;
public override Widget build(BuildContext context) {

void _handleDragEnd(DragEndDetails details) {
D.assert(mounted);
D.assert(_backGestureController != null);
_backGestureController.dragEnd(_convertToLogical(details.velocity.pixelsPerSecond.dx / context.size.width) ?? 0);
_backGestureController.dragEnd(_convertToLogical(details.velocity.pixelsPerSecond.dx / context.size.width) ?? 0.0f);
_backGestureController = null;
}

fit: StackFit.passthrough,
children: new List<Widget> {
widget.child,
new Positioned(
left: 0.0f,
new PositionedDirectional(
start: 0.0f,
width: dragAreaWidth,
top: 0.0f,
bottom: 0.0f,

)
)
),
}
);
}

this.barrierColor = barrierColor;
this.builder = builder;
this.barrierLabel = barrierLabel;
public readonly string barrierLabel;
public readonly Color barrierColor;
public override Color barrierColor { get; }
public override string barrierLabel { get; }
public override bool barrierDismissible {
get { return true; }

7
com.unity.uiwidgets/Runtime/cupertino/segmented_control.cs


data: iconTheme,
child: new DefaultTextStyle(
style: textStyle,
child: child /*Semantics(
button: true,
inMutuallyExclusiveGroup: true,
selected: widget.groupValue.Equals(currentKey),
child: child
)*/
child: child
)
)
);

2
com.unity.uiwidgets/Runtime/cupertino/switch.cs


void _handleTap() {
if (isInteractive) {
widget.onChanged(!widget.value);
//_emitVibration();
}
}

if (isInteractive) {
needsPositionAnimation = false;
_reactionController.forward();
//_emitVibration();
}
}

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 || UNITY_ANDROID
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);
}
}

4
com.unity.uiwidgets/Runtime/foundation/diagnostics.cs


public static bool _isSingleLine(DiagnosticsTreeStyle? style) {
return style == DiagnosticsTreeStyle.singleLine;
}
public static bool FloatEqual(float left, float right) {
return Mathf.Abs(left - right) < precisionErrorTolerance;
}
}

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,

2
com.unity.uiwidgets/Runtime/material/app_bar.cs


child: appBar
)
),
widget.bottomOpacity == 1.0f
foundation_.FloatEqual(widget.bottomOpacity, 1.0f)
? (Widget) widget.bottom
: new Opacity(
opacity: new Interval(0.25f, 1.0f, curve: Curves.fastOutSlowIn).transform(widget

2
com.unity.uiwidgets/Runtime/material/app_bar_theme.cs


public bool Equals(AppBarTheme other) {
return other.brightness == brightness
&& other.color == color
&& other.elevation == elevation
&& Equals(other.elevation, elevation)
&& other.iconTheme == iconTheme
&& other.actionsIconTheme == actionsIconTheme
&& other.textTheme == textTheme;

4
com.unity.uiwidgets/Runtime/material/divider.cs


child: new Container(
height: thickness,
//TODO: update to EdgeInsetsGeometry
/*margin: EdgeInsetsDirectional.only(start: indent,
end: endIndent),*/
margin: EdgeInsetsDirectional.only(start: indent,
end: endIndent),
decoration: new BoxDecoration(
border: new Border(
bottom: createBorderSide(context, color: color, width: thickness))

2
com.unity.uiwidgets/Runtime/material/navigation_rail_theme.cs


);
}
static NavigationRailThemeData lerp(NavigationRailThemeData a, NavigationRailThemeData b, float t) {
public static NavigationRailThemeData lerp(NavigationRailThemeData a, NavigationRailThemeData b, float t) {
if (a == null && b == null)
return null;
return new NavigationRailThemeData(

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> {

69
com.unity.uiwidgets/Runtime/material/theme_data.cs


using System.Collections.Generic;
using System.Linq;
using uiwidgets;
using Unity.UIWidgets.animation;
using Unity.UIWidgets.painting;
using Unity.UIWidgets.rendering;
using Unity.UIWidgets.ui;
using Unity.UIWidgets.widgets;

Color bottomAppBarColor = null,
Color cardColor = null,
Color dividerColor = null,
Color focusColor = null,
Color hoverColor = null,
Color highlightColor = null,
Color splashColor = null,
InteractiveInkFeatureFactory splashFactory = null,

Color buttonColor = null,
ButtonThemeData buttonTheme = null,
ToggleButtonsThemeData toggleButtonsTheme = null,
Color secondaryHeaderColor = null,
Color textSelectionColor = null,
Color cursorColor = null,

IconThemeData accentIconTheme = null,
SliderThemeData sliderTheme = null,
TabBarTheme tabBarTheme = null,
TooltipThemeData tooltipTheme = null,
CardTheme cardTheme = null,
ChipThemeData chipTheme = null,
RuntimePlatform? platform = null,

ColorScheme colorScheme = null,
DialogTheme dialogTheme = null,
FloatingActionButtonThemeData floatingActionButtonTheme = null,
NavigationRailThemeData navigationRailTheme = null,
Typography typography = null,
SnackBarThemeData snackBarTheme = null,
BottomSheetThemeData bottomSheetTheme = null,

}
buttonColor = buttonColor ?? (isDark ? primarySwatch[600] : Colors.grey[300]);
focusColor = focusColor ??(isDark ? Colors.white.withOpacity(0.12f) : Colors.black.withOpacity(0.12f));
hoverColor = hoverColor ??(isDark ? Colors.white.withOpacity(0.04f) : Colors.black.withOpacity(0.04f));
focusColor: focusColor,
hoverColor: hoverColor,
disabledColor = disabledColor ?? (isDark ? Colors.white30 : Colors.black38);
toggleButtonsTheme = toggleButtonsTheme?? new ToggleButtonsThemeData();
disabledColor = disabledColor ?? (isDark ? Colors.white38 : Colors.black38);
highlightColor = highlightColor ??
(isDark
? material_._kDarkThemeHighlightColor

valueIndicatorTextStyle: accentTextTheme.body2);
tabBarTheme = tabBarTheme ?? new TabBarTheme();
tooltipTheme = tooltipTheme ?? new TooltipThemeData();
labelStyle: textTheme.body2
labelStyle: textTheme.bodyText1
navigationRailTheme = navigationRailTheme ?? new NavigationRailThemeData();
snackBarTheme = snackBarTheme ?? new SnackBarThemeData();
bottomSheetTheme = bottomSheetTheme ?? new BottomSheetThemeData();
popupMenuTheme = popupMenuTheme ?? new PopupMenuThemeData();

this.bottomAppBarColor = bottomAppBarColor;
this.cardColor = cardColor;
this.dividerColor = dividerColor;
this.focusColor = focusColor;
this.hoverColor = hoverColor;
this.highlightColor = highlightColor;
this.splashColor = splashColor;
this.splashFactory = splashFactory;

this.buttonTheme = buttonTheme;
this.toggleButtonsTheme = toggleButtonsTheme;
this.buttonColor = buttonColor;
this.secondaryHeaderColor = secondaryHeaderColor;
this.textSelectionColor = textSelectionColor;

this.accentIconTheme = accentIconTheme;
this.sliderTheme = sliderTheme;
this.tabBarTheme = tabBarTheme;
this.tooltipTheme = tooltipTheme;
this.cardTheme = cardTheme;
this.chipTheme = chipTheme;
this.platform = platform.Value;

this.colorScheme = colorScheme;
this.dialogTheme = dialogTheme;
this.floatingActionButtonTheme = floatingActionButtonTheme;
this.navigationRailTheme = navigationRailTheme;
this.typography = typography;
this.snackBarTheme = snackBarTheme;
this.bottomSheetTheme = bottomSheetTheme;

Color bottomAppBarColor = null,
Color cardColor = null,
Color dividerColor = null,
Color focusColor = null,
Color hoverColor = null,
Color highlightColor = null,
Color splashColor = null,
InteractiveInkFeatureFactory splashFactory = null,

ButtonThemeData buttonTheme = null,
Color buttonColor = null,
ToggleButtonsThemeData toggleButtonsTheme = null,
Color secondaryHeaderColor = null,
Color textSelectionColor = null,
Color cursorColor = null,

IconThemeData primaryIconTheme = null,
IconThemeData accentIconTheme = null,
TabBarTheme tabBarTheme = null,
TooltipThemeData tooltipTheme = null,
CardTheme cardTheme = null,
ChipThemeData chipTheme = null,
RuntimePlatform? platform = null,

ColorScheme colorScheme = null,
DialogTheme dialogTheme = null,
FloatingActionButtonThemeData floatingActionButtonTheme = null,
NavigationRailThemeData navigationRailTheme = null,
Typography typography = null,
SnackBarThemeData snackBarTheme = null,
BottomSheetThemeData bottomSheetTheme = null,

D.assert(bottomAppBarColor != null);
D.assert(cardColor != null);
D.assert(dividerColor != null);
D.assert(focusColor != null);
D.assert(hoverColor != null);
D.assert(highlightColor != null);
D.assert(splashColor != null);
D.assert(splashFactory != null);

D.assert(toggleableActiveColor != null);
D.assert(buttonTheme != null);
D.assert(toggleButtonsTheme != null);
D.assert(secondaryHeaderColor != null);
D.assert(textSelectionColor != null);
D.assert(cursorColor != null);

D.assert(typography != null);
D.assert(buttonColor != null);
D.assert(tabBarTheme != null);
D.assert(tooltipTheme != null);
D.assert(navigationRailTheme != null);
D.assert(snackBarTheme != null);
D.assert(bottomSheetTheme != null);
D.assert(popupMenuTheme != null);

return new ThemeData(
brightness: brightness,
visualDensity: visualDensity,
primaryColor: primaryColor,
primaryColorBrightness: primaryColorBrightness,
primaryColorLight: primaryColorLight,

bottomAppBarColor: bottomAppBarColor,
cardColor: cardColor,
dividerColor: dividerColor,
focusColor: focusColor,
hoverColor: hoverColor,
highlightColor: highlightColor,
splashColor: splashColor,
splashFactory: splashFactory,

buttonTheme: buttonTheme,
buttonColor: buttonColor,
toggleButtonsTheme: toggleButtonsTheme,
toggleableActiveColor: toggleableActiveColor,
secondaryHeaderColor: secondaryHeaderColor,
textSelectionColor: textSelectionColor,

accentIconTheme: accentIconTheme,
sliderTheme: sliderTheme,
tabBarTheme: tabBarTheme,
tooltipTheme:tooltipTheme,
cardTheme: cardTheme,
chipTheme: chipTheme,
platform: platform,

colorScheme: colorScheme,
dialogTheme: dialogTheme,
floatingActionButtonTheme: floatingActionButtonTheme,
navigationRailTheme: navigationRailTheme,
typography: typography,
snackBarTheme: snackBarTheme,
bottomSheetTheme: bottomSheetTheme,

Color bottomAppBarColor = null,
Color cardColor = null,
Color dividerColor = null,
Color focusColor = null,
Color hoverColor = null,
Color highlightColor = null,
Color splashColor = null,
InteractiveInkFeatureFactory splashFactory = null,

ButtonThemeData buttonTheme = null,
ToggleButtonsThemeData toggleButtonsTheme = null,
Color buttonColor = null,
Color secondaryHeaderColor = null,
Color textSelectionColor = null,

IconThemeData primaryIconTheme = null,
IconThemeData accentIconTheme = null,
TabBarTheme tabBarTheme = null,
TooltipThemeData tooltipTheme = null,
CardTheme cardTheme = null,
ChipThemeData chipTheme = null,
RuntimePlatform? platform = null,

ColorScheme colorScheme = null,
DialogTheme dialogTheme = null,
FloatingActionButtonThemeData floatingActionButtonTheme = null,
NavigationRailThemeData navigationRailTheme = null,
Typography typography = null,
SnackBarThemeData snackBarTheme = null,
BottomSheetThemeData bottomSheetTheme = null,

bottomAppBarColor: bottomAppBarColor ?? this.bottomAppBarColor,
cardColor: cardColor ?? this.cardColor,
dividerColor: dividerColor ?? this.dividerColor,
focusColor: focusColor ?? this.focusColor,
hoverColor: hoverColor ?? this.hoverColor,
highlightColor: highlightColor ?? this.highlightColor,
splashColor: splashColor ?? this.splashColor,
splashFactory: splashFactory ?? this.splashFactory,

buttonTheme: buttonTheme ?? this.buttonTheme,
toggleButtonsTheme: toggleButtonsTheme ?? this.toggleButtonsTheme,
buttonColor: buttonColor ?? this.buttonColor,
secondaryHeaderColor: secondaryHeaderColor ?? this.secondaryHeaderColor,
textSelectionColor: textSelectionColor ?? this.textSelectionColor,

primaryIconTheme: primaryIconTheme ?? this.primaryIconTheme,
accentIconTheme: accentIconTheme ?? this.accentIconTheme,
tabBarTheme: tabBarTheme ?? this.tabBarTheme,
tooltipTheme: tooltipTheme ?? this.tooltipTheme,
cardTheme: cardTheme ?? this.cardTheme,
chipTheme: chipTheme ?? this.chipTheme,
platform: platform ?? this.platform,

colorScheme: colorScheme ?? this.colorScheme,
dialogTheme: dialogTheme ?? this.dialogTheme,
floatingActionButtonTheme: floatingActionButtonTheme ?? this.floatingActionButtonTheme,
navigationRailTheme: navigationRailTheme ?? this.navigationRailTheme,
typography: typography ?? this.typography,
snackBarTheme: snackBarTheme ?? this.snackBarTheme,
bottomSheetTheme: bottomSheetTheme ?? this.bottomSheetTheme,

bottomAppBarColor: Color.lerp(a.bottomAppBarColor, b.bottomAppBarColor, t),
cardColor: Color.lerp(a.cardColor, b.cardColor, t),
dividerColor: Color.lerp(a.dividerColor, b.dividerColor, t),
focusColor: Color.lerp(a.focusColor, b.focusColor, t),
hoverColor: Color.lerp(a.hoverColor, b.hoverColor, t),
highlightColor: Color.lerp(a.highlightColor, b.highlightColor, t),
splashColor: Color.lerp(a.splashColor, b.splashColor, t),
splashFactory: t < 0.5 ? a.splashFactory : b.splashFactory,

buttonTheme: t < 0.5 ? a.buttonTheme : b.buttonTheme,
toggleButtonsTheme: ToggleButtonsThemeData.lerp(a.toggleButtonsTheme, b.toggleButtonsTheme, t),
buttonColor: Color.lerp(a.buttonColor, b.buttonColor, t),
secondaryHeaderColor: Color.lerp(a.secondaryHeaderColor, b.secondaryHeaderColor, t),
textSelectionColor: Color.lerp(a.textSelectionColor, b.textSelectionColor, t),

accentIconTheme: IconThemeData.lerp(a.accentIconTheme, b.accentIconTheme, t),
sliderTheme: SliderThemeData.lerp(a.sliderTheme, b.sliderTheme, t),
tabBarTheme: TabBarTheme.lerp(a.tabBarTheme, b.tabBarTheme, t),
tooltipTheme: TooltipThemeData.lerp(a.tooltipTheme, b.tooltipTheme, t),
cardTheme: CardTheme.lerp(a.cardTheme, b.cardTheme, t),
chipTheme: ChipThemeData.lerp(a.chipTheme, b.chipTheme, t),
platform: t < 0.5 ? a.platform : b.platform,

dialogTheme: DialogTheme.lerp(a.dialogTheme, b.dialogTheme, t),
floatingActionButtonTheme: FloatingActionButtonThemeData.lerp(a.floatingActionButtonTheme,
b.floatingActionButtonTheme, t),
navigationRailTheme: NavigationRailThemeData.lerp(a.navigationRailTheme, b.navigationRailTheme, t),
typography: Typography.lerp(a.typography, b.typography, t),
snackBarTheme: SnackBarThemeData.lerp(a.snackBarTheme, b.snackBarTheme, t),
bottomSheetTheme: BottomSheetThemeData.lerp(a.bottomSheetTheme, b.bottomSheetTheme, t),

other.bottomAppBarColor == bottomAppBarColor &&
other.cardColor == cardColor &&
other.dividerColor == dividerColor &&
other.focusColor == focusColor &&
other.hoverColor == hoverColor &&
other.highlightColor == highlightColor &&
other.splashColor == splashColor &&
other.splashFactory == splashFactory &&

other.buttonTheme == buttonTheme &&
other.toggleButtonsTheme == toggleButtonsTheme &&
other.buttonColor == buttonColor &&
other.secondaryHeaderColor == secondaryHeaderColor &&
other.textSelectionColor == textSelectionColor &&

other.primaryIconTheme == primaryIconTheme &&
other.accentIconTheme == accentIconTheme &&
other.tabBarTheme == tabBarTheme &&
other.tooltipTheme == tooltipTheme &&
other.cardTheme == cardTheme &&
other.chipTheme == chipTheme &&
other.platform == platform &&

other.colorScheme == colorScheme &&
other.dialogTheme == dialogTheme &&
other.floatingActionButtonTheme == floatingActionButtonTheme &&
other.navigationRailTheme == navigationRailTheme &&
other.typography == typography &&
other.snackBarTheme == snackBarTheme &&
other.bottomSheetTheme == bottomSheetTheme &&

hashCode = (hashCode * 397) ^ bottomAppBarColor.GetHashCode();
hashCode = (hashCode * 397) ^ cardColor.GetHashCode();
hashCode = (hashCode * 397) ^ dividerColor.GetHashCode();
hashCode = (hashCode * 397) ^ focusColor.GetHashCode();
hashCode = (hashCode * 397) ^ hoverColor.GetHashCode();
hashCode = (hashCode * 397) ^ highlightColor.GetHashCode();
hashCode = (hashCode * 397) ^ splashColor.GetHashCode();
hashCode = (hashCode * 397) ^ splashFactory.GetHashCode();

hashCode = (hashCode * 397) ^ buttonTheme.GetHashCode();
hashCode = (hashCode * 397) ^ toggleButtonsTheme.GetHashCode();
hashCode = (hashCode * 397) ^ buttonColor.GetHashCode();
hashCode = (hashCode * 397) ^ secondaryHeaderColor.GetHashCode();
hashCode = (hashCode * 397) ^ textSelectionColor.GetHashCode();

hashCode = (hashCode * 397) ^ accentIconTheme.GetHashCode();
hashCode = (hashCode * 397) ^ sliderTheme.GetHashCode();
hashCode = (hashCode * 397) ^ tabBarTheme.GetHashCode();
hashCode = (hashCode * 397) ^ tooltipTheme.GetHashCode();
hashCode = (hashCode * 397) ^ cardTheme.GetHashCode();
hashCode = (hashCode * 397) ^ chipTheme.GetHashCode();
hashCode = (hashCode * 397) ^ platform.GetHashCode();

hashCode = (hashCode * 397) ^ colorScheme.GetHashCode();
hashCode = (hashCode * 397) ^ dialogTheme.GetHashCode();
hashCode = (hashCode * 397) ^ floatingActionButtonTheme.GetHashCode();
hashCode = (hashCode * 397) ^ navigationRailTheme.GetHashCode();
hashCode = (hashCode * 397) ^ typography.GetHashCode();
hashCode = (hashCode * 397) ^ snackBarTheme.GetHashCode();
hashCode = (hashCode * 397) ^ bottomSheetTheme.GetHashCode();

defaultValue: defaultData.cardColor));
properties.add(new DiagnosticsProperty<Color>("dividerColor", dividerColor,
defaultValue: defaultData.dividerColor));
properties.add(new ColorProperty("focusColor", focusColor, defaultValue: defaultData.focusColor, level: DiagnosticLevel.debug));
properties.add(new ColorProperty("hoverColor", hoverColor, defaultValue: defaultData.hoverColor, level: DiagnosticLevel.debug));
properties.add(new DiagnosticsProperty<Color>("highlightColor", highlightColor,
defaultValue: defaultData.highlightColor));
properties.add(new DiagnosticsProperty<Color>("splashColor", splashColor,

properties.add(new DiagnosticsProperty<Color>("disabledColor", disabledColor,
defaultValue: defaultData.disabledColor));
properties.add(new DiagnosticsProperty<ButtonThemeData>("buttonTheme", buttonTheme));
properties.add(new DiagnosticsProperty<ToggleButtonsThemeData>("toggleButtonsTheme", toggleButtonsTheme, level: DiagnosticLevel.debug));
properties.add(new DiagnosticsProperty<Color>("buttonColor", buttonColor,
defaultValue: defaultData.buttonColor));
properties.add(new DiagnosticsProperty<Color>("secondaryHeaderColor", secondaryHeaderColor,

properties.add(new DiagnosticsProperty<IconThemeData>("accentIconTheme", accentIconTheme));
properties.add(new DiagnosticsProperty<SliderThemeData>("sliderTheme", sliderTheme));
properties.add(new DiagnosticsProperty<TabBarTheme>("tabBarTheme", tabBarTheme));
properties.add(new DiagnosticsProperty<TooltipThemeData>("tooltipTheme", tooltipTheme, level: DiagnosticLevel.debug));
properties.add(new DiagnosticsProperty<CardTheme>("cardTheme", cardTheme));
properties.add(new DiagnosticsProperty<ChipThemeData>("chipTheme", chipTheme));
properties.add(

defaultValue: defaultData.dialogTheme));
properties.add(new DiagnosticsProperty<FloatingActionButtonThemeData>("floatingActionButtonTheme",
floatingActionButtonTheme, defaultValue: defaultData.floatingActionButtonTheme));
properties.add(new DiagnosticsProperty<NavigationRailThemeData>("navigationRailThemeData", navigationRailTheme, defaultValue: defaultData.navigationRailTheme, level: DiagnosticLevel.debug));
properties.add(new DiagnosticsProperty<Typography>("typography", typography,
defaultValue: defaultData.typography));
properties.add(new DiagnosticsProperty<SnackBarThemeData>("snackBarTheme", snackBarTheme, defaultValue: defaultData.snackBarTheme, level: DiagnosticLevel.debug));

4
com.unity.uiwidgets/Runtime/painting/basic_types.cs


Axis axis,
bool reverse) {
switch (axis) {
/*case Axis.horizontal:
return reverse ? AxisDirection.left : AxisDirection.right;
case Axis.vertical:
return reverse ? AxisDirection.up : AxisDirection.down;*/
case Axis.horizontal:
D.assert(WidgetsD.debugCheckHasDirectionality(context));
TextDirection textDirection = Directionality.of(context);

9
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);

public readonly float scale;
public override Future<FileImage> obtainKey(ImageConfiguration configuration) {
return Future.value(FutureOr.value(this)).to<FileImage>();
return new SynchronousFuture<FileImage>(this);
}
public override ImageStreamCompleter load(FileImage key, DecoderCallback decode) {

2
com.unity.uiwidgets/Runtime/painting/image_stream.cs


return true;
}
return Equals(image, other.image) && scale.Equals(other.scale);
return image.Equals(other.image) && scale.Equals(other.scale);
}
public override bool Equals(object obj) {

2
com.unity.uiwidgets/Runtime/painting/matrix_utils.cs


return (e > f) ? e : f;
}
static Matrix4 createCylindricalProjectionTransform(
public static Matrix4 createCylindricalProjectionTransform(
float radius,
float angle,
float perspective = 0.001f,

9
com.unity.uiwidgets/Runtime/rendering/binding.cs


}
readonly protected bool inEditorWindow;
/* MouseTracker _createMouseTracker() {
return new MouseTracker(pointerRouter, (Offset offset) => {
return renderView.layer.find<MouseTrackerAnnotation>(
offset
);
}, inEditorWindow);
}*/
protected virtual void drawFrame() {
D.assert(renderView != null);

56
com.unity.uiwidgets/Runtime/rendering/layer.cs


}
}
/*internal override S find<S>(Offset regionOffset) {
return null;
}*/
public override void addToScene(SceneBuilder builder, Offset layerOffset = null) {
layerOffset = layerOffset ?? Offset.zero;
builder.addPicture(layerOffset, picture,

}
/*internal override S find<S>(Offset regionOffset) {
Layer current = lastChild;
while (current != null) {
S value = current.find<S>(regionOffset);
if (value != null) {
return value;
}
current = current.previousSibling;
}
return null;
}*/
public override bool findAnnotations<S>(
AnnotationResult<S> result,
Offset localPosition,

properties.add(new DiagnosticsProperty<Offset>("offset", offset));
}
/*public Scene buildScene(SceneBuilder builder) {
List<PictureLayer> temporaryLayers = null;
D.assert(() => {
if (RenderingDebugUtils.debugCheckElevationsEnabled) {
temporaryLayers = _debugCheckElevations();
}
return true;
});
updateSubtreeNeedsAddToScene();
addToScene(builder);
Scene scene = builder.build();
D.assert(() => {
if (temporaryLayers != null) {
foreach (PictureLayer temporaryLayer in temporaryLayers) {
temporaryLayer.remove();
}
}
return true;
});
return scene;
}*/
public Future<ui.Image> toImage(Rect bounds, float pixelRatio = 1.0f)// async
{
D.assert(bounds != null);

var totalOffset = offset + layerOffset;
if (totalOffset != Offset.zero) {
_lastEffectiveTransform = Matrix4.translationValues(totalOffset.dx, totalOffset.dy, 0);
_lastEffectiveTransform = Matrix4.translationValues(totalOffset.dx, totalOffset.dy, 0.0f);
_lastEffectiveTransform.multiply(transform);
}

_lastOffset = offset + layerOffset;
if (_lastOffset != Offset.zero) {
engineLayer = builder.pushTransform(
Matrix4.translationValues(_lastOffset.dx, _lastOffset.dy,0)
._m4storage,
Matrix4.translationValues(_lastOffset.dx, _lastOffset.dy,0.0f).storage,
oldLayer: engineLayer as TransformEngineLayer);
}

return null;
}
Matrix4 result = Matrix4.translationValues(-_lastOffset.dx, -_lastOffset.dy,0 );
Matrix4 result = Matrix4.translationValues(-_lastOffset.dx, -_lastOffset.dy,0.0f );
result.multiply(_lastTransform);
return result;
}

_establishTransform();
if (_lastTransform != null) {
engineLayer = builder.pushTransform(
_lastTransform._m4storage,
_lastTransform.storage,
oldLayer: engineLayer as TransformEngineLayer);
addChildrenToScene(builder);
builder.pop();

_lastOffset = null;
var matrix = Matrix4.translationValues(unlinkedOffset.dx, unlinkedOffset.dy, 0);
var matrix = Matrix4.translationValues(unlinkedOffset.dx, unlinkedOffset.dy, 0.0f);
matrix._m4storage,
matrix.storage,
oldLayer: engineLayer as TransformEngineLayer);
addChildrenToScene(builder);
builder.pop();

transform.multiply(_lastTransform);
}
else {
transform.multiply(Matrix4.translationValues(unlinkedOffset.dx, unlinkedOffset.dy, 0));
transform.multiply(Matrix4.translationValues(unlinkedOffset.dx, unlinkedOffset.dy, 0.0f));
}
}

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


var radius = size.height * _diameterRatio / 2.0f;
var deltaY = radius * Mathf.Sin(angle);
Matrix4 transform = Matrix4.identity();
// Matrix4x4 transform2 = MatrixUtils.createCylindricalProjectionTransform(
// radius: this.size.height * this._diameterRatio / 2.0f,
// angle: angle,
// perspective: this._perspective
// );
// Offset offsetToCenter = new Offset(untransformedPaintingCoordinates.dx, -this._topScrollMarginExtent);
Offset offsetToCenter =
new Offset(untransformedPaintingCoordinates.dx, -deltaY - _topScrollMarginExtent);
Matrix4 transform = MatrixUtils.createCylindricalProjectionTransform(
radius: size.height * _diameterRatio / 2.0f,
angle: angle,
perspective: _perspective
);
// Offset that helps painting everything in the center (e.g. angle = 0).
Offset offsetToCenter = new Offset(
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);
});

46
com.unity.uiwidgets/Runtime/rendering/paragraph.cs


bool _hasHoverRecognizer;
MouseTrackerAnnotation _hoverAnnotation;
/*void _resetHoverHandler() {
_hasHoverRecognizer = (_textPainter.text as TextSpan)?.hasHoverRecognizer ?? false;
_previousHoverSpan = null;
_pointerHoverInside = false;
if (_hoverAnnotation != null && attached) {
RendererBinding.instance.mouseTracker.detachAnnotation(_hoverAnnotation);
}
if (_hasHoverRecognizer) {
_hoverAnnotation = new MouseTrackerAnnotation(
onEnter: _onPointerEnter,
onHover: _onPointerHover,
onExit: _onPointerExit);
if (attached) {
RendererBinding.instance.mouseTracker.attachAnnotation(_hoverAnnotation);
}
}
else {
_hoverAnnotation = null;
}
}*/
void _handleKeyEvent(RawKeyEvent keyEvent) {
//only allow KCommand.copy

}
base.detach();
/*if (_hoverAnnotation != null) {
RendererBinding.instance.mouseTracker.dispose();//detachAnnotation(_hoverAnnotation);
}*/
}
TextSelection _selection;

_pointerHoverInside = true;
}
/*void _onPointerExit(PointerEvent evt) {
_pointerHoverInside = false;
(_previousHoverSpan as TextSpan)?.hoverRecognizer?.OnPointerLeave?.Invoke();
_previousHoverSpan = null;
}*/
/*void _onPointerHover(PointerEvent evt) {
_layoutTextWithConstraints(constraints);
Offset offset = globalToLocal(evt.position);
TextPosition position = _textPainter.getPositionForOffset(offset);
InlineSpan span = _textPainter.text.getSpanForPosition(position);
if (_previousHoverSpan != span) {
(_previousHoverSpan as TextSpan)?.hoverRecognizer?.OnPointerLeave?.Invoke();
(span as TextSpan)?.hoverRecognizer?.OnPointerEnter?.Invoke((PointerHoverEvent) evt);
_previousHoverSpan = span;
}
}*/
public override void handleEvent(PointerEvent evt, HitTestEntry entry) {
D.assert(debugHandleEvent(evt, entry));

311
com.unity.uiwidgets/Runtime/rendering/proxy_box.cs


public delegate void PointerScrollEventListener(PointerScrollEvent evt);
/*public class RenderPointerListener : RenderProxyBoxWithHitTestBehavior {
public RenderPointerListener(
PointerDownEventListener onPointerDown = null,
PointerMoveEventListener onPointerMove = null,
PointerEnterEventListener onPointerEnter = null,
PointerHoverEventListener onPointerHover = null,
PointerExitEventListener onPointerExit = null,
PointerUpEventListener onPointerUp = null,
PointerCancelEventListener onPointerCancel = null,
PointerSignalEventListener onPointerSignal = null,
PointerScrollEventListener onPointerScroll = null,
PointerDragFromEditorEnterEventListener onPointerDragFromEditorEnter = null,
PointerDragFromEditorHoverEventListener onPointerDragFromEditorHover = null,
PointerDragFromEditorExitEventListener onPointerDragFromEditorExit = null,
PointerDragFromEditorReleaseEventListener onPointerDragFromEditorRelease = null,
HitTestBehavior behavior = HitTestBehavior.deferToChild,
RenderBox child = null
) : base(behavior: behavior, child: child) {
this.onPointerDown = onPointerDown;
this.onPointerMove = onPointerMove;
this.onPointerUp = onPointerUp;
this.onPointerCancel = onPointerCancel;
this.onPointerSignal = onPointerSignal;
this.onPointerScroll = onPointerScroll;
_onPointerEnter = onPointerEnter;
_onPointerHover = onPointerHover;
_onPointerExit = onPointerExit;
_onPointerDragFromEditorEnter = onPointerDragFromEditorEnter;
_onPointerDragFromEditorHover = onPointerDragFromEditorHover;
_onPointerDragFromEditorExit = onPointerDragFromEditorExit;
_onPointerDragFromEditorRelease = onPointerDragFromEditorRelease;
if (_onPointerEnter != null ||
_onPointerHover != null ||
_onPointerExit != null ||
_onPointerDragFromEditorEnter != null ||
_onPointerDragFromEditorHover != null ||
_onPointerDragFromEditorExit != null ||
_onPointerDragFromEditorRelease != null
) {
_hoverAnnotation = new MouseTrackerAnnotation(
onEnter: _onPointerEnter,
onHover: _onPointerHover,
onExit: _onPointerExit,
onDragFromEditorEnter: _onPointerDragFromEditorEnter,
onDragFromEditorHover: _onPointerDragFromEditorHover,
onDragFromEditorExit: _onPointerDragFromEditorExit,
onDragFromEditorRelease: _onPointerDragFromEditorRelease
);
}
}
PointerDragFromEditorEnterEventListener _onPointerDragFromEditorEnter;
public PointerDragFromEditorEnterEventListener onPointerDragFromEditorEnter {
get { return _onPointerDragFromEditorEnter; }
set {
if (_onPointerDragFromEditorEnter != value) {
_onPointerDragFromEditorEnter = value;
_updateAnnotations();
}
}
}
PointerDragFromEditorExitEventListener _onPointerDragFromEditorExit;
public PointerDragFromEditorExitEventListener onPointerDragFromEditorExit {
get { return _onPointerDragFromEditorExit; }
set {
if (_onPointerDragFromEditorExit != value) {
_onPointerDragFromEditorExit = value;
_updateAnnotations();
}
}
}
PointerDragFromEditorHoverEventListener _onPointerDragFromEditorHover;
public PointerDragFromEditorHoverEventListener onPointerDragFromEditorHover {
get { return _onPointerDragFromEditorHover; }
set {
if (_onPointerDragFromEditorHover != value) {
_onPointerDragFromEditorHover = value;
_updateAnnotations();
}
}
}
PointerDragFromEditorReleaseEventListener _onPointerDragFromEditorRelease;
public PointerDragFromEditorReleaseEventListener onPointerDragFromEditorRelease {
get { return _onPointerDragFromEditorRelease; }
set {
if (_onPointerDragFromEditorRelease != value) {
_onPointerDragFromEditorRelease = value;
_updateAnnotations();
}
}
}
public PointerEnterEventListener onPointerEnter {
get { return _onPointerEnter; }
set {
if (_onPointerEnter != value) {
_onPointerEnter = value;
_updateAnnotations();
}
}
}
PointerEnterEventListener _onPointerEnter;
public PointerHoverEventListener onPointerHover {
get { return _onPointerHover; }
set {
if (_onPointerHover != value) {
_onPointerHover = value;
_updateAnnotations();
}
}
}
PointerHoverEventListener _onPointerHover;
public PointerExitEventListener onPointerExit {
get { return _onPointerExit; }
set {
if (_onPointerExit != value) {
_onPointerExit = value;
_updateAnnotations();
}
}
}
PointerExitEventListener _onPointerExit;
public PointerDownEventListener onPointerDown;
public PointerMoveEventListener onPointerMove;
public PointerUpEventListener onPointerUp;
public PointerCancelEventListener onPointerCancel;
public PointerSignalEventListener onPointerSignal;
public PointerScrollEventListener onPointerScroll;
MouseTrackerAnnotation _hoverAnnotation;
public MouseTrackerAnnotation hoverAnnotation {
get { return _hoverAnnotation; }
}
void _updateAnnotations() {
D.assert(_onPointerEnter != _hoverAnnotation.onEnter ||
_onPointerHover != _hoverAnnotation.onHover ||
_onPointerExit != _hoverAnnotation.onExit
#if UNITY_EDITOR
|| _onPointerDragFromEditorEnter != _hoverAnnotation.onDragFromEditorEnter
|| _onPointerDragFromEditorHover != _hoverAnnotation.onDragFromEditorHover
|| _onPointerDragFromEditorExit != _hoverAnnotation.onDragFromEditorExit
|| _onPointerDragFromEditorRelease != _hoverAnnotation.onDragFromEditorRelease
#endif
, () => "Shouldn't call _updateAnnotations if nothing has changed.");
if (_hoverAnnotation != null && attached) {
RendererBinding.instance.mouseTracker.detachAnnotation(_hoverAnnotation);
}
if (_onPointerEnter != null ||
_onPointerHover != null ||
_onPointerExit != null
#if UNITY_EDITOR
|| _onPointerDragFromEditorEnter != null
|| _onPointerDragFromEditorHover != null
|| _onPointerDragFromEditorExit != null
|| _onPointerDragFromEditorRelease != null
#endif
) {
_hoverAnnotation = new MouseTrackerAnnotation(
onEnter: _onPointerEnter,
onHover: _onPointerHover,
onExit: _onPointerExit
#if UNITY_EDITOR
, onDragFromEditorEnter: _onPointerDragFromEditorEnter
, onDragFromEditorHover: _onPointerDragFromEditorHover
, onDragFromEditorExit: _onPointerDragFromEditorExit
, onDragFromEditorRelease: _onPointerDragFromEditorRelease
#endif
);
if (attached) {
RendererBinding.instance.mouseTracker.attachAnnotation(_hoverAnnotation);
}
}
else {
_hoverAnnotation = null;
}
markNeedsPaint();
}
public override void attach(object owner) {
base.attach(owner);
if (_hoverAnnotation != null) {
RendererBinding.instance.mouseTracker.attachAnnotation(_hoverAnnotation);
}
}
public override void detach() {
base.detach();
if (_hoverAnnotation != null) {
RendererBinding.instance.mouseTracker.detachAnnotation(_hoverAnnotation);
}
}
public override void paint(PaintingContext context, Offset offset) {
if (_hoverAnnotation != null) {
AnnotatedRegionLayer<MouseTrackerAnnotation> layer = new AnnotatedRegionLayer<MouseTrackerAnnotation>(
_hoverAnnotation, size: size, offset: offset);
context.pushLayer(layer, base.paint, offset);
}
else {
base.paint(context, offset);
}
}
protected override void performResize() {
size = constraints.biggest;
}
public override void handleEvent(PointerEvent evt, HitTestEntry entry) {
D.assert(debugHandleEvent(evt, entry));
if (onPointerDown != null && evt is PointerDownEvent) {
onPointerDown((PointerDownEvent) evt);
return;
}
if (onPointerMove != null && evt is PointerMoveEvent) {
onPointerMove((PointerMoveEvent) evt);
return;
}
if (onPointerUp != null && evt is PointerUpEvent) {
onPointerUp((PointerUpEvent) evt);
return;
}
if (onPointerCancel != null && evt is PointerCancelEvent) {
onPointerCancel((PointerCancelEvent) evt);
return;
}
if (onPointerSignal != null && evt is PointerSignalEvent) {
onPointerSignal((PointerSignalEvent) evt);
return;
}
if (onPointerScroll != null && evt is PointerScrollEvent) {
onPointerScroll((PointerScrollEvent) evt);
}
}
public override void debugFillProperties(DiagnosticPropertiesBuilder properties) {
base.debugFillProperties(properties);
var listeners = new List<string>();
if (onPointerDown != null) {
listeners.Add("down");
}
if (onPointerMove != null) {
listeners.Add("move");
}
if (onPointerEnter != null) {
listeners.Add("enter");
}
if (onPointerHover != null) {
listeners.Add("hover");
}
if (onPointerExit != null) {
listeners.Add("exit");
}
if (onPointerUp != null) {
listeners.Add("up");
}
if (onPointerCancel != null) {
listeners.Add("cancel");
}
if (onPointerSignal != null) {
listeners.Add("signal");
}
if (listeners.isEmpty()) {
listeners.Add("<none>");
}
properties.add(new EnumerableProperty<string>("listeners", listeners));
}
}*/
class RenderPointerListener : RenderProxyBoxWithHitTestBehavior {
public RenderPointerListener(
PointerDownEventListener onPointerDown = null,

16
com.unity.uiwidgets/Runtime/rendering/proxy_sliver.cs


};
}
}
/*public class RenderSliverAnimatedOpacity : RenderProxySliver ,RenderAnimatedOpacityMixin<RenderSliver>{
public RenderSliverAnimatedOpacity(
Animation<double> opacity = null,
bool alwaysIncludeSemantics = false,
RenderSliver sliver = null
):base(sliver) {
D.assert(opacity != null);
D.assert(alwaysIncludeSemantics != null);
this.opacity = opacity;
this.alwaysIncludeSemantics = alwaysIncludeSemantics;
child = sliver;
}
}*/
}

2
com.unity.uiwidgets/Runtime/scheduler2/binding.cs


Completer _nextFrameCompleter;
Future endOfFrame {
public Future endOfFrame {
get {
if (_nextFrameCompleter == null) {
if (schedulerPhase == SchedulerPhase.idle)

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[]>();
}

2
com.unity.uiwidgets/Runtime/ui2/Matrix4.cs


static float TOLERANCE = 0.000001f;
public float[] storage {
get => _m4storage;
get { return _m4storage; }
}
public static void solve2(Matrix4 A, Vector2 x, Vector2 b) {

43
com.unity.uiwidgets/Runtime/ui2/painting.cs


using System.Runtime.InteropServices;
using System.Text;
using AOT;
using Unity.UIWidgets.animation;
using Unity.UIWidgets.async2;
using Unity.UIWidgets.foundation;
using UnityEngine;

public int rowBytes;
}
public class Image : NativeWrapperDisposable {
public class Image : NativeWrapperDisposable, IEquatable<Image> {
internal Image(IntPtr ptr) : base(ptr) {
}

Debug.LogException(ex);
}
}
public override string ToString() => $"[{width}\u00D7{height}]";
[DllImport(NativeBindings.dllName)]

[DllImport(NativeBindings.dllName)]
static extern IntPtr Image_toByteData(IntPtr ptr, int format, Image_toByteDataCallback callback,
IntPtr callbackHandle);
public bool Equals(Image other) {
return other != null && width == other.width && height == other.height && _ptr.Equals(other._ptr);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) {
return false;
}
if (ReferenceEquals(this, obj)) {
return true;
}
if (obj.GetType() != GetType()) {
return false;
}
return Equals((Image) obj);
}
public static bool operator ==(Image left, Image right) {
return Equals(left, right);
}
public static bool operator !=(Image left, Image right) {
return !Equals(left, right);
}
public override int GetHashCode() {
unchecked {
var hashCode = (width != null ? width.GetHashCode() : 0);
hashCode = (hashCode * 397) ^(height != null ? height.GetHashCode() : 0);
hashCode = (hashCode * 397) ^ (_ptr != null ? _ptr.GetHashCode() : 0);
return hashCode;
}
}
}
/*

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;
}

26
com.unity.uiwidgets/Runtime/widgets/editable_text.cs


using Unity.UIWidgets.async2;
using Unity.UIWidgets.foundation;
using Unity.UIWidgets.gestures;
//using Unity.UIWidgets.material;
using Unity.UIWidgets.material;
using Unity.UIWidgets.painting;
using Unity.UIWidgets.rendering;
using Unity.UIWidgets.scheduler2;

if (textChanged && widget.onChanged != null)
widget.onChanged(value.text);
_lastFormattedUnmodifiedTextEditingValue = _receivedRemoteTextEditingValue;
/*
var textChanged = _value?.text != value?.text || isIMEInput;
if (textChanged && widget.inputFormatters != null && widget.inputFormatters.isNotEmpty()) {
foreach (var formatter in widget.inputFormatters) {
value = formatter.formatEditUpdate(_value, value);
}
_value = value;
_updateRemoteEditingValueIfNeeded();
//_updateImePosIfNeed();
}
else {
_value = value;
}
if (textChanged && widget.onChanged != null) {
widget.onChanged(value.text);
}*/
}
void _onCursorColorTick() {

public readonly TextSelectionDelegate textSelectionDelegate;
public readonly bool? paintCursorAboveText;
public readonly float? devicePixelRatio;
//public readonly GlobalKeyEventHandlerDelegate globalKeyEventHandler;
public readonly Locale locale;
public _Editable(
Key key = null,

bool enableInteractiveSelection = true,
TextSelectionDelegate textSelectionDelegate = null,
float? devicePixelRatio = null
//GlobalKeyEventHandlerDelegate globalKeyEventHandler = null
) : base(key) {
) : base(key) {
this.textSpan = textSpan;
this.value = value;
this.startHandleLayerLink = startHandleLayerLink;

this.selectionWidthStyle = selectionWidthStyle;
this.enableInteractiveSelection = enableInteractiveSelection;
this.devicePixelRatio = devicePixelRatio;
//this.globalKeyEventHandler = globalKeyEventHandler;
}
public override RenderObject createRenderObject(BuildContext context) {

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;
}
}

4
com.unity.uiwidgets/Runtime/widgets/focus_traversal.cs


public static void insertionSort<T>(List<T> list,
Comparator<T> compare = null, int start = 0, int end =0) {
//compare ??= defaultCompare<T>();
//compare = compare == null ? defaultCompare<T>();
end = end == 0 ?list.Count : end;
for (int pos = start + 1; pos < end; pos++) {

public interface DirectionalFocusTraversalPolicyMixin {
//Dictionary<FocusScopeNode, _DirectionalPolicyData> _policyData = new Dictionary<FocusScopeNode, _DirectionalPolicyData>();
void invalidateScopeData(FocusScopeNode node);
void changedScope(FocusNode node = null, FocusScopeNode oldScope = null);
FocusNode findFirstFocusInDirection(FocusNode currentNode, TraversalDirection direction);

2
com.unity.uiwidgets/Runtime/widgets/framework.cs


}
}
void reassemble(Element root) {
public void reassemble(Element root) {
try {
D.assert(root._parent == null);
D.assert(root.owner == this);

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));
}

68
com.unity.uiwidgets/Runtime/widgets/list_wheel_scroll_view.cs


if (children.isEmpty()) {
return null;
}
return new Container(child: children[Mathf.Abs(index % children.Count)]);
return new IndexedSemantics(child: children[Mathf.Abs(index % children.Count)]);
}
public bool shouldRebuild(ListWheelChildDelegate oldDelegate) {

public Widget build(BuildContext context, int index) {
if (childCount == null) {
Widget child = builder(context, index);
return child == null ? null : new Container(child: child);
return child == null ? null : new IndexedSemantics(child: child);
}
if (index < 0 || index >= childCount) {

return new Container(child: builder(context, index));
return new IndexedSemantics(child: builder(context, index));
}
public int trueIndexOf(int index) {

class ListWheelScrollViewUtils {
public static int _getItemFromOffset(
float? offset = null,
float? itemExtent = null,
float? minScrollExtent = null,
float? maxScrollExtent = null
float offset ,
float itemExtent ,
float minScrollExtent ,
float maxScrollExtent
var _itemExtent = itemExtent ?? 1.0f;
return (_clipOffsetToScrollableRange(offset ?? 0.0f , minScrollExtent ?? 0.0f, maxScrollExtent ?? 0.0f) / _itemExtent).round();
return (_clipOffsetToScrollableRange(offset, minScrollExtent, maxScrollExtent) / itemExtent).round();
}
public static float _clipOffsetToScrollableRange(
float offset,

() =>
"The selectedItem property cannot be read when multiple scroll views are attached to the same FixedExtentScrollController."
);
_FixedExtentScrollPosition position = (_FixedExtentScrollPosition) this.position;
_FixedExtentScrollPosition position = (_FixedExtentScrollPosition) this.position;
return position.itemIndex;
}
}

TimeSpan? duration = null,
Curve curve = null
TimeSpan duration,
Curve curve
duration: duration ?? new TimeSpan(0,0,0,0,0),
duration: duration,
return Future.wait<object>(futures);
}

public class FixedExtentMetrics : FixedScrollMetrics, IFixedExtentMetrics {
public FixedExtentMetrics(
float? minScrollExtent = null,
float? maxScrollExtent = null,
float? pixels = null,
float? viewportDimension = null,
AxisDirection axisDirection = AxisDirection.down,
int? itemIndex = null
float minScrollExtent ,
float maxScrollExtent,
float pixels ,
float viewportDimension ,
AxisDirection axisDirection ,
int itemIndex
minScrollExtent: minScrollExtent ?? 0.0f,
maxScrollExtent: maxScrollExtent ?? 0.0f,
pixels: pixels ?? 0.0f,
viewportDimension: viewportDimension ?? 0.0f,
minScrollExtent: minScrollExtent ,
maxScrollExtent: maxScrollExtent ,
pixels: pixels ,
viewportDimension: viewportDimension ,
this.itemIndex = itemIndex ?? 0;
this.itemIndex = itemIndex;
}
public int itemIndex { get; set; }

) : base(
physics: physics,
context: context,
initialPixels: _getItemExtentFromScrollContext(context) * initialItem,
initialPixels: _getItemExtentFromScrollContext(context) * (initialItem ?? 0.0f),
keepScrollOffset: keepScrollOffset,
oldPosition: oldPosition,
debugLabel: debugLabel

static float _getItemExtentFromScrollContext(ScrollContext context) {
_FixedExtentScrollableState scrollable = (_FixedExtentScrollableState) context;
return scrollable.itemExtent ?? 0.0f;
return scrollable.itemExtent;
}
public float itemExtent {

class _FixedExtentScrollable : Scrollable {
public _FixedExtentScrollable(
float itemExtent,
ScrollPhysics physics = null,
float? itemExtent = null,
ScrollPhysics physics = null,
) : base(
key: key,
axisDirection: axisDirection,

this.itemExtent = itemExtent;
}
public readonly float? itemExtent;
public readonly float itemExtent;
public override State createState() {
return new _FixedExtentScrollableState();

class _FixedExtentScrollableState : ScrollableState {
public float? itemExtent {
public float itemExtent {
get {
_FixedExtentScrollable actualWidget = (_FixedExtentScrollable) widget;
return actualWidget.itemExtent;

public class ListWheelScrollView : StatefulWidget {
public ListWheelScrollView(
List<Widget> children,
float itemExtent,
Key key = null,
ScrollController controller = null,
ScrollPhysics physics = null,

bool useMagnifier = false,
float magnification = 1.0f,
float overAndUnderCenterOpacity = 1.0f,
float? itemExtent = null,
float squeeze = 1.0f,
ValueChanged<int> onSelectedItemChanged = null,
bool clipToSize = true,

}
public ListWheelScrollView (
float itemExtent,
Key key = null,
ScrollController controller = null,
ScrollPhysics physics = null,

bool useMagnifier = false,
float magnification = 1.0f,
float? itemExtent = null,
float squeeze = 1.0f,
ValueChanged<int> onSelectedItemChanged = null,
float overAndUnderCenterOpacity = 1.0f,

public readonly float offAxisFraction;
public readonly bool useMagnifier;
public readonly float magnification;
public readonly float? itemExtent;
public readonly float itemExtent;
public readonly float overAndUnderCenterOpacity;
public readonly float squeeze;
public readonly ValueChanged<int> onSelectedItemChanged;

1
com.unity.uiwidgets/Runtime/widgets/localizations.cs


}
public abstract class LocalizationsDelegate<T> : LocalizationsDelegate {
//public abstract Future<T> load(Locale locale);
public override Type type {
get { return typeof(T); }
}

41
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);

public virtual Future<RoutePopDisposition> willPop() {
/// async
return Future.value(isFirst
? RoutePopDisposition.bubble
: RoutePopDisposition.pop).to<RoutePopDisposition>();

_RouteEntry routeEntry = null;
foreach (var historyEntry in _navigator._history) {
if (_RouteEntry.isRoutePredicate(this)(historyEntry)) {
//Route
routeEntry = historyEntry;
break;
}

get { return _overlayKey.currentState; }
}
public List<OverlayEntry> _allRouteOverlayEntries { ///sync
public List<OverlayEntry> _allRouteOverlayEntries {
//yield* entry.route.overlayEntries;
/*foreach (var historyOverlayEntry in historyEntry.route.overlayEntries) {
yield return historyOverlayEntry;
}*/
}
return overlayEntries;
}

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);
}
// todo
developer.developer_.postEvent("Flutter.Navigation", new Hashtable{
{"route", routeJsonable}
});

}
}
D.assert(anyEntry,()=> "Navigator has no active routes to replace.");
//_history.lastWhere(_RouteEntry.isPresentPredicate).complete(result, isReplaced: true);
_RouteEntry lastEntry = null;
foreach (var historyEntry in _history) {
if (_RouteEntry.isPresentPredicate(historyEntry)) {

D.assert(index >= 0, () => "There are no routes below the specified anchorRoute.");
_history.Insert(index + 1, new _RouteEntry(newRoute, initialState: _RouteLifecycle.replace));
//_history[index].remove(isReplaced: true);
_history.RemoveAt(index);
_flushHistoryUpdates();
D.assert(() => {

}
public bool canPop() {
IEnumerable<_RouteEntry> iterator = new List<_RouteEntry>();//_history.where(_RouteEntry.isPresentPredicate).iterator;
IEnumerable<_RouteEntry> iterator = new List<_RouteEntry>();
foreach (var historyEntry in _history) {
if (_RouteEntry.isPresentPredicate(historyEntry)) {
iterator.Append(historyEntry);

return true;
});
_RouteEntry entry = null; //_history.lastWhere(_RouteEntry.isPresentPredicate);
_RouteEntry entry = null;
foreach (_RouteEntry route in _history) {
if (_RouteEntry.isPresentPredicate(route)) {
entry = route;

});
D.assert(route._navigator == this);
bool wasCurrent = route.isCurrent;
_RouteEntry entry = null; //_history.firstWhere(_RouteEntry.isRoutePredicate(route), orElse: () => null);
_RouteEntry entry = null;
foreach (_RouteEntry routeEntry in _history) {
if (_RouteEntry.isRoutePredicate(route)(routeEntry)) {
entry = routeEntry;

RenderAbsorbPointer absorber =
_overlayKey.currentContext?.findAncestorRenderObjectOfType<RenderAbsorbPointer>();
setState(() => { absorber.absorbing = true; });//absorber?.
setState(() => {
if(absorber != null)
absorber.absorbing = true;
});
}
_activePointers.ToList().ForEach(WidgetsBinding.instance.cancelPointer);

public override Widget build(BuildContext context) {
D.assert(!_debugLocked);//_debuglocked = false;
D.assert(!_debugLocked);
D.assert(_history.isNotEmpty());
return new Listener(
onPointerDown: _handlePointerDown,

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; }
}

17
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

}
public virtual bool maintainState { get; }
public bool offstage {
public virtual bool offstage {
get { return _offstage; }
set {
if (_offstage == value) {

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);
}

9
com.unity.uiwidgets/Runtime/widgets/scroll_position.cs


this.keepScrollOffset = keepScrollOffset;
this.debugLabel = debugLabel;
_coordinator = coordinator;
if (oldPosition != null) {
absorb(oldPosition);
}

public bool hasMaxScrollExtent {
get { return _maxScrollExtent != null; }
}
public override float pixels {
get {
D.assert(_pixels != null);

D.assert(other != null);
D.assert(other.context == context);
D.assert(_pixels == null);
_minScrollExtent = other.minScrollExtent;
_maxScrollExtent = other.maxScrollExtent;
_minScrollExtent = other._minScrollExtent;
_maxScrollExtent = other._maxScrollExtent;
_viewportDimension = other.viewportDimension;
_viewportDimension = other._viewportDimension;
D.assert(activity == null);
D.assert(other.activity != null);

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


if (widget.physics != null) {
_physics = widget.physics.applyTo(_physics);
}
ScrollController controller = widget.controller;
ScrollPosition oldPosition = position;
if (oldPosition != null) {

});
}
_position = controller == null
? null
: controller.createScrollPosition(_physics, this, oldPosition);
_position = _position
?? new ScrollPositionWithSingleContext(physics: _physics, context: this,
oldPosition: oldPosition);
if (controller == null) {
_position = new ScrollPositionWithSingleContext(physics: _physics, context: this, oldPosition: oldPosition);
}
else {
_position = controller?.createScrollPosition(_physics, this, oldPosition)
?? new ScrollPositionWithSingleContext(physics: _physics, context: this, oldPosition: oldPosition);
}
D.assert(position != null);
if (controller != null) {
controller.attach(position);

}
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) {

31
com.unity.uiwidgets/Runtime/widgets/sliver.cs


RenderBox _currentBeforeChild;
protected override void performRebuild() {
//_didUnderflow = false;
_childWidgets.Clear();
base.performRebuild();
_currentBeforeChild = null;

_currentlyUpdatingChildIndex = index;
if(_childElements.getOrDefault(index) != null &&
_childElements.getOrDefault(index) != newChildren.getOrDefault(index))
// if (_childElements[index] != null && _childElements[index] != newChildren[index])
{
_childElements[index] = updateChild(_childElements[index], null, index);
}

}
return newChild;
/*SliverMultiBoxAdaptorParentData oldParentData = null;
if (child != null && child.renderObject != null) {
oldParentData = (SliverMultiBoxAdaptorParentData) child.renderObject.parentData;
}
Element newChild = base.updateChild(child, newWidget, newSlot);
SliverMultiBoxAdaptorParentData newParentData = null;
if (newChild != null && newChild.renderObject != null) {
newParentData = (SliverMultiBoxAdaptorParentData) newChild.renderObject.parentData;
}
if (oldParentData != newParentData && oldParentData != null && newParentData != null) {
newParentData.layoutOffset = oldParentData.layoutOffset;
}
return newChild;*/
}
internal override void forgetChild(Element child) {

}).ToList().ForEach(e => visitor(e));
}
}
/*public class SliverFillRemaining : SingleChildRenderObjectWidget {
public SliverFillRemaining(
Key key = null,
Widget child = null
) : base(key: key, child: child) {
}
public override RenderObject createRenderObject(BuildContext context) {
return new RenderSliverFillRemaining();
}
}*/
public class KeepAlive : ParentDataWidget<IKeepAliveParentDataMixin> {
public KeepAlive(

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


) : base(key: key, child: child) {
D.assert(style != null);
D.assert(softWrap != null);
D.assert(overflow != null);
D.assert(textWidthBasis != null);
this.style = style;
this.textAlign = textAlign;
this.softWrap = softWrap;

public static DefaultTextStyle of(BuildContext context) {
return context.dependOnInheritedWidgetOfExactType<DefaultTextStyle>() ?? new DefaultTextStyle();
}
public override bool updateShouldNotify(InheritedWidget oldWidget) {
//InheritedWidget
//DefaultTextStyle
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) {

}
/*public class DefaultTextStyle : InheritedWidget {
public DefaultTextStyle(
Key key = null,
TextStyle style = null,
TextAlign? textAlign = null,
bool softWrap = true,
TextOverflow overflow = TextOverflow.clip,
int? maxLines = null,
Widget child = null
) : base(key, child) {
D.assert(style != null);
D.assert(maxLines == null || maxLines > 0);
D.assert(child != null);
this.style = style;
this.textAlign = textAlign;
this.softWrap = softWrap;
this.overflow = overflow;
this.maxLines = maxLines;
}
DefaultTextStyle() {
style = new TextStyle();
textAlign = null;
softWrap = true;
overflow = TextOverflow.clip;
maxLines = null;
}
public static DefaultTextStyle fallback() {
return _fallback;
}
static readonly DefaultTextStyle _fallback = new DefaultTextStyle();
public static Widget merge(
Key key = null,
TextStyle style = null,
TextAlign? textAlign = null,
bool? softWrap = null,
TextOverflow? overflow = null,
int? maxLines = null,
Widget child = null
) {
D.assert(child != null);
return new Builder(builder: (context => {
var parent = of(context);
return new DefaultTextStyle(
key: key,
style: parent.style.merge(style),
textAlign: textAlign ?? parent.textAlign,
softWrap: softWrap ?? parent.softWrap,
overflow: overflow ?? parent.overflow,
maxLines: maxLines ?? parent.maxLines,
child: child
);
}));
}
public readonly TextStyle style;
public readonly TextAlign? textAlign;
public readonly bool softWrap;
public readonly TextOverflow overflow;
public readonly int? maxLines;
public static DefaultTextStyle of(BuildContext context) {
var inherit = (DefaultTextStyle) context.inheritFromWidgetOfExactType(typeof(DefaultTextStyle));
return inherit ?? fallback();
}
public override bool updateShouldNotify(InheritedWidget w) {
var oldWidget = (DefaultTextStyle) w;
return style != oldWidget.style ||
textAlign != oldWidget.textAlign ||
softWrap != oldWidget.softWrap ||
overflow != oldWidget.overflow ||
maxLines != oldWidget.maxLines;
}
public override void debugFillProperties(DiagnosticPropertiesBuilder properties) {
base.debugFillProperties(properties);
if (style != null) {
style.debugFillProperties(properties);
}
properties.add(new EnumProperty<TextAlign?>("textAlign", textAlign,
defaultValue: foundation_.kNullDefaultValue));
properties.add(new FlagProperty("softWrap", value: softWrap, ifTrue: "wrapping at box width",
ifFalse: "no wrapping except at line break characters", showName: true));
properties.add(new EnumProperty<TextOverflow>("overflow", overflow,
defaultValue: foundation_.kNullDefaultValue));
properties.add(new IntProperty("maxLines", maxLines,
defaultValue: foundation_.kNullDefaultValue));
}
}*/
public class Text : StatelessWidget {
public Text(string data,

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


);
}
}
/*public abstract class TextSelectionGestureDetectorBuilderDelegate {
public GlobalKey<EditableTextState> editableTextKey { get; }
public bool forcePressEnabled {
get;
}
public bool selectionEnabled { get; }
}*/
public interface TextSelectionGestureDetectorBuilderDelegate {
GlobalKey<EditableTextState> editableTextKey { get; }

9
com.unity.uiwidgets/Runtime/widgets/texture.cs


namespace Unity.UIWidgets.widgets {
public class Texture : LeafRenderObjectWidget {
// TODO: check whether following is needed
// public static void textureFrameAvailable(Window instance = null) {
// if (instance == null) {
// WindowAdapter.windowAdapters.ForEach(w => w.scheduleFrame(false));
// } else {
// instance.scheduleFrame(false);
// }
// }
public Texture(
Key key = null,
int? textureId = null) : base(key: key) {

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:
正在加载...
取消
保存