Scripts/Uiika.cs
Станислав Хозяенок 99199eed0d 28.04.2025
2025-04-28 11:31:01 +07:00

1711 lines
60 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;
using System;
using System.Text.RegularExpressions;
using UnityEngine.Events;
using System.Globalization;
using System.Linq;
using Assets.Scripts;
using UI.Dates;
using Trackman;
using System.Reflection;
using UnityEditor;
class PlayBackControlUI
{
public Button ButtonRotateLeft { get; set; }
public Button ButtonRotateRight { get; set; }
public Button ButtonPause { get; set; }
public Button ButtonPlay { get; set; }
public VisualElement Pause { get; set; }
public VisualElement Play { get; set; }
public Label CurrentBarTime { get; set; }
public Label CurrentLocation { get; set; }
public VisualElement Speedx1 { get; set; }
public VisualElement Speedx2 { get; set; }
public VisualElement Speedx4 { get; set; }
public VisualElement Speedx8 { get; set; }
public VisualElement Speedx16 { get; set; }
public VisualElement Speedx32 { get; set; }
public VisualElement Speedx64 { get; set; }
public VisualElement RotateCamera { get; set; }
public Button ButtonRotateCamera { get; set; }
}
public class TextInputModel
{
private int cursorIndex = 0;
public int CursorIndex
{
get => cursorIndex;
set
{
if (cursorIndex != value || IsDoImmidateUpdate)
{
IsDoImmidateUpdate = false;
if (value == Value.Length)
{
cursorIndex = Value.Length - 1;
}
else
{
int newValue = value;
if (Mask != null)
{
if (newValue < cursorIndex)
{
while (true)
{
if (Mask[newValue] == Pattern)
{
break;
}
--newValue;
if (newValue < 0)
{
newValue = cursorIndex;
break;
}
}
}
else
{
while (true)
{
if (Mask[newValue] == Pattern)
{
break;
}
++newValue;
if (newValue == Value.Length)
{
newValue = cursorIndex;
break;
}
}
}
}
cursorIndex = newValue;
Debug.Log(newValue);
}
IsNeedSkeep = true;
EventIndexChange.Invoke(cursorIndex);
}
}
}
public string Mask { get; set; } = null;
public char Pattern = '*';
public bool IsNeedSkeep = false;
public bool IsDoImmidateUpdate = false;
public string Value { get; set; } = "";
public UnityEvent<int> EventIndexChange = new UnityEvent<int>();
}
public class ProgressBarModel
{
public DateTime DateBegin { get => dateBegin; set => dateBegin = value; }
public DateTime DateEnd { get => dateEnd; set => dateEnd = value; }
public DateTime CurrentTime { get => currentTime; set => currentTime = value; }
public short Speed { get => speed; set => speed = value; }
public float LastDeltaTime { get => lastDeltaTime; set => lastDeltaTime = value; }
private DateTime dateBegin;
private DateTime dateEnd;
private short speed;
private DateTime currentTime;
public UnityEvent CurrentTimeChanged { get; set; } = new UnityEvent();
public UnityEvent FinishWatch { get; set; } = new UnityEvent();
private float lastDeltaTime;
public void UpdateCurrentTimeDelta(float deltaTime)
{
LastDeltaTime = deltaTime;
currentTime = currentTime.AddSeconds(deltaTime * speed);
if (currentTime < dateBegin)
{
currentTime = dateBegin;
CurrentTimeChanged.Invoke();
}
if (currentTime > dateEnd)
{
currentTime = dateEnd;
CurrentTimeChanged.Invoke();
FinishWatch.Invoke();
}
else
{
CurrentTimeChanged.Invoke();
}
}
public void UpdateCurrentTimePercent(float percentTime)
{
currentTime = dateBegin.Add((dateEnd - dateBegin) * percentTime);
if (currentTime > dateEnd)
{
currentTime = dateEnd;
FinishWatch.Invoke();
}
else
{
CurrentTimeChanged.Invoke();
}
}
public void UpdateCurrentTimeSeconds(int secondsFromBegin)
{
currentTime = dateBegin.AddSeconds(secondsFromBegin);
if (currentTime > dateEnd)
{
currentTime = dateEnd;
FinishWatch.Invoke();
}
else
{
CurrentTimeChanged.Invoke();
}
}
public float GetProgress()
{
return (float)(currentTime - dateBegin).TotalSeconds / (float)(dateEnd - dateBegin).TotalSeconds;
}
}
class ProgressBarUI
{
public VisualElement RootElement { get; set; }
public PlayBackControlUI PlayBackControl { get; set; }
VisualElement emptyBar;
VisualElement loadedBar;
VisualElement passedBar;
VisualElement scrollElement;
private VisualElement bar;
private Label currentLocation;
public VisualElement Bar { get => bar; set => bar = value; }
public VisualElement EmptyBar { get => emptyBar; set => emptyBar = value; }
public VisualElement LoadedBar { get => loadedBar; set => loadedBar = value; }
public VisualElement PassedBar { get => passedBar; set => passedBar = value; }
public VisualElement ScrollElement { get => scrollElement; set => scrollElement = value; }
public Label CurrentLocation { get => currentLocation; set => currentLocation = value; }
public void UpdatePassedBar(float progress)
{
progress *= 100;
PassedBar.style.width = new Length(progress, LengthUnit.Percent);
ScrollElement.style.left = new Length(progress, LengthUnit.Percent);
}
}
class ProgressBarController
{
ProgressBarUI ui;
ProgressBarModel model;
public ProgressBarUI UI { get => ui; }
public ProgressBarModel Model { get => model; }
private float lastUpdateTime;
bool isRunning;
public bool IsRunning
{
get => isRunning;
set
{
if (isRunning != value)
{
isRunning = value;
if (isRunning)
{
ui.PlayBackControl.Pause.style.display = DisplayStyle.Flex;
ui.PlayBackControl.Play.style.display = DisplayStyle.None;
}
else
{
ui.PlayBackControl.Pause.style.display = DisplayStyle.None;
ui.PlayBackControl.Play.style.display = DisplayStyle.Flex;
}
}
}
}
public ProgressBarController(ProgressBarUI ui, ProgressBarModel model)
{
this.ui = ui;
this.model = model;
lastUpdateTime = Time.time;
ui.Bar.RegisterCallback<MouseDownEvent>(OnMouseDown);
ui.Bar.RegisterCallback<MouseUpEvent>(OnMouseUp);
ui.Bar.RegisterCallback<MouseLeaveEvent>(OnMouseLeave);
ui.Bar.RegisterCallback<MouseMoveEvent>(OnMouseMove);
ui.ScrollElement.RegisterCallback<MouseDownEvent>((elm) => { Debug.Log("MouseDownEvent ScrollElement"); });
model.CurrentTimeChanged.AddListener(ProgressBarTimeChangeHandler);
model.FinishWatch.AddListener(OnEndWatchHandler);
InitButtonEvents();
InitSpeedButtons();
IsRunning = false;
}
// Логика обработки переключения
VisualElement selectedControl;
Dictionary<VisualElement, short> speedValueDictionary = new Dictionary<VisualElement, short>();
void InitSpeedButtons()
{
selectedControl = ui.PlayBackControl.Speedx1;
InitSpeedButton(ui.PlayBackControl.Speedx1);
InitSpeedButton(ui.PlayBackControl.Speedx2);
InitSpeedButton(ui.PlayBackControl.Speedx4);
InitSpeedButton(ui.PlayBackControl.Speedx8);
InitSpeedButton(ui.PlayBackControl.Speedx16);
InitSpeedButton(ui.PlayBackControl.Speedx32);
InitSpeedButton(ui.PlayBackControl.Speedx64);
SelectButton(selectedControl);
speedValueDictionary.Add(ui.PlayBackControl.Speedx1, 1);
speedValueDictionary.Add(ui.PlayBackControl.Speedx2, 2);
speedValueDictionary.Add(ui.PlayBackControl.Speedx4, 4);
speedValueDictionary.Add(ui.PlayBackControl.Speedx8, 8);
speedValueDictionary.Add(ui.PlayBackControl.Speedx16, 16);
speedValueDictionary.Add(ui.PlayBackControl.Speedx32, 32);
speedValueDictionary.Add(ui.PlayBackControl.Speedx64, 64);
ui.PlayBackControl.ButtonRotateCamera.clicked += () => {
if (SceneParams.Instance.cameraSettings.IsAutoRotateCamera)
{
SceneParams.Instance.cameraSettings.IsAutoRotateCamera = false;
// Выключаем поворот камеры
}
else
{
SceneParams.Instance.cameraSettings.IsAutoRotateCamera = true;
// Включаем поворот камеры
}
DoUpdateRotateCamera();
};
DoUpdateRotateCamera();
}
private void DoUpdateRotateCamera()
{
if (!SceneParams.Instance.cameraSettings.IsAutoRotateCamera)
{
if (ColorUtility.TryParseHtmlString("#FFFFFFFF", out Color color))
{
ui.PlayBackControl.RotateCamera.style.unityBackgroundImageTintColor = color;
};
}
else
{
if (ColorUtility.TryParseHtmlString("#00A1E7FF", out Color color))
{
ui.PlayBackControl.RotateCamera.style.unityBackgroundImageTintColor = color;
};
}
ui.PlayBackControl.RotateCamera.MarkDirtyRepaint();
}
void InitSpeedButton(VisualElement control)
{
Button button = control.Q<Button>();
Label label = control.Q<Label>();
button.clicked += () =>
{
SelectButtonRemove(selectedControl);
SelectButton(control);
selectedControl = control;
UpdateSpeed(selectedControl);
};
SelectButtonRemove(control);
}
void UpdateSpeed(VisualElement control)
{
model.Speed = speedValueDictionary[control];
}
void SelectButton(VisualElement element)
{
Label label = element.Q<Label>();
if (ColorUtility.TryParseHtmlString("#6D757E", out Color color))
{
label.style.color = color;
};
if (ColorUtility.TryParseHtmlString("#FFFFFF", out Color colorBackground))
{
element.style.backgroundColor = colorBackground;
};
}
void SelectButtonRemove(VisualElement element)
{
Label label = element.Q<Label>();
if (ColorUtility.TryParseHtmlString("#FFFFFF", out Color color))
{
label.style.color = color;
};
if (ColorUtility.TryParseHtmlString("#FFFFFF00", out Color colorBackground))
{
element.style.backgroundColor = colorBackground;
};
}
bool isDragging = false;
private void OnMouseDown(MouseDownEvent evt)
{
// Проверяем, нажата ли левая кнопка мыши
if (evt.button == (int)UnityEngine.UIElements.MouseButton.LeftMouse)
{
isDragging = true; // Устанавливаем флаг перетаскивания
//SceneParams.Instance.cameraSettings.IsBlockMove = true;
evt.StopPropagation(); // Останавливаем дальнейшую обработку события
}
}
private void OnMouseUp(MouseUpEvent evt)
{
// Проверяем, отпущена ли левая кнопка мыши
if (evt.button == (int)UnityEngine.UIElements.MouseButton.LeftMouse)
{
isDragging = false; // Сбрасываем флаг перетаскивания
evt.StopPropagation(); // Останавливаем дальнейшую обработку события
UpdateWithX(evt.localMousePosition.x);
//SceneParams.Instance.cameraSettings.IsBlockMove = false;
}
}
private void OnMouseLeave(MouseLeaveEvent evt)
{
isDragging = false;
evt.StopPropagation();
//SceneParams.Instance.cameraSettings.IsBlockMove = false;
}
private void OnMouseMove(MouseMoveEvent evt)
{
// Если перетаскивание активно, обновляем позицию
if (isDragging)
{
// Получаем локальную позицию мыши относительно родителя
Vector2 localPosition = ui.Bar.WorldToLocal(evt.mousePosition);
UpdateWithX(localPosition.x);
}
}
private void UpdateWithX(float xPos)
{
Vector2 beginPos = GetElementStartPosition(ui.EmptyBar);
Vector2 endPos = GetElementEndPosition(ui.EmptyBar);
if (xPos < beginPos.x)
{
return;
}
if (xPos > endPos.x)
{
return;
}
float percent = (xPos - beginPos.x) / (endPos.x - beginPos.x);
model.UpdateCurrentTimePercent(percent);
}
private void InitButtonEvents()
{
ui.PlayBackControl.ButtonPlay.clicked += () =>
{
lastUpdateTime = Time.time;
IsRunning = true;
};
ui.PlayBackControl.ButtonPause.clicked += () =>
{
IsRunning = false;
};
ui.PlayBackControl.ButtonRotateLeft.clicked += () =>
{
model.UpdateCurrentTimeDelta(-30);
};
ui.PlayBackControl.ButtonRotateRight.clicked += () =>
{
model.UpdateCurrentTimeDelta(30);
};
}
private void OnEndWatchHandler()
{
IsRunning = false;
}
private Vector2 GetElementStartPosition(VisualElement element)
{
return element.localBound.position;
}
private Vector2 GetElementEndPosition(VisualElement element)
{
return new Vector2(element.localBound.xMax, element.localBound.yMax);
}
bool isShowDays = false;
bool isShowHours = false;
bool isShowMinutes = false;
bool isShowSeconds = false;
string allTime = "";
private void detectTime(int lastSeconds, out int days, out int hours, out int minutes, out int seconds)
{
days = lastSeconds / 86400;
lastSeconds %= 86400;
hours = lastSeconds / 3600;
lastSeconds %= 3600;
minutes = lastSeconds / 60;
seconds = lastSeconds % 60;
}
public void StartPlayer(DateTime beginDate, DateTime endDate)
{
model.DateBegin = beginDate;
model.DateEnd = endDate;
model.CurrentTime = beginDate;
ui.RootElement.visible = true;
isShowDays = false;
isShowHours = false;
isShowMinutes = false;
isShowSeconds = false;
TimeSpan diffTime = endDate - beginDate;
int lastSeconds = (int)diffTime.TotalSeconds;
int days, hours, minutes, seconds;
detectTime(lastSeconds, out days, out hours, out minutes, out seconds);
if (days != 0)
{
isShowDays = true; isShowHours = true; isShowMinutes = true; isShowSeconds = true;
}
else if (hours != 0)
{
isShowHours = true; isShowMinutes = true; isShowSeconds = true;
}
else if (minutes != 0)
{
isShowMinutes = true; isShowSeconds = true;
}
else
{
isShowSeconds = true;
}
allTime = GetStrTime(days, hours, minutes, seconds);
model.CurrentTimeChanged.Invoke();
}
string GetStrTime(TimeSpan diffTime)
{
int lastSeconds = (int)diffTime.TotalSeconds;
int days, hours, minutes, seconds;
detectTime(lastSeconds, out days, out hours, out minutes, out seconds);
return GetStrTime(days, hours, minutes, seconds);
}
string GetStrTime(int days, int hours, int minutes, int seconds)
{
string formattedDifference = "";
if (isShowDays)
{
formattedDifference += $"{days}";
}
if (isShowHours)
{
if (formattedDifference.Length > 0) formattedDifference += ":";
formattedDifference += $"{hours:D2}";
}
if (isShowMinutes)
{
if (formattedDifference.Length > 0) formattedDifference += ":";
formattedDifference += $"{minutes:D2}";
}
if (isShowSeconds)
{
if (formattedDifference.Length > 0) formattedDifference += ":";
formattedDifference += $"{seconds:D2}";
}
return formattedDifference;
}
public void Update()
{
if (!IsRunning) return;
float deltaTime = Time.time - lastUpdateTime; // <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD>, <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD>
lastUpdateTime = Time.time;
model.UpdateCurrentTimeDelta(deltaTime);
}
public UnityEvent<DateTimeChangedData> EventCurrentDateTimeChanged = new UnityEvent<DateTimeChangedData>();
void ProgressBarTimeChangeHandler()
{
ui.UpdatePassedBar(model.GetProgress());
UpdateCurrentBarTime();
EventCurrentDateTimeChanged.Invoke(new DateTimeChangedData() { NewTime = model.CurrentTime, Speed = model.Speed, DeltaTime = model.LastDeltaTime });
}
void UpdateCurrentBarTime()
{
TimeSpan diffTime = model.CurrentTime - model.DateBegin;
ui.PlayBackControl.CurrentBarTime.text = $"{GetStrTime(diffTime)}/ {allTime}";
}
}
public class DateTimeChangedData
{
public DateTime NewTime { get; set; }
public short Speed { get; set; }
public float DeltaTime { get; set; }
public DateTimeChangedData()
{
}
}
public class RequestFormUI
{
public VisualElement BeginIcon { get; set; }
public VisualElement EndIcon { get; set; }
public VisualElement DateBeginCalendar { get; set; }
public VisualElement DateEndCalendar { get; set; }
public Button ButtonDateBegin { get; set; }
public Button ButtonDateEnd { get; set; }
public List<TextField> ListTextFields { get; set; }
public VisualElement HideRequest { get; set; }
public Button ButtonWatch { get; set; }
public TextField TagTextField { get; set; }
public TextField DateBeginTextField { get; set; }
public TextField DateEndTextField { get; set; }
public VisualElement LoadingIcon { get; set; }
}
public class ModelHideForm
{
bool isHide = false;
bool isWidthChanging = false;
float styleLengthHide = 24;
float styleLengthView = 319;
float durationAnimateChangeWidth = 0.5f;
public bool IsHide { get => isHide; set => isHide = value; }
public float StyleLengthHide { get => styleLengthHide; set => styleLengthHide = value; }
public float StyleLengthView { get => styleLengthView; set => styleLengthView = value; }
public bool IsWidthChanging { get => isWidthChanging; set => isWidthChanging = value; }
public float DurationAnimateChangeWidth { get => durationAnimateChangeWidth; set => durationAnimateChangeWidth = value; }
}
public class RequestFormModel : ModelHideForm
{
public TextInputModel Tag { get; set; }
public TextInputModel DateBegin { get; set; }
public TextInputModel DateEnd { get; set; }
public Button ButtonWatch { get; set; }
}
public class WidthAnimator
{
public static IEnumerator AnimateWidth(VisualElement element, float targetWidth, float duration, System.Action actionOnComplete = null)
{
// Получаем текущую ширину элемента
float startWidth = element.resolvedStyle.width;
float elapsedTime = 0f;
while (elapsedTime < duration)
{
// Вычисляем интерполяцию
float newWidth = Mathf.Lerp(startWidth, targetWidth, elapsedTime / duration);
element.style.width = new StyleLength(newWidth);
elapsedTime += Time.deltaTime;
yield return null; // Ждем следующий кадр
}
// Устанавливаем конечное значение ширины
element.style.width = new StyleLength(targetWidth);
// Вызываем действие по завершении анимации, если оно задано
actionOnComplete?.Invoke();
}
}
public class RequestFormController
{
RequestFormUI ui;
RequestFormModel model;
public RequestFormUI UI { get => ui; set => ui = value; }
public RequestFormModel Model { get => model; set => model = value; }
MonoBehaviour monoBehaviorScript;
public RequestFormController(MonoBehaviour monoBehaviorScript)
{
this.monoBehaviorScript = monoBehaviorScript;
}
public void Init()
{
model.Tag = new TextInputModel() { Value = ProjectSettings.DefaultTag };
model.DateBegin = new TextInputModel() { Value = ProjectSettings.DefaultDateBegin, Mask = "**.**.**** **:**" };
model.DateEnd = new TextInputModel() { Value = ProjectSettings.DefaultDateEnd, Mask = "**.**.**** **:**" };
ui.HideRequest.RegisterCallback<ClickEvent>((ent) =>
{
ShowForm(monoBehaviorScript);
HideForm(monoBehaviorScript);
});
ui.HideRequest.RegisterCallback<MouseEnterEvent>((ent) =>
{
VisualElement rect = ui.HideRequest.Q<VisualElement>("Rect");
VisualElement vector = ui.HideRequest.Q<VisualElement>("Vector");
if (ColorUtility.TryParseHtmlString("#00A1E7", out Color color))
{
rect.style.backgroundColor = color;
vector.style.unityBackgroundImageTintColor = color;
};
});
ui.HideRequest.RegisterCallback<MouseLeaveEvent>((ent) =>
{
VisualElement rect = ui.HideRequest.Q<VisualElement>("Rect");
VisualElement vector = ui.HideRequest.Q<VisualElement>("Vector");
if (ColorUtility.TryParseHtmlString("#6D757E", out Color color))
{
rect.style.backgroundColor = color;
vector.style.unityBackgroundImageTintColor = color;
};
});
ui.ButtonWatch.RegisterCallback<MouseEnterEvent>((ent) =>
{
if (ColorUtility.TryParseHtmlString("#00A1E7", out Color color))
{
ui.ButtonWatch.style.backgroundColor = color;
};
});
ui.ButtonWatch.RegisterCallback<MouseLeaveEvent>((ent) =>
{
if (ColorUtility.TryParseHtmlString("#6D757E", out Color color))
{
ui.ButtonWatch.style.backgroundColor = color;
};
});
model.StyleLengthView = 234;
}
public void HideForm(MonoBehaviour script)
{
if (model.IsHide) return;
if (model.IsWidthChanging) return;
model.IsWidthChanging = true;
model.IsHide = true;
script.StartCoroutine(WidthAnimator.AnimateWidth(ui.HideRequest.parent, model.StyleLengthHide, model.DurationAnimateChangeWidth,
() => { model.IsWidthChanging = false; }
));
}
public void ShowForm(MonoBehaviour script)
{
if (!model.IsHide) return;
if (model.IsWidthChanging) return;
model.IsWidthChanging = true;
model.IsHide = false;
script.StartCoroutine(WidthAnimator.AnimateWidth(ui.HideRequest.parent, model.StyleLengthView, model.DurationAnimateChangeWidth,
() => { model.IsWidthChanging = false; }
));
}
internal void Update()
{
//if (model.Tag.IsNeedSkeep)
//{
// //model.Tag.IsNeedSkeep = false;
//}
//else
//{
model.Tag.CursorIndex = ui.TagTextField.cursorIndex;
//}
model.DateBegin.CursorIndex = ui.DateBeginTextField.cursorIndex;
model.DateEnd.CursorIndex = ui.DateEndTextField.cursorIndex;
}
}
public class TagHistoryUI
{
public VisualElement RootElement { get; set; }
public VisualElement HideTable { get; set; }
public VisualTreeAsset TableRowAsset { get; set; }
public VisualElement ScrollTable { get; set; }
}
public class TagHistoryModel : ModelHideForm { }
public class TagHistoryController
{
TagHistoryUI ui;
TagHistoryModel model;
public TagHistoryUI UI { get => ui; set => ui = value; }
public TagHistoryModel Model { get => model; set => model = value; }
MonoBehaviour monoBehaviorScript;
public TagHistoryController(MonoBehaviour monoBehaviorScript)
{
this.monoBehaviorScript = monoBehaviorScript;
}
public void Init()
{
ui.HideTable.RegisterCallback<ClickEvent>((ent) =>
{
ShowForm(monoBehaviorScript);
HideForm(monoBehaviorScript);
});
ui.HideTable.RegisterCallback<MouseEnterEvent>((ent) =>
{
VisualElement rect = ui.HideTable.Q<VisualElement>("Rect");
VisualElement vector = ui.HideTable.Q<VisualElement>("Vector");
if (ColorUtility.TryParseHtmlString("#00A1E7", out Color color))
{
rect.style.backgroundColor = color;
vector.style.unityBackgroundImageTintColor = color;
};
});
ui.HideTable.RegisterCallback<MouseLeaveEvent>((ent) =>
{
VisualElement rect = ui.HideTable.Q<VisualElement>("Rect");
VisualElement vector = ui.HideTable.Q<VisualElement>("Vector");
if (ColorUtility.TryParseHtmlString("#6D757E", out Color color))
{
rect.style.backgroundColor = color;
vector.style.unityBackgroundImageTintColor = color;
};
});
LocalUtills utils = new LocalUtills() { RootVisualElement = ui.RootElement };
ui.ScrollTable = utils.GetVisualElementByName<VisualElement>("ScrollTable");
}
public void HideForm(MonoBehaviour script)
{
if (model.IsHide) return;
if (model.IsWidthChanging) return;
model.IsWidthChanging = true;
model.IsHide = true;
script.StartCoroutine(WidthAnimator.AnimateWidth(ui.RootElement, model.StyleLengthHide, model.DurationAnimateChangeWidth,
() => { model.IsWidthChanging = false; }));
}
public void ShowForm(MonoBehaviour script)
{
if (!model.IsHide) return;
if (model.IsWidthChanging) return;
model.IsWidthChanging = true;
model.IsHide = false;
script.StartCoroutine(WidthAnimator.AnimateWidth(ui.RootElement, model.StyleLengthView, model.DurationAnimateChangeWidth,
() => { model.IsWidthChanging = false; }
));
}
}
public class Uiika : MonoBehaviour
{
[Header("UIDocument")]
public UIDocument UI;
public VisualTreeAsset tabletemplate;
public VisualTreeAsset markPointOnBar;
public GameObject CanvasCalendar;
public Texture2D CursorSelect;
public Label forcodes { get; set; } // <-- UI <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
private bool isStartSuccess = false;
TagHistoryUI tagHistoryUI;
public ThanksStASSForTheNiceMethod Caller;
public DateTime DatBegin { get; set; }
public DateTime DatEnd { get; set; }
public UnityEvent<DateTimeChangedData> EventCurrentDateTimeChanged { get => progressBarController.EventCurrentDateTimeChanged; }
public void Update()
{
if (isStartSuccess == false) return;
requestFormController.Update();
progressBarController.Update();
calendarController.Update();
}
void TextFiledCursorIndexChanged(TextField textField, int pos)
{
textField.cursorIndex = pos;
textField.SelectRange(pos, pos + 1);
}
ProgressBarController progressBarController;
RequestFormController requestFormController;
TagHistoryController tagHistoryController;
public class CalendarModel
{
UI.Dates.DatePicker datePicker;
GameObject calendarCanvas;
bool isCalendarActive = false;
public bool IsCalendarActive { get => isCalendarActive; set => isCalendarActive = value; }
public GameObject CalendarCanvas { get => calendarCanvas; set => calendarCanvas = value; }
public DatePicker DatePicker { get => datePicker; set => datePicker = value; }
public RectTransform DatePickerRectTransform { get; set; }
}
public class CalendarController
{
CalendarModel model;
VisualElement lastCaller = null;
public float ChangeOffsetY = 0;
public CalendarController(GameObject calendarCanvas, CalendarModel calendarModel)
{
model = calendarModel;
model.CalendarCanvas = calendarCanvas;
Transform childTransform = calendarCanvas.transform.Find("DatePicker - Inline");
model.DatePicker = childTransform.gameObject.GetComponent<UI.Dates.DatePicker>();
calendarCanvas.SetActive(calendarModel.IsCalendarActive);
model.DatePickerRectTransform = model.DatePicker.gameObject.GetComponent<RectTransform>();
}
public CalendarModel Model { get => model; set => model = value; }
public VisualElement LastCaller { get => lastCaller; set => lastCaller = value; }
public void UpdateDateByRectUI(UnityEngine.Rect? rectUI = null)
{
UnityEngine.Rect rect;
if (rectUI == null)
{
rect = lastCaller.worldBound;
} else
{
rect = (UnityEngine.Rect)rectUI;
}
var rectCanvasCalendar = model.DatePickerRectTransform;
float x = rect.x + rectCanvasCalendar.rect.width * rectCanvasCalendar.localScale.x / 2;
float y = -rect.y - rectCanvasCalendar.rect.height * rectCanvasCalendar.localScale.y / 2;
if (ChangeOffsetY != 0)
{
y += ChangeOffsetY;
ChangeOffsetY = 0;
}
//rectCanvasCalendar.position = new Vector3(0, 0, 0);
rectCanvasCalendar.anchoredPosition3D = new Vector3(x, y, 0);
}
public void Hide()
{
if(lastCaller != null)
{
lastCaller.style.height = 0;
if (model.IsCalendarActive)
{
model.IsCalendarActive = false;
model.CalendarCanvas.SetActive(false);
}
}
}
public int IsNeedUpdate = -1;
public void Update()
{
if (IsNeedUpdate > 0)
{
--IsNeedUpdate;
if (IsNeedUpdate == 0)
{
UpdateDateByRectUI();
}
}
}
}
CalendarController calendarController;
public void Start()
{
var root = UI.rootVisualElement;
utills.RootVisualElement = root;
forcodes = GetVisualElementByName<Label>("forcodes");
forcodes.style.display = DisplayStyle.None;
requestFormController = new RequestFormController(this)
{
UI = new RequestFormUI()
{
BeginIcon = GetVisualElementByName<VisualElement>("DataBeginIcon"),
EndIcon = GetVisualElementByName<VisualElement>("DataEndIcon"),
ButtonDateBegin = GetVisualElementByName<Button>("BDateBegin"),
ButtonDateEnd = GetVisualElementByName<Button>("BDateEnd"),
ListTextFields = GetVisualElementsByName<TextField>("MyText"),
HideRequest = GetVisualElementByName<VisualElement>("HideRequest"),
ButtonWatch = GetVisualElementByName<Button>("ButtonWatch"),
LoadingIcon = GetVisualElementByName<VisualElement>("LoadingIcon"),
DateBeginCalendar = GetVisualElementByName<VisualElement>("DateBeginCalendar"),
DateEndCalendar = GetVisualElementByName<VisualElement>("DateEndCalendar")
},
Model = new RequestFormModel()
{
IsHide = false
}
};
requestFormController.Init();
calendarController = new CalendarController(CanvasCalendar,new CalendarModel());
requestFormController.UI.ButtonDateBegin.clicked += () =>
{
if (CanvasCalendar == null) return;
UpdateCalendar(requestFormController.UI.DateBeginCalendar);
};
requestFormController.UI.ButtonDateEnd.clicked += () =>
{
if (CanvasCalendar == null) return;
UpdateCalendar(requestFormController.UI.DateEndCalendar);
};
foreach (TextField textField in requestFormController.UI.ListTextFields)
{
DetermineTextField(textField);
}
InitTextField(tagTextField);
InitTextField(dateBeginTextField);
InitTextField(dateEndTextField);
ProgressBarUI progressBarUI = new ProgressBarUI()
{
EmptyBar = GetVisualElementByName<VisualElement>("EmptyBar"),
LoadedBar = GetVisualElementByName<VisualElement>("LoadedBar"),
PassedBar = GetVisualElementByName<VisualElement>("PassedBar"),
ScrollElement = GetVisualElementByName<VisualElement>("ScrollElement"),
Bar = GetVisualElementByName<VisualElement>("Bar"),
CurrentLocation = GetVisualElementByName<Label>("CurrentLocation"),
PlayBackControl = new PlayBackControlUI()
{
ButtonRotateLeft = GetVisualElementByName<Button>("ButtonRotateLeft"),
ButtonRotateRight = GetVisualElementByName<Button>("ButtonRotateRight"),
ButtonPause = GetVisualElementByName<Button>("ButtonPause"),
ButtonPlay = GetVisualElementByName<Button>("ButtonPlay"),
Pause = GetVisualElementByName<VisualElement>("pause"),
Play = GetVisualElementByName<VisualElement>("play"),
CurrentBarTime = GetVisualElementByName<Label>("CurrentBarTime"),
CurrentLocation = GetVisualElementByName<Label>("CurrentLocation"),
Speedx1 = GetVisualElementByName<VisualElement>("Speedx1"),
Speedx2 = GetVisualElementByName<VisualElement>("Speedx2"),
Speedx4 = GetVisualElementByName<VisualElement>("Speedx4"),
Speedx8 = GetVisualElementByName<VisualElement>("Speedx8"),
Speedx16 = GetVisualElementByName<VisualElement>("Speedx16"),
Speedx32 = GetVisualElementByName<VisualElement>("Speedx32"),
Speedx64 = GetVisualElementByName<VisualElement>("Speedx64"),
RotateCamera = GetVisualElementByName<VisualElement>("rotate-camera"),
ButtonRotateCamera = GetVisualElementByName<Button>("ButtonRotateCamera"),
},
RootElement = GetVisualElementByName<VisualElement>("PlayBackControl"),
};
ProgressBarModel progressBarModel = new ProgressBarModel()
{
Speed = 1
};
progressBarController = new ProgressBarController(progressBarUI, progressBarModel);
progressBarUI.RootElement.visible = false;
isStartSuccess = true;
tagHistoryUI = new TagHistoryUI()
{
RootElement = GetVisualElementByName<VisualElement>("TagHistory"),
HideTable = GetVisualElementByName<VisualElement>("HideTable"),
TableRowAsset = tabletemplate
};
tagHistoryController = new TagHistoryController(this)
{
UI = tagHistoryUI,
Model = new TagHistoryModel()
{
IsHide = true
}
};
tagHistoryController.Init();
tagHistoryController.UI.RootElement.visible = false;
// Действия при нажатии на кнопку
requestFormController.UI.ButtonWatch.clicked += () =>
{
calendarController.Hide();
RequestButtonPressed();
};
requestFormController.UI.HideRequest.RegisterCallback<ClickEvent>((evt) =>
{
calendarController.Hide();
});
// Запрещаем скроллинг, когда курсор над объектом
InitBlockingZoomElements(new List<VisualElement>() {
requestFormController.UI.HideRequest.parent,
progressBarController.UI.RootElement,
progressBarController.UI.RootElement,
tagHistoryController.UI.RootElement
});
Debug.Log("isStartSuccess = true");
}
void InitBlockingZoomElements(List<VisualElement> visualElements)
{
foreach(var element in visualElements)
{
element.RegisterCallback<MouseEnterEvent>((evt) => { BlockZoom(); });
element.RegisterCallback<MouseLeaveEvent>((evt) => { UnBlockZoom(); });
}
}
public void BlockZoom()
{
SceneParams.Instance.cameraSettings.IsBlockMove = true;
SceneParams.Instance.cameraSettings.IsBlockZoom = true;
}
public void UnBlockZoom()
{
SceneParams.Instance.cameraSettings.IsBlockMove = false;
SceneParams.Instance.cameraSettings.IsBlockZoom = false;
}
public int waitTick = 2;
void UpdateCalendar(VisualElement currentCaller)
{
if(currentCaller == requestFormController.UI.DateBeginCalendar)
{
calendarController.Model.DatePicker.SelectedDate = DateTime.ParseExact(requestFormController.UI.DateBeginTextField.text, dateFormat, providerDateFormat);
}
if (currentCaller == requestFormController.UI.DateEndCalendar)
{
calendarController.Model.DatePicker.SelectedDate = DateTime.ParseExact(requestFormController.UI.DateEndTextField.text, dateFormat, providerDateFormat);
}
calendarController.Model.IsCalendarActive = !calendarController.Model.IsCalendarActive;
if (calendarController.Model.IsCalendarActive == false)
{
if (calendarController.LastCaller != currentCaller)
{
// Скрываем
calendarController.Model.IsCalendarActive = true;
calendarController.LastCaller.style.height = 0;
}
}
Transform childTransform = CanvasCalendar.transform.Find("DatePicker - Inline");
var datePicker = childTransform.gameObject.GetComponent<DatePicker>();
if (calendarController.Model.IsCalendarActive)
{
currentCaller.style.height = 177;
calendarController.LastCaller = currentCaller;
calendarController.IsNeedUpdate = waitTick; // Обработка в следующем тике
}
else
{
currentCaller.style.height = 0;
}
calendarController.Model.CalendarCanvas.SetActive(calendarController.Model.IsCalendarActive);
}
public static readonly string dateFormat = "dd.MM.yyyy HH:mm";
public static readonly CultureInfo providerDateFormat = CultureInfo.InvariantCulture;
private void InitTextField(TextFieldData textField)
{
textField.Field.selectAllOnMouseUp = false;
textField.Field.selectAllOnFocus = false;
textField.Field.RegisterCallback<KeyDownEvent>((KeyDownEvent ev) =>
{
OnKeyDownTextField(ev, textField);
});
textField.Model.EventIndexChange.AddListener(
(index) =>
{
TextFiledCursorIndexChanged(textField.Field, index);
});
}
private void OnKeyDownTextField(KeyDownEvent evt, TextFieldData fieldData)
{
if (evt.keyCode == KeyCode.LeftArrow)
{
MoveTextFieldCaretLeft(fieldData);
}
}
void MoveTextFieldCaretLeft(TextFieldData fieldData)
{
int lastIndex = fieldData.Model.CursorIndex;
fieldData.Field.SelectRange(fieldData.Field.value.Length, fieldData.Field.value.Length);
fieldData.Field.cursorIndex = lastIndex - 1;
fieldData.Model.IsDoImmidateUpdate = true;
}
public void SetMarkText(string markText)
{
progressBarController.UI.CurrentLocation.text = markText;
}
class TextFieldData
{
public TextField Field { get; set; }
public TextInputModel Model { get; set; }
}
private TextFieldData tagTextField;
private TextFieldData dateBeginTextField;
private TextFieldData dateEndTextField;
private void DetermineTextField(TextField field)
{
switch (field.label)
{
case "tag":
{
tagTextField = new TextFieldData() { Field = field, Model = requestFormController.Model.Tag };
requestFormController.UI.TagTextField = field;
field.SetValueWithoutNotify(requestFormController.Model.Tag.Value);
field.cursorIndex = requestFormController.Model.Tag.CursorIndex;
//field.selectAllOnFocus = false;
field.RegisterValueChangedCallback(evt =>
{
UpdateTextField(IsValidTag, tagTextField, evt.newValue);
});
break;
}
case "dateBegin":
{
dateBeginTextField = new TextFieldData() { Field = field, Model = requestFormController.Model.DateBegin };
requestFormController.UI.DateBeginTextField = field;
field.SetValueWithoutNotify(requestFormController.Model.DateBegin.Value);
field.cursorIndex = requestFormController.Model.DateBegin.CursorIndex;
field.RegisterValueChangedCallback(evt =>
{
UpdateTextField(IsValidDate, dateBeginTextField, evt.newValue);
});
break;
}
case "dateEnd":
{
dateEndTextField = new TextFieldData() { Field = field, Model = requestFormController.Model.DateEnd };
requestFormController.UI.DateEndTextField = field;
field.cursorIndex = requestFormController.Model.DateEnd.CursorIndex;
field.SetValueWithoutNotify(requestFormController.Model.DateEnd.Value);
field.RegisterValueChangedCallback(evt =>
{
UpdateTextField(IsValidDate, dateEndTextField, evt.newValue);
});
break;
}
default: break;
}
}
private void UpdateTextField(Func<string, bool> isValid, TextFieldData data, string newValue)
{
if (isValid(newValue))
{
data.Model.Value = newValue;
}
else
{
data.Field.SetValueWithoutNotify(data.Model.Value);
if (data.Model.Value.Length > newValue.Length)
{
MoveTextFieldCaretLeft(data);
}
}
}
public void HandleNewDate()
{
DateTime selectedDate = calendarController.Model.DatePicker.SelectedDate;
if (calendarController.LastCaller == requestFormController.UI.DateBeginCalendar)
{
// Получаем текущее время из текстового поля
DateTime currentBeginDateTime = DateTime.ParseExact(requestFormController.UI.DateBeginTextField.text, dateFormat, providerDateFormat);
// Объединяем новую дату с текущим временем
DateTime newBeginDateTime = new DateTime(selectedDate.Year, selectedDate.Month, selectedDate.Day, currentBeginDateTime.Hour, currentBeginDateTime.Minute, currentBeginDateTime.Second);
// Устанавливаем новое значение в текстовое поле
requestFormController.UI.DateBeginTextField.value = newBeginDateTime.ToString(dateFormat);
}
if (calendarController.LastCaller == requestFormController.UI.DateEndCalendar)
{
// Получаем текущее время из текстового поля
DateTime currentEndDateTime = DateTime.ParseExact(requestFormController.UI.DateEndTextField.text, dateFormat, providerDateFormat);
// Объединяем новую дату с текущим временем
DateTime newEndDateTime = new DateTime(selectedDate.Year, selectedDate.Month, selectedDate.Day, currentEndDateTime.Hour, currentEndDateTime.Minute, currentEndDateTime.Second);
// Устанавливаем новое значение в текстовое поле
requestFormController.UI.DateEndTextField.value = newEndDateTime.ToString(dateFormat);
}
}
private bool IsValidTag(string value)
{
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> 8 <20><><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
return Regex.IsMatch(value, @"^\d{8}$");
}
private bool IsValidDate(string value)
{
if (Regex.IsMatch(value, @"^\d{2}\.\d{2}\.\d{4} \d{2}:\d{2}$") == false) return false;
var dateTimeParts = value.Split(' ');
var datePart = dateTimeParts[0];
var timePart = dateTimeParts[1];
var dateComponents = datePart.Split('.');
int day = int.Parse(dateComponents[0]);
int month = int.Parse(dateComponents[1]);
int year = int.Parse(dateComponents[2]);
var timeComponents = timePart.Split(':');
int hour = int.Parse(timeComponents[0]);
int minute = int.Parse(timeComponents[1]);
try
{
var dateTime = new DateTime(year, month, day, hour, minute, 0);
return true;
}
catch (ArgumentOutOfRangeException)
{
return false;
}
}
static string MakeUrl(DateTime dDateBegin,
DateTime dDateEnd,
TimeSpan dTimeBegin,
TimeSpan dTimeEnd, string tagSerialNumber)
{
const string sheme = ProjectSettings.Sheme;
const string host = ProjectSettings.Host;
const string port = ProjectSettings.Port;
const string method = ProjectSettings.Method;
string returnValue =
$"{sheme}://{host}:{port}/{method}"
+ $"&date_start={string.Format("{0:yyyy-MM-dd}", dDateBegin)}%20{string.Format("{0:hh\\:mm\\:ss}", dTimeBegin)}"
+ $"&date_end={string.Format("{0:yyyy-MM-dd}", dDateEnd)}%20{string.Format("{0:hh\\:mm\\:ss}", dTimeEnd)}"
+ $"&tag={tagSerialNumber}";
Debug.Log(returnValue);
return returnValue;
}
protected void RequestButtonPressed()
{
DateTime dDateBegin;
DateTime dDateEnd;
TimeSpan dTimeBegin;
TimeSpan dTimeEnd;
requestFormController.UI.ButtonWatch.SetEnabled(false);
forcodes.style.display = DisplayStyle.None;
Caller.ClearList();
string dateBeginText = requestFormController.Model.DateBegin.Value;
string dateEndText = requestFormController.Model.DateEnd.Value;
dDateBegin = DateTime.ParseExact(dateBeginText, dateFormat, providerDateFormat);
dTimeBegin = dDateBegin.TimeOfDay;
dDateEnd = DateTime.ParseExact(dateEndText, dateFormat, providerDateFormat);
dTimeEnd = dDateEnd.TimeOfDay;
DatBegin = dDateBegin;
DatEnd = dDateEnd;
string tag = requestFormController.UI.TagTextField.value;
Caller.URL = MakeUrl(DatBegin, DatEnd, dTimeBegin, dTimeEnd, tag);
Caller.Request();
Debug.Log("Inputs fields OK");
requestFormController.UI.LoadingIcon.visible = true;
}
public void DoActionsOnRequestSuccess()
{
requestFormController.UI.ButtonWatch.SetEnabled(true);
progressBarController.StartPlayer(DatBegin, DatEnd);
tagHistoryController.UI.RootElement.visible = true;
progressBarController.UI.RootElement.visible = true;
requestFormController.UI.LoadingIcon.visible = false;
tagHistoryController.ShowForm(this);
requestFormController.HideForm(this);
SceneParams.Instance.IsDataHistoryLoaded = true;
SceneParams.Instance.cameraSettings.IsBlockZoom = false;
SceneParams.Instance.cameraSettings.IsBlockMove = false;
SceneParams.Instance.cameraSettings.IsStartPos = false;
Camera.main.transform.localEulerAngles = new Vector3(20, 0, 0);
MakeTable();
AddMarkPointOnBar();
}
public void DoActionsOnRequestFailed(string failedMessage)
{
requestFormController.UI.ButtonWatch.SetEnabled(true);
forcodes.style.display = DisplayStyle.Flex;
if(failedMessage == "")
{
failedMessage = "В данный момент сервис временно недоступен.";
}
forcodes.text = failedMessage;
requestFormController.UI.LoadingIcon.visible = false;
}
public void SetResponseCode(string Code)
{
forcodes.text = "Ответ HTTP: " + Code;
}
class MarkHronologyRecord
{
public int totalCountSeconds;
public List<MarkItem> items;
}
public void MakeTable()
{
tagHistoryController.UI.ScrollTable.Clear();
//foreach (string x in Caller.MarksTime)
//{
// string[] strArray = x.Split("!");
// int second = int.Parse(strArray[1]);
// TimeSpan timeSpan = TimeSpan.FromSeconds(second);
// var newElement = tagHistoryController.UI.TableRowAsset.Instantiate();
// newElement.Q<Label>("MarkTimeSec").text = string.Format("{0:D2}:{1:D2}:{2:D2}<7D>", timeSpan.Hours,timeSpan.Minutes,timeSpan.Seconds);
// newElement.Q<Label>("MarkOtmetka").text = strArray[0];
// newElement.style.width = new StyleLength(new Length(100, LengthUnit.Percent));
// tagHistoryController.UI.ScrollTable.Add(newElement);
//}
Dictionary<string, MarkHronologyRecord> timeSpentDictionary = new Dictionary<string, MarkHronologyRecord>();
// Подсчет времени
foreach (var item in Caller.MarksHronology)
{
// Проверяем, есть ли уже запись в словаре
if (timeSpentDictionary.ContainsKey(item.name))
{
// Если есть, добавляем время
var findedElm = timeSpentDictionary[item.name];
findedElm.totalCountSeconds += item.time_spend;
findedElm.items.Add(item);
}
else
{
// Если нет, создаем новую запись
var newElement = new MarkHronologyRecord();
newElement.totalCountSeconds = item.time_spend;
newElement.items = new List<MarkItem>() { item};
timeSpentDictionary.Add(item.name, newElement) ;
}
}
var sortedTimeSpent = timeSpentDictionary
.OrderByDescending(entry => entry.Value.totalCountSeconds) // Сортировка по убыванию
.ToList();
foreach (var entry in sortedTimeSpent)
{
TimeSpan timeSpan = TimeSpan.FromSeconds(entry.Value.totalCountSeconds);
var newElement = tagHistoryController.UI.TableRowAsset.Instantiate();
newElement.Q<Label>("MarkTimeSec").text = string.Format("{0:D2}:{1:D2}:{2:D2}", timeSpan.Hours, timeSpan.Minutes, timeSpan.Seconds);
var markOtmetka = newElement.Q<Label>("MarkOtmetka");
markOtmetka.text = entry.Key;
newElement.Q<Label>("CountElements").text = $"{entry.Value.items.Count}";
newElement.pickingMode = PickingMode.Position;
Button button = newElement.Q<Button>("Button");
ScrollView scrollView = newElement.Q<ScrollView>("ScrollView");
if (scrollView != null)
{
scrollView.style.height = new StyleLength(new Length(0, LengthUnit.Pixel));
scrollView.style.visibility = Visibility.Hidden;
VisualElement countBackground = newElement.Q<VisualElement>("CountBackground");
button.clicked += () =>
{
if (scrollView.style.visibility == Visibility.Hidden)
{
scrollView.style.height = StyleKeyword.Auto;//new StyleLength(new Length(400, LengthUnit.Pixel));
scrollView.style.visibility = Visibility.Visible;
if (ColorUtility.TryParseHtmlString("#00A1E7", out var color))
{
countBackground.style.backgroundColor = color;
};
}
else
{
scrollView.style.height = new StyleLength(new Length(0, LengthUnit.Pixel));
scrollView.style.visibility = Visibility.Hidden;
if (ColorUtility.TryParseHtmlString("#51575E", out var color))
{
countBackground.style.backgroundColor = color;
};
}
};
foreach (var item in entry.Value.items)
{
Button newLabel = new Button();
TimeSpan timeSpan1 = TimeSpan.FromSeconds(item.time_start);
TimeSpan timeSpan2 = TimeSpan.FromSeconds(item.time_end);
string text1 = string.Format("{0:D2}:{1:D2}:{2:D2}", timeSpan1.Hours, timeSpan1.Minutes, timeSpan1.Seconds);
string text2 = string.Format("{0:D2}:{1:D2}:{2:D2}", timeSpan2.Hours, timeSpan2.Minutes, timeSpan2.Seconds);
newLabel.text = $"{text1} - {text2}";
//newLabel.AddToClassList(".unity-base-override");
//newLabel.AddToClassList(".Frame-782");
//newLabel.AddToClassList(".n-nine");
Color color;
if (ColorUtility.TryParseHtmlString("#6D757E", out color))
{
newLabel.style.backgroundColor = color;
};
if (ColorUtility.TryParseHtmlString("#FFFFFF", out color))
{
newLabel.style.color = color;
};
newLabel.style.paddingBottom = 6;
newLabel.style.paddingTop = 6;
newLabel.style.paddingLeft = 0;
newLabel.style.paddingRight = 0;
newLabel.style.marginTop = 4;
newLabel.style.marginBottom = 0;
newLabel.style.marginLeft = 4;
newLabel.style.marginRight = 4;
newLabel.style.SetBorderWidth(0);
newLabel.clicked += () =>
{
OnMarkTimeLineClicked(item);
};
;
UnityEngine.Cursor.SetCursor(CursorSelect, Vector2.zero, CursorMode.Auto);
scrollView.Add(newLabel);
}
} else
{
Debug.Log("scrollView is NULL");
}
newElement.style.width = new StyleLength(new Length(100, LengthUnit.Percent));
// регистрируем изменение курсора
//newElement.RegisterCallback<MouseEnterEvent>(OnMouseEnterAddCustomCursor);
//newElement.RegisterCallback<MouseLeaveEvent>(OnMouseLeaveAddCursor);
tagHistoryController.UI.ScrollTable.Add(newElement);
}
}
private void OnMouseEnterAddCustomCursor(MouseEnterEvent evt)
{
// Set the custom cursor when the mouse enters the element
UnityEngine.Cursor.SetCursor(CursorSelect, Vector2.zero, CursorMode.Auto);
}
private void OnMouseLeaveAddCursor(MouseLeaveEvent evt)
{
// Reset the cursor when the mouse leaves the element
UnityEngine.Cursor.SetCursor(null, Vector2.zero, CursorMode.Auto);
}
//public void SetCursor(VisualElement element, MouseCursor cursor)
//{
// object objCursor = new UnityEngine.UIElements.Cursor();
// PropertyInfo fields = typeof(UnityEngine.UIElements.Cursor).GetProperty("defaultCursorId", BindingFlags.NonPublic | BindingFlags.Instance);
// fields.SetValue(objCursor, (int)cursor);
// element.style.cursor = new StyleCursor((UnityEngine.UIElements.Cursor)objCursor);
//}
void OnMarkTimeLineClicked(MarkItem item)
{
progressBarController.Model.UpdateCurrentTimeSeconds(item.time_start);
}
public void AddMarkPointOnBar()
{
TimeSpan difference = progressBarController.Model.DateEnd.Subtract(progressBarController.Model.DateBegin);
var rootElement = progressBarController.UI.EmptyBar;
rootElement.Clear();
// Получаем количество секунд
int seconds = (int)difference.TotalSeconds;
foreach (MarkItem mark in Caller.MarksHronology)
{
var newElement = markPointOnBar.Instantiate();
newElement.style.width = new StyleLength(new Length(4, LengthUnit.Pixel));
newElement.style.height = new StyleLength(new Length(100, LengthUnit.Percent));
rootElement.Add(newElement);
newElement.style.position = Position.Absolute;
newElement.style.left = new Length(((float)mark.time_end / seconds) * 100, LengthUnit.Percent);
}
var beginElement = markPointOnBar.Instantiate();
beginElement.style.width = new StyleLength(new Length(4, LengthUnit.Pixel));
beginElement.style.height = new StyleLength(new Length(100, LengthUnit.Percent));
rootElement.Add(beginElement);
beginElement.style.position = Position.Absolute;
beginElement.style.left = new Length(((float)Caller.MarksHronology.First().time_start / seconds) * 100, LengthUnit.Percent);
}
LocalUtills utills = new LocalUtills();
private Canvas canvasCalendary;
public T GetVisualElementByName<T>(string elementName) where T : VisualElement
{
return utills.GetVisualElementByName<T>(elementName);
}
public List<T> GetVisualElementsByName<T>(string elementName) where T : VisualElement
{
return utills.GetVisualElementsByName<T>(elementName);
}
}
internal class LocalUtills
{
public VisualElement RootVisualElement { get; set; }
public T GetVisualElementByName<T>(string elementName) where T : VisualElement
{
T element = RootVisualElement.Q<T>(elementName);
if (element == null)
{
throw new Exception($"Элемент не найден '{elementName}'.");
}
return element;
}
public List<T> GetVisualElementsByName<T>(string elementName) where T : VisualElement
{
var elements = RootVisualElement.Query<T>(elementName).ToList();
if (elements.Count == 0)
{
throw new System.Exception($"Элемент не найден'{elementName}'.");
}
return elements;
}
}