XREditorWorkQueue.cs
3.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
using System;
using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEngine;
namespace UnityEditor.XR.Management
{
internal class EditorWorkQueueBase
{
const string k_DefaultSessionStateString = "0BADF00D";
internal static bool SessionStateHasStoredData(string queueName)
{
return SessionState.GetString(queueName, k_DefaultSessionStateString) != EditorWorkQueueBase.k_DefaultSessionStateString;
}
}
internal class EditorWorkQueue<T> : EditorWorkQueueBase
{
[Serializable]
struct Queue
{
[SerializeField]
public List<T> workItems;
}
public string QueueName { get; set; }
private static Lazy<EditorWorkQueue<T>> s_Instance = new Lazy<EditorWorkQueue<T>>();
public static EditorWorkQueue<T> Instance => s_Instance.Value;
public bool HasWorkItems => EditorWorkQueueBase.SessionStateHasStoredData(QueueName);
public Action<T> ProcessItemCallback { get; set; }
public void StartQueue()
{
EditorApplication.update += ProcessWorkQueue;
}
public void QueueWorkItem(T workItem)
{
Queue queue = new Queue();
queue.workItems = new List<T>();
if (EditorWorkQueueBase.SessionStateHasStoredData(QueueName))
{
string fromJson = SessionState.GetString(QueueName, "{}");
JsonUtility.FromJsonOverwrite(fromJson, queue);
}
if (queue.workItems == null)
{
queue.workItems = new List<T>();
}
queue.workItems.Add(workItem);
string json = JsonUtility.ToJson(queue);
SessionState.SetString(QueueName, json);
StartQueue();
}
private static void ProcessWorkQueue()
{
EditorApplication.update -= ProcessWorkQueue;
if (!Instance.HasWorkItems)
return;
T workItem = GetNextWorkItem();
if (Instance.ProcessItemCallback != null)
Instance.ProcessItemCallback(workItem);
if (Instance.HasWorkItems)
EditorApplication.update += ProcessWorkQueue;
}
private static T GetNextWorkItem()
{
T ret = default(T);
if (!Instance.HasWorkItems)
{
return ret;
}
string fromJson = SessionState.GetString(Instance.QueueName, "{}");
SessionState.EraseString(Instance.QueueName);
Queue queue = JsonUtility.FromJson<Queue>(fromJson);
if (queue.workItems.Count <= 0)
{
return ret;
}
ret = queue.workItems[0];
queue.workItems.Remove(ret);
if (queue.workItems.Count > 0)
{
string json = JsonUtility.ToJson(queue);
SessionState.SetString(Instance.QueueName, json);
}
return ret;
}
}
}