浏览代码

Merge pull request #94 from Unity-Technologies/editorwindow

add editorWindow support
/siyaoH-1.17-PlatformMessage
GitHub 4 年前
当前提交
a0310c21
共有 34 个文件被更改,包括 1336 次插入374 次删除
  1. 2
      Samples/UIWidgetsSamples_2019_4/Assets/UIWidgetsGallery/demo/cupertino/cupertino_switch_demo.cs
  2. 3
      Samples/UIWidgetsSamples_2019_4/Assets/UIWidgetsSample.asmdef
  3. 2
      com.unity.uiwidgets/Editor/UIWidgetsPanelEditor.cs
  4. 386
      com.unity.uiwidgets/Runtime/engine2/UIWidgetsPanel.cs
  5. 7
      com.unity.uiwidgets/Runtime/painting/image_provider.cs
  6. 7
      com.unity.uiwidgets/Runtime/services/asset_bundle.cs
  7. 27
      com.unity.uiwidgets/Runtime/ui2/window.cs
  8. 21
      engine/src/shell/platform/unity/darwin/macos/uiwidgets_panel.h
  9. 64
      engine/src/shell/platform/unity/darwin/macos/uiwidgets_panel.mm
  10. 3
      engine/src/shell/platform/unity/darwin/macos/uiwidgets_system.h
  11. 20
      engine/src/shell/platform/unity/darwin/macos/uiwidgets_system.mm
  12. 33
      engine/src/shell/platform/unity/darwin/macos/unity_surface_manager.mm
  13. 42
      engine/src/shell/platform/unity/windows/uiwidgets_panel.cc
  14. 15
      engine/src/shell/platform/unity/windows/uiwidgets_panel.h
  15. 19
      engine/src/shell/platform/unity/windows/uiwidgets_system.cc
  16. 3
      engine/src/shell/platform/unity/windows/uiwidgets_system.h
  17. 3
      Samples/UIWidgetsSamples_2019_4/Assets/Editor.meta
  18. 14
      Samples/UIWidgetsSamples_2019_4/Assets/UIWidgetsGallery/UIWidgetsGallery.asmdef
  19. 129
      com.unity.uiwidgets/Editor/UIWidgetsEditorPanel.cs
  20. 8
      com.unity.uiwidgets/Editor/third_parties.meta
  21. 377
      com.unity.uiwidgets/Runtime/engine2/UIWidgetsPanelWrapper.cs
  22. 3
      Samples/UIWidgetsSamples_2019_4/Assets/Editor/EditorWindowSample.meta
  23. 7
      Samples/UIWidgetsSamples_2019_4/Assets/Editor/EditorWindowSample/UIWidgetsEditorWindowSample.asmdef.meta
  24. 21
      Samples/UIWidgetsSamples_2019_4/Assets/Editor/EditorWindowSample/GalleryMain.cs
  25. 16
      Samples/UIWidgetsSamples_2019_4/Assets/Editor/EditorWindowSample/UIWidgetsEditorWindowSample.asmdef
  26. 3
      Samples/UIWidgetsSamples_2019_4/Assets/Editor/EditorWindowSample/GalleryMain.cs.meta
  27. 39
      com.unity.uiwidgets/Editor/third_parties/EditorCoroutines.cs
  28. 8
      com.unity.uiwidgets/Editor/third_parties/editor_coroutines.meta
  29. 407
      com.unity.uiwidgets/Editor/third_parties/editor_coroutines/EditorCoroutines.cs
  30. 21
      com.unity.uiwidgets/Editor/third_parties/editor_coroutines/LICENSE

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

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

386
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);
public enum UIWidgetsWindowType {
InvalidPanel = 0,
GameObjectPanel = 1,
EditorWindowPanel = 2
}
public interface IUIWidgetsWindow {
Offset windowPosToScreenPos(Offset offset);
var desc = new RenderTextureDescriptor(
width, height, RenderTextureFormat.ARGB32, 0) {
useMipMap = false,
autoGenerateMips = false,
};
void startCoroutine(IEnumerator routing);
_renderTexture = new RenderTexture(desc) {hideFlags = HideFlags.HideAndDontSave};
_renderTexture.Create();
bool isActive();
_width = width;
_height = height;
_devicePixelRatio = devicePixelRatio;
void mainEntry();
texture = _renderTexture;
}
void onNewFrameScheduled();
void _destroyRenderTexture() {
D.assert(_renderTexture != null);
texture = null;
ObjectUtils.SafeDestroy(_renderTexture);
_renderTexture = null;
}
UIWidgetsWindowType getWindowType();
}
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;
texture = null;
}
public partial class UIWidgetsPanel : RawImage, IUIWidgetsWindow {
UIWidgetsPanelWrapper _wrapper;
[DllImport(NativeBindings.dllName)]
static extern void UIWidgetsPanel_onEnable(IntPtr ptr,
IntPtr nativeTexturePtr, int width, int height, float dpi, string streamingAssetsPath,
string font_settings);
public float devicePixelRatioOverride;
[DllImport(NativeBindings.dllName)]
static extern void UIWidgetsPanel_onRenderTexture(
IntPtr ptr, IntPtr nativeTexturePtr, int width, int height, float dpi);
}
public bool hardwareAntiAliasing;
#elif UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX
public partial class UIWidgetsPanel {
Texture _renderTexture;
void _createRenderTexture(int width, int height, float devicePixelRatio) {
D.assert(_renderTexture == null);
_width = width;
_height = height;
_devicePixelRatio = devicePixelRatio;
public UIWidgetsWindowType getWindowType() {
return UIWidgetsWindowType.GameObjectPanel;
void _destroyRenderTexture() {
D.assert(_renderTexture != null);
var releaseOK = UIWidgetsPanel_releaseNativeTexture(_ptr);
D.assert(releaseOK);
_renderTexture = null;
texture = null;
public bool isActive() {
return IsActive();
void _enableUIWidgetsPanel(string font_settings) {
D.assert(_renderTexture == null);
IntPtr native_tex_ptr = UIWidgetsPanel_onEnable(_ptr, _width, _height, _devicePixelRatio,
Application.streamingAssetsPath, font_settings);
D.assert(native_tex_ptr != IntPtr.Zero);
public void startCoroutine(IEnumerator routing) {
StartCoroutine(routing);
}
_renderTexture =
Texture2D.CreateExternalTexture(_width, _height, TextureFormat.BGRA32, false, true, native_tex_ptr);
texture = _renderTexture;
public void onNewFrameScheduled() {
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);
_renderTexture =
Texture2D.CreateExternalTexture(_width, _height, TextureFormat.BGRA32, false, true, native_tex_ptr);
public Offset windowPosToScreenPos(Offset offset) {
Camera camera = null;
if (canvas.renderMode != RenderMode.ScreenSpaceCamera) {
camera = canvas.GetComponent<GraphicRaycaster>().eventCamera;
}
texture = _renderTexture;
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() {
}

void Input_OnGUI() {
Event e = Event.current;
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;
}
UIWidgetsPanel_onMouseMove(_ptr, pos.Value.x, pos.Value.y);
_wrapper.OnMouseMove(pos);
if (pos == null) {
return;
}
var delta = Input.mouseScrollDelta;
UIWidgetsPanel_onScroll(_ptr, delta.x, delta.y, pos.Value.x, pos.Value.y);
_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);
[DllImport(NativeBindings.dllName)]
static extern void UIWidgetsPanel_onScroll(IntPtr ptr, float x, float y, float px, float py);
}
}

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


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

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

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


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

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

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


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

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

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

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

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

42
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,
const char* streaming_assets_path,

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

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

15
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 OnMouseLeave();
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_; }

Mono_Handle handle_;
EntrypointCallback entrypoint_callback_;
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

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": []
}

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

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