forked from homuler/MediaPipeUnityPlugin
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathGUIConsole.cs
More file actions
109 lines (91 loc) · 2.56 KB
/
Copy pathGUIConsole.cs
File metadata and controls
109 lines (91 loc) · 2.56 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
// Copyright (c) 2021 homuler
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file or at
// https://opensource.org/licenses/MIT.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
namespace Mediapipe.Unity.UI
{
public class GUIConsole : MonoBehaviour
{
[SerializeField] private GameObject _logLinePrefab;
[SerializeField] private int _maxLines = 200;
private const string _ContentPath = "Viewport/Content";
private Transform _contentRoot;
private MemoizedLogger _logger;
private Queue<MemoizedLogger.LogStruct> _scheduledLogs;
private int _lines = 0;
private ScrollRect scrollRect => gameObject.GetComponent<ScrollRect>();
private void Start()
{
_scheduledLogs = new Queue<MemoizedLogger.LogStruct>();
InitializeView();
}
private void LateUpdate()
{
RenderScheduledLogs();
}
private void OnDestroy()
{
_logger.OnLogOutput -= ScheduleLog;
}
private void InitializeView()
{
_contentRoot = gameObject.transform.Find(_ContentPath).gameObject.transform;
if (!(Logger.InternalLogger is MemoizedLogger))
{
return;
}
_logger = (MemoizedLogger)Logger.InternalLogger;
lock (((ICollection)_logger.histories).SyncRoot)
{
foreach (var log in _logger.histories)
{
AppendLog(log);
}
_logger.OnLogOutput += ScheduleLog;
}
var _ = StartCoroutine(ScrollToBottom());
}
private void ScheduleLog(MemoizedLogger.LogStruct logStruct)
{
lock (((ICollection)_scheduledLogs).SyncRoot)
{
_scheduledLogs.Enqueue(logStruct);
}
}
private void RenderScheduledLogs()
{
lock (((ICollection)_scheduledLogs).SyncRoot)
{
while (_scheduledLogs.Count > 0)
{
AppendLog(_scheduledLogs.Dequeue());
}
}
if (scrollRect.verticalNormalizedPosition < 1e-6)
{
var _ = StartCoroutine(ScrollToBottom());
}
}
private void AppendLog(MemoizedLogger.LogStruct logStruct)
{
var logLine = Instantiate(_logLinePrefab, _contentRoot).GetComponent<LogLine>();
logLine.SetLog(logStruct);
if (++_lines > _maxLines)
{
Destroy(_contentRoot.GetChild(0).gameObject);
_lines--;
}
}
private IEnumerator ScrollToBottom()
{
yield return new WaitForEndOfFrame();
Canvas.ForceUpdateCanvases();
scrollRect.verticalNormalizedPosition = 0f;
}
}
}