This commit is contained in:
2026-11-24 15:51:02 +01:00
parent cca4d73e41
commit f4aa17114a
22092 changed files with 5042406 additions and 0 deletions
@@ -0,0 +1,46 @@
using Codice.Client.Commands;
using Codice.Client.Common;
using PlasticGui;
using Unity.PlasticSCM.Editor.UI;
namespace Unity.PlasticSCM.Editor.Views
{
internal class ApplyShelveWithConflictsQuestionerBuilder :
IApplyShelveWithConflictsQuestionerBuilder
{
public IApplyShelveWithConflictsQuestioner Get()
{
return new ApplyShelveWithConflictsQuestioner();
}
}
internal class ApplyShelveWithConflictsQuestioner : IApplyShelveWithConflictsQuestioner
{
ApplyShelveWithConflictsAction IApplyShelveWithConflictsQuestioner.ApplyShelveWithConflicts(
string dstObject, long shelvesetId)
{
ApplyShelveWithConflictsAction result = ApplyShelveWithConflictsAction.Cancel;
GUIActionRunner.RunGUIAction(() =>
{
result = ConfirmContinue(dstObject);
});
return result;
}
static ApplyShelveWithConflictsAction ConfirmContinue(string dstObject)
{
GuiMessage.GuiMessageResponseButton result = GuiMessage.ShowQuestion(
PlasticLocalization.Name.ApplyShelveWithConflictsTitle.GetString(),
PlasticLocalization.Name.ApplyShelveWithConflictsExplanation.GetString(dstObject),
PlasticLocalization.Name.ResolveConflictsNow.GetString(),
PlasticLocalization.Name.ResolveConflictsLater.GetString(),
null);
return result == GuiMessage.GuiMessageResponseButton.Positive
? ApplyShelveWithConflictsAction.ApplyShelve
: ApplyShelveWithConflictsAction.Cancel;
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: da54c27b153842f8b52711ef467ad986
timeCreated: 1731516829
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 51b7ec8ab0194da09e85cb9e71ebb449
timeCreated: 1769776471
@@ -0,0 +1,194 @@
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEngine;
using Codice.CM.Common;
using PlasticGui;
using PlasticGui.WorkspaceWindow.Attributes;
using Unity.PlasticSCM.Editor.UI;
namespace Unity.PlasticSCM.Editor.Views.Attributes
{
internal class ApplyAttributeView : ApplyAttributeDialogOperations.IApplyAttributeDialog
{
internal string SelectedAttributeName => mSelectedAttributeName;
internal string SelectedAttributeValue => mSelectedAttributeValue;
internal ApplyAttributeView(
RepositorySpec repSpec,
IProgressControls progressControls,
AttributeDataDialog parentWindow)
{
mRepSpec = repSpec;
mProgressControls = progressControls;
mParentWindow = parentWindow;
}
void AttributeNameComboBox_Changed(object selectedAttributeName)
{
mSelectedAttributeName = (string)selectedAttributeName;
ApplyAttributeDialogOperations.GetValuesForAttribute(
mRepSpec,
(string)selectedAttributeName,
mProgressControls,
this);
}
internal void SetAttributeToEdit(AttributeRealizationInfo attribute)
{
mAttributeToEdit = attribute;
AddAttribute(new AttributeInfo()
{
Name = attribute.AttributeName,
FIdAcl = attribute.IdAttribute
});
}
void ApplyAttributeDialogOperations.IApplyAttributeDialog.AddAttribute(
AttributeInfo attrInfo)
{
AddAttribute(attrInfo);
}
void ApplyAttributeDialogOperations.IApplyAttributeDialog.FillAttributes(IList attributes)
{
mAttributeNames = new List<string>();
foreach (AttributeInfo attribute in attributes)
mAttributeNames.Add(attribute.Name);
if (attributes.Count > 0)
{
mSelectedAttributeName = ((AttributeInfo)attributes[0]).Name;
ApplyAttributeDialogOperations.GetValuesForAttribute(
mRepSpec, mSelectedAttributeName, mProgressControls, this);
}
}
void ApplyAttributeDialogOperations.IApplyAttributeDialog.FillValues(IList values)
{
mAttributeValues = values.Cast<string>().ToList();
if (mAttributeToEdit != null)
{
mSelectedAttributeValue = mAttributeToEdit.Value;
return;
}
if (values.Count > 0)
mSelectedAttributeValue = (string)values[0];
}
internal void OkButtonAction()
{
ApplyAttributeData applyAttributeData = new ApplyAttributeData(
mSelectedAttributeName,
mSelectedAttributeValue);
ApplyAttributeValidation.Validation(applyAttributeData, mParentWindow, mProgressControls);
}
void NewAttributeButton_Clicked()
{
mParentWindow.ToggleCreateAttributeView(true);
}
void AddAttribute(AttributeInfo attrInfo)
{
mAttributeNames.Add(attrInfo.Name);
mSelectedAttributeName = attrInfo.Name;
ApplyAttributeDialogOperations.GetValuesForAttribute(
mRepSpec, attrInfo.Name, mProgressControls, this);
mParentWindow.ToggleCreateAttributeView(false);
}
internal void OnGUI()
{
using (new EditorGUILayout.HorizontalScope())
{
DoAttributeNamesCombo();
if (mAttributeNames == null && GUILayout.Button(PlasticLocalization.Name.New.GetString(), GUILayout.ExpandWidth(false)))
{
NewAttributeButton_Clicked();
}
}
GUILayout.Space(5);
using (new EditorGUILayout.HorizontalScope())
{
GUILayout.Label(
PlasticLocalization.Name.AttributeValueLabel.GetString(),
GUILayout.Width(LABEL_WIDTH));
Rect valueRect = GUILayoutUtility.GetRect(
GUIContent.none,
EditorStyles.textField,
GUILayout.ExpandWidth(true));
mSelectedAttributeValue = DropDownTextField.DoDropDownTextField(
mSelectedAttributeValue,
DROPDOWN_CONTROL_NAME,
mAttributeValues,
(selectedAttributeValue) =>
{
mSelectedAttributeValue = (string)selectedAttributeValue;
},
valueRect);
}
}
void DoAttributeNamesCombo()
{
GUI.enabled = mAttributeToEdit == null;
GUILayout.Label(
PlasticLocalization.Name.AttributeNameLabel.GetString(),
GUILayout.Width(LABEL_WIDTH));
Rect rect = GUILayoutUtility.GetRect(
new GUIContent(), EditorStyles.popup, GUILayout.ExpandWidth(true));
if (GUI.Button(rect, mSelectedAttributeName, EditorStyles.popup))
{
GenericMenu menu = new GenericMenu();
foreach (string attributeName in mAttributeNames)
{
menu.AddItem(
new GUIContent(UnityMenuItem.EscapedText(attributeName)),
false,
AttributeNameComboBox_Changed,
attributeName);
}
menu.DropDown(rect);
}
GUI.enabled = true;
}
AttributeRealizationInfo mAttributeToEdit;
string mSelectedAttributeName;
List<string> mAttributeNames = new List<string>();
string mSelectedAttributeValue;
List<string> mAttributeValues = new List<string>();
readonly RepositorySpec mRepSpec;
readonly IProgressControls mProgressControls;
readonly AttributeDataDialog mParentWindow;
const float LABEL_WIDTH = 100f;
const string DROPDOWN_CONTROL_NAME = "ApplyAttributeDialog.AttributeValueDropdown";
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: eb8bc19bacda426fb5ae209e56bd32d3
timeCreated: 1769778648
@@ -0,0 +1,156 @@
using UnityEditor;
using Codice.CM.Common;
using PlasticGui;
using PlasticGui.WorkspaceWindow.Attributes;
using Unity.PlasticSCM.Editor.UI;
namespace Unity.PlasticSCM.Editor.Views.Attributes
{
internal class AttributeDataDialog : PlasticDialog
{
internal static ApplyAttributeData BuildForApplyAttribute(
RepositorySpec repSpec, IWorkspaceWindow workspaceWindow, EditorWindow parentWindow)
{
AttributeDataDialog dialog = Create(null, repSpec, workspaceWindow);
ResponseType dialogResult = dialog.RunModal(parentWindow);
ApplyAttributeData result = new ApplyAttributeData(
dialog.mApplyAttributeView.SelectedAttributeName,
dialog.mApplyAttributeView.SelectedAttributeValue);
result.Result = dialogResult == ResponseType.Ok;
return result;
}
internal static ApplyAttributeData BuildForEditAttributeRealization(
AttributeRealizationInfo attribute,
RepositorySpec repSpec,
IWorkspaceWindow workspaceWindow,
EditorWindow parentWindow)
{
AttributeDataDialog dialog = Create(attribute, repSpec, workspaceWindow);
ResponseType dialogResult = dialog.RunModal(parentWindow);
ApplyAttributeData result = new ApplyAttributeData(
dialog.mApplyAttributeView.SelectedAttributeName,
dialog.mApplyAttributeView.SelectedAttributeValue);
result.Result = dialogResult == ResponseType.Ok;
return result;
}
static AttributeDataDialog Create(
AttributeRealizationInfo attribute,
RepositorySpec repSpec,
IWorkspaceWindow workspaceWindow)
{
var instance = CreateInstance<AttributeDataDialog>();
instance.mRepSpec = repSpec;
instance.mIsEditingAttribute = attribute != null;
instance.mApplyAttributeView = new ApplyAttributeView(
repSpec, instance.mProgressControls, instance);
if (attribute != null)
{
instance.mApplyAttributeView.SetAttributeToEdit(attribute);
return instance;
}
instance.mCreateAttributeView = new CreateAttributeView(
repSpec,
workspaceWindow,
instance.mApplyAttributeView,
instance.mProgressControls,
instance);
ApplyAttributeDialogOperations.LoadAttributes(
repSpec, instance.mProgressControls, instance.mApplyAttributeView);
instance.ToggleCreateAttributeView(false);
return instance;
}
protected override string GetTitle()
{
if (mShowCreateAttributeView)
return PlasticLocalization.Name.CreateAttribute.GetString();
if (mIsEditingAttribute)
return PlasticLocalization.Name.EditAttributeTitle.GetString();
return PlasticLocalization.Name.ApplyAttribute.GetString();
}
protected override string GetExplanation()
{
if (mShowCreateAttributeView)
return PlasticLocalization.Name.CreateAttributeExplanation.GetString(mRepSpec);
return PlasticLocalization.Name.ApplyAttributeExplanation.GetString();
}
internal override void OkButtonAction()
{
if (mShowCreateAttributeView)
{
mCreateAttributeView.OkButtonAction();
return;
}
mApplyAttributeView.OkButtonAction();
}
internal override void CancelButtonAction()
{
if (mShowCreateAttributeView)
{
ToggleCreateAttributeView(false);
return;
}
base.CancelButtonAction();
}
internal void ToggleCreateAttributeView(bool show)
{
mShowCreateAttributeView = show;
mOkButtonText = mShowCreateAttributeView ?
PlasticLocalization.Name.CreateButton.GetString() :
PlasticLocalization.Name.ApplyButton.GetString();
mCancelButtonText = mShowCreateAttributeView ?
PlasticLocalization.Name.BackButton.GetString() :
PlasticLocalization.Name.CancelButton.GetString();
UnityInternals.UnityEditor.EditorGUI.activeEditor?.EndEditing();
}
protected override void DoComponentsArea()
{
// HACK: GetTitle is not called once the dialog is shown
titleContent.text = GetTitle();
if (mShowCreateAttributeView)
{
mCreateAttributeView.OnGUI();
return;
}
mApplyAttributeView.OnGUI();
}
ApplyAttributeView mApplyAttributeView;
CreateAttributeView mCreateAttributeView;
RepositorySpec mRepSpec;
bool mIsEditingAttribute;
bool mShowCreateAttributeView;
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: a14bb815cfde49609ae0abed939d849b
timeCreated: 1769698643
@@ -0,0 +1,270 @@
using UnityEngine;
using UnityEditor;
using Codice.CM.Common;
using PlasticGui;
using PlasticGui.WorkspaceWindow.Attributes;
using Unity.PlasticSCM.Editor.UI;
using Unity.PlasticSCM.Editor.Views.Properties;
#if !UNITY_6000_3_OR_NEWER
using EditorGUI = Unity.PlasticSCM.Editor.UnityInternals.UnityEditor.EditorGUI;
#endif
namespace Unity.PlasticSCM.Editor.Views.Attributes
{
internal class AttributePanel : AttributePanelOperations.IAttributePanel
{
internal interface IAttributesPanel
{
internal void RemovePanel(AttributePanel attributePanel);
}
internal Vector2 DesiredSize => mDesiredSize;
internal AttributePanel(
RepositorySpec repSpec,
AttributeRealizationInfo attribute,
IProgressControls progressControls,
IAttributesPanel attributesPanel,
IWorkspaceWindow workspaceWindow,
EditorWindow window)
{
mRepSpec = repSpec;
mAttribute = attribute;
mProgressControls = progressControls;
mAttributesPanel = attributesPanel;
mWorkspaceWindow = workspaceWindow;
mWindow = window;
Color solidColor = AttributeColor.FromAttributeName(mAttribute.AttributeName);
mNameForegroundColor = solidColor;
mOutlineColor = new Color(solidColor.r, solidColor.g, solidColor.b, 0.5f);;
mFillColor = new Color(solidColor.r, solidColor.g, solidColor.b, 0.1f);
CalculateTextAndDesiredSize();
}
internal void Update()
{
if (!mbEditButtonClicked)
return;
mbEditButtonClicked = false;
EditButton_Click();
}
internal void OnGUI(float availableWidth)
{
GUIStyle labelStyle = UnityStyles.AttributesPanel.AttributeLabel;
GUIStyle editButtonStyle= UnityStyles.AttributesPanel.AttributeLabelButton;
GUIStyle removeButtonStyle= UnityStyles.AttributesPanel.AttributeLabelRightButton;
float buttonsWidth = editButtonStyle.fixedWidth +
removeButtonStyle.fixedWidth +
editButtonStyle.margin.horizontal +
removeButtonStyle.margin.horizontal +
SEPARATOR_WIDTH + 2 * SEPARATOR_MARGIN;
string cutText = CutText(
mPlainText,
mRichText,
labelStyle,
availableWidth - buttonsWidth,
mNameForegroundColor,
out Vector2 textSize);
Rect totalRect = GUILayoutUtility.GetRect(
0,
0,
GUILayout.Width(textSize.x + buttonsWidth + labelStyle.margin.horizontal),
GUILayout.Height(textSize.y + labelStyle.margin.vertical));
Rect boxRect = new Rect(
totalRect.x + labelStyle.margin.left,
totalRect.y + labelStyle.margin.top,
totalRect.width - labelStyle.margin.horizontal,
totalRect.height - labelStyle.margin.vertical);
Rect editButtonRect = new Rect(
boxRect.x + textSize.x,
boxRect.y + (boxRect.height - editButtonStyle.fixedHeight) / 2,
editButtonStyle.fixedWidth,
editButtonStyle.fixedHeight);
Rect separatorRect = new Rect(
editButtonRect.xMax + SEPARATOR_MARGIN,
boxRect.y,
SEPARATOR_WIDTH,
boxRect.height);
Rect removeButtonRect = new Rect(
separatorRect.xMax + SEPARATOR_MARGIN,
boxRect.y + (boxRect.height - removeButtonStyle.fixedHeight) / 2,
removeButtonStyle.fixedWidth,
removeButtonStyle.fixedHeight);
UnityEditor.EditorGUI.DrawRect(boxRect, mFillColor);
EditorGUI.DrawOutline(boxRect, 1, mOutlineColor);
UnityEditor.EditorGUI.DrawRect(separatorRect, mOutlineColor);
GUI.Label(
boxRect,
new GUIContent(cutText, cutText != mRichText ? mRichText : string.Empty),
labelStyle);
if (GUI.Button(
editButtonRect,
Images.GetEditIcon(),
editButtonStyle))
{
mbEditButtonClicked = true;
}
if (GUI.Button(
removeButtonRect,
Images.GetCloseIcon(),
removeButtonStyle))
{
RemoveButton_Click();
}
}
void AttributePanelOperations.IAttributePanel.DisableEditionMode()
{
mAttribute.Value = mEditAttributeValue;
CalculateTextAndDesiredSize();
PropertiesRefreshNotifier.Notify();
}
void AttributePanelOperations.IAttributePanel.Remove()
{
mAttributesPanel.RemovePanel(this);
PropertiesRefreshNotifier.Notify();
}
void EditButton_Click()
{
ApplyAttributeData applyAttributeData = AttributeDataDialog.BuildForEditAttributeRealization(
mAttribute, mRepSpec, mWorkspaceWindow, mWindow);
if (!applyAttributeData.Result)
return;
mEditAttributeValue = applyAttributeData.AttributeValue;
AttributePanelOperations.ChangeAttributeValue(
mRepSpec, mAttribute, applyAttributeData.AttributeValue,
mProgressControls, this);
}
void RemoveButton_Click()
{
AttributePanelOperations.DeleteAttribute(
mRepSpec, mAttribute, mProgressControls, this);
}
void CalculateTextAndDesiredSize()
{
GUIStyle labelStyle = UnityStyles.AttributesPanel.AttributeLabel;
GUIStyle editButtonStyle = UnityStyles.AttributesPanel.AttributeLabelButton;
GUIStyle removeButtonStyle = UnityStyles.AttributesPanel.AttributeLabelRightButton;
mPlainText = string.Format("{0}: {1}", mAttribute.AttributeName, mAttribute.Value);
mRichText = string.Format(
"<b><color={0}>{1}:</color></b> {2}",
GetHexString(mNameForegroundColor),
mAttribute.AttributeName,
mAttribute.Value);
Vector2 desiredTextSize = labelStyle.CalcSize(new GUIContent(mRichText));
mDesiredSize =
desiredTextSize +
new Vector2(
labelStyle.margin.horizontal +
editButtonStyle.fixedWidth +
removeButtonStyle.fixedWidth +
editButtonStyle.margin.horizontal +
removeButtonStyle.margin.horizontal +
SEPARATOR_WIDTH + 2 * SEPARATOR_MARGIN,
labelStyle.margin.vertical);
}
static string CutText(
string plainText,
string richText,
GUIStyle style,
float availableWidth,
Color nameForegroundColor,
out Vector2 usedSize)
{
usedSize = new Vector2();
availableWidth -= style.margin.horizontal;
Vector2 fullTextSize = style.CalcSize(new GUIContent(richText));
if (fullTextSize.x < availableWidth)
{
usedSize = fullTextSize;
return richText;
}
string textResult = string.Format("<b><color={0}>", GetHexString(nameForegroundColor));
bool bReachedAttributeValue = false;
foreach (char c in plainText)
{
Vector2 currentSize = style.CalcSize(
new GUIContent(
textResult + c + ELLIPSIS + (!bReachedAttributeValue ? "</color></b>" : string.Empty)));
if (currentSize.x >= availableWidth)
return textResult + ELLIPSIS + (!bReachedAttributeValue ? "</color></b>" : string.Empty);
usedSize = currentSize;
textResult += c;
if (!bReachedAttributeValue && c == ':')
{
bReachedAttributeValue = true;
textResult += "</color></b>";
}
}
return textResult + ELLIPSIS;
}
static string GetHexString(Color color)
{
return string.Format(
"#{0}{1}{2}{3}",
((int)(color.r * 255)).ToString("X2"),
((int)(color.g * 255)).ToString("X2"),
((int)(color.b * 255)).ToString("X2"),
((int)(color.a * 255)).ToString("X2"));
}
string mRichText;
string mPlainText;
Vector2 mDesiredSize;
string mEditAttributeValue;
bool mbEditButtonClicked;
readonly Color mNameForegroundColor;
readonly Color mOutlineColor;
readonly Color mFillColor;
readonly RepositorySpec mRepSpec;
readonly AttributeRealizationInfo mAttribute;
readonly IProgressControls mProgressControls;
readonly IAttributesPanel mAttributesPanel;
readonly IWorkspaceWindow mWorkspaceWindow;
readonly EditorWindow mWindow;
const string ELLIPSIS = "...";
const float SEPARATOR_WIDTH = 1;
const float SEPARATOR_MARGIN = 4;
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 7d5374a12bef4020a4e16051c301ba71
timeCreated: 1769602516
@@ -0,0 +1,249 @@
using System;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using Codice.CM.Common;
using PlasticGui;
using PlasticGui.WorkspaceWindow.Attributes;
using Unity.PlasticSCM.Editor.UI;
using Unity.PlasticSCM.Editor.UI.Progress;
using Unity.PlasticSCM.Editor.Views.Properties;
namespace Unity.PlasticSCM.Editor.Views.Attributes
{
internal class AttributesPanel :
AttributesPanelOperations.IAttributesPanel,
AttributePanel.IAttributesPanel
{
internal AttributesPanel(
Action repaint,
IWorkspaceWindow workspaceWindow,
EditorWindow window)
{
mRepaint = repaint;
mWorkspaceWindow = workspaceWindow;
mWindow = window;
mProgressControls = new ProgressControlsForViews();
}
internal void UpdateRepositorySpec(RepositorySpec repSpec)
{
mRepSpec = repSpec;
}
internal void UpdateInfo(long objId)
{
if (objId == -1)
{
Clear();
return;
}
if (mObjId == objId)
return;
mObjId = objId;
AttributesPanelOperations.Refresh(
mRepSpec, mObjId, mProgressControls, this);
}
internal void Clear()
{
mObjId = -1;
ClearAttributePanels();
}
internal void Refresh()
{
if (mObjId == -1 || mRepSpec == null)
return;
mIsApplyingAttribute = false;
AttributesPanelOperations.Refresh(
mRepSpec, mObjId, mProgressControls, this);
}
internal void Update()
{
foreach (AttributePanel attributePanel in mAttributePanels)
attributePanel.Update();
if (!mbOpenApplyAttributeDialog)
return;
mbOpenApplyAttributeDialog = false;
ApplyAttributesButton_Click();
}
internal void OnGUI()
{
if (mObjId == -1)
return;
using (new GUILayout.HorizontalScope())
{
EditorGUILayout.Space(HORIZONTAL_MARGIN, false);
DrawAttributePanels(mAttributePanels, mLastValidAvailableWidth - 2 * HORIZONTAL_MARGIN);
EditorGUILayout.Space(HORIZONTAL_MARGIN, false);
}
Rect layoutRect = GUILayoutUtility.GetRect(0, 0, GUILayout.ExpandWidth(true));
if (Event.current.type == EventType.Repaint)
{
mLastValidAvailableWidth = layoutRect.width;
}
DrawAddAttributeButton();
}
internal bool IsAvailable()
{
return mObjId != -1;
}
void DrawAttributePanels(List<AttributePanel> attributePanels, float availableWidth)
{
float currentLineWidth = 0f;
bool isNewLine = true;
bool showScrollbar = mLastDesiredHeight > MAX_HEIGHT;
if (showScrollbar)
availableWidth -= UnityConstants.SCROLLBAR_WIDTH;
mScrollPosition = GUILayout.BeginScrollView(
mScrollPosition,
false,
false,
GUIStyle.none,
showScrollbar ? GUI.skin.verticalScrollbar : GUIStyle.none,
GUILayout.Height(showScrollbar ? MAX_HEIGHT : mLastDesiredHeight));
if (Event.current.type == EventType.Repaint)
mLastDesiredHeight = 0;
using (new GUILayout.VerticalScope())
{
foreach (AttributePanel attributePanel in attributePanels)
{
float panelWidth = attributePanel.DesiredSize.x;
if (currentLineWidth + panelWidth >= availableWidth && !isNewLine)
{
GUILayout.EndHorizontal();
isNewLine = true;
currentLineWidth = 0f;
}
if (isNewLine)
{
GUILayout.BeginHorizontal();
isNewLine = false;
if (Event.current.type == EventType.Repaint)
mLastDesiredHeight += attributePanel.DesiredSize.y;
}
attributePanel.OnGUI(availableWidth);
currentLineWidth = currentLineWidth + panelWidth;
}
if (!isNewLine)
GUILayout.EndHorizontal();
}
GUILayout.EndScrollView();
}
void DrawAddAttributeButton()
{
if (GUILayout.Button(
new GUIContent(
PlasticLocalization.Name.AddAttributeButton.GetString(), Images.GetAddIcon()),
UnityStyles.AttributesPanel.AddAttributeButton,
GUILayout.ExpandWidth(false)))
{
mbOpenApplyAttributeDialog = true;
}
}
void ApplyAttributesButton_Click()
{
ApplyAttributeData applyAttributeData = AttributeDataDialog.BuildForApplyAttribute(
mRepSpec, mWorkspaceWindow, mWindow);
mIsApplyingAttribute = true;
AttributesPanelOperations.ApplyAttribute(
mRepSpec, mObjId, applyAttributeData, mProgressControls, this);
}
void AttributesPanelOperations.IAttributesPanel.Fill(
AttributeRealizationInfo[] attributeRealizations)
{
bool shouldNotify = mIsApplyingAttribute;
mIsApplyingAttribute = false;
ClearAttributePanels();
foreach (AttributeRealizationInfo attribute in attributeRealizations)
{
AttributePanel attributePanel = new AttributePanel(
mRepSpec,
attribute,
mProgressControls,
this,
mWorkspaceWindow,
mWindow);
mAttributePanels.Add(attributePanel);
}
if (shouldNotify)
PropertiesRefreshNotifier.Notify();
mRepaint();
}
void AttributesPanelOperations.IAttributesPanel.EnableApplyAttributesButton()
{
}
void AttributesPanelOperations.IAttributesPanel.DisableApplyAttributesButton()
{
}
void AttributePanel.IAttributesPanel.RemovePanel(AttributePanel attributePanel)
{
mAttributePanels.Remove(attributePanel);
}
void ClearAttributePanels()
{
mAttributePanels.Clear();
}
float mLastDesiredHeight;
float mLastValidAvailableWidth;
Vector2 mScrollPosition;
RepositorySpec mRepSpec;
long mObjId;
bool mbOpenApplyAttributeDialog;
bool mIsApplyingAttribute;
readonly IProgressControls mProgressControls;
readonly List<AttributePanel> mAttributePanels = new List<AttributePanel>();
readonly Action mRepaint;
readonly IWorkspaceWindow mWorkspaceWindow;
readonly EditorWindow mWindow;
const int HORIZONTAL_MARGIN = 2;
const float MAX_HEIGHT = 90f;
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: ed6af67100cc4771885346e6963669f6
timeCreated: 1769601225
@@ -0,0 +1,137 @@
using UnityEditor;
using UnityEngine;
using Codice.CM.Common;
using PlasticGui;
using PlasticGui.WorkspaceWindow.Attributes;
using PlasticGui.WorkspaceWindow.QueryViews.Attributes;
using Unity.PlasticSCM.Editor.UI;
#if !UNITY_6000_3_OR_NEWER
using EditorGUI = Unity.PlasticSCM.Editor.UnityInternals.UnityEditor.EditorGUI;
#endif
namespace Unity.PlasticSCM.Editor.Views.Attributes
{
internal class CreateAttributeView : IPlasticDialogCloser
{
internal CreateAttributeView(
RepositorySpec repSpec,
IWorkspaceWindow workspaceWindow,
ApplyAttributeDialogOperations.IApplyAttributeDialog applyAttributeView,
IProgressControls progressControls,
AttributeDataDialog parentWindow)
{
mRepSpec = repSpec;
mWorkspaceWindow = workspaceWindow;
mApplyAttributeView = applyAttributeView;
mProgressControls = progressControls;
mParentWindow = parentWindow;
}
void IPlasticDialogCloser.CloseDialog()
{
mParentWindow.ToggleCreateAttributeView(false);
ApplyAttributeDialogOperations.CreateAttribute(
BuildCreationData(),
mWorkspaceWindow,
mProgressControls,
mApplyAttributeView);
}
internal void OkButtonAction()
{
AttributeDataValidation.AsyncValidation(
BuildCreationData(),
this,
mProgressControls);
}
AttributeData BuildCreationData()
{
return new AttributeData(
mRepSpec,
null,
mAttributeName,
mComments);
}
internal void OnGUI()
{
using (new EditorGUILayout.VerticalScope())
{
using (new EditorGUILayout.HorizontalScope())
{
GUILayout.Label(
PlasticLocalization.Name.AttributeNameLabel.GetString(),
GUILayout.Width(HORIZONTAL_ALIGNMENT));
Rect nameRect = GUILayoutUtility.GetRect(
new GUIContent(string.Empty),
EditorStyles.textField,
GUILayout.Width(ENTRIES_WIDTH));
GUI.SetNextControlName(NAME_FIELD_CONTROL_NAME);
mAttributeName = UnityEditor.EditorGUI.TextField(nameRect, mAttributeName);
if (!mWasNameFieldFocused)
{
UnityEditor.EditorGUI.FocusTextInControl(NAME_FIELD_CONTROL_NAME);
mWasNameFieldFocused = true;
}
}
GUILayout.Space(5);
using (new EditorGUILayout.HorizontalScope())
{
using (new EditorGUILayout.VerticalScope(GUILayout.Width(HORIZONTAL_ALIGNMENT)))
{
GUILayout.Space(49);
GUILayout.Label(
PlasticLocalization.Name.AttributeCommentLabel.GetString(),
GUILayout.Width(HORIZONTAL_ALIGNMENT));
}
using (new EditorGUILayout.VerticalScope())
{
Rect commentRect = GUILayoutUtility.GetRect(
new GUIContent(string.Empty),
EditorStyles.textArea,
GUILayout.Height(COMMENTS_HEIGHT),
GUILayout.Width(ENTRIES_WIDTH));
mComments = EditorGUI.ScrollableTextAreaInternal(
commentRect,
mComments,
ref mScrollPosition,
EditorStyles.textArea);
GUILayout.Space(5);
GUILayout.Label(
PlasticLocalization.Name.AttributeHelpLabel.GetString(),
UnityStyles.Dialog.MiniLabelText);
}
}
}
}
string mAttributeName = string.Empty;
string mComments = string.Empty;
Vector2 mScrollPosition;
bool mWasNameFieldFocused;
readonly RepositorySpec mRepSpec;
readonly IWorkspaceWindow mWorkspaceWindow;
readonly ApplyAttributeDialogOperations.IApplyAttributeDialog mApplyAttributeView;
readonly IProgressControls mProgressControls;
readonly AttributeDataDialog mParentWindow;
const int HORIZONTAL_ALIGNMENT = 100;
const int COMMENTS_HEIGHT = 200;
const int ENTRIES_WIDTH = 350;
const string NAME_FIELD_CONTROL_NAME = "CreateAttributeNameField";
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 56ea95e3e56f40af895e3479028feb82
timeCreated: 1769784765
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 15fe89692edc49a4891091bd0e1c6536
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,20 @@
using UnityEditor.IMGUI.Controls;
#if UNITY_6000_2_OR_NEWER
using TreeViewItem = UnityEditor.IMGUI.Controls.TreeViewItem<int>;
#endif
namespace Unity.PlasticSCM.Editor.Views.Branches
{
class BranchListViewItem : TreeViewItem
{
internal object ObjectInfo { get; private set; }
internal BranchListViewItem(int id, object objectInfo)
: base(id, 1)
{
ObjectInfo = objectInfo;
displayName = id.ToString();
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: ebbbce5f7ed39ab45b6f43340727ba5e
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,125 @@
using System;
using System.Collections.Generic;
using UnityEditor.IMGUI.Controls;
using UnityEngine;
using PlasticGui;
using Unity.PlasticSCM.Editor.UI;
using Unity.PlasticSCM.Editor.UI.Tree;
namespace Unity.PlasticSCM.Editor.Views.Branches
{
internal enum BranchesListColumn
{
Name,
Comment,
CreatedBy,
CreationDate,
}
[Serializable]
internal class BranchesListHeaderState : MultiColumnHeaderState, ISerializationCallbackReceiver
{
internal static BranchesListHeaderState GetDefault()
{
return new BranchesListHeaderState(BuildColumns());
}
internal static List<string> GetColumnNames()
{
List<string> result = new List<string>();
result.Add(PlasticLocalization.GetString(PlasticLocalization.Name.NameColumn));
result.Add(PlasticLocalization.GetString(PlasticLocalization.Name.CommentColumn));
result.Add(PlasticLocalization.GetString(PlasticLocalization.Name.CreatedByColumn));
result.Add(PlasticLocalization.GetString(PlasticLocalization.Name.CreationDateColumn));
return result;
}
internal static string GetColumnName(BranchesListColumn column)
{
switch (column)
{
case BranchesListColumn.Name:
return PlasticLocalization.GetString(PlasticLocalization.Name.NameColumn);
case BranchesListColumn.Comment:
return PlasticLocalization.GetString(PlasticLocalization.Name.CommentColumn);
case BranchesListColumn.CreatedBy:
return PlasticLocalization.GetString(PlasticLocalization.Name.CreatedByColumn);
case BranchesListColumn.CreationDate:
return PlasticLocalization.GetString(PlasticLocalization.Name.CreationDateColumn);
default:
return null;
}
}
void ISerializationCallbackReceiver.OnAfterDeserialize()
{
if (mHeaderTitles != null)
TreeHeaderColumns.SetTitles(columns, mHeaderTitles);
if (mColumnsAllowedToggleVisibility != null)
TreeHeaderColumns.SetVisibilities(columns, mColumnsAllowedToggleVisibility);
}
void ISerializationCallbackReceiver.OnBeforeSerialize()
{
}
static Column[] BuildColumns()
{
return new Column[]
{
new Column()
{
width = UnityConstants.BranchesColumns.BRANCHES_NAME_WIDTH,
minWidth = UnityConstants.BranchesColumns.BRANCHES_NAME_MIN_WIDTH,
headerContent = new GUIContent(
GetColumnName(BranchesListColumn.Name)),
allowToggleVisibility = false,
sortingArrowAlignment = TextAlignment.Right
},
new Column()
{
width = UnityConstants.BranchesColumns.COMMENT_WIDTH,
minWidth = UnityConstants.BranchesColumns.COMMENT_MIN_WIDTH,
headerContent = new GUIContent(
GetColumnName(BranchesListColumn.Comment)),
sortingArrowAlignment = TextAlignment.Right
},
new Column()
{
width = UnityConstants.BranchesColumns.CREATEDBY_WIDTH,
minWidth = UnityConstants.BranchesColumns.CREATEDBY_MIN_WIDTH,
headerContent = new GUIContent(
GetColumnName(BranchesListColumn.CreatedBy)),
sortingArrowAlignment = TextAlignment.Right
},
new Column()
{
width = UnityConstants.BranchesColumns.CREATION_DATE_WIDTH,
minWidth = UnityConstants.BranchesColumns.CREATION_DATE_MIN_WIDTH,
headerContent = new GUIContent(
GetColumnName(BranchesListColumn.CreationDate)),
sortingArrowAlignment = TextAlignment.Right
},
};
}
BranchesListHeaderState(Column[] columns)
: base(columns)
{
if (mHeaderTitles == null)
mHeaderTitles = TreeHeaderColumns.GetTitles(columns);
if (mColumnsAllowedToggleVisibility == null)
mColumnsAllowedToggleVisibility = TreeHeaderColumns.GetVisibilities(columns);
}
[SerializeField]
string[] mHeaderTitles;
[SerializeField]
bool[] mColumnsAllowedToggleVisibility;
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: f4a41e458bcb22946bcfa6b165c90288
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,498 @@
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using UnityEditor.IMGUI.Controls;
using Codice.CM.Common;
using PlasticGui;
using PlasticGui.WorkspaceWindow.QueryViews;
using PlasticGui.WorkspaceWindow.QueryViews.Branches;
using Unity.PlasticSCM.Editor.UI;
using Unity.PlasticSCM.Editor.UI.Avatar;
using Unity.PlasticSCM.Editor.UI.Tree;
using Time = Codice.Client.Common.Time;
#if UNITY_6000_2_OR_NEWER
using TreeViewItem = UnityEditor.IMGUI.Controls.TreeViewItem<int>;
#endif
namespace Unity.PlasticSCM.Editor.Views.Branches
{
internal class BranchesListView :
PlasticTreeView,
IPlasticTree<BranchTreeNode>
{
internal GenericMenu Menu { get { return mMenu.Menu; } }
internal BranchesListView(
BranchesListHeaderState headerState,
List<string> columnNames,
BranchesViewMenu menu,
IGetRepositorySpec getRepositorySpec,
IGetWorkingObject getWorkingObject,
Func<bool> getIsHiddenBranchesMode,
Action delayedSelectionChangedAction,
Action doubleClickAction,
Action<IEnumerable<object>> afterItemsChangedAction)
{
mColumnNames = columnNames;
mMenu = menu;
mGetRepositorySpec = getRepositorySpec;
mGetWorkingObject = getWorkingObject;
mGetIsHiddenBranchesMode = getIsHiddenBranchesMode;
mDelayedSelectionChangedAction = delayedSelectionChangedAction;
mDoubleClickAction = doubleClickAction;
mAfterItemsChangedAction = afterItemsChangedAction;
multiColumnHeader = new MultiColumnHeader(headerState);
multiColumnHeader.canSort = true;
multiColumnHeader.sortingChanged += SortingChanged;
mDelayedFilterAction = new DelayedActionBySecondsRunner(
DelayedSearchChanged, UnityConstants.SEARCH_DELAYED_INPUT_ACTION_INTERVAL);
mDelayedSelectionRunner = new DelayedActionBySecondsRunner(
DelayedSelectionChanged, UnityConstants.SELECTION_DELAYED_INPUT_ACTION_INTERVAL);
}
protected override void SelectionChanged(IList<int> selectedIds)
{
mDelayedSelectionRunner.Run();
}
protected override IList<TreeViewItem> BuildRows(
TreeViewItem rootItem)
{
if (mQueryResult == null)
{
ClearRows(rootItem, mRows);
return mRows;
}
RegenerateRows(
mListViewItemIds,
mQueryResult.GetObjects(),
rootItem, mRows);
return mRows;
}
protected override void SearchChanged(string newSearch)
{
mDelayedFilterAction.Run();
}
protected override void ContextClicked()
{
mMenu.Popup();
Repaint();
}
public override void OnGUI(Rect rect)
{
base.OnGUI(rect);
if (!HasKeyboardFocus())
return;
Event e = Event.current;
if (e.type != EventType.KeyDown)
return;
bool isProcessed = mMenu.ProcessKeyActionIfNeeded(e);
if (isProcessed)
{
e.Use();
GUIUtility.ExitGUI();
}
}
protected override void RowGUI(RowGUIArgs args)
{
if (args.item is BranchListViewItem)
{
BranchListViewItem branchListViewItem = (BranchListViewItem)args.item;
BranchesListViewItemGUI(
mQueryResult,
rowHeight,
branchListViewItem,
args,
RepObjectInfoView.IsHighlighted(
branchListViewItem.ObjectInfo, mGetWorkingObject.Get()),
mGetIsHiddenBranchesMode(),
Repaint);
return;
}
base.RowGUI(args);
}
protected override void DoubleClickedItem(int id)
{
if (GetSelection().Count != 1)
return;
mDoubleClickAction();
}
internal void Refilter()
{
if (mQueryResult == null)
return;
Filter filter = new Filter(searchString);
mQueryResult.ApplyFilter(filter, mColumnNames);
}
internal void Sort()
{
if (mQueryResult == null)
return;
int sortedColumnIdx = multiColumnHeader.state.sortedColumnIndex;
bool sortAscending = multiColumnHeader.IsSortedAscending(sortedColumnIdx);
mQueryResult.Sort(
mColumnNames[sortedColumnIdx],
sortAscending);
}
internal List<RepositorySpec> GetSelectedRepositories()
{
List<RepositorySpec> result = new List<RepositorySpec>();
IList<int> selectedIds = GetSelection();
if (selectedIds.Count == 0)
return result;
foreach (KeyValuePair<object, int> item
in mListViewItemIds.GetInfoItems())
{
if (!selectedIds.Contains(item.Value))
continue;
RepositorySpec repSpec =
mQueryResult.GetRepositorySpec(item.Key);
result.Add(repSpec);
}
return result;
}
internal List<RepObjectInfo> GetSelectedRepObjectInfos()
{
List<RepObjectInfo> result = new List<RepObjectInfo>();
IList<int> selectedIds = GetSelection();
if (selectedIds.Count == 0)
return result;
foreach (KeyValuePair<object, int> item
in mListViewItemIds.GetInfoItems())
{
if (!selectedIds.Contains(item.Value))
continue;
RepObjectInfo repObjectInfo =
mQueryResult.GetRepObjectInfo(item.Key);
result.Add(repObjectInfo);
}
return result;
}
internal List<object> GetSelectedVisibleItems()
{
List<object> result = new List<object>();
IList<int> selectedIds = GetSelection();
if (selectedIds.Count == 0)
return result;
foreach (TreeViewItem row in mRows)
{
if (!selectedIds.Contains(row.id))
continue;
result.Add(((BranchListViewItem)row).ObjectInfo);
}
return result;
}
internal void SelectRepObjectInfos(
List<RepObjectInfo> repObjectsToSelect)
{
List<int> idsToSelect = new List<int>();
foreach (RepObjectInfo repObjectInfo in repObjectsToSelect)
{
int repObjectInfoId = GetTreeIdForItem(repObjectInfo);
if (repObjectInfoId == -1)
continue;
idsToSelect.Add(repObjectInfoId);
}
TableViewOperations.SetSelectionAndScroll(this, idsToSelect);
}
void IPlasticTree<BranchTreeNode>.FillItemsAndSelectRows(
IPlasticTree treeModel,
List<IPlasticTreeNode> itemsToSelect,
Filter currentFilter)
{
mListViewItemIds.Clear();
List<RepObjectInfo> branchesToSelect = BranchesSelection.GetBranchesToSelect(
this, itemsToSelect);
int defaultRow = TableViewOperations.GetFirstSelectedRow(this);
mQueryResult = BuildViewQueryResult(
EnumQueryObjectType.Branch, treeModel, mGetRepositorySpec.Get());
UpdateResults();
BranchesSelection.SelectBranches(this, branchesToSelect, defaultRow);
}
void DelayedSearchChanged()
{
UpdateResults();
TableViewOperations.ScrollToSelection(this);
}
void UpdateResults()
{
Refilter();
Sort();
mAfterItemsChangedAction(mQueryResult.GetObjects());
Reload();
}
void DelayedSelectionChanged()
{
if (!HasSelection())
return;
mDelayedSelectionChangedAction();
}
void SortingChanged(MultiColumnHeader multiColumnHeader)
{
Sort();
Reload();
}
int GetTreeIdForItem(RepObjectInfo repObjectInfo)
{
foreach (KeyValuePair<object, int> item in mListViewItemIds.GetInfoItems())
{
RepObjectInfo currentRepObjectInfo =
mQueryResult.GetRepObjectInfo(item.Key);
if (!currentRepObjectInfo.Equals(repObjectInfo))
continue;
if (!currentRepObjectInfo.GUID.Equals(repObjectInfo.GUID))
continue;
return item.Value;
}
return -1;
}
static void RegenerateRows(
ListViewItemIds<object> listViewItemIds,
List<object> objectInfos,
TreeViewItem rootItem,
List<TreeViewItem> rows)
{
ClearRows(rootItem, rows);
if (objectInfos.Count == 0)
return;
foreach (object objectInfo in objectInfos)
{
int objectId;
if (!listViewItemIds.TryGetInfoItemId(objectInfo, out objectId))
objectId = listViewItemIds.AddInfoItem(objectInfo);
BranchListViewItem branchListViewItem =
new BranchListViewItem(objectId, objectInfo);
rootItem.AddChild(branchListViewItem);
rows.Add(branchListViewItem);
}
}
static void ClearRows(
TreeViewItem rootItem,
List<TreeViewItem> rows)
{
if (rootItem.hasChildren)
rootItem.children.Clear();
rows.Clear();
}
static void BranchesListViewItemGUI(
ViewQueryResult queryResult,
float rowHeight,
BranchListViewItem item,
RowGUIArgs args,
bool isBoldText,
bool isHiddenBranchesMode,
Action avatarLoadedAction)
{
for (int visibleColumnIdx = 0; visibleColumnIdx < args.GetNumVisibleColumns(); visibleColumnIdx++)
{
Rect cellRect = args.GetCellRect(visibleColumnIdx);
if (visibleColumnIdx == 0)
{
cellRect.x += UnityConstants.FIRST_COLUMN_WITHOUT_ICON_INDENT;
cellRect.width -= UnityConstants.FIRST_COLUMN_WITHOUT_ICON_INDENT;
}
BranchesListColumn column =
(BranchesListColumn)args.GetColumn(visibleColumnIdx);
BranchesListViewItemCellGUI(
cellRect,
rowHeight,
queryResult,
item,
column,
avatarLoadedAction,
isHiddenBranchesMode,
args.selected,
args.focused,
isBoldText);
}
}
static void BranchesListViewItemCellGUI(
Rect rect,
float rowHeight,
ViewQueryResult queryResult,
BranchListViewItem item,
BranchesListColumn column,
Action avatarLoadedAction,
bool isHiddenBranchesMode,
bool isSelected,
bool isFocused,
bool isBoldText)
{
RepObjectInfo repObjectInfo = queryResult.GetRepObjectInfo(item.ObjectInfo);
string columnText = RepObjectInfoView.GetColumnText(
queryResult.GetRepositorySpec(item.ObjectInfo),
repObjectInfo,
BranchesListHeaderState.GetColumnName(column));
if (column == BranchesListColumn.Name)
{
DrawTreeViewItem.ForItemCell(
rect,
rowHeight,
-1,
isHiddenBranchesMode ?
Images.GetHideIcon() :
Images.GetBranchIcon(),
null,
null,
columnText,
isSelected,
isFocused,
isBoldText,
false,
false,
DrawTreeViewItem.TextTrimming.Path);
return;
}
if (column == BranchesListColumn.CreatedBy)
{
DrawTreeViewItem.ForItemCell(
rect,
rowHeight,
-1,
GetAvatar.ForEmail(columnText, avatarLoadedAction),
null,
null,
columnText,
isSelected,
isFocused,
isBoldText,
false);
return;
}
if (column == BranchesListColumn.CreationDate)
{
DrawTreeViewItem.ForLabel(
rect,
new GUIContent(
Time.GetLongTimeAgoString(repObjectInfo.LocalTimeStamp),
columnText),
isSelected,
isFocused,
isBoldText);
return;
}
DrawTreeViewItem.ForLabel(
rect,
columnText,
isSelected,
isFocused,
isBoldText);
}
static ViewQueryResult BuildViewQueryResult(
EnumQueryObjectType objectType, IPlasticTree treeModel, RepositorySpec repositorySpec)
{
IList<object> resultObjects = new List<object>();
foreach (BranchTreeNode node in treeModel.GetNodes())
{
resultObjects.Add(node.BranchInfo);
}
return new ViewQueryResult(objectType, resultObjects, repositorySpec);
}
ListViewItemIds<object> mListViewItemIds = new ListViewItemIds<object>();
ViewQueryResult mQueryResult;
readonly DelayedActionBySecondsRunner mDelayedFilterAction;
readonly DelayedActionBySecondsRunner mDelayedSelectionRunner;
readonly Action<IEnumerable<object>> mAfterItemsChangedAction;
readonly Func<bool> mGetIsHiddenBranchesMode;
readonly Action mDelayedSelectionChangedAction;
readonly IGetWorkingObject mGetWorkingObject;
readonly IGetRepositorySpec mGetRepositorySpec;
readonly Action mDoubleClickAction;
readonly BranchesViewMenu mMenu;
readonly List<string> mColumnNames;
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 1b909cb14b9a08c45b5d03f0b61feecb
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,97 @@
using System.Collections.Generic;
using System.Linq;
using Codice.CM.Common;
using PlasticGui;
using PlasticGui.WorkspaceWindow.QueryViews.Branches;
using Unity.PlasticSCM.Editor.UI.Tree;
namespace Unity.PlasticSCM.Editor.Views.Branches
{
internal static class BranchesSelection
{
internal static void SelectBranches(
BranchesListView listView,
List<RepObjectInfo> branchesToSelect,
int defaultRow)
{
if (branchesToSelect == null || branchesToSelect.Count == 0)
{
TableViewOperations.SelectFirstRow(listView);
return;
}
listView.SelectRepObjectInfos(branchesToSelect);
if (listView.HasSelection())
return;
TableViewOperations.SelectDefaultRow(listView, defaultRow);
if (listView.HasSelection())
return;
TableViewOperations.SelectFirstRow(listView);
}
internal static List<RepObjectInfo> GetSelectedRepObjectInfos(
BranchesListView listView)
{
return listView.GetSelectedRepObjectInfos();
}
internal static int GetSelectedVisibleBranchesCount(
BranchesListView listView)
{
return listView.GetSelectedVisibleItems().Count;
}
internal static BranchInfo GetSelectedBranch(
BranchesListView listView)
{
List<RepObjectInfo> selectedRepObjectsInfos = listView.GetSelectedRepObjectInfos();
if (selectedRepObjectsInfos.Count == 0)
return null;
return (BranchInfo)selectedRepObjectsInfos[0];
}
internal static List<BranchInfo> GetSelectedBranches(
BranchesListView listView)
{
return listView.GetSelectedRepObjectInfos().Cast<BranchInfo>().ToList();
}
internal static RepositorySpec GetSelectedRepository(
BranchesListView listView)
{
List<RepositorySpec> selectedRepositories = listView.GetSelectedRepositories();
if (selectedRepositories.Count == 0)
return null;
return selectedRepositories[0];
}
internal static List<RepositorySpec> GetSelectedRepositories(
BranchesListView listView)
{
return listView.GetSelectedRepositories();
}
internal static List<RepObjectInfo> GetBranchesToSelect(
BranchesListView listView, List<IPlasticTreeNode> itemsToSelect)
{
if (itemsToSelect == null || itemsToSelect.Count == 0)
return GetSelectedRepObjectInfos(listView);
List<RepObjectInfo> result = new List<RepObjectInfo>();
foreach (BranchTreeNode node in itemsToSelect)
result.Add(node.BranchInfo);
return result;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 73306fe71bf092d4495ff28ee02b766b
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,629 @@
using System;
using System.Collections.Generic;
using UnityEditor;
using UnityEditor.IMGUI.Controls;
using UnityEngine;
using Codice.Client.Common.EventTracking;
using Codice.Client.Common.Threading;
using Codice.CM.Common;
using Codice.CM.Common.Mount;
using GluonGui;
using PlasticGui;
using PlasticGui.WorkspaceWindow;
using PlasticGui.WorkspaceWindow.MergeRequest;
using PlasticGui.WorkspaceWindow.QueryViews;
using PlasticGui.WorkspaceWindow.QueryViews.Branches;
using PlasticGui.WorkspaceWindow.Update;
using Unity.PlasticSCM.Editor.AssetUtils;
using Unity.PlasticSCM.Editor.AssetUtils.Processor;
using Unity.PlasticSCM.Editor.AssetsOverlays.Cache;
using Unity.PlasticSCM.Editor.Inspector.Properties;
using Unity.PlasticSCM.Editor.Tool;
using Unity.PlasticSCM.Editor.UI;
using Unity.PlasticSCM.Editor.UI.Progress;
using Unity.PlasticSCM.Editor.UI.Tree;
using Unity.PlasticSCM.Editor.Views.Branches.Dialogs;
using Unity.PlasticSCM.Editor.Views.Merge;
using GluonIncomingChangesUpdater = PlasticGui.Gluon.WorkspaceWindow.IncomingChangesUpdater;
using IGluonUpdateReport = PlasticGui.Gluon.IUpdateReport;
#if !UNITY_6000_3_OR_NEWER
using SplitterGUILayout = Unity.PlasticSCM.Editor.UnityInternals.UnityEditor.SplitterGUILayout;
using SplitterState = Unity.PlasticSCM.Editor.UnityInternals.UnityEditor.SplitterState;
#endif
namespace Unity.PlasticSCM.Editor.Views.Branches
{
internal partial class BranchesTab :
IRefreshableView,
IQueryRefreshableView,
IBranchMenuOperations,
ILaunchCodeReviewWindow,
IGetQueryText,
IGetFilter,
FillBranchesView.IShowContentView,
FillBranchesView.IShowHiddenBranchesButton
{
internal string EmptyStateMessage { get { return mEmptyStatePanel.Text; } }
internal bool ShowHiddenBranchesForTesting { set { mShowHiddenBranches = value; } }
internal DateFilter DateFilterForTesting { set { mDateFilter = value; } }
internal IBranchMenuOperations Operations { get { return this; } }
internal BranchesListView Table { get { return mBranchesListView; } }
internal bool IsVisible { get; set; } = true; // we need to initialize it to true for the OnDelayedSelectionChanged event to be executed on tests
internal BranchesTab(
WorkspaceInfo wkInfo,
ViewHost viewHost,
WorkspaceWindow workspaceWindow,
BranchInfo branchToSelect,
IViewSwitcher viewSwitcher,
IMergeViewLauncher mergeViewLauncher,
IUpdateReport updateReport,
IGluonUpdateReport gluonUpdateReport,
IShelvedChangesUpdater shelvedChangesUpdater,
IAssetStatusCache assetStatusCache,
ISaveAssets saveAssets,
LaunchTool.IShowDownloadPlasticExeWindow showDownloadPlasticExeWindow,
LaunchTool.IProcessExecutor processExecutor,
WorkspaceOperationsMonitor workspaceOperationsMonitor,
IPendingChangesUpdater pendingChangesUpdater,
IncomingChangesUpdater developerIncomingChangesUpdater,
GluonIncomingChangesUpdater gluonIncomingChangesUpdater,
EditorWindow parentWindow,
bool isGluonMode,
bool showHiddenBranches)
{
mWkInfo = wkInfo;
mViewHost = viewHost;
mWorkspaceWindow = workspaceWindow;
mGluonUpdateReport = gluonUpdateReport;
mShelvedChangesUpdater = shelvedChangesUpdater;
mAssetStatusCache = assetStatusCache;
mSaveAssets = saveAssets;
mShowDownloadPlasticExeWindow = showDownloadPlasticExeWindow;
mProcessExecutor = processExecutor;
mWorkspaceOperationsMonitor = workspaceOperationsMonitor;
mPendingChangesUpdater = pendingChangesUpdater;
mDeveloperIncomingChangesUpdater = developerIncomingChangesUpdater;
mGluonIncomingChangesUpdater = gluonIncomingChangesUpdater;
mParentWindow = parentWindow;
mIsGluonMode = isGluonMode;
mShowHiddenBranches = showHiddenBranches;
mProgressControls = new ProgressControlsForViews();
mShelvePendingChangesQuestionerBuilder =
new ShelvePendingChangesQuestionerBuilder(parentWindow);
mEnableSwitchAndShelveFeatureDialog = new EnableSwitchAndShelveFeature(
PlasticGui.Plastic.API.GetRepositorySpec(mWkInfo),
mParentWindow);
mEmptyStatePanel = new EmptyStatePanel(parentWindow.Repaint);
mFillBranchesView = new FillBranchesView(
wkInfo,
null,
null,
this,
this,
this,
this);
BuildComponents(mFillBranchesView);
mBranchOperations = new BranchOperations(
wkInfo,
workspaceWindow,
mergeViewLauncher,
this,
ViewType.BranchesView,
mProgressControls,
updateReport,
new ApplyShelveReport(parentWindow),
new ContinueWithPendingChangesQuestionerBuilder(viewSwitcher, parentWindow),
mShelvePendingChangesQuestionerBuilder,
new ApplyShelveWithConflictsQuestionerBuilder(),
pendingChangesUpdater,
developerIncomingChangesUpdater,
shelvedChangesUpdater,
mEnableSwitchAndShelveFeatureDialog);
RefreshAndSelect(branchToSelect);
}
internal void OnEnable()
{
mSearchField.downOrUpArrowKeyPressed +=
SearchField_OnDownOrUpArrowKeyPressed;
}
internal void OnDisable()
{
mSearchField.downOrUpArrowKeyPressed -=
SearchField_OnDownOrUpArrowKeyPressed;
TreeHeaderSettings.Save(
mBranchesListView.multiColumnHeader.state,
UnityConstants.BRANCHES_TABLE_SETTINGS_NAME);
}
internal void Update()
{
mProgressControls.UpdateProgress(mParentWindow);
}
internal SerializableBranchesTabState GetSerializableState()
{
return new SerializableBranchesTabState(
BranchesSelection.GetSelectedBranch(mBranchesListView),
mShowHiddenBranches);
}
internal void OnGUI()
{
EditorGUILayout.BeginVertical();
DoActionsToolbar(
mProgressControls,
mDateFilter,
ref mShowHiddenBranches,
mSearchField,
mBranchesListView,
this);
Rect viewRect = OverlayProgress.CaptureViewRectangle();
GUI.enabled = !mProgressControls.IsOperationRunning();
Rect rect = GUILayoutUtility.GetRect(0, 100000, 0, 100000);
mBranchesListView.OnGUI(rect);
if (Event.current.type == EventType.Layout)
mShouldShowEmptyState = !mEmptyStatePanel.IsEmpty();
if (mShouldShowEmptyState)
mEmptyStatePanel.OnGUI(rect);
GUI.enabled = true;
EditorGUILayout.EndVertical();
if (mProgressControls.IsOperationRunning())
{
OverlayProgress.DoOverlayProgress(
viewRect,
mProgressControls.ProgressData.ProgressPercent,
mProgressControls.ProgressData.ProgressMessage);
}
}
internal void SetWorkingObjectInfo(BranchInfo branchInfo)
{
mFillBranchesView.UpdateWorkingObject(branchInfo, mWkInfo);
}
internal void SetLaunchToolForTesting(
LaunchTool.IShowDownloadPlasticExeWindow showDownloadPlasticExeWindow,
LaunchTool.IProcessExecutor processExecutor)
{
mShowDownloadPlasticExeWindow = showDownloadPlasticExeWindow;
mProcessExecutor = processExecutor;
}
void IRefreshableView.Refresh()
{
// VCS-1005209 - There are scenarios where the list of branches need to check for incoming changes.
// For example, deleting the active branch will automatically switch your workspace to the parent changeset,
// which might have incoming changes.
if (mDeveloperIncomingChangesUpdater != null)
mDeveloperIncomingChangesUpdater.Update(DateTime.Now);
if (mGluonIncomingChangesUpdater != null)
mGluonIncomingChangesUpdater.Update(DateTime.Now);
RefreshAndSelect(null);
}
//IQueryRefreshableView
public void RefreshAndSelect(RepObjectInfo objectToSelect)
{
List<IPlasticTreeNode> branchesToSelect = objectToSelect == null ?
null : new List<IPlasticTreeNode> { new BranchTreeNode(
null, (BranchInfo)objectToSelect, null) };
if (branchesToSelect == null && EditorWindow.focusedWindow == mParentWindow)
Selection.activeObject = null;
mFillBranchesView.FillView(
mBranchesListView,
mProgressControls,
null,
null,
null,
branchesToSelect,
FillBranchesView.ViewMode.List,
mShowHiddenBranches);
}
BranchInfo IBranchMenuOperations.GetSelectedBranch()
{
return BranchesSelection.GetSelectedBranch(mBranchesListView);
}
int IBranchMenuOperations.GetSelectedBranchesCount()
{
return BranchesSelection.GetSelectedVisibleBranchesCount(mBranchesListView);
}
bool IBranchMenuOperations.AreHiddenBranchesShown()
{
return mShowHiddenBranches;
}
void IBranchMenuOperations.CreateBranch()
{
CreateBranch();
}
void IBranchMenuOperations.CreateTopLevelBranch() { }
void IBranchMenuOperations.SwitchToBranch()
{
SwitchToBranchForMode();
}
void IBranchMenuOperations.MergeBranch()
{
mBranchOperations.MergeBranch(
BranchesSelection.GetSelectedRepository(mBranchesListView),
BranchesSelection.GetSelectedBranch(mBranchesListView));
}
void IBranchMenuOperations.CherrypickBranch() { }
void IBranchMenuOperations.MergeToBranch() { }
void IBranchMenuOperations.PullBranch() { }
void IBranchMenuOperations.PullRemoteBranch() { }
void IBranchMenuOperations.SyncWithGit() { }
void IBranchMenuOperations.PushBranch() { }
void IBranchMenuOperations.DiffBranch()
{
LaunchDiffOperations.DiffBranch(
mShowDownloadPlasticExeWindow,
mProcessExecutor,
BranchesSelection.GetSelectedRepository(mBranchesListView),
BranchesSelection.GetSelectedBranch(mBranchesListView),
mIsGluonMode);
}
void IBranchMenuOperations.DiffWithAnotherBranch() { }
void IBranchMenuOperations.ViewChangesets() { }
void IBranchMenuOperations.RenameBranch()
{
RepositorySpec repSpec = BranchesSelection.GetSelectedRepository(mBranchesListView);
BranchInfo branchInfo = BranchesSelection.GetSelectedBranch(mBranchesListView);
BranchRenameData branchRenameData = RenameBranchDialog.GetBranchRenameData(
repSpec,
branchInfo,
mParentWindow);
mBranchOperations.RenameBranch(branchRenameData);
}
void IBranchMenuOperations.HideUnhideBranch()
{
if (mShowHiddenBranches)
{
mBranchOperations.UnhideBranch(
BranchesSelection.GetSelectedRepositories(mBranchesListView),
BranchesSelection.GetSelectedBranches(mBranchesListView));
return;
}
mBranchOperations.HideBranch(
BranchesSelection.GetSelectedRepositories(mBranchesListView),
BranchesSelection.GetSelectedBranches(mBranchesListView));
}
void IBranchMenuOperations.DeleteBranch()
{
var branchesToDelete = BranchesSelection.GetSelectedBranches(mBranchesListView);
if (!DeleteBranchDialog.ConfirmDelete(mParentWindow, branchesToDelete))
return;
mBranchOperations.DeleteBranch(
BranchesSelection.GetSelectedRepositories(mBranchesListView),
branchesToDelete,
DeleteBranchOptions.IncludeChangesets,
!mShowHiddenBranches);
}
void IBranchMenuOperations.CreateCodeReview()
{
RepositorySpec repSpec = BranchesSelection.GetSelectedRepository(mBranchesListView);
BranchInfo branchInfo = BranchesSelection.GetSelectedBranch(mBranchesListView);
NewCodeReviewBehavior choice = SelectNewCodeReviewBehavior.For(repSpec.Server);
switch (choice)
{
case NewCodeReviewBehavior.CreateAndOpenInDesktop:
mBranchOperations.CreateReview(repSpec, branchInfo, this);
break;
case NewCodeReviewBehavior.RequestFromUnityCloud:
OpenRequestReviewPage.ForBranch(repSpec, branchInfo.BranchId);
break;
case NewCodeReviewBehavior.Ask:
default:
break;
}
}
void ILaunchCodeReviewWindow.Show(
WorkspaceInfo wkInfo,
RepositorySpec repSpec,
ReviewInfo reviewInfo,
RepObjectInfo repObjectInfo,
bool bShowReviewChangesTab)
{
LaunchTool.OpenCodeReview(
mShowDownloadPlasticExeWindow,
mProcessExecutor,
repSpec,
reviewInfo.Id,
mIsGluonMode);
}
void IBranchMenuOperations.CreateMergeRequest() { }
void IBranchMenuOperations.ViewPermissions() { }
string IGetQueryText.Get()
{
return QueryConstants.BuildBranchesQuery(
mDateFilter.GetLayoutFilter(), mShowHiddenBranches);
}
Filter IGetFilter.Get()
{
return new Filter(mBranchesListView.searchString);
}
void IGetFilter.Clear()
{
// Not used by the Plugin, needed for the Reset filters button
}
void FillBranchesView.IShowContentView.ShowContentPanel()
{
mEmptyStatePanel.UpdateContent(string.Empty);
}
void FillBranchesView.IShowContentView.ShowEmptyStatePanel(
string explanationText, bool showResetFilterButton)
{
mEmptyStatePanel.UpdateContent(explanationText);
}
bool FillBranchesView.IShowHiddenBranchesButton.IsChecked
{
get { return mShowHiddenBranches; }
set { mShowHiddenBranches = value; }
}
void SearchField_OnDownOrUpArrowKeyPressed()
{
mBranchesListView.SetFocusAndEnsureSelectedItem();
}
void OnDelayedSelectionChanged()
{
if (EditorWindow.focusedWindow != mParentWindow)
return;
if (!IsVisible)
return;
List<RepObjectInfo> selectedBranches = BranchesSelection.
GetSelectedRepObjectInfos(mBranchesListView);
if (selectedBranches.Count != 1)
return;
RepositorySpec repSpec = BranchesSelection.GetSelectedRepository(mBranchesListView);
MountPointWithPath mountPoint = MountPointWithPath.BuildWorkspaceRootMountPoint(repSpec);
RepObjectInfo cachedBranch = selectedBranches[0];
BranchInfo resolvedBranch = null;
IThreadWaiter waiter = ThreadWaiter.GetWaiter(10);
waiter.Execute(
threadOperationDelegate: delegate
{
resolvedBranch = PlasticGui.Plastic.API.GetBranchInfo(
repSpec, cachedBranch.GUID);
},
afterOperationDelegate: delegate
{
if (waiter.Exception != null)
{
ExceptionsHandler.DisplayException(waiter.Exception);
return;
}
List<RepObjectInfo> selectedBranches = BranchesSelection.
GetSelectedRepObjectInfos(mBranchesListView);
if (selectedBranches.Count != 1 || !selectedBranches[0].Equals(cachedBranch))
return;
SelectedRepObjectInfoData.SetActiveObject(resolvedBranch, repSpec, mountPoint);
});
}
static void DoActionsToolbar(
ProgressControlsForViews progressControls,
DateFilter dateFilter,
ref bool showHiddenBranchesButton,
SearchField searchField,
BranchesListView branchesListView,
IRefreshableView view)
{
EditorGUILayout.BeginHorizontal(EditorStyles.toolbar);
if (GUILayout.Button(
new GUIContent(Images.GetRefreshIcon(),
PlasticLocalization.Name.RefreshButton.GetString()),
UnityStyles.ToolbarButtonLeft,
GUILayout.Width(UnityConstants.TOOLBAR_ICON_BUTTON_WIDTH)))
{
view.Refresh();
}
DrawDateFilter(progressControls, dateFilter, view);
GUILayout.FlexibleSpace();
DrawShowHiddenBranchesButton(
progressControls, ref showHiddenBranchesButton, branchesListView, view);
GUILayout.Space(2);
DrawSearchField.For(
searchField,
branchesListView,
UnityConstants.SEARCH_FIELD_WIDTH);
EditorGUILayout.EndHorizontal();
}
static void DrawDateFilter(
ProgressControlsForViews progressControls,
DateFilter dateFilter,
IRefreshableView view)
{
GUI.enabled = !progressControls.IsOperationRunning();
EditorGUI.BeginChangeCheck();
dateFilter.FilterType = (DateFilter.Type)
EditorGUILayout.EnumPopup(
dateFilter.FilterType,
EditorStyles.toolbarDropDown,
GUILayout.Width(UnityConstants.TOOLBAR_DATE_FILTER_COMBO_WIDTH));
if (EditorGUI.EndChangeCheck())
{
EnumPopupSetting<DateFilter.Type>.Save(
dateFilter.FilterType,
UnityConstants.BRANCHES_DATE_FILTER_SETTING_NAME);
view.Refresh();
}
GUI.enabled = true;
}
static void DrawShowHiddenBranchesButton(
ProgressControlsForViews progressControls,
ref bool showHiddenBranches,
BranchesListView branchesListView,
IRefreshableView view)
{
GUI.enabled = !progressControls.IsOperationRunning();
EditorGUI.BeginChangeCheck();
showHiddenBranches = GUILayout.Toggle(
showHiddenBranches,
new GUIContent(
showHiddenBranches ?
Images.GetUnhideIcon() :
Images.GetHideIcon(),
showHiddenBranches ?
PlasticLocalization.Name.DontShowHiddenBranchesTooltip.GetString() :
PlasticLocalization.Name.ShowHiddenBranchesTooltip.GetString()),
EditorStyles.toolbarButton,
GUILayout.Width(UnityConstants.TOOLBAR_ICON_BUTTON_WIDTH));
if (EditorGUI.EndChangeCheck())
{
TrackFeatureUseEvent.For(
BranchesSelection.GetSelectedRepository(branchesListView),
TrackFeatureUseEvent.Features.Branches.ToggleShowHiddenBranches);
view.Refresh();
}
GUI.enabled = true;
}
void BuildComponents(FillBranchesView fillBranchesView)
{
mSearchField = new SearchField();
mSearchField.downOrUpArrowKeyPressed += SearchField_OnDownOrUpArrowKeyPressed;
DateFilter.Type dateFilterType =
EnumPopupSetting<DateFilter.Type>.Load(
UnityConstants.BRANCHES_DATE_FILTER_SETTING_NAME,
DateFilter.Type.LastMonth);
mDateFilter = new DateFilter(dateFilterType);
BranchesListHeaderState headerState =
BranchesListHeaderState.GetDefault();
TreeHeaderSettings.Load(headerState,
UnityConstants.BRANCHES_TABLE_SETTINGS_NAME,
(int)BranchesListColumn.CreationDate, false);
mBranchesListView = new BranchesListView(
headerState,
BranchesListHeaderState.GetColumnNames(),
new BranchesViewMenu(this, mGluonIncomingChangesUpdater != null),
fillBranchesView,
fillBranchesView,
() => mShowHiddenBranches,
delayedSelectionChangedAction: OnDelayedSelectionChanged,
doubleClickAction: ((IBranchMenuOperations)this).DiffBranch,
afterItemsChangedAction: fillBranchesView.ShowContentOrEmptyState);
mBranchesListView.Reload();
}
bool mShouldShowEmptyState;
bool mShowHiddenBranches;
DateFilter mDateFilter;
SearchField mSearchField;
BranchesListView mBranchesListView;
LaunchTool.IProcessExecutor mProcessExecutor;
LaunchTool.IShowDownloadPlasticExeWindow mShowDownloadPlasticExeWindow;
readonly BranchOperations mBranchOperations;
readonly FillBranchesView mFillBranchesView;
readonly EmptyStatePanel mEmptyStatePanel;
readonly SwitchAndShelve.IEnableSwitchAndShelveFeatureDialog mEnableSwitchAndShelveFeatureDialog;
readonly IShelvePendingChangesQuestionerBuilder mShelvePendingChangesQuestionerBuilder;
readonly ProgressControlsForViews mProgressControls;
readonly bool mIsGluonMode;
readonly EditorWindow mParentWindow;
readonly IPendingChangesUpdater mPendingChangesUpdater;
readonly GluonIncomingChangesUpdater mGluonIncomingChangesUpdater;
readonly IncomingChangesUpdater mDeveloperIncomingChangesUpdater;
readonly WorkspaceOperationsMonitor mWorkspaceOperationsMonitor;
readonly ISaveAssets mSaveAssets;
readonly IAssetStatusCache mAssetStatusCache;
readonly IShelvedChangesUpdater mShelvedChangesUpdater;
readonly IGluonUpdateReport mGluonUpdateReport;
readonly WorkspaceWindow mWorkspaceWindow;
readonly ViewHost mViewHost;
readonly WorkspaceInfo mWkInfo;
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 2350e7d7f6d79024da24dea8f15a6881
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,174 @@
using Codice.Client.Common.Threading;
using Codice.CM.Common;
using Codice.LogWrapper;
using GluonGui.WorkspaceWindow.Views.WorkspaceExplorer.Explorer;
using PlasticGui.WorkspaceWindow.QueryViews.Branches;
using Unity.PlasticSCM.Editor.AssetUtils;
using Unity.PlasticSCM.Editor.UI;
using Unity.PlasticSCM.Editor.Views.Branches.Dialogs;
namespace Unity.PlasticSCM.Editor.Views.Branches
{
internal partial class BranchesTab
{
void SwitchToBranchForMode()
{
bool isCancelled;
mSaveAssets.UnderWorkspaceWithConfirmation(
mWkInfo.ClientPath, mWorkspaceOperationsMonitor,
canContinueWithDirtyScenes: false,
out isCancelled);
if (isCancelled)
return;
if (mIsGluonMode)
{
SwitchToBranchForGluon();
return;
}
SwitchToBranchForDeveloper();
}
void SwitchToBranchForDeveloper()
{
RepositorySpec repSpec = BranchesSelection.GetSelectedRepository(mBranchesListView);
BranchInfo branchInfo = BranchesSelection.GetSelectedBranch(mBranchesListView);
mBranchOperations.SwitchToBranch(
repSpec,
branchInfo,
RefreshAsset.BeforeLongAssetOperation,
items => RefreshAsset.AfterLongAssetOperation(
mAssetStatusCache,
ProjectPackages.ShouldBeResolvedFromUpdateReport(mWkInfo, items)));
}
void SwitchToBranchForGluon()
{
BranchInfo branchInfo = BranchesSelection.GetSelectedBranch(mBranchesListView);
new SwitchToUIOperation().SwitchToBranch(
mWkInfo,
branchInfo,
mViewHost,
mPendingChangesUpdater,
mGluonIncomingChangesUpdater,
new UnityPlasticGuiMessage(),
mProgressControls,
mWorkspaceWindow.GluonProgressOperationHandler,
mGluonUpdateReport,
mWorkspaceWindow,
mShelvePendingChangesQuestionerBuilder,
mShelvedChangesUpdater,
mEnableSwitchAndShelveFeatureDialog,
RefreshAsset.BeforeLongAssetOperation,
items => RefreshAsset.AfterLongAssetOperation(
mAssetStatusCache,
ProjectPackages.ShouldBeResolvedFromPaths(mWkInfo, items)));
}
void CreateBranch()
{
if (BranchesSelection.GetSelectedVisibleBranchesCount(mBranchesListView) > 0)
{
CreateBranchFromSelectedBranch();
return;
}
CreateBranchFromMainOrCurrentBranch();
}
void CreateBranchFromSelectedBranch()
{
RepositorySpec repSpec = BranchesSelection.GetSelectedRepository(mBranchesListView);
BranchInfo branchInfo = BranchesSelection.GetSelectedBranch(mBranchesListView);
BranchCreationData branchCreationData = CreateBranchDialog.CreateBranchFromLastParentBranchChangeset(
mParentWindow, repSpec, branchInfo, null);
CreateBranchForMode(branchCreationData);
}
void CreateBranchFromMainOrCurrentBranch()
{
RepositorySpec repSpec = null;
BranchInfo currentBranchInfo = null;
BranchInfo mainBranchInfo = null;
IThreadWaiter waiter = ThreadWaiter.GetWaiter();
waiter.Execute(
/*threadOperationDelegate*/ delegate
{
repSpec = PlasticGui.Plastic.API.GetRepositorySpec(mWkInfo);
currentBranchInfo = PlasticGui.Plastic.API.GetWorkingBranch(mWkInfo);
mainBranchInfo = PlasticGui.Plastic.API.GetMainBranch(mWkInfo);
},
/*afterOperationDelegate*/ delegate
{
if (waiter.Exception != null)
{
ExceptionsHandler.LogException(typeof(BranchesTab).Name, waiter.Exception);
return;
}
if (repSpec == null || currentBranchInfo == null || mainBranchInfo == null)
{
mLog.DebugFormat("Error obtaining the base information for the branch creation");
return;
}
BranchCreationData branchCreationData = CreateBranchDialog.CreateBranchFromMainOrCurrentBranch(
mParentWindow, repSpec, mainBranchInfo, currentBranchInfo, null);
CreateBranchForMode(branchCreationData);
});
}
void CreateBranchForMode(BranchCreationData branchCreationData)
{
if (mIsGluonMode)
{
CreateBranchForGluon(branchCreationData);
return;
}
CreateBranchForDeveloper(branchCreationData);
}
void CreateBranchForDeveloper(BranchCreationData branchCreationData)
{
mBranchOperations.CreateBranch(
branchCreationData,
RefreshAsset.BeforeLongAssetOperation,
items => RefreshAsset.AfterLongAssetOperation(
mAssetStatusCache,
ProjectPackages.ShouldBeResolvedFromUpdateReport(mWkInfo, items)));
}
void CreateBranchForGluon(BranchCreationData branchCreationData)
{
CreateBranchOperation.CreateBranch(
mWkInfo,
branchCreationData,
mViewHost,
mPendingChangesUpdater,
mGluonIncomingChangesUpdater,
new UnityPlasticGuiMessage(),
mProgressControls,
mWorkspaceWindow.GluonProgressOperationHandler,
mGluonUpdateReport,
mWorkspaceWindow,
mShelvePendingChangesQuestionerBuilder,
mShelvedChangesUpdater,
mEnableSwitchAndShelveFeatureDialog,
RefreshAsset.BeforeLongAssetOperation,
items => RefreshAsset.AfterLongAssetOperation(
mAssetStatusCache,
ProjectPackages.ShouldBeResolvedFromPaths(mWkInfo, items)));
}
static readonly ILog mLog = PlasticApp.GetLogger("BranchesTab");
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 732707d2b1ec963458b4ab9ffe539cbe
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,299 @@
using UnityEditor;
using UnityEngine;
using Codice.CM.Common;
using PlasticGui;
using PlasticGui.WorkspaceWindow.QueryViews.Branches;
using Unity.PlasticSCM.Editor.UI;
namespace Unity.PlasticSCM.Editor.Views.Branches
{
internal class BranchesViewMenu
{
internal GenericMenu Menu { get { return mMenu; } }
internal BranchesViewMenu(
IBranchMenuOperations branchMenuOperations,
bool isGluonMode)
{
mBranchMenuOperations = branchMenuOperations;
mIsGluonMode = isGluonMode;
BuildComponents();
}
internal void Popup()
{
mMenu = new GenericMenu();
UpdateMenuItems(mMenu);
mMenu.ShowAsContext();
}
internal bool ProcessKeyActionIfNeeded(Event e)
{
BranchMenuOperations operationToExecute = GetMenuOperations(e);
if (operationToExecute == BranchMenuOperations.None)
return false;
BranchMenuOperations operations =
BranchMenuUpdater.GetAvailableMenuOperations(
mBranchMenuOperations.GetSelectedBranchesCount(),
mIsGluonMode,
false);
if (!operations.HasFlag(operationToExecute))
return false;
ProcessMenuOperation(operationToExecute, mBranchMenuOperations);
return true;
}
void CreateBranchMenuItem_Click()
{
mBranchMenuOperations.CreateBranch();
}
void SwitchToBranchMenuItem_Click()
{
mBranchMenuOperations.SwitchToBranch();
}
void RenameBranchMenuItem_Click()
{
mBranchMenuOperations.RenameBranch();
}
void HideUnhideBranchMenuItem_Click()
{
mBranchMenuOperations.HideUnhideBranch();
}
void DeleteBranchMenuItem_Click()
{
mBranchMenuOperations.DeleteBranch();
}
void MergeBranchMenuItem_Click()
{
mBranchMenuOperations.MergeBranch();
}
void DiffBranchMenuItem_Click()
{
mBranchMenuOperations.DiffBranch();
}
void CreateCodeReviewMenuItem_Click()
{
mBranchMenuOperations.CreateCodeReview();
}
void UpdateMenuItems(GenericMenu menu)
{
BranchMenuOperations operations = BranchMenuUpdater.GetAvailableMenuOperations(
mBranchMenuOperations.GetSelectedBranchesCount(), mIsGluonMode, false);
AddBranchMenuItem(
mCreateBranchMenuItemContent,
menu,
operations,
BranchMenuOperations.CreateBranch,
CreateBranchMenuItem_Click);
AddBranchMenuItem(
mSwitchToBranchMenuItemContent,
menu,
operations,
BranchMenuOperations.SwitchToBranch,
SwitchToBranchMenuItem_Click);
if (!mIsGluonMode)
{
menu.AddSeparator(string.Empty);
AddBranchMenuItem(
mMergeBranchMenuItemContent,
menu,
operations,
BranchMenuOperations.MergeBranch,
MergeBranchMenuItem_Click);
}
menu.AddSeparator(string.Empty);
mDiffBranchMenuItemContent.text = string.Format("{0} {1}",
PlasticLocalization.Name.DiffBranchMenuItem.GetString(GetSelectedBranchName()),
GetPlasticShortcut.ForDiff());
AddBranchMenuItem(
mDiffBranchMenuItemContent,
menu,
operations,
BranchMenuOperations.DiffBranch,
DiffBranchMenuItem_Click);
menu.AddSeparator(string.Empty);
AddBranchMenuItem(
mRenameBranchMenuItemContent,
menu,
operations,
BranchMenuOperations.Rename,
RenameBranchMenuItem_Click);
mHideUnhideBranchMenuItemContent.text = string.Format("{0} {1}",
mBranchMenuOperations.AreHiddenBranchesShown() ?
PlasticLocalization.Name.BranchMenuItemUnhideBranch.GetString() :
PlasticLocalization.Name.BranchMenuItemHideBranch.GetString(),
GetPlasticShortcut.ForHideUnhide());
AddBranchMenuItem(
mHideUnhideBranchMenuItemContent,
menu,
operations,
BranchMenuOperations.HideUnhide,
HideUnhideBranchMenuItem_Click);
AddBranchMenuItem(
mDeleteBranchMenuItemContent,
menu,
operations,
BranchMenuOperations.Delete,
DeleteBranchMenuItem_Click);
menu.AddSeparator(string.Empty);
AddBranchMenuItem(
mCreateCodeReviewMenuItemContent,
menu,
operations,
BranchMenuOperations.CreateCodeReview,
CreateCodeReviewMenuItem_Click);
}
string GetSelectedBranchName()
{
if (mBranchMenuOperations.GetSelectedBranchesCount() == 0)
return string.Empty;
BranchInfo branchInfo = mBranchMenuOperations.GetSelectedBranch();
return GetShorten.BranchNameFromBranch(branchInfo);
}
static void AddBranchMenuItem(
GUIContent menuItemContent,
GenericMenu menu,
BranchMenuOperations operations,
BranchMenuOperations operationsToCheck,
GenericMenu.MenuFunction menuFunction)
{
if (operations.HasFlag(operationsToCheck))
{
menu.AddItem(
menuItemContent,
false,
menuFunction);
return;
}
menu.AddDisabledItem(menuItemContent);
}
static void ProcessMenuOperation(
BranchMenuOperations operationToExecute,
IBranchMenuOperations branchMenuOperations)
{
if (operationToExecute == BranchMenuOperations.Rename)
{
branchMenuOperations.RenameBranch();
return;
}
if (operationToExecute == BranchMenuOperations.Delete)
{
branchMenuOperations.DeleteBranch();
return;
}
if (operationToExecute == BranchMenuOperations.MergeBranch)
{
branchMenuOperations.MergeBranch();
return;
}
if (operationToExecute == BranchMenuOperations.DiffBranch)
{
branchMenuOperations.DiffBranch();
return;
}
if (operationToExecute == BranchMenuOperations.HideUnhide)
{
branchMenuOperations.HideUnhideBranch();
return;
}
}
static BranchMenuOperations GetMenuOperations(Event e)
{
if (Keyboard.IsKeyPressed(e, KeyCode.F2))
return BranchMenuOperations.Rename;
if (Keyboard.IsKeyPressed(e, KeyCode.Delete))
return BranchMenuOperations.Delete;
if (Keyboard.IsControlOrCommandKeyPressed(e) &&
Keyboard.IsKeyPressed(e, KeyCode.M))
return BranchMenuOperations.MergeBranch;
if (Keyboard.IsControlOrCommandKeyPressed(e) &&
Keyboard.IsKeyPressed(e, KeyCode.D))
return BranchMenuOperations.DiffBranch;
if (Keyboard.IsControlOrCommandKeyPressed(e) &&
Keyboard.IsKeyPressed(e, KeyCode.H))
return BranchMenuOperations.HideUnhide;
return BranchMenuOperations.None;
}
void BuildComponents()
{
mCreateBranchMenuItemContent = new GUIContent(
PlasticLocalization.GetString(PlasticLocalization.Name.BranchMenuItemCreateBranch));
mSwitchToBranchMenuItemContent = new GUIContent(
PlasticLocalization.GetString(PlasticLocalization.Name.BranchMenuItemSwitchToBranch));
mMergeBranchMenuItemContent = new GUIContent(string.Format("{0} {1}",
PlasticLocalization.GetString(PlasticLocalization.Name.BranchMenuItemMergeFromBranch),
GetPlasticShortcut.ForMerge()));
mDiffBranchMenuItemContent = new GUIContent();
mRenameBranchMenuItemContent = new GUIContent(string.Format("{0} {1}",
PlasticLocalization.GetString(PlasticLocalization.Name.BranchMenuItemRenameBranch),
GetPlasticShortcut.ForRename()));
mHideUnhideBranchMenuItemContent = new GUIContent();
mDeleteBranchMenuItemContent = new GUIContent(string.Format("{0} {1}",
PlasticLocalization.GetString(PlasticLocalization.Name.BranchMenuItemDeleteBranch),
GetPlasticShortcut.ForDelete()));
mCreateCodeReviewMenuItemContent = new GUIContent(
PlasticLocalization.Name.BranchMenuCreateANewCodeReview.GetString());
}
GenericMenu mMenu;
GUIContent mCreateBranchMenuItemContent;
GUIContent mSwitchToBranchMenuItemContent;
GUIContent mMergeBranchMenuItemContent;
GUIContent mDiffBranchMenuItemContent;
GUIContent mRenameBranchMenuItemContent;
GUIContent mHideUnhideBranchMenuItemContent;
GUIContent mDeleteBranchMenuItemContent;
GUIContent mCreateCodeReviewMenuItemContent;
readonly IBranchMenuOperations mBranchMenuOperations;
readonly bool mIsGluonMode;
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: a1f5156c89fd104459e8ec0cc3098899
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 16e16045695760047a9bd172458c5d6b
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,373 @@
using UnityEditor;
using UnityEngine;
using Codice.Client.Common;
using Codice.CM.Common;
using PlasticGui;
using PlasticGui.WorkspaceWindow;
using PlasticGui.WorkspaceWindow.QueryViews.Branches;
using Unity.PlasticSCM.Editor.UI;
#if !UNITY_6000_3_OR_NEWER
using EditorGUI = Unity.PlasticSCM.Editor.UnityInternals.UnityEditor.EditorGUI;
#endif
namespace Unity.PlasticSCM.Editor.Views.Branches.Dialogs
{
class CreateBranchDialog : PlasticDialog
{
internal BranchInfo SelectedBranchBase { get { return mSelectedBaseBranch; } }
internal string NewBranchName { get { return mNewBranchName; } set { mNewBranchName = value; } }
internal bool AllowToChangeBaseBranch { get { return mAllowToChangeBaseBranch; } }
protected override Rect DefaultRect
{
get
{
var baseRect = base.DefaultRect;
return new Rect(baseRect.x, baseRect.y, 710, baseRect.height);
}
}
protected override string GetTitle()
{
return mAllowToChangeBaseBranch ?
PlasticLocalization.Name.CreateChildBranchBasedOnTitle.GetString() :
PlasticLocalization.Name.CreateChildBranchTitle.GetString();
}
protected override void DoComponentsArea()
{
DoTopArea();
DoFieldsArea();
}
internal static BranchCreationData CreateBranchFromMainOrCurrentBranch(
EditorWindow parentWindow,
RepositorySpec repSpec,
BranchInfo mainBranch,
BranchInfo currentBranch,
string proposedBranchName)
{
string changesetStr = PlasticLocalization.Name.LastChangeset.GetString();
string explanation = BranchCreationUserInfo.GetFromObjectString(
repSpec, currentBranch, changesetStr);
return CreateBranch(
parentWindow,
repSpec,
mainBranch,
mainBranch,
currentBranch,
-1,
explanation,
true,
proposedBranchName);
}
internal static BranchCreationData CreateBranchFromLastParentBranchChangeset(
EditorWindow parentWindow,
RepositorySpec repSpec,
BranchInfo parentBranchInfo,
string proposedBranchName)
{
string changesetStr = PlasticLocalization.Name.LastChangeset.GetString();
string explanation = BranchCreationUserInfo.GetFromObjectString(
repSpec, parentBranchInfo, changesetStr);
return CreateBranch(
parentWindow,
repSpec,
parentBranchInfo,
null,
null,
-1,
explanation,
false,
proposedBranchName);
}
internal static BranchCreationData CreateBranchFromChangeset(
EditorWindow parentWindow,
RepositorySpec repSpec,
ChangesetInfo changesetInfo,
string proposedBranchName)
{
BranchInfo parentBranchInfo = BranchInfoCache.GetBranch(
repSpec, changesetInfo.BranchId);
string changesetStr = SpecPreffix.CHANGESET + changesetInfo.ChangesetId.ToString();
string explanation = BranchCreationUserInfo.GetFromObjectString(
repSpec, parentBranchInfo, changesetStr);
return CreateBranch(
parentWindow,
repSpec,
parentBranchInfo,
null,
null,
changesetInfo.ChangesetId,
explanation,
false,
proposedBranchName);
}
internal static BranchCreationData CreateBranchFromLabel(
EditorWindow parentWindow,
RepositorySpec repSpec,
MarkerExtendedInfo labelInfo)
{
BranchInfo parentBranchInfo = BranchInfoCache.GetBranch(
repSpec, labelInfo.BranchId);
string explanation = BranchCreationUserInfo.GetFromObjectString(
repSpec, labelInfo);
return CreateBranch(
parentWindow,
repSpec,
parentBranchInfo,
null,
null,
labelInfo.Changeset,
explanation,
false,
null);
}
internal void CheckMainBranchRadioToggle()
{
mIsMainBranchSelected = true;
mIsCurrentBranchSelected = false;
mSelectedBaseBranch = mMainBranch;
}
internal void CheckCurrentBranchRadioToggle()
{
mIsMainBranchSelected = false;
mIsCurrentBranchSelected = true;
mSelectedBaseBranch = mCurrentBranch;
}
static BranchCreationData CreateBranch(
EditorWindow parentWindow,
RepositorySpec repSpec,
BranchInfo baseBranch,
BranchInfo mainBranch,
BranchInfo currentBranch,
long changesetId,
string explanation,
bool allowToChangeBaseBranch,
string proposedBranchName)
{
CreateBranchDialog dialog = Create(
repSpec,
baseBranch,
mainBranch,
currentBranch,
changesetId,
explanation,
allowToChangeBaseBranch,
proposedBranchName);
ResponseType dialogueResult = dialog.RunModal(parentWindow);
BranchCreationData result = dialog.BuildCreationData();
result.Result = dialogueResult == ResponseType.Ok;
return result;
}
void DoTopArea()
{
if (mAllowToChangeBaseBranch)
{
DoBranchSelectionArea();
return;
}
Paragraph(string.Format("{0} {1}",
PlasticLocalization.Name.CreateChildBranchExplanation.GetString(), mExplanation));
}
void DoBranchSelectionArea()
{
int descriptionLabelLeftMargin = 25;
GUILayout.BeginVertical();
if (GUILayout.Toggle(
mIsMainBranchSelected,
GetBranchName.FromFullBranchName(mMainBranch.Name),
UnityStyles.Dialog.BoldRadioToggle))
{
mIsMainBranchSelected = true;
mIsCurrentBranchSelected = false;
mSelectedBaseBranch = mMainBranch;
}
GUILayout.BeginHorizontal();
GUILayout.Space(descriptionLabelLeftMargin);
GUILayout.Label(
PlasticLocalization.Name.CreateChildBranchBasedOnMainExplanation.GetString(),
EditorStyles.miniLabel);
GUILayout.EndHorizontal();
if (GUILayout.Toggle(
mIsCurrentBranchSelected,
GetBranchName.FromFullBranchName(mCurrentBranch.Name),
UnityStyles.Dialog.BoldRadioToggle))
{
mIsMainBranchSelected = false;
mIsCurrentBranchSelected = true;
mSelectedBaseBranch = mCurrentBranch;
}
GUILayout.BeginHorizontal();
GUILayout.Space(descriptionLabelLeftMargin);
GUILayout.Label(
PlasticLocalization.Name.CreateChildBranchBasedOnCurrentBranchExplanation.GetString(),
EditorStyles.miniLabel);
GUILayout.EndHorizontal();
GUILayout.Space(15);
GUILayout.EndVertical();
}
void DoFieldsArea()
{
GUILayout.BeginVertical();
using (new EditorGUILayout.HorizontalScope())
{
GUILayout.Label(
PlasticLocalization.Name.BranchNameEntry.GetString(),
GUILayout.Width(100));
Rect nameRect = GUILayoutUtility.GetRect(
new GUIContent(string.Empty),
EditorStyles.textField,
GUILayout.ExpandWidth(true));
GUI.SetNextControlName(NAME_FIELD_CONTROL_NAME);
mNewBranchName = UnityEditor.EditorGUI.TextField(nameRect, mNewBranchName);
FocusTextAreaIfNeeded(NAME_FIELD_CONTROL_NAME);
}
GUILayout.Space(5);
using (new EditorGUILayout.HorizontalScope())
{
using (new EditorGUILayout.VerticalScope(GUILayout.Width(100)))
{
GUILayout.Space(49);
GUILayout.Label(
PlasticLocalization.Name.CommentsEntry.GetString(),
GUILayout.Width(100));
}
Rect commentRect = GUILayoutUtility.GetRect(
new GUIContent(string.Empty),
EditorStyles.textArea,
GUILayout.Height(100),
GUILayout.ExpandWidth(true));
GUI.SetNextControlName(COMMENT_TEXTAREA_CONTROL_NAME);
mComment = EditorGUI.ScrollableTextAreaInternal(
commentRect,
mComment,
ref mScrollPosition,
EditorStyles.textArea);
}
GUILayout.Space(15);
mSwitchToBranch = GUILayout.Toggle(
mSwitchToBranch,
PlasticLocalization.Name.SwitchToBranchCheckButton.GetString());
GUILayout.Space(5);
GUILayout.EndVertical();
}
Vector2 mScrollPosition;
internal override void OkButtonAction()
{
BranchCreationValidation.AsyncValidation(
BuildCreationData(), this, mProgressControls);
}
internal static CreateBranchDialog Create(
RepositorySpec repSpec,
BranchInfo baseBranch,
BranchInfo mainBranch,
BranchInfo currentBranch,
long changesetId,
string explanation,
bool allowToChangeBaseBranch,
string proposedBranchName)
{
CreateBranchDialogAssertions.AssertValidBaseBranchChangeArguments(
mainBranch,
currentBranch,
allowToChangeBaseBranch);
if (allowToChangeBaseBranch && currentBranch.IsMainBranch())
allowToChangeBaseBranch = false;
var instance = CreateInstance<CreateBranchDialog>();
instance.IsResizable = false;
instance.mEnterKeyAction = instance.OkButtonAction;
instance.AddControlConsumingEnterKey(COMMENT_TEXTAREA_CONTROL_NAME);
instance.mEscapeKeyAction = instance.CloseButtonAction;
instance.mOkButtonText = PlasticLocalization.Name.CreateButton.GetString();
instance.mRepositorySpec = repSpec;
instance.mSelectedBaseBranch = baseBranch;
instance.mMainBranch = mainBranch;
instance.mCurrentBranch = currentBranch;
instance.mAllowToChangeBaseBranch = allowToChangeBaseBranch;
instance.mNewBranchName = proposedBranchName == null ?
string.Empty : proposedBranchName;
instance.mComment = "";
instance.mSwitchToBranch = true;
instance.mExplanation = explanation;
instance.mChangesetId = changesetId;
return instance;
}
BranchCreationData BuildCreationData()
{
return new BranchCreationData(
mRepositorySpec,
mSelectedBaseBranch,
mChangesetId,
mNewBranchName,
mComment,
null,
mSwitchToBranch);
}
RepositorySpec mRepositorySpec;
BranchInfo mSelectedBaseBranch;
BranchInfo mMainBranch;
BranchInfo mCurrentBranch;
bool mAllowToChangeBaseBranch;
long mChangesetId;
string mNewBranchName;
string mComment;
bool mSwitchToBranch;
string mExplanation;
bool mIsMainBranchSelected = true;
bool mIsCurrentBranchSelected;
const string NAME_FIELD_CONTROL_NAME = "CreateBranchNameField";
const string COMMENT_TEXTAREA_CONTROL_NAME = "CreateBranchCommentTextArea";
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: a0fc5252a48d8b34f945b4ae3ad45030
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,91 @@
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using Codice.CM.Common;
using PlasticGui;
using Unity.PlasticSCM.Editor.UI;
namespace Unity.PlasticSCM.Editor.Views.Branches.Dialogs
{
internal class DeleteBranchDialog : PlasticDialog
{
internal static bool ConfirmDelete(
EditorWindow parentWindow,
IList<BranchInfo> branches)
{
DeleteBranchDialog dialog = Create(branches);
return dialog.RunModal(parentWindow) == ResponseType.Ok;
}
protected override string GetExplanation()
{
return mMessage;
}
protected override string GetTitle()
{
return mTitle;
}
protected override void DoOkButton()
{
GUI.enabled = IsDeleteButtonEnabled();
if (NormalButton(PlasticLocalization.Name.DeleteButton.GetString()))
OkButtonAction();
GUI.enabled = true;
}
protected override void DoButtonsArea()
{
using (new EditorGUILayout.HorizontalScope())
{
GUILayout.FlexibleSpace();
mConfirmDelete = EntryBuilder.CreateToggleEntry(
PlasticLocalization.Name.ConfirmationCheckBox.GetString(),
mConfirmDelete);
GUILayout.Space(10);
DoButtonsWithPlatformOrdering(DoOkButton, DoCloseButton, DoCancelButton);
}
}
internal override void OkButtonAction()
{
if (!IsDeleteButtonEnabled())
return;
base.OkButtonAction();
}
bool IsDeleteButtonEnabled()
{
return mConfirmDelete;
}
static DeleteBranchDialog Create(IList<BranchInfo> branches)
{
var instance = CreateInstance<DeleteBranchDialog>();
instance.mMessage = DeleteObjectsAlert.BuildDeleteBranchConfirmationMessage(branches);
instance.mEnterKeyAction = instance.OkButtonAction;
instance.mEscapeKeyAction = instance.CancelButtonAction;
instance.mCancelButtonText = PlasticLocalization.Name.NoButton.GetString();
instance.mNumberOfBranches = branches.Count;
instance.mTitle = PlasticLocalization.Name.ConfirmDeleteTitle.GetString();
return instance;
}
const int MAX_ITEMS_TO_SHOW = 10;
string mMessage;
string mTitle;
int mNumberOfBranches;
bool mConfirmDelete;
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 6780ea954e283bd4f82686f6e5ebafee
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,39 @@
using UnityEditor;
using Codice.CM.Common;
using PlasticGui;
using PlasticGui.WorkspaceWindow.QueryViews.Branches;
using Unity.PlasticSCM.Editor.UI;
namespace Unity.PlasticSCM.Editor.Views.Branches.Dialogs
{
internal class RenameBranchDialog
{
internal static BranchRenameData GetBranchRenameData(
RepositorySpec repSpec,
BranchInfo branchInfo,
EditorWindow parentWindow)
{
InputTextDialogResult dialogResult = InputTextDialog.GetInputText(
PlasticLocalization.Name.RenameBranchTitle.GetString(),
null,
PlasticLocalization.GetString(PlasticLocalization.Name.NewName),
GetShorten.BranchNameFromString(branchInfo.BranchName),
PlasticLocalization.GetString(PlasticLocalization.Name.RenameButton),
(text, closer, progressControls) =>
{
BranchRenameData data = new BranchRenameData(
repSpec, branchInfo, text);
BranchRenameValidation.AsyncValidation(data, closer, progressControls);
},
parentWindow,
width: 500);
BranchRenameData result = new BranchRenameData(
repSpec, branchInfo, dialogResult.Text);
result.Result = dialogResult.Result;
return result;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 1de62e30afcba544e8e8da4b93a4fa39
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,23 @@
using System;
using Codice.CM.Common;
namespace Unity.PlasticSCM.Editor.Views.Branches
{
[Serializable]
internal class SerializableBranchesTabState
{
internal BranchInfo BranchToSelect;
internal bool ShowHiddenBranches;
internal bool IsInitialized { get; private set; }
internal SerializableBranchesTabState(
BranchInfo branchToSelect,
bool showHiddenBranches)
{
ShowHiddenBranches = showHiddenBranches;
IsInitialized = true;
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 9e592d81aca24e489c0bac69b894dd31
timeCreated: 1741940913
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 96fe449559fb4e1995ab8503958a61ed
timeCreated: 1768299231
@@ -0,0 +1,280 @@
using System;
using Codice.Utils;
using PlasticGui;
using Unity.PlasticSCM.Editor.UI;
using Unity.PlasticSCM.Editor.UI.UIElements;
using UnityEditor;
using UnityEditor.UIElements;
using UnityEngine;
using UnityEngine.UIElements;
namespace Unity.PlasticSCM.Editor.Views.BranchExplorer
{
internal class BrExSearchField : VisualElement
{
internal string Text
{
get { return mSearchField.value; }
set { mSearchField.value = value; }
}
internal event Action DelayedSearchTextChanged;
internal event Action NextSearchResultRequested;
internal event Action PreviousSearchResultRequested;
internal BrExSearchField()
{
CreateGUI();
mSearchRunner = new DelayedActionBySecondsRunner(
OnDelayedSearchChanged,
UnityConstants.SEARCH_DELAYED_INPUT_ACTION_INTERVAL);
}
internal void Dispose()
{
mSearchField.UnregisterValueChangedCallback(OnSearchFieldChanged);
mSearchField.UnregisterCallback<KeyDownEvent>(OnSearchFieldKeyDown, TrickleDown.TrickleDown);
mPreviousButton.UnregisterCallback<MouseEnterEvent>(OnNavigationButtonMouseEnter);
mPreviousButton.UnregisterCallback<MouseLeaveEvent>(OnNavigationButtonMouseLeave);
mNextButton.UnregisterCallback<MouseEnterEvent>(OnNavigationButtonMouseEnter);
mNextButton.UnregisterCallback<MouseLeaveEvent>(OnNavigationButtonMouseLeave);
}
internal void FocusSearchField()
{
mSearchField.Focus();
}
internal void UpdateSearchCounter(int currentIndex, int totalResults)
{
if (string.IsNullOrEmpty(mSearchField.value))
return;
if (totalResults == 0)
{
mSearchCounterLabel.text = "0/0";
mPreviousButton.SetEnabled(false);
mNextButton.SetEnabled(false);
}
else
{
mSearchCounterLabel.text = string.Format("{0}/{1}", currentIndex, totalResults);
mPreviousButton.SetEnabled(true);
mNextButton.SetEnabled(true);
}
}
void OnDelayedSearchChanged()
{
DelayedSearchTextChanged?.Invoke();
}
void CreateGUI()
{
style.flexDirection = FlexDirection.Row;
style.alignItems = Align.Center;
mSearchField = BuildSearchField();
Add(mSearchField);
var overlayContainer = BuildOverlayContainer();
Add(overlayContainer);
}
ToolbarSearchField BuildSearchField()
{
var searchField = new ToolbarSearchField();
searchField.style.width = 220;
searchField.style.flexGrow = 1;
searchField.tooltip = string.Format("{0}{1}{2}",
PlasticLocalization.Name.BranchExplorerSearchFieldTooltip.GetString(),
Environment.NewLine,
GetSearchTextBoxShortcutsTooltipString());
searchField.RegisterValueChangedCallback(OnSearchFieldChanged);
searchField.RegisterCallback<KeyDownEvent>(OnSearchFieldKeyDown, TrickleDown.TrickleDown);
var textField = searchField.Q<TextField>();
if (textField != null)
{
textField.style.paddingRight = 55;
textField.SetTextCursor();
}
return searchField;
}
VisualElement BuildOverlayContainer()
{
var container = new VisualElement();
container.style.position = Position.Absolute;
container.style.right = 18;
container.style.top = 0;
container.style.bottom = 0;
container.style.flexDirection = FlexDirection.Row;
container.style.alignItems = Align.Center;
container.pickingMode = PickingMode.Ignore;
mSearchCounterLabel = BuildSearchCounterLabel();
container.Add(mSearchCounterLabel);
mPreviousButton = CreateNavigationButton(
OnPreviousButtonClicked,
PlasticLocalization.Name.PreviousLabel.GetString(),
Images.GetArrowCaretLeftIcon(),
marginRight: 2);
container.Add(mPreviousButton);
mNextButton = CreateNavigationButton(
OnNextButtonClicked,
PlasticLocalization.Name.NextLabel.GetString(),
Images.GetArrowCaretRightIcon());
container.Add(mNextButton);
return container;
}
Label BuildSearchCounterLabel()
{
var label = new Label();
label.style.color = UnityStyles.Colors.SecondaryLabel;
label.style.fontSize = 11;
label.style.unityTextAlign = TextAnchor.MiddleCenter;
label.style.marginLeft = 4;
label.style.marginRight = 0;
label.pickingMode = PickingMode.Ignore;
return label;
}
void OnNavigationButtonMouseEnter(MouseEnterEvent evt)
{
VisualElement button = (VisualElement)evt.currentTarget;
button.style.backgroundColor = StyleKeyword.Null;
}
void OnNavigationButtonMouseLeave(MouseLeaveEvent evt)
{
VisualElement button = (VisualElement)evt.currentTarget;
button.style.backgroundColor = Color.clear;
}
Button CreateNavigationButton(
Action clickEvent,
string tooltip,
Texture2D image,
float marginRight = 0)
{
Button result = new Button(clickEvent);
result.tooltip = tooltip;
result.style.backgroundImage = image;
result.style.width = NAVIGATION_BUTTON_SIZE;
result.style.height = NAVIGATION_BUTTON_SIZE;
result.style.marginLeft = 0;
result.style.marginRight = marginRight;
result.style.paddingLeft = 0;
result.style.paddingRight = 0;
result.style.paddingTop = 0;
result.style.paddingBottom = 0;
result.style.borderLeftWidth = 0;
result.style.borderRightWidth = 0;
result.style.borderTopWidth = 0;
result.style.borderBottomWidth = 0;
result.visible = false;
result.style.backgroundColor = Color.clear;
result.SetMouseCursor(MouseCursor.Arrow);
result.RegisterCallback<MouseEnterEvent>(OnNavigationButtonMouseEnter);
result.RegisterCallback<MouseLeaveEvent>(OnNavigationButtonMouseLeave);
return result;
}
void OnSearchFieldKeyDown(KeyDownEvent evt)
{
KeyboardActions.SearchAction searchAction =
KeyboardActions.GetSearchAction(evt);
if (searchAction == KeyboardActions.SearchAction.None)
return;
if (searchAction == KeyboardActions.SearchAction.Clean)
{
evt.StopPropagation();
mSearchField.value = string.Empty;
return;
}
if (searchAction == KeyboardActions.SearchAction.PreviousSearch)
{
evt.StopPropagation();
PreviousSearchResultRequested?.Invoke();
return;
}
if (searchAction == KeyboardActions.SearchAction.NextSearch)
{
evt.StopPropagation();
NextSearchResultRequested?.Invoke();
return;
}
}
void OnSearchFieldChanged(ChangeEvent<string> evt)
{
mSearchRunner.Run();
UpdateSearchControlsVisibility();
}
void UpdateSearchControlsVisibility()
{
if (string.IsNullOrEmpty(mSearchField.value))
{
mSearchCounterLabel.text = string.Empty;
mSearchCounterLabel.visible = false;
mPreviousButton.visible = false;
mNextButton.visible = false;
return;
}
mSearchCounterLabel.visible = true;
mPreviousButton.visible = true;
mNextButton.visible = true;
}
void OnNextButtonClicked()
{
NextSearchResultRequested?.Invoke();
}
void OnPreviousButtonClicked()
{
PreviousSearchResultRequested?.Invoke();
}
static string GetSearchTextBoxShortcutsTooltipString()
{
if (PlatformIdentifier.IsWindows())
return PlasticLocalization.Name
.BranchExplorerSearchFieldShortcutsTooltipForWindows.GetString();
if (PlatformIdentifier.IsMac())
return PlasticLocalization.Name
.BranchExplorerSearchFieldShortcutsTooltipForMacOS.GetString();
return PlasticLocalization.Name
.BranchExplorerSearchFieldShortcutsTooltipForLinux.GetString();
}
ToolbarSearchField mSearchField;
Label mSearchCounterLabel;
Button mPreviousButton;
Button mNextButton;
readonly DelayedActionBySecondsRunner mSearchRunner;
const float NAVIGATION_BUTTON_SIZE = 12f;
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 08501ac9dc864ac3998d286a2a36aaf2
timeCreated: 1770213834
@@ -0,0 +1,54 @@
using System;
using UnityEngine;
using UnityEngine.UIElements;
using PlasticGui;
namespace Unity.PlasticSCM.Editor.Views.BranchExplorer
{
internal class BranchExplorerEmptyStatePanel : VisualElement
{
internal BranchExplorerEmptyStatePanel(Action resetFiltersAction)
{
mResetFiltersAction = resetFiltersAction;
CreateGUI();
}
internal void Dispose()
{
if (mResetFiltersButton != null)
mResetFiltersButton.clicked -= OnResetFiltersClicked;
}
void CreateGUI()
{
style.flexGrow = 1;
style.alignItems = Align.Center;
style.justifyContent = Justify.Center;
Label emptyStateLabel = new Label(
PlasticLocalization.Name.NoBranchesMatchingFilters.GetString());
emptyStateLabel.style.unityTextAlign = TextAnchor.MiddleCenter;
emptyStateLabel.style.whiteSpace = WhiteSpace.Normal;
Add(emptyStateLabel);
mResetFiltersButton = new Button();
mResetFiltersButton.text =
PlasticLocalization.Name.ResetFilters.GetString();
mResetFiltersButton.style.marginTop = 20;
mResetFiltersButton.clicked += OnResetFiltersClicked;
Add(mResetFiltersButton);
}
void OnResetFiltersClicked()
{
mResetFiltersAction?.Invoke();
}
readonly Action mResetFiltersAction;
Button mResetFiltersButton;
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 9448d1113e54b49bca25d38a852635b2
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,56 @@
using System;
using Codice.Client.BaseCommands.BranchExplorer;
using Codice.Client.Common.Threading;
using PlasticGui.WorkspaceWindow.BranchExplorer;
using Unity.PlasticSCM.Editor.UI;
namespace Unity.PlasticSCM.Editor.Views.BranchExplorer
{
internal class BranchExplorerFocusListener : BranchExplorerSelection.IBranchExplorerFocusListener
{
internal BranchExplorerFocusListener()
{
mRunner = new DelayedActionBySecondsRunner(
NotifyDelayedFocusChanged,
UnityConstants.SELECTION_DELAYED_INPUT_ACTION_INTERVAL);
}
void BranchExplorerSelection.IBranchExplorerFocusListener.OnFocusChanged(ObjectDrawInfo objecDrawInfo)
{
mFocusedObjectDrawInfo = objecDrawInfo;
mRunner.Run();
}
internal void AddFocusedObjectObserver(IFocusedObjectObserver observer)
{
mFocusObserver = observer;
}
internal void RemoveFocusedObjectObserver()
{
mFocusObserver = null;
}
void NotifyDelayedFocusChanged()
{
if (mFocusObserver == null)
return;
try
{
mFocusObserver.DelayedFocusedObjectChanged(mFocusedObjectDrawInfo);
}
catch (Exception ex)
{
ExceptionsHandler.HandleException("BranchExplorerFocusListener", ex);
}
}
ObjectDrawInfo mFocusedObjectDrawInfo;
IFocusedObjectObserver mFocusObserver;
DelayedActionBySecondsRunner mRunner;
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 02516f77f52743eeb912e608678868ef
timeCreated: 1769526786
@@ -0,0 +1,766 @@
using System;
using System.Collections.Generic;
using UnityEditor;
using UnityEditor.UIElements;
using UnityEngine.UIElements;
using Codice.Client.BaseCommands;
using Codice.Client.BaseCommands.BranchExplorer;
using Codice.Client.BaseCommands.BranchExplorer.ExplorerTree;
using Codice.Client.BaseCommands.BranchExplorer.Layout;
using Codice.Client.BaseCommands.Config;
using Codice.Client.Common.EventTracking;
using Codice.Client.Common.Threading;
using Codice.Client.Common.WebApi;
using Codice.CM.Common;
using PlasticGui;
using PlasticGui.WorkspaceWindow;
using PlasticGui.WorkspaceWindow.BranchExplorer;
using PlasticGui.WorkspaceWindow.BranchExplorer.Search;
using PlasticGui.WorkspaceWindow.Configuration;
using PlasticGui.WorkspaceWindow.Filters;
using Unity.PlasticSCM.Editor.Tool;
using Unity.PlasticSCM.Editor.Headless;
using Unity.PlasticSCM.Editor.UI;
using Unity.PlasticSCM.Editor.UI.UIElements;
using Unity.PlasticSCM.Editor.Views.BranchExplorer.Options;
using Unity.PlasticSCM.Editor.Views.BranchExplorer.Virtualization;
using Unity.PlasticSCM.Editor.Views.Filters;
using LayoutFilters = Codice.Client.BaseCommands.LayoutFilters;
namespace Unity.PlasticSCM.Editor.Views.BranchExplorer
{
internal class BranchExplorerView :
VisualElement,
IRefreshableView,
IQueryRefreshableView,
IWorkingObjectRefreshableView,
IFocusedObjectObserver,
IVirtualCanvasUpdateVisualsListener,
IVirtualCanvasUpdateListener,
FiltersPanel.IFilterableView,
BranchExplorerOptionsWindow.IBranchExplorerView
{
internal BranchExplorerViewer BranchExplorerViewer { get { return mBranchExplorerViewer; } }
internal BranchExplorerView(
WorkspaceInfo wkInfo,
RepositorySpec repSpec,
IPlasticWebRestApi restApi,
LaunchTool.IProcessExecutor processExecutor,
LaunchTool.IShowDownloadPlasticExeWindow showDownloadPlasticExeWindow,
EditorWindow window)
{
mWkInfo = wkInfo;
mRepSpec = repSpec;
CreateGUI(repSpec, restApi, processExecutor, showDownloadPlasticExeWindow, window);
mBranchExplorerViewer.InitializeBranchExplorerViewMenu(
restApi,
mWkInfo,
window,
new HeadlessWorkspaceWindow(() => { }, SetWorkingObjectInfo),
new HeadlessViewSwitcher(),
new HeadlessMergeViewLauncher(UVCSPlugin.Instance),
this,
mSelectedObjectResolver,
mProgressControls,
null, //guiHelpEvents,
null, //mOpenedCodeReviewWindows,
UVCSPlugin.Instance.AssetStatusCache,
UVCSPlugin.Instance.PendingChangesUpdater,
PlasticGui.Plastic.API.IsGluonWorkspace(mWkInfo) ?
UVCSPlugin.Instance.GluonIncomingChangesUpdater :
UVCSPlugin.Instance.DeveloperIncomingChangesUpdater,
GetShelvedChangesUpdater(),
null,
processExecutor,
showDownloadPlasticExeWindow);
((IRefreshableView)this).Refresh();
}
internal void Dispose()
{
if (mFocusListener != null)
mFocusListener.RemoveFocusedObjectObserver();
mBranchExplorerViewer.Dispose();
mEmptyStatePanel.Dispose();
UnregisterCallback<KeyDownEvent>(OnKeyDown);
mSearchField.DelayedSearchTextChanged -= OnDelayedSearchChanged;
mSearchField.NextSearchResultRequested -= OnNextSearchrResultRequested;
mSearchField.PreviousSearchResultRequested -= OnPreviousSearchrResultRequested;
mSearchField.Dispose();
}
internal void RecalculateLayout()
{
mProgressControls.ShowProgress(
PlasticLocalization.GetString(PlasticLocalization.Name.CalculatingViewLayout),
TimeSpan.FromMilliseconds(1000));
mBranchExplorerViewer.SaveRelativePosition();
IThreadWaiter waiter = ThreadWaiter.GetWaiter();
waiter.Execute(
threadOperationDelegate: delegate
{
mBranchExplorerViewer.RecalculateLayout(mRepSpec);
},
afterOperationDelegate: delegate
{
((IProgressControls)mProgressControls).HideProgress();
if (waiter.Exception != null)
{
ExceptionsHandler.DisplayException(waiter.Exception);
return;
}
mBranchExplorerViewer.UpdateLayout();
RefreshSearchResultsIfNeeded();
UpdateEmptyStateVisibility();
});
}
void IVirtualCanvasUpdateVisualsListener.OnVisualsUpdated()
{
try
{
if (mIsPendingToApplySearch)
{
ApplySearch();
return;
}
if (mIsFirstLoad)
{
mBranchExplorerViewer.NavigateToHome(false, false);
return;
}
mBranchExplorerViewer.RestoreRelativePosition();
}
finally
{
mIsFirstLoad = false;
}
}
internal void OnWindowFocused()
{
if (mBranchExplorerViewer == null)
return;
ObjectDrawInfo selectedObject =
mBranchExplorerViewer.Selection.GetSingleSelectedObject();
if (selectedObject == null)
return;
mSelectedObjectDataUpdater.UpdateDisplayData(selectedObject);
}
void IFocusedObjectObserver.DelayedFocusedObjectChanged(ObjectDrawInfo focusedObject)
{
schedule.Execute(() =>
{
TrackDelayedFocusedObjectChangedEvent(focusedObject, mRepSpec);
});
mSelectedObjectDataUpdater.UpdateDisplayData(focusedObject);
}
static void TrackDelayedFocusedObjectChangedEvent(ObjectDrawInfo focusedObject, RepositorySpec repSpec)
{
if (focusedObject is ChangesetDrawInfo)
{
TrackFeatureUseEvent.For(
repSpec,
TrackFeatureUseEvent.Features.BranchExplorer.SelectChangeset);
return;
}
if (focusedObject is BranchDrawInfo)
{
TrackFeatureUseEvent.For(
repSpec,
TrackFeatureUseEvent.Features.BranchExplorer.SelectBranch);
return;
}
if (focusedObject is LabelDrawInfo)
{
TrackFeatureUseEvent.For(
repSpec,
TrackFeatureUseEvent.Features.BranchExplorer.SelectLabel);
return;
}
}
void IVirtualCanvasUpdateListener.OnDelayedCanvasUpdate()
{
// pending to check if it is needed
}
void FiltersPanel.IFilterableView.ApplyFilter()
{
RecalculateLayout();
}
bool FiltersPanel.IFilterableView.ApplyDateFilter(
LayoutFilters.DateFilter oldFilter, LayoutFilters.DateFilter newFilter)
{
((IRefreshableView)this).Refresh();
return true;
}
void IRefreshableView.Refresh()
{
((IQueryRefreshableView)this).RefreshAndSelect(null);
}
void IWorkingObjectRefreshableView.Refresh(WorkingObjectInfo workingObjectInfo)
{
SetWorkingObjectInfo(workingObjectInfo);
}
void BranchExplorerOptionsWindow.IBranchExplorerView.Redraw()
{
mBranchExplorerViewer.UpdateColorConfig();
mBranchExplorerViewer.Redraw();
}
void BranchExplorerOptionsWindow.IBranchExplorerView.Refresh()
{
((IRefreshableView)this).Refresh();
}
void BranchExplorerOptionsWindow.IBranchExplorerView.ClearSearchResults()
{
mBranchExplorerViewer.Search.ClearSearchResults();
}
void IQueryRefreshableView.RefreshAndSelect(RepObjectInfo objectToSelect)
{
if (mIsUpdating)
return;
mIsUpdating = true;
CheckRepositorySpecChanged();
RefreshIncomingChangesUpdater();
RefreshShelvedChangesUpdater();
((IProgressControls)mProgressControls).ShowProgress(PlasticLocalization.GetString(
PlasticLocalization.Name.LoadingBranchExplorer));
mBranchExplorerViewer.SaveRelativePosition();
/*List<ResolvedUser> availableUsers = new List<ResolvedUser>();*/
BrExLayout brExLayout = null;
BrExTree brExTree = null;
WorkingObjectInfo workingObjectInfo = null;
bool bInitializeConfig = false;
//ResolvedUser currentUser = null;
IThreadWaiter waiter = ThreadWaiter.GetWaiter();
waiter.Execute(
threadOperationDelegate: delegate
{
if (mConfig == null)
{
mConfig = WorkspaceUIConfiguration.Get(mWkInfo);
mBranchExplorerViewer.SetWorkspaceUIConfiguration(mConfig);
mFiltersPanel.SetWorkspaceUIConfiguration(mConfig);
bInitializeConfig = true;
}
workingObjectInfo = CalculateWorkingObjectInfo(mWkInfo);
//UpdateWorkingBranchInBranchFilter(workingObjectInfo);
brExLayout = CalculateLayout(
mWkInfo,
mRepSpec,
mConfig,
workingObjectInfo,
out brExTree);
mBranchExplorerViewer.SetLayout(brExLayout, brExTree);
/*currentUser = PlasticGui.Plastic.API.GetCurrentUser(mRepSpec.Server);
UpdateFilterBranchNames(mConfig, brExTree.GetBranches());
UpdateFilterUserNames(mConfig, availableUsers);*/
},
afterOperationDelegate: delegate
{
try
{
mBranchExplorerViewer.SetColorConfig(
mWkInfo,
mRepSpec);
if (bInitializeConfig)
{
mBranchExplorerViewer.Zoom.InitializeZoomLevel();
}
if (waiter.Exception != null)
{
ExceptionsHandler.DisplayException(waiter.Exception);
return;
}
mBranchExplorerViewer.UpdateLayout();
RefreshSearchResultsIfNeeded();
UpdateEmptyStateVisibility();
mBranchExplorerViewer.SelectObject(objectToSelect);
/*mFiltersPanel.SetData(
UserFilterModel.ToModel(availableUsers),
UserFilterModel.ToModel(currentUser),
BranchFilterModel.ToModel(brExTree.GetBranches(), workingObjectInfo.BranchInfo),
BranchFilterModel.ToModel(workingObjectInfo.BranchInfo));*/
mFiltersPanel.LoadConfiguration();
}
finally
{
((IProgressControls)mProgressControls).HideProgress();
mIsUpdating = false;
}
});
}
void SetWorkingObjectInfo(WorkingObjectInfo workingObjectInfo)
{
if (mIsUpdating)
return;
if (IsHomeChangesetVisible(workingObjectInfo.GetChangesetId()))
{
SetWorkingObjectInfoAndRecalculateLayout(workingObjectInfo);
return;
}
((IRefreshableView)this).Refresh();
}
bool IsHomeChangesetVisible(long homeChangesetId)
{
return FindDrawInfo.GetChangeset(
mBranchExplorerViewer?.ExplorerLayout?.ChangesetDraws,
homeChangesetId) != null;
}
void SetWorkingObjectInfoAndRecalculateLayout(WorkingObjectInfo workingObjectInfo)
{
if (mIsUpdating)
return;
mIsUpdating = true;
mProgressControls.ShowProgress(
PlasticLocalization.GetString(PlasticLocalization.Name.CalculatingViewLayout),
TimeSpan.FromMilliseconds(1000));
CheckRepositorySpecChanged();
IThreadWaiter waiter = ThreadWaiter.GetWaiter();
waiter.Execute(
threadOperationDelegate: delegate
{
Guid currentObject;
mBranchExplorerViewer.ExplorerTree.SetCurrentBranchAndChangeset(
workingObjectInfo.GetChangesetId(),
workingObjectInfo.BranchInfo != null ? workingObjectInfo.BranchInfo.Name : string.Empty,
out currentObject);
//UpdateWorkingBranchInBranchFilter(workingObjectInfo);
mBranchExplorerViewer.ExplorerTree.CalculateRelevantChangesets();
BrExLayout brExLayout = null;
BrExTree brExTree = null;
brExLayout = CalculateLayout(
mWkInfo,
mRepSpec,
mConfig,
workingObjectInfo,
out brExTree);
mBranchExplorerViewer.SetLayout(brExLayout, brExTree);
},
afterOperationDelegate: delegate
{
((IProgressControls)mProgressControls).HideProgress();
mIsUpdating = false;
if (waiter.Exception != null)
{
ExceptionsHandler.DisplayException(waiter.Exception);
return;
}
/*mFiltersPanel.BranchFilterButtonPanel.FilterPopup.UpdateCurrentModel(
BranchFilterModel.ToModel(workingObjectInfo.BranchInfo));*/
mBranchExplorerViewer.UpdateLayout();
});
}
static BrExLayout CalculateLayout(
WorkspaceInfo wkInfo,
RepositorySpec repSpec,
WorkspaceUIConfiguration config,
WorkingObjectInfo workingObjectInfo,
out BrExTree brExTree)
{
return PlasticGui.Plastic.API.GetBranchExplorerLayout(
wkInfo,
repSpec,
GetFilters(wkInfo, repSpec, config.Rules, null),
config.DisplayOptions,
workingObjectInfo,
out brExTree);
}
static FilterCollection GetFilters(
WorkspaceInfo wkInfo,
RepositorySpec repSpec,
List<Rule> rulesConfig,
CustomFilterData customFilterData)
{
if (customFilterData == null)
return ObtainFilters.FromRules(wkInfo, repSpec, rulesConfig);
return CustomBranchExplorer.BuildCustomSelectedBranchesFilter(customFilterData);
}
static WorkingObjectInfo CalculateWorkingObjectInfo(WorkspaceInfo wkInfo)
{
if (wkInfo.IsTemporary)
return WorkingObjectInfo.Empty;
return WorkingObjectInfo.Calculate(wkInfo);
}
void UpdateEmptyStateVisibility()
{
if (mBranchExplorerViewer.ExplorerLayout == null)
return;
if (mBranchExplorerViewer.ExplorerLayout.ColumnDraws.Count == 0)
{
mBranchExplorerViewer.visible = false;
mEmptyStatePanel.visible = true;
return;
}
mBranchExplorerViewer.visible = true;
mEmptyStatePanel.visible = false;
}
void CheckRepositorySpecChanged()
{
RepositorySpec repSpec = PlasticGui.Plastic.API.GetRepositorySpec(mWkInfo);
if (repSpec == null || repSpec.Equals(mRepSpec))
return;
mRepSpec = repSpec;
UpdateRepositorySpecInViews(mRepSpec);
}
void UpdateRepositorySpecInViews(RepositorySpec repSpec)
{
mSelectedObjectResolver.UpdateRepositorySpec(repSpec);
mSelectedObjectDataUpdater.UpdateRepositorySpec(repSpec);
mBranchExplorerViewer.UpdateRepositorySpec(repSpec);
mFiltersPanel.UpdateRepositorySpec(repSpec);
}
void ResetFiltersClick()
{
TrackFeatureUseEvent.For(
mRepSpec,
TrackFeatureUseEvent.Features.DesktopGUI.Filters.Reset);
mConfig.DisplayOptions.DateFilter = LayoutFilters.DateFilter.OneMonthAgo;
mConfig.DisplayOptions.BranchFilter = null;
mConfig.DisplayOptions.UserFilter = null;
mConfig.DisplayOptions.DisplayOnlyRelevantChangesets = false;
mConfig.DisplayOptions.DisplayOnlyPendingToMergeBranches = false;
mConfig.DisplayOptions.ShowRelatedBranches = false;
mConfig.Save(mWkInfo);
mFiltersPanel.LoadConfiguration();
RecalculateLayout();
}
void OnRefreshClicked()
{
((IRefreshableView)this).Refresh();
}
void OnOptionsClicked()
{
BranchExplorerOptionsWindow.ShowWindow();
}
void RefreshIncomingChangesUpdater()
{
if (UVCSPlugin.Instance.DeveloperIncomingChangesUpdater != null)
UVCSPlugin.Instance.DeveloperIncomingChangesUpdater.Update(DateTime.Now);
if (UVCSPlugin.Instance.GluonIncomingChangesUpdater != null)
UVCSPlugin.Instance.GluonIncomingChangesUpdater.Update(DateTime.Now);
}
void RefreshShelvedChangesUpdater()
{
UVCSWindow window = GetWindowIfOpened.UVCS();
if (window == null)
return;
window.ShelvedChangesUpdater?.Update(DateTime.Now);
}
void CreateGUI(
RepositorySpec repSpec,
IPlasticWebRestApi restApi,
LaunchTool.IProcessExecutor processExecutor,
LaunchTool.IShowDownloadPlasticExeWindow showDownloadPlasticExeWindow,
EditorWindow window)
{
style.flexDirection = FlexDirection.Column;
style.flexGrow = 1;
var toolbar = ControlBuilder.Toolbar.Create();
mRefreshButton = ControlBuilder.Toolbar.CreateImageButtonLeft(
Images.GetRefreshIcon(),
PlasticLocalization.Name.RefreshButton.GetString(),
OnRefreshClicked);
mFiltersPanel = new FiltersPanel(
mWkInfo,
mRepSpec,
FilterableViewType.BranchExplorerView,
this);
toolbar.Add(mRefreshButton);
toolbar.Add(mFiltersPanel);
var flexibleSpacer = new ToolbarSpacer();
flexibleSpacer.style.flexGrow = 1;
toolbar.Add(flexibleSpacer);
mSearchField = new BrExSearchField();
mSearchField.DelayedSearchTextChanged += OnDelayedSearchChanged;
mSearchField.NextSearchResultRequested += OnNextSearchrResultRequested;
mSearchField.PreviousSearchResultRequested += OnPreviousSearchrResultRequested;
toolbar.Add(mSearchField);
Add(toolbar);
mBranchExplorerViewer = CreateBranchExplorerArea(
repSpec, restApi, processExecutor, showDownloadPlasticExeWindow, window);
mEmptyStatePanel = new BranchExplorerEmptyStatePanel(
ResetFiltersClick);
mEmptyStatePanel.visible = false;
mEmptyStatePanel.style.position = Position.Absolute;
mEmptyStatePanel.style.left = 0;
mEmptyStatePanel.style.right = 0;
mEmptyStatePanel.style.top = 0;
mEmptyStatePanel.style.bottom = 0;
var contentContainer = new VisualElement();
contentContainer.style.flexGrow = 1;
contentContainer.Add(mBranchExplorerViewer);
contentContainer.Add(mEmptyStatePanel);
Add(contentContainer);
mSelectedObjectDataUpdater = new SelectedObjectDataUpdater(mRepSpec, window);
mProgressControls = new OverlayProgressControls(
mRefreshButton,
mBranchExplorerViewer.OptionsButton,
mBranchExplorerViewer.HomeButton,
mBranchExplorerViewer.ZoomInButton,
mBranchExplorerViewer.ZoomOutButton,
mFiltersPanel);
Add(mProgressControls);
RegisterCallback<KeyDownEvent>(OnKeyDown);
}
void OnKeyDown(KeyDownEvent evt)
{
if (!KeyboardEvents.IsFindShortcutPressed(evt))
return;
evt.StopPropagation();
mSearchField.FocusSearchField();
}
void OnPreviousSearchrResultRequested()
{
FocusPreviousSearchResult();
}
void OnNextSearchrResultRequested()
{
FocusNextSearchResult();
}
void OnDelayedSearchChanged()
{
if (mIsUpdating)
{
mIsPendingToApplySearch = true;
return;
}
ApplySearch();
}
void ApplySearch()
{
mIsPendingToApplySearch = false;
ApplyNewSearchIfChanged();
}
bool ApplyNewSearchIfChanged()
{
BranchExplorerSearch search = mBranchExplorerViewer.Search;
if (!search.FindItemsIfChanged(mSearchField.Text.Trim()))
return false;
search.FocusFirstSearchResult();
UpdateSearchCounter();
return true;
}
void FocusNextSearchResult()
{
if (mIsUpdating)
return;
if (ApplyNewSearchIfChanged())
return;
mBranchExplorerViewer.Search.FocusNextSearchResult();
UpdateSearchCounter();
}
void FocusPreviousSearchResult()
{
if (mIsUpdating)
return;
if (ApplyNewSearchIfChanged())
return;
mBranchExplorerViewer.Search.FocusPreviousSearchResult();
UpdateSearchCounter();
}
void RefreshSearchResultsIfNeeded()
{
if (mIsPendingToApplySearch)
return;
mBranchExplorerViewer.Search.RefreshCurrentSearch();
UpdateSearchCounter();
}
void UpdateSearchCounter()
{
BranchExplorerSearch search = mBranchExplorerViewer.Search;
mSearchField.UpdateSearchCounter(
search.CurrentSearchIndex,
search.TotalSearchResults);
}
BranchExplorerViewer CreateBranchExplorerArea(
RepositorySpec repSpec,
IPlasticWebRestApi restApi,
LaunchTool.IProcessExecutor processExecutor,
LaunchTool.IShowDownloadPlasticExeWindow showDownloadPlasticExeWindow,
EditorWindow window)
{
mFocusListener = new BranchExplorerFocusListener();
mFocusListener.AddFocusedObjectObserver(this);
IIssueTrackerExtension extension = PlasticGui.Plastic.API.GetIssueTracker(
GlobalConfig.Instance, mWkInfo);
BranchExplorerSelection selectionHandler =
new BranchExplorerSelection(mFocusListener);
mSelectedObjectResolver = new BranchExplorerSelectedObjectResolver(
repSpec, selectionHandler);
return new BranchExplorerViewer(
mWkInfo,
mRepSpec,
extension,
selectionHandler,
this,
this,
OnOptionsClicked);
}
static IShelvedChangesUpdater GetShelvedChangesUpdater()
{
UVCSWindow window = GetWindowIfOpened.UVCS();
if (window == null)
return null;
return window.ShelvedChangesUpdater;
}
WorkspaceInfo mWkInfo;
RepositorySpec mRepSpec;
OverlayProgressControls mProgressControls;
BranchExplorerFocusListener mFocusListener;
BranchExplorerSelectedObjectResolver mSelectedObjectResolver;
volatile bool mIsUpdating;
bool mIsPendingToApplySearch;
bool mIsFirstLoad = true;
WorkspaceUIConfiguration mConfig;
ToolbarButton mRefreshButton;
FiltersPanel mFiltersPanel;
BranchExplorerViewer mBranchExplorerViewer;
BranchExplorerEmptyStatePanel mEmptyStatePanel;
BrExSearchField mSearchField;
SelectedObjectDataUpdater mSelectedObjectDataUpdater;
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: b05368a4ef1a4635b2e0337c41502e63
timeCreated: 1768305487
@@ -0,0 +1,760 @@
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;
using UnityEditor;
using Codice.Client.BaseCommands;
using Codice.Client.BaseCommands.BranchExplorer;
using Codice.Client.BaseCommands.BranchExplorer.ExplorerTree;
using Codice.Client.BaseCommands.BranchExplorer.Layout;
using Codice.Client.Common.WebApi;
using Codice.Client.IssueTracker;
using Codice.CM.Common;
using PlasticGui;
using PlasticGui.Help;
using PlasticGui.WorkspaceWindow;
using PlasticGui.WorkspaceWindow.BranchExplorer;
using PlasticGui.WorkspaceWindow.BranchExplorer.Search;
using PlasticGui.WorkspaceWindow.Configuration;
using PlasticGui.WorkspaceWindow.MergeRequest;
using Unity.PlasticSCM.Editor.AssetsOverlays.Cache;
using Unity.PlasticSCM.Editor.UI;
using Unity.PlasticSCM.Editor.Tool;
using Unity.PlasticSCM.Editor.Views.BranchExplorer.Drawing.Shapes;
using Unity.PlasticSCM.Editor.Views.BranchExplorer.Menu;
using Unity.PlasticSCM.Editor.Views.BranchExplorer.Drawing.Shapes.Colors;
using Unity.PlasticSCM.Editor.Views.BranchExplorer.Virtualization;
using Unity.PlasticSCM.Editor.Views.BranchExplorer.Zoom;
using Unity.PlasticSCM.Editor.UI.UIElements;
namespace Unity.PlasticSCM.Editor.Views.BranchExplorer
{
internal interface IBrExNavigate
{
void NavigateToShape(VirtualShape shape, bool animate = true);
}
internal class BranchExplorerViewer : VisualElement,
IBrExNavigate,
BrExShape.IBrExShapeClickListener,
BranchExplorerSearch.IBrExNavigate
{
internal VirtualCanvas VirtualCanvas { get { return mVirtualCanvas; } }
internal ColorProvider ColorProvider { get { return mColorProvider; } }
internal BrExTree ExplorerTree { get { return mExplorerTree; } }
internal Button OptionsButton { get { return mOptionsButton; } }
internal Button ZoomInButton { get { return mZoomInButton; } }
internal Button ZoomOutButton { get { return mZoomOutButton; } }
internal Button HomeButton { get { return mHomeButton; } }
internal BrExZoom Zoom { get { return mZoom; } }
internal BrExLayout ExplorerLayout { get { return mExplorerLayout; } }
internal BranchExplorerSelection Selection { get {return mSelectionHandler; } }
internal BranchExplorerSearch Search { get { return mSearchHandler; } }
internal BranchExplorerViewer(
WorkspaceInfo wkInfo,
RepositorySpec repSpec,
IIssueTrackerExtension issueTracker,
BranchExplorerSelection selectionHandler,
IVirtualCanvasUpdateVisualsListener loadedListener,
IVirtualCanvasUpdateListener updatedListener,
Action onOptionsClicked = null)
{
mWkInfo = wkInfo;
mRepSpec = repSpec;
mIssueTracker = issueTracker;
mSelectionHandler = selectionHandler;
mOnOptionsClicked = onOptionsClicked;
CreateGUI(loadedListener, updatedListener);
mSearchHandler = new BranchExplorerSearch(this, GetVirtualShapes);
}
internal void InitializeBranchExplorerViewMenu(
IPlasticWebRestApi restApi,
WorkspaceInfo wkInfo,
EditorWindow window,
IWorkspaceWindow workspaceWindow,
IViewSwitcher switcher,
IMergeViewLauncher mergeViewLauncher,
BranchExplorerView branchExplorerView,
BranchExplorerSelectedObjectResolver selectedObjectResolver,
IProgressControls progressControls,
GuiHelpEvents guiHelpEvents,
OpenedCodeReviewWindows openedCodeReviewWindows,
IAssetStatusCache assetStatusCache,
IPendingChangesUpdater pendingChangesUpdater,
IIncomingChangesUpdater incomingChangesUpdater,
IShelvedChangesUpdater shelvedChangesUpdater,
IWorkspaceModeNotificationUpdater workspaceModeNotificationUpdater,
LaunchTool.IProcessExecutor processExecutor,
LaunchTool.IShowDownloadPlasticExeWindow showDownloadPlasticExeWindow)
{
mBranchExplorerViewMenu = new BranchExplorerViewMenu(
restApi,
wkInfo,
mRepSpec,
window,
workspaceWindow,
switcher,
mergeViewLauncher,
branchExplorerView,
this,
mSelectionHandler,
selectedObjectResolver,
progressControls,
guiHelpEvents,
openedCodeReviewWindows,
assetStatusCache,
pendingChangesUpdater,
incomingChangesUpdater,
shelvedChangesUpdater,
workspaceModeNotificationUpdater,
processExecutor,
showDownloadPlasticExeWindow);
}
internal void UpdateRepositorySpec(RepositorySpec repSpec)
{
mBranchExplorerViewMenu?.UpdateRepositorySpec(repSpec);
mTaskLoader?.UpdateRepositorySpec(repSpec);
mUserNameResolver?.UpdateRepositorySpec(repSpec);
mCommentResolver?.UpdateRepositorySpec(repSpec);
}
internal void SetWorkspaceUIConfiguration(
WorkspaceUIConfiguration workspaceUIConfiguration)
{
mConfig = workspaceUIConfiguration;
mZoom.SetWorkspaceUIConfiguration(workspaceUIConfiguration);
mSearchHandler.SetWorkspaceUIConfiguration(workspaceUIConfiguration);
}
internal void SetLayout(BrExLayout brExLayout, BrExTree brExTree)
{
mExplorerLayout = brExLayout;
mExplorerTree = brExTree;
}
internal void SetColorConfig(
WorkspaceInfo wkInfo,
RepositorySpec repSpec)
{
mColorProvider = new ColorProvider(
repSpec, wkInfo, mExplorerTree);
UpdateColorProviderRulesConfiguration(
mColorProvider, mConfig.Rules);
}
internal void UpdateColorConfig()
{
if (mColorProvider == null || mConfig == null)
return;
UpdateColorProviderRulesConfiguration(
mColorProvider,
mConfig.Rules);
}
internal ChangesetDrawInfo SaveRelativePosition()
{
ChangesetDrawInfo changesetDrawInfo = FindReferenceChangeset.FromChangesetShapes(
mVirtualCanvas.GetChangesetShapes());
if (changesetDrawInfo == null)
return null;
mRelativePositionShape = BuildRelativePositionChangeset(
changesetDrawInfo,
mZoom);
return changesetDrawInfo;
}
internal void RecalculateLayout(RepositorySpec repSpec)
{
if (mExplorerTree == null)
return;
mExplorerLayout = PlasticGui.Plastic.API.GetBranchExplorerLayout(
repSpec, mExplorerTree, mConfig.DisplayOptions);
}
internal void NavigateToHome(bool selectShape = true, bool animate = true)
{
if (mExplorerLayout == null)
return;
ObjectDrawInfo homeDrawInfo = FindDrawInfo.
GetHomeDrawInfo(
mExplorerLayout.ChangesetDraws,
mExplorerLayout.BranchDraws);
if (homeDrawInfo == null || homeDrawInfo.Visual == null)
return;
NavigateToShape((VirtualShape)homeDrawInfo.Visual, selectShape, animate);
}
internal void RestoreRelativePosition()
{
if (mRelativePositionShape == null)
return;
try
{
ChangesetDrawInfo newDraw = GetChangesetDrawToRestorePosition(
mRelativePositionShape.DrawInfo,
mVirtualCanvas.Layout.ChangesetDraws);
if (newDraw == null)
return;
float x = (newDraw.Bounds.X - mRelativePositionShape.RelativePosition.x) * mZoom.ZoomLevel;
float y = (newDraw.Bounds.Y - mRelativePositionShape.RelativePosition.y) * mZoom.ZoomLevel;
mZoom.Offset = new Vector2(x, y);
}
finally
{
mRelativePositionShape = null;
}
}
internal void UpdateLayout()
{
ResetTaskLoader();
ResetUserNameResolver();
ResetCommentResolver();
if (mExplorerLayout == null)
return;
VirtualCanvasFiller.FillVirtualCanvas(
mVirtualCanvas,
mExplorerLayout,
mConfig,
mColorProvider,
mTaskLoader,
mUserNameResolver,
mCommentResolver);
SearchAndSelectionUpdater.Update(
mSearchHandler,
mSelectionHandler,
GetVirtualShapes);
}
internal void Dispose()
{
if (mTaskLoader != null)
mTaskLoader.TasksLoaded -= TaskLoadFinished;
if (mUserNameResolver != null)
mUserNameResolver.UserNamesResolved -= UserNamesResolved;
if (mCommentResolver != null)
mCommentResolver.ChangesetCommentsResolved -= ChangesetCommentsResolved;
mScrollViewer.OnScrollChanged -= OnScrollChanged;
mScrollViewer.UnregisterCallback<MouseDownEvent>(OnMouseDown);
mScrollViewer.UnregisterCallback<KeyDownEvent>(OnKeyDown);
mScrollViewer.UnregisterCallback<PointerMoveEvent>(
OnPointerMoveResetPressedState);
mScrollViewer.Dispose();
mExplorerLayout = null;
mVirtualCanvas.Dispose();
mZoom.Dispose();
mPan.Dispose();
}
internal void SelectObject(RepObjectInfo objectToSelect)
{
/*if (objectToSelect == null)
return;
ObjectDraw drawToSelect = GetDrawObject(objectToSelect);
if (drawToSelect == null)
return;
SelectObject(drawToSelect);*/
}
internal void SelectObject(ObjectDrawInfo targetObject)
{
if (targetObject == null)
return;
VirtualShape targetVirtualShape =
(VirtualShape)targetObject.Visual;
if (targetVirtualShape == null)
return;
NavigateToShape(targetVirtualShape);
}
void BranchExplorerSearch.IBrExNavigate.NavigateToShape(IVirtualShape shape, bool animate)
{
NavigateToShape((VirtualShape)shape, animate);
}
void BrExShape.IBrExShapeClickListener.OnShapeClicked(
VirtualShape shape, bool isMultiSelection)
{
SelectShape(shape, isMultiSelection);
}
void BrExShape.IBrExShapeClickListener.OnContextMenuRequested()
{
mBranchExplorerViewMenu.Popup();
mPendingPointerReset = true;
}
void OnPointerMoveResetPressedState(PointerMoveEvent evt)
{
if (!mPendingPointerReset)
return;
mPendingPointerReset = false;
// The IMGUI GenericMenu consumes the right-button PointerUp,
// leaving UIElements with pressedButtons bit 2 (right button)
// permanently set. This breaks hover detection on shapes
// because PointerEnterEvent.pressedButtons != 0.
// A synthetic MouseUp clears the stale state.
schedule.Execute(() =>
{
if (panel == null)
return;
using (var upEvt = MouseUpEvent.GetPooled(
new Event { type = EventType.MouseUp, button = 1 }))
{
panel.visualTree.SendEvent(upEvt);
}
});
}
internal void Redraw()
{
mVirtualCanvas.Redraw();
}
internal void ScrollChangesetIntoView(long changesetId)
{
mVirtualCanvas.ScrollChangesetIntoView(changesetId);
}
void BrExShape.IBrExShapeClickListener.OnShapeDoubleClicked()
{
mBranchExplorerViewMenu.ExecuteDefaultAction();
}
void IBrExNavigate.NavigateToShape(VirtualShape shape, bool animate)
{
NavigateToShape(shape, animate);
}
void SelectShape(
VirtualShape shape, bool isMultiSelection)
{
mSelectionHandler.SelectShape(shape, isMultiSelection);
}
void ResetTaskLoader()
{
if (mTaskLoader != null)
{
mTaskLoader.Clean();
return;
}
if (mIssueTracker == null)
return;
mTaskLoader = new AsyncTaskLoader(
mRepSpec, new RequestTaskDelegate(RequestTaskInfo),
mIssueTracker.GetWorkingMode());
mTaskLoader.TasksLoaded += TaskLoadFinished;
}
void ResetUserNameResolver()
{
if (mUserNameResolver != null)
{
mUserNameResolver.Clean();
return;
}
mUserNameResolver = new AsyncUserNameResolver(mRepSpec);
mUserNameResolver.UserNamesResolved += UserNamesResolved;
}
void ResetCommentResolver()
{
if (mCommentResolver != null)
{
mCommentResolver.Clean();
return;
}
mCommentResolver = new AsyncChangesetCommentResolver(mRepSpec);
mCommentResolver.ChangesetCommentsResolved += ChangesetCommentsResolved;
}
Dictionary<string, PlasticTask> RequestTaskInfo(
List<string> visibleBranches)
{
if (mConfig == null
|| !mConfig.DisplayOptions.DisplayTaskInfoOnBranches
|| mIssueTracker == null)
{
return null;
}
if (mIssueTracker.GetWorkingMode() != ExtensionWorkingMode.TaskOnBranch)
return null;
return mIssueTracker.Extension.GetTasksForBranches(visibleBranches);
}
void OnKeyDown(KeyDownEvent evt)
{
if (mBranchExplorerViewMenu.ProcessKeyActionIfNeeded(evt.ToIMGUIEvent()))
{
evt.StopPropagation();
return;
}
if (!ProcessNavigationKeyEvent(evt))
return;
evt.StopPropagation();
}
void NavigateToShape(VirtualShape shape, bool selectShape = true, bool animate = true)
{
if (selectShape)
SelectShape(shape, false);
mZoom.ScrollIntoView(shape.BoundsForNavigation, animate);
}
bool ProcessNavigationKeyEvent(KeyDownEvent evt)
{
KeyboardActions.NavigationAction navigationAction =
KeyboardActions.GetNavigationAction(evt);
if (navigationAction == KeyboardActions.NavigationAction.None)
return false;
ObjectDrawInfo selectedObject =
mSelectionHandler.GetSingleSelectedObject();
if (selectedObject == null)
return true;
ObjectDrawInfo targetObject = null;
switch (navigationAction)
{
case KeyboardActions.NavigationAction.MoveUp:
targetObject = FindDrawInfo.GetObjectOnTop(
selectedObject, mExplorerLayout);
break;
case KeyboardActions.NavigationAction.MoveDown:
targetObject = FindDrawInfo.GetObjectOnBottom(
selectedObject, mExplorerLayout);
break;
case KeyboardActions.NavigationAction.MoveRight:
targetObject = FindDrawInfo.GetObjectOnRight(
selectedObject, mExplorerLayout,
KeyboardEvents.IsShiftPressed(evt));
break;
case KeyboardActions.NavigationAction.MoveLeft:
targetObject = FindDrawInfo.GetObjectOnLeft(
selectedObject, mExplorerLayout,
KeyboardEvents.IsShiftPressed(evt),
KeyboardEvents.IsAltPressed(evt),
mConfig.DisplayOptions.DisplayOnlyRelevantChangesets);
break;
case KeyboardActions.NavigationAction.Escape:
targetObject = FindDrawInfo.GetAlternativeObject(
selectedObject, mExplorerLayout);
break;
case KeyboardActions.NavigationAction.Home:
targetObject = FindDrawInfo.GetInitialChangeset(
selectedObject);
break;
case KeyboardActions.NavigationAction.End:
targetObject = FindDrawInfo.GetEndChangeset(
selectedObject);
break;
}
if (targetObject != null)
{
SelectObject(targetObject);
}
return true;
}
void TaskLoadFinished()
{
EditorDispatcher.Dispatch(Redraw);
}
void UserNamesResolved()
{
EditorDispatcher.Dispatch(Redraw);
}
void ChangesetCommentsResolved()
{
EditorDispatcher.Dispatch(
() => mVirtualCanvas.RedrawChangesetCommentShapes());
}
static void UpdateColorProviderRulesConfiguration(
ColorProvider colorProvider, List<Rule> rules)
{
colorProvider.SetRulesConfiguration(rules);
}
void CreateGUI(
IVirtualCanvasUpdateVisualsListener loadedListener,
IVirtualCanvasUpdateListener updatedListener)
{
style.flexGrow = 1;
mScrollViewer = new CanvasScrollView();
mScrollViewer.OnScrollChanged += OnScrollChanged;
mScrollViewer.focusable = true;
mScrollViewer.tabIndex = 0;
mScrollViewer.RegisterCallback<MouseDownEvent>(OnMouseDown);
mScrollViewer.RegisterCallback<KeyDownEvent>(OnKeyDown);
mScrollViewer.RegisterCallback<PointerMoveEvent>(
OnPointerMoveResetPressedState);
mScrollViewer.style.flexGrow = 1;
mVirtualCanvas = new VirtualCanvas(
mScrollViewer,
loadedListener,
updatedListener);
mScrollViewer.ContentContainer.Add(mVirtualCanvas);
VisualElement buttonsPanel = CreateButtonsPanel();
mScrollViewer.Viewport.Add(buttonsPanel);
Add(mScrollViewer);
mZoom = new BrExZoom(
mWkInfo,
mScrollViewer,
mVirtualCanvas);
mPan = new BrExPan(
mScrollViewer.Viewport,
mZoom);
if (mDebugRealizedShapes)
{
VisualElement statusPanel = CreateStatusPanel();
statusPanel.schedule.Execute(UpdateStatus).Every(250);
Add(statusPanel);
}
}
void OnMouseDown(MouseDownEvent evt)
{
if (evt.button != (int)MouseButton.LeftMouse)
return;
mScrollViewer.Focus();
}
void OnScrollChanged(Vector2 value)
{
if (mVirtualCanvas == null)
return;
mVirtualCanvas.OnScrollChanged();
}
void UpdateStatus()
{
List<BrExShape> shapes = mVirtualCanvas.GetShapes();
mStatusLabel.text = string.Format(
"Realized {0} visual shapes", shapes.Count);
}
static ChangesetDrawInfo GetChangesetDrawToRestorePosition(
ChangesetDrawInfo relativePositionShape,
List<ChangesetDrawInfo> changesetDraws)
{
ChangesetDrawInfo result = FindDrawInfo.GetChangeset(
changesetDraws, ((BrExChangeset)relativePositionShape.Tag).Id);
if (result != null)
return result;
// not found -> It could be not visible due to a filter
// try to find the nearest changeset
result = FindDrawInfo.GetNearestChangeset(
relativePositionShape, changesetDraws);
if (result != null)
return result;
// show last visible changeset in this case
return FindDrawInfo.GetNewestChangeset(changesetDraws);
}
static RelativePositionChangeset BuildRelativePositionChangeset(
ChangesetDrawInfo drawInfo,
BrExZoom zoom)
{
float x = drawInfo.Bounds.X - (zoom.Offset.x / zoom.ZoomLevel);
float y = drawInfo.Bounds.Y - (zoom.Offset.y / zoom.ZoomLevel);
return new RelativePositionChangeset(
drawInfo,
new Vector2(x, y));
}
VisualElement CreateButtonsPanel()
{
VisualElement buttonsPanel = new VisualElement();
buttonsPanel.style.position = Position.Absolute;
buttonsPanel.style.right = 20;
buttonsPanel.style.bottom = 20;
buttonsPanel.style.flexDirection = FlexDirection.Row;
buttonsPanel.style.alignItems = Align.FlexEnd;
float buttonSize = 30;
mOptionsButton = ControlBuilder.Button.CreateImageButton(
Images.GetSettingsIcon(),
PlasticLocalization.Name.BrexOptionsWindowTitle.GetString(),
() => { mOnOptionsClicked?.Invoke(); });
mOptionsButton.style.width = buttonSize;
mOptionsButton.style.height = buttonSize;
mOptionsButton.style.marginRight = 0;
mOptionsButton.style.marginBottom = 0;
mHomeButton = ControlBuilder.Button.CreateImageButton(
Images.GetButtonHomeIcon(),
PlasticLocalization.Name.GoHomeTooltip.GetString(),
() => { NavigateToHome(); });
mHomeButton.style.marginRight = 0;
mHomeButton.style.width = buttonSize;
mHomeButton.style.height = buttonSize;
mZoomInButton = ControlBuilder.ButtonGroup.CreateImageTopButton(
Images.GetZoomInIcon(),
PlasticLocalization.Name.ZoomIn.GetString(),
() => { mZoom.ZoomIn(); });
mZoomInButton.style.marginRight = 0;
mZoomInButton.style.width = buttonSize;
mZoomInButton.style.height = buttonSize;
mZoomOutButton = ControlBuilder.ButtonGroup.CreateImageBottomButton(
Images.GetZoomOutIcon(),
PlasticLocalization.Name.ZoomOut.GetString(),
() => { mZoom.ZoomOut(); });
mZoomOutButton.style.width = buttonSize;
mZoomOutButton.style.height = buttonSize;
mZoomOutButton.style.marginRight = 0;
mZoomOutButton.style.marginBottom = 0;
VisualElement rightColumn = new VisualElement();
rightColumn.Add(mHomeButton);
rightColumn.Add(mZoomInButton);
rightColumn.Add(mZoomOutButton);
buttonsPanel.Add(mOptionsButton);
buttonsPanel.Add(rightColumn);
return buttonsPanel;
}
VisualElement CreateStatusPanel()
{
VisualElement statusPanel = new VisualElement();
statusPanel.style.backgroundColor = new StyleColor(new Color(0.6f, 0.329f, 0.0f));
mStatusLabel = new Label("Ready");
mStatusLabel.style.color = new StyleColor(Color.white);
mStatusLabel.style.marginBottom = mStatusLabel.style.marginTop = mStatusLabel.style.marginLeft = mStatusLabel.style.marginRight = 5;
statusPanel.Add(mStatusLabel);
return statusPanel;
}
IEnumerable GetVirtualShapes()
{
return mVirtualCanvas.VirtualChildren;
}
class RelativePositionChangeset
{
internal ChangesetDrawInfo DrawInfo { get; private set; }
internal Vector2 RelativePosition { get; private set; }
internal RelativePositionChangeset(ChangesetDrawInfo drawInfo, Vector2 relativePosition)
{
DrawInfo = drawInfo;
RelativePosition = relativePosition;
}
}
// set to true to enable a label showing the number
// of currently realized shapes in the canvas
bool mDebugRealizedShapes;
AsyncTaskLoader mTaskLoader;
RelativePositionChangeset mRelativePositionShape;
AsyncUserNameResolver mUserNameResolver;
AsyncChangesetCommentResolver mCommentResolver;
Button mOptionsButton;
Button mHomeButton;
Button mZoomInButton;
Button mZoomOutButton;
BrExTree mExplorerTree;
BrExLayout mExplorerLayout;
WorkspaceUIConfiguration mConfig;
ColorProvider mColorProvider;
CanvasScrollView mScrollViewer;
VirtualCanvas mVirtualCanvas;
BrExZoom mZoom;
BrExPan mPan;
BranchExplorerViewMenu mBranchExplorerViewMenu;
bool mPendingPointerReset;
readonly BranchExplorerSearch mSearchHandler;
readonly BranchExplorerSelection mSelectionHandler;
readonly IIssueTrackerExtension mIssueTracker;
readonly Action mOnOptionsClicked;
readonly RepositorySpec mRepSpec;
readonly WorkspaceInfo mWkInfo;
Label mStatusLabel;
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 19cfdd73a6f34b2db2d31238e87e09c5
timeCreated: 1768316850
@@ -0,0 +1,149 @@
using UnityEditor;
using UnityEngine;
using UnityEngine.UIElements;
using Codice.Client.Common.EventTracking;
using Codice.CM.Common;
using Unity.PlasticSCM.Editor.Tool;
using Unity.PlasticSCM.Editor.UI;
namespace Unity.PlasticSCM.Editor.Views.BranchExplorer
{
internal class BranchExplorerWindow : EditorWindow
{
internal BranchExplorerView BranchExplorerView => mBranchExplorerView;
internal void OnWorkspaceCreated(WorkspaceInfo wkInfo)
{
mWkInfo = wkInfo;
mRepSpec = PlasticGui.Plastic.API.GetRepositorySpec(mWkInfo);
ShowBranchExplorer();
}
void CreateGUI()
{
mMainView = new VisualElement();
mMainView.style.flexGrow = 1;
rootVisualElement.Add(mMainView);
if (mWkInfo == null)
{
ShowEmptyState();
return;
}
ShowBranchExplorer();
}
void OnEnable()
{
mUVCSPlugin = UVCSPlugin.Instance;
titleContent.image = Images.GetBranchExplorerIcon();
mUVCSPlugin.Enable();
TryFindWorkspace();
}
void OnFocus()
{
if (mUVCSPlugin == null)
return;
if (mWkInfo == null)
{
if (!TryFindWorkspace())
return;
ShowBranchExplorer();
}
if (mBranchExplorerView != null)
mBranchExplorerView.OnWindowFocused();
}
bool TryFindWorkspace()
{
if (!mUVCSPlugin.ConnectionMonitor.IsConnected)
return false;
mWkInfo = FindWorkspace.InfoForApplicationPath(
ApplicationDataPath.Get(), PlasticGui.Plastic.API);
if (mWkInfo == null)
return false;
mRepSpec = PlasticGui.Plastic.API.GetRepositorySpec(mWkInfo);
return true;
}
void OnDestroy()
{
TrackFeatureUseEvent.For(
mRepSpec,
TrackFeatureUseEvent.Features.UnityPackage.CloseBranchExplorerView);
if (mGameInstallation != null)
mGameInstallation.Dispose();
CloseWindowIfOpened.BranchExplorerOptions();
if (mBranchExplorerView != null)
mBranchExplorerView.Dispose();
}
void ShowEmptyState()
{
if (mMainView == null)
return;
if (mEmptyStateView == null)
mEmptyStateView = new EmptyStateView(OnCreateWorkspaceButtonClicked);
mMainView.Clear();
mMainView.Add(mEmptyStateView);
}
void ShowBranchExplorer()
{
if (mMainView == null)
return;
if (mBranchExplorerView == null)
mBranchExplorerView = new BranchExplorerView(
mWkInfo,
mRepSpec,
PlasticGui.Plastic.WebRestAPI,
mProcessExecutor,
mShowDownloadPlasticExeWindow,
this);
mMainView.Clear();
mMainView.Add(mBranchExplorerView);
mGameInstallation = Game.Launcher.Install(
mBranchExplorerView.BranchExplorerViewer, mBranchExplorerView);
}
void OnCreateWorkspaceButtonClicked()
{
ShowWindow.UVCS();
}
Game.Launcher mGameInstallation;
WorkspaceInfo mWkInfo;
RepositorySpec mRepSpec;
VisualElement mMainView;
BranchExplorerView mBranchExplorerView;
EmptyStateView mEmptyStateView;
LaunchTool.IProcessExecutor mProcessExecutor =
new LaunchTool.ProcessExecutor();
LaunchTool.IShowDownloadPlasticExeWindow mShowDownloadPlasticExeWindow =
new LaunchTool.ShowDownloadPlasticExeWindow();
UVCSPlugin mUVCSPlugin;
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 95c33d7b5f64474d9f2c07832c033127
timeCreated: 1768299261
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 08971b3b50484acd81bdf19e0b4beb5f
timeCreated: 1768318376
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 9a92ce7bfd964dae89e964f40874a3c2
timeCreated: 1768318387
@@ -0,0 +1,356 @@
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;
using Codice.Client.BaseCommands.BranchExplorer.Layout;
using Codice.Utils;
using Unity.PlasticSCM.Editor.UI.UIElements;
using Unity.PlasticSCM.Editor.Views.BranchExplorer.Virtualization;
namespace Unity.PlasticSCM.Editor.Views.BranchExplorer.Drawing.Shapes
{
internal class BrExShape : VisualElement
{
internal const float MinZoomToShowText = 0.5f;
internal interface IBrExShapeClickListener
{
void OnShapeClicked(VirtualShape shape, bool isMultiSelection);
void OnShapeDoubleClicked();
void OnContextMenuRequested();
}
internal VirtualShape VirtualShape { get { return mVirtualShape; } }
internal BrExShape(VirtualShape virtualShape)
{
SetVirtualShape(virtualShape);
generateVisualContent += OnGenerateVisualContent;
RegisterCallback<PointerDownEvent>(OnMouseDown);
RegisterCallback<ContextClickEvent>(OnContextClick);
if (!HasTooltip(this))
return;
//mBrExShapeTooltipPopup = new BrExShapeTooltipPopup(this);
//LogicalChildren.Add(mBrExShapeTooltipPopup);
}
internal bool IsLinkNavigationTarget
{
get { return mIsLinkNavigationTarget; }
set
{
if (mIsLinkNavigationTarget == value)
return;
mIsLinkNavigationTarget = value;
MarkDirtyRepaint();
}
}
internal bool IsSearchResult
{
get { return mIsSearchResult; }
set
{
if (mIsSearchResult == value)
return;
mIsSearchResult = value;
MarkDirtyRepaint();
}
}
internal bool IsCurrentSearchResult
{
get { return mIsCurrentSearchResult; }
set
{
if (mIsCurrentSearchResult == value)
return;
mIsCurrentSearchResult = value;
MarkDirtyRepaint();
}
}
internal bool IsSelected
{
get { return mIsSelected; }
set
{
if (mIsSelected == value)
return;
mIsSelected = value;
MarkDirtyRepaint();
}
}
internal DisplayOptions DisplayOptions
{
get { return mVirtualShape.Config.DisplayOptions; }
}
internal virtual void Dispose()
{
//mBrExShapeTooltipPopup?.Dispose();
generateVisualContent -= OnGenerateVisualContent;
UnregisterCallback<PointerDownEvent>(OnMouseDown);
UnregisterCallback<ContextClickEvent>(OnContextClick);
}
internal virtual void Redraw()
{
MarkDirtyRepaint();
}
internal virtual void OnScrollChanged() { }
internal virtual bool HasContextMenu() => false;
public override bool ContainsPoint(Vector2 localPoint)
{
if (!MustNotifyClick(this))
return false;
return base.ContainsPoint(localPoint);
}
// internal for testing purposes
internal void OnMouseDown(PointerDownEvent e)
{
if (!MustNotifyClick(this))
return;
if (IsDoubleClick(e))
{
OnMouseDoubleClick(e);
return;
}
OnMouseClick(
e.button,
e.commandKey,
e.ctrlKey);
}
void OnMouseDoubleClick(PointerDownEvent e)
{
if (MouseEvents.IsRightButtonPressed(e))
return;
if (!MustNotifyDoubleClick(this))
return;
IBrExShapeClickListener clickListener =
GetFirstAncestorOfType<IBrExShapeClickListener>();
if (clickListener == null)
return;
clickListener.OnShapeDoubleClicked();
}
void OnMouseClick(
int clickedMouseButton,
bool isCommandKeyPressed,
bool isCtrlKeyPressed)
{
if (!IsSelectionEvent(clickedMouseButton, IsSelected))
return;
IBrExShapeClickListener clickListener =
GetFirstAncestorOfType<IBrExShapeClickListener>();
if (clickListener == null)
return;
clickListener.OnShapeClicked(
GetVirtualShapeForSelection(),
IsMultipleSelection(isCommandKeyPressed, isCtrlKeyPressed));
}
// internal for testing purposes
internal void OnContextClick(ContextClickEvent e)
{
OnMouseClick(
e.button,
e.commandKey,
e.ctrlKey);
IBrExShapeClickListener clickListener =
GetFirstAncestorOfType<IBrExShapeClickListener>();
if (clickListener == null)
return;
if (!HasContextMenu())
return;
clickListener.OnContextMenuRequested();
e.StopPropagation();
}
static bool MustNotifyClick(BrExShape shape)
{
return shape is BranchShape ||
shape is BranchCaptionShape ||
shape is ChangesetShape ||
shape is LabelShape ||
shape is MergeLinkShape;
}
static bool MustNotifyDoubleClick(BrExShape shape)
{
return shape is BranchShape ||
shape is BranchCaptionShape ||
shape is ChangesetShape ||
shape is LabelShape;
}
static bool HasTooltip(BrExShape shape)
{
return shape is BranchShape ||
shape is BranchCaptionShape ||
shape is ChangesetShape ||
shape is LabelShape;
}
static bool IsDoubleClick(PointerDownEvent e)
{
return e.clickCount == 2;
}
static bool IsSelectionEvent(int mouseButton, bool isSelected)
{
if (MouseEvents.IsRightButtonPressed(mouseButton) && isSelected)
return false;
return true;
}
static bool IsMultipleSelection(
bool isCommandKeyPressed,
bool isCtrlKeyPressed)
{
if (PlatformIdentifier.IsMac())
return isCommandKeyPressed;
return isCtrlKeyPressed;
}
void OnGenerateVisualContent(MeshGenerationContext ctx)
{
GenerateVisualContent(ctx.painter2D);
if (!mIsDrawDebugBoundsEnabled)
return;
DrawDebugBounds(ctx.painter2D, this);
}
protected virtual void GenerateVisualContent(Painter2D painter) { }
protected virtual void SetVirtualShape(VirtualShape virtualShape)
{
mVirtualShape = virtualShape;
IsSelected = mVirtualShape.IsSelected;
IsSearchResult = mVirtualShape.IsSearchResult;
IsCurrentSearchResult = mVirtualShape.IsCurrentSearchResult;
IsLinkNavigationTarget = mVirtualShape.IsLinkNavigationTarget;
style.width = mVirtualShape.Bounds.width;
style.height = mVirtualShape.Bounds.height;
}
protected internal virtual VirtualShape GetVirtualShapeForSelection()
{
return mVirtualShape;
}
protected void DrawDebugHitTestingBounds(Painter2D painter, List<Vector2> polygon)
{
painter.lineWidth = 1;
painter.strokeColor = new Color(1f, 0f, 1f, 1f);
painter.DrawPoligon(polygon);
painter.Stroke();
}
static void DrawDebugBounds(Painter2D painter, BrExShape shape)
{
painter.lineWidth = 1;
if (shape is ColumnHeaderShape)
{
// brown
painter.strokeColor = new Color(0.6f, 0.4f, 0.2f, 1f);
painter.DrawRect(new Rect(0, 0, shape.VirtualShape.Bounds.width, shape.VirtualShape.Bounds.height));
painter.Stroke();
}
else if (shape is BranchShape)
{
// red
painter.strokeColor = new Color(1f, 0f, 0f, 1f);
painter.DrawRect(new Rect(0, 0, shape.VirtualShape.Bounds.width, shape.VirtualShape.Bounds.height));
painter.Stroke();
}
else if (shape is BranchCaptionShape)
{
// aquamarine
painter.strokeColor = new Color(0.5f, 1f, 0.83f, 1f);
painter.DrawRect(new Rect(0, 0, shape.VirtualShape.Bounds.width, shape.VirtualShape.Bounds.height));
painter.Stroke();
}
else if (shape is ChangesetShape)
{
// blue
painter.strokeColor = new Color(0f, 0f, 1f, 1f);
painter.DrawRect(new Rect(0, 0, shape.VirtualShape.Bounds.width, shape.VirtualShape.Bounds.height));
painter.Stroke();
}
else if (shape is LabelShape)
{
// green
painter.strokeColor = new Color(0f, 1f, 0f, 1f);
painter.DrawRect(new Rect(0, 0, shape.VirtualShape.Bounds.width, shape.VirtualShape.Bounds.height));
painter.Stroke();
}
else if (shape is ParentLinkShape)
{
// organge
painter.strokeColor = new Color(1f, 0.5f, 0f, 1f);
painter.DrawRect(new Rect(0, 0, shape.VirtualShape.Bounds.width, shape.VirtualShape.Bounds.height));
painter.Stroke();
}
else if (shape is MergeLinkShape)
{
// magenta
painter.strokeColor = new Color(1f, 0f, 1f, 1f);
painter.DrawRect(new Rect(0, 0, shape.VirtualShape.Bounds.width, shape.VirtualShape.Bounds.height));
}
painter.Stroke();
}
// enable to draw the shape geometry bounds
static readonly bool mIsDrawDebugBoundsEnabled = false;
bool mIsLinkNavigationTarget;
bool mIsSearchResult;
bool mIsCurrentSearchResult;
bool mIsSelected;
protected VirtualShape mVirtualShape;
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 2eacfa118da243d793403d45660ec6e1
timeCreated: 1768318397
@@ -0,0 +1,239 @@
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;
using Codice.Client.BaseCommands.BranchExplorer;
using Codice.Client.BaseCommands.BranchExplorer.Layout;
using PlasticGui;
using PlasticGui.WorkspaceWindow.BranchExplorer;
using Unity.PlasticSCM.Editor.UI;
using Unity.PlasticSCM.Editor.Views.BranchExplorer.Drawing.Shapes.Colors;
using Unity.PlasticSCM.Editor.Views.BranchExplorer.Virtualization;
namespace Unity.PlasticSCM.Editor.Views.BranchExplorer.Drawing.Shapes
{
internal class BranchCaptionShape : BrExShape
{
internal BranchDrawInfo BranchDraw => VirtualShape.DrawInfo as BranchDrawInfo;
internal static string BuildName(string branchFullName)
{
return "branch-caption-" + branchFullName;
}
internal BranchCaptionShape(
VirtualShape virtualShape,
AsyncTaskLoader taskLoader) : base(virtualShape)
{
mTaskLoader = taskLoader;
name = BuildName(BranchDraw.Caption);
mCaptionContainer = new VisualElement();
mCaptionContainer.style.position = Position.Absolute;
mCaptionContainer.style.backgroundColor = BrExColors.Branch.GetCaptionBackgroundBrush();
mCaptionContainer.style.borderTopLeftRadius = CornerRadius;
mCaptionContainer.style.borderTopRightRadius = CornerRadius;
mCaptionContainer.style.borderBottomLeftRadius = CornerRadius;
mCaptionContainer.style.borderBottomRightRadius = CornerRadius;
mCaptionContainer.style.paddingLeft = TextPaddingX;
mCaptionContainer.style.paddingRight = TextPaddingX;
mCaptionContainer.style.paddingTop = TextPaddingY;
mCaptionContainer.style.paddingBottom = TextPaddingY;
mCaptionContainer.style.maxWidth = BranchDraw.Bounds.Width + 2 * TextPaddingX;
mCaptionContainer.style.maxHeight = MaxHeight;
mCaptionLabel = new Label();
mCaptionLabel.style.unityFontStyleAndWeight = FontStyle.Bold;
mCaptionLabel.style.color = UnityStyles.Colors.Label;
mCaptionLabel.style.marginBottom = 0;
mCaptionLabel.style.marginTop = 0;
mCaptionLabel.style.paddingBottom = 0;
mCaptionLabel.style.paddingTop = 0;
mCaptionLabel.style.whiteSpace = WhiteSpace.Normal;
mCaptionLabel.style.textOverflow = TextOverflow.Ellipsis;
mCaptionLabel.style.overflow = Overflow.Hidden;
mCaptionLabel.RegisterCallback<GeometryChangedEvent>(OnLabelGeometryChanged);
mDescriptionLabel = new Label();
mDescriptionLabel.style.fontSize = 10;
mDescriptionLabel.style.color = UnityStyles.Colors.SecondaryLabel;
mDescriptionLabel.style.marginBottom = 0;
mDescriptionLabel.style.marginTop = 0;
mDescriptionLabel.style.paddingBottom = 0;
mDescriptionLabel.style.paddingTop = 0;
mDescriptionLabel.style.whiteSpace = WhiteSpace.Normal;
mDescriptionLabel.style.textOverflow = TextOverflow.Ellipsis;
mDescriptionLabel.style.overflow = Overflow.Hidden;
mDescriptionLabel.RegisterCallback<GeometryChangedEvent>(OnLabelGeometryChanged);
mCaptionLabel.text = GetBranchName(BranchDraw, DisplayOptions);
mDescriptionLabel.text = GetBranchDescription(BranchDraw, DisplayOptions, mTaskLoader);
mCaptionContainer.Add(mCaptionLabel);
mCaptionContainer.Add(mDescriptionLabel);
Add(mCaptionContainer);
RegisterCallback<AttachToPanelEvent>(OnAttachToPanel);
}
public override bool ContainsPoint(Vector2 localPoint)
{
return mCaptionContainer.localBound.Contains(localPoint);
}
internal override void Dispose()
{
base.Dispose();
mCaptionLabel.UnregisterCallback<GeometryChangedEvent>(OnLabelGeometryChanged);
mDescriptionLabel.UnregisterCallback<GeometryChangedEvent>(OnLabelGeometryChanged);
UnregisterCallback<AttachToPanelEvent>(OnAttachToPanel);
}
internal override void Redraw()
{
mCaptionLabel.text = GetBranchName(BranchDraw , DisplayOptions);
mDescriptionLabel.text = GetBranchDescription(BranchDraw, DisplayOptions, mTaskLoader);
UpdateLayout();
base.Redraw();
}
internal override bool HasContextMenu() => true;
internal override void OnScrollChanged()
{
UpdateVisibilityForZoom();
UpdateContainerLayout();
}
protected override void GenerateVisualContent(Painter2D painter)
{
if (!DisplayOptions.DisplayTaskInfoOnBranches)
return;
mTaskLoader.RequestTaskInfo(new List<BranchRequest>()
{
new BranchRequest(BranchDraw.Id, BranchDraw.Caption),
});
}
protected internal override VirtualShape GetVirtualShapeForSelection()
{
// return the branch shape so selection highlights the whole branch
VirtualCanvas canvas = GetFirstAncestorOfType<VirtualCanvas>();
foreach (BrExShape brExShape in canvas.GetShapes())
{
if (brExShape is BranchShape branchShape &&
branchShape.BranchDrawInfo.Guid == BranchDraw.Guid)
return brExShape.VirtualShape;
}
return null;
}
void OnAttachToPanel(AttachToPanelEvent evt)
{
UpdateVisibilityForZoom();
}
void OnLabelGeometryChanged(GeometryChangedEvent evt)
{
UpdateLayout();
}
void UpdateVisibilityForZoom()
{
visible = IsVisibleForZoomLevel();
}
bool IsVisibleForZoomLevel()
{
VirtualCanvas canvas = GetFirstAncestorOfType<VirtualCanvas>();
return canvas != null && canvas.ZoomLevel >= BrExShape.MinZoomToShowText;
}
void UpdateLayout()
{
if (HasDescription())
{
mCaptionLabel.style.maxHeight = MaxHeight * 0.7f;
mDescriptionLabel.style.maxHeight = MaxHeight - mCaptionLabel.resolvedStyle.height;
}
else
{
mCaptionLabel.style.maxHeight = MaxHeight;
mDescriptionLabel.style.maxHeight = 0;
}
UpdateContainerLayout();
}
void UpdateContainerLayout()
{
VirtualCanvas canvas = this.GetFirstAncestorOfType<VirtualCanvas>();
if (canvas == null)
return;
float translatedScrollX = (canvas.ScrollOffset.x / canvas.ZoomLevel) - BranchDraw.Bounds.X;
float captionX = translatedScrollX > 0 ?
translatedScrollX + BrExDrawProperties.BranchCaptionOffsetX :
0;
float containerHeight = mCaptionContainer.resolvedStyle.height;
if (float.IsNaN(containerHeight) || containerHeight == 0)
{
// estimate height from labels
containerHeight = mCaptionLabel.resolvedStyle.height +
(HasDescription() ? mDescriptionLabel.resolvedStyle.height : 0) +
2 * TextPaddingY;
}
float captionY = -containerHeight - VerticalMargin;
mCaptionContainer.style.translate = new Translate(
captionX,
captionY);
}
bool HasDescription()
{
return !string.IsNullOrEmpty(mDescriptionLabel.text);
}
static string GetBranchName(
BranchDrawInfo branch,
DisplayOptions displayOptions)
{
return displayOptions.DisplayFullBranchNames ?
branch.Caption :
((BrExBranch)branch.Tag).Name;
}
static string GetBranchDescription(
BranchDrawInfo branch,
DisplayOptions displayOptions,
AsyncTaskLoader taskLoader)
{
if (!displayOptions.DisplayTaskInfoOnBranches)
return string.Empty;
return CommentFormatter.GetFormattedComment(
taskLoader.GetTaskInfoForBranch(branch.Caption));
}
readonly VisualElement mCaptionContainer;
readonly Label mCaptionLabel;
readonly Label mDescriptionLabel;
readonly AsyncTaskLoader mTaskLoader;
const float TextPaddingX = 12;
const float TextPaddingY = 3;
const float VerticalMargin = 5;
const float CornerRadius = 6;
const float MaxHeight = 80;
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: c02d2b10240a45b9a7a91666db0900bf
timeCreated: 1768387985
@@ -0,0 +1,387 @@
using System.Collections.Generic;
using Codice.Client.BaseCommands.BranchExplorer;
using UnityEngine;
using UnityEngine.UIElements;
namespace Unity.PlasticSCM.Editor.Views.BranchExplorer.Drawing.Shapes
{
internal static class BranchGeometry
{
const float BRANCH_RADIUS = 12f;
internal static void Draw(
Painter2D painter,
Rect main,
SubBranchContainerDrawInfo[] subrectangles,
out List<Vector2> hitTestPolygon)
{
Draw(
painter,
main.x, main.y, main.width, main.height,
subrectangles,
out hitTestPolygon);
}
static void Draw(
Painter2D painter,
float x,
float y,
float width,
float height,
SubBranchContainerDrawInfo[] containers,
out List<Vector2> hitTestPolygon)
{
hitTestPolygon = new List<Vector2>();
int shapeOffset =
(BrExDrawProperties.ChangesetDrawingHeight -
BrExDrawProperties.BranchHeight) / 2;
y += shapeOffset;
height -= shapeOffset * 2;
List<Rect> subRectangles = GetSubRectangles(containers);
List<Rect> rectangles = CalculateFusions(subRectangles);
Rect branchRectangle = new Rect(x, y, width, height);
AdjustLastRectangle(rectangles, branchRectangle);
AdjustFirstRectangle(rectangles, branchRectangle);
float radius = height / 2;
float xw = x + width;
float yh = y + height;
float xwr = xw - radius;
float xr = x + radius;
float r2 = radius * 2;
float xwr2 = xw - r2;
float angle = 180f;
Vector2 rightArcTargetPoint = new Vector2(xwr, yh);
if (rectangles.Count > 0)
{
Rect last = rectangles[rectangles.Count - 1];
if (last.xMax >= xwr2 + r2)
{
angle = 90f;
rightArcTargetPoint = new Vector2(xw, y + radius);
}
}
painter.BeginPath();
// Start at top-left after left arc
Vector2 currentPoint = new Vector2(xr, y);
painter.MoveTo(currentPoint);
hitTestPolygon.Add(currentPoint);
// Top Edge
currentPoint = new Vector2(xwr, y);
painter.LineTo(currentPoint);
hitTestPolygon.Add(currentPoint);
// Right arc
painter.PreciseArcTo(
currentPoint,
rightArcTargetPoint,
new Vector2(radius, radius),
angle,
false,
ArcDirection.Clockwise);
hitTestPolygon.Add(new Vector2(xw, y)); // top-right corner
hitTestPolygon.Add(new Vector2(xw, yh)); // bottom-right corner
currentPoint = rightArcTargetPoint;
hitTestPolygon.Add(currentPoint);
// Bottom Edge
float currentx = rightArcTargetPoint.x;
float currenty = rightArcTargetPoint.y;
if (rectangles != null)
{
for (int i = rectangles.Count - 1; i >= 0; i--)
{
Rect currentRectangle = rectangles[i];
Vector2 end = AddBottomRectangle(
painter,
currentRectangle,
currentx,
currenty,
x,
shapeOffset,
ref currentPoint,
hitTestPolygon);
currentx = end.x;
currenty = currentRectangle.y + shapeOffset;
}
}
float angle2 = 180f;
if (rectangles.Count > 0 && rectangles[0].x <= x)
{
angle2 = 90f;
Vector2 leftArcStart = new Vector2(rectangles[0].x, y + radius);
painter.LineTo(leftArcStart);
hitTestPolygon.Add(leftArcStart);
currentPoint = leftArcStart;
}
else
{
Vector2 leftArcStart = new Vector2(xr, yh);
painter.LineTo(leftArcStart);
hitTestPolygon.Add(leftArcStart);
currentPoint = leftArcStart;
}
// Left arc
Vector2 leftArcTarget = new Vector2(xr, y);
painter.PreciseArcTo(
currentPoint,
leftArcTarget,
new Vector2(radius, radius),
angle2,
false,
ArcDirection.Clockwise);
hitTestPolygon.Add(new Vector2(x, yh)); // bottom-left corner
hitTestPolygon.Add(new Vector2(x, y)); // top-left corner
painter.ClosePath();
}
// Add a rectangle in the bottom, from right to left
static Vector2 AddBottomRectangle(
Painter2D painter,
Rect r,
float x,
float y,
float minx,
float shapeOffset,
ref Vector2 currentPoint,
List<Vector2> hitTestPolygon)
{
r = new Rect(r.x, r.y + shapeOffset, r.width, r.height);
float xTopLeft = r.x - BRANCH_RADIUS;
float xTopRight = r.xMax + BRANCH_RADIUS;
float xBottomLeft = r.x + BRANCH_RADIUS;
float xBottomRight = r.xMax - BRANCH_RADIUS;
float yTop = r.y + BRANCH_RADIUS;
float yBottom = r.yMax - BRANCH_RADIUS;
Vector2 arcSize = new Vector2(BRANCH_RADIUS, BRANCH_RADIUS);
if (x > r.xMax)
{
Vector2 topRight = new Vector2(xTopRight, r.y);
painter.LineTo(topRight);
hitTestPolygon.Add(topRight);
currentPoint = topRight;
Vector2 arcTarget = new Vector2(r.xMax, yTop);
painter.PreciseArcTo(
currentPoint,
arcTarget,
arcSize,
90f,
false,
ArcDirection.CounterClockwise);
// Go directly to arc target (diagonal covers the outward-curving arc)
hitTestPolygon.Add(arcTarget);
currentPoint = arcTarget;
}
Vector2 rightBottom = new Vector2(r.xMax, yBottom);
painter.LineTo(rightBottom);
hitTestPolygon.Add(rightBottom);
currentPoint = rightBottom;
Vector2 bottomRight = new Vector2(xBottomRight, r.yMax);
painter.PreciseArcTo(
currentPoint,
bottomRight,
arcSize,
90f,
false,
ArcDirection.Clockwise);
hitTestPolygon.Add(new Vector2(r.xMax, r.yMax)); // corner point
hitTestPolygon.Add(bottomRight);
currentPoint = bottomRight;
Vector2 bottomLeft = new Vector2(xBottomLeft, r.yMax);
painter.LineTo(bottomLeft);
hitTestPolygon.Add(bottomLeft);
currentPoint = bottomLeft;
Vector2 leftBottom = new Vector2(r.x, yBottom);
painter.PreciseArcTo(
currentPoint,
leftBottom,
arcSize,
90f,
false,
ArcDirection.Clockwise);
hitTestPolygon.Add(new Vector2(r.x, r.yMax)); // corner point
hitTestPolygon.Add(leftBottom);
currentPoint = leftBottom;
Vector2 leftTop = new Vector2(r.x, yTop);
painter.LineTo(leftTop);
hitTestPolygon.Add(leftTop);
currentPoint = leftTop;
if (r.x > minx)
{
Vector2 topLeft = new Vector2(xTopLeft, r.y);
painter.PreciseArcTo(
currentPoint,
topLeft,
arcSize,
90f,
false,
ArcDirection.CounterClockwise);
// Go directly to arc target (diagonal covers the outward-curving arc)
hitTestPolygon.Add(topLeft);
currentPoint = topLeft;
}
else
{
Vector2 topLeft = new Vector2(r.x, r.y);
painter.LineTo(topLeft);
hitTestPolygon.Add(topLeft);
currentPoint = topLeft;
}
// return where the path ends
return new Vector2(xTopLeft, r.y);
}
// internal for testing
internal static List<Rect> CalculateFusions(List<Rect> rectangles)
{
if (rectangles.Count < 2)
return rectangles;
List<Rect> result = new List<Rect>();
for (int i = 0; i < rectangles.Count - 1; i++)
{
Rect current = rectangles[i];
Rect next = rectangles[i + 1];
if (current.xMax + (2 * BRANCH_RADIUS) >= next.x)
{
return CalculateFusions(Fusion(rectangles, current, next, i, i + 1));
}
result.Add(current);
}
result.Add(rectangles[rectangles.Count - 1]);
return result;
}
// internal for testing
internal static List<Rect> Fusion(
List<Rect> rectangles,
Rect current,
Rect next,
int index1,
int index2)
{
List<Rect> result = new List<Rect>();
Rect fusioned = new Rect(
current.x,
current.y,
current.width + 2 * BRANCH_RADIUS + next.width,
Mathf.Max(current.height, next.height));
for (int i = 0; i < rectangles.Count; i++)
{
if (i == index2)
continue;
if (i == index1)
{
result.Add(fusioned);
}
else
{
result.Add(rectangles[i]);
}
}
return result;
}
// internal for testing
internal static void AdjustFirstRectangle(List<Rect> rectangles, Rect branchRectangle)
{
if (rectangles.Count == 0)
return;
Rect first = rectangles[0];
if (branchRectangle.x + (3 * BRANCH_RADIUS) > first.x)
{
Rect newFirst = new Rect(
branchRectangle.x,
first.y,
first.width + (first.x - branchRectangle.x),
first.height);
rectangles[0] = newFirst;
}
}
// internal for testing
internal static void AdjustLastRectangle(List<Rect> rectangles, Rect branchRectangle)
{
if (rectangles.Count == 0)
return;
Rect last = rectangles[rectangles.Count - 1];
if (last.x + last.width + (3 * BRANCH_RADIUS) >= branchRectangle.x + branchRectangle.width)
{
Rect newLast = new Rect(
last.x,
last.y,
branchRectangle.xMax - last.x,
last.height);
rectangles[rectangles.Count - 1] = newLast;
}
}
// internal for testing
internal static List<Rect> GetSubRectangles(SubBranchContainerDrawInfo[] containers)
{
List<Rect> result = new List<Rect>();
if (containers == null)
return result;
foreach (SubBranchContainerDrawInfo container in containers)
{
result.Add(ConvertToRect(container.Bounds));
}
return result;
}
// internal for testing
internal static Rect ConvertToRect(BrExRectangle rectangle)
{
return new Rect(
rectangle.X, rectangle.Y, rectangle.Width, rectangle.Height);
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 9dd73ad7202d44c7ac002aeb112ff0fa
timeCreated: 1768818686
@@ -0,0 +1,186 @@
using System.Collections.Generic;
using Codice.Client.BaseCommands.BranchExplorer;
using Unity.PlasticSCM.Editor.UI;
using Unity.PlasticSCM.Editor.Views.BranchExplorer.Drawing.Shapes.Colors;
using Unity.PlasticSCM.Editor.Views.BranchExplorer.Virtualization;
using UnityEngine;
using UnityEngine.UIElements;
namespace Unity.PlasticSCM.Editor.Views.BranchExplorer.Drawing.Shapes
{
internal class BranchShape : BrExShape
{
// internal for testing purposes
internal bool IsHovered { get { return mIsHovered; } }
internal BranchDrawInfo BranchDrawInfo { get { return VirtualShape.DrawInfo as BranchDrawInfo; } }
internal Color ResolvedColor { get { return mResolvedColor; } }
internal static string BuildName(string branchFullName)
{
return "branch-" + branchFullName;
}
internal BranchShape(VirtualShape virtualShape, ColorProvider colorProvider) : base(virtualShape)
{
mColorProvider = colorProvider;
name = BuildName(BranchDrawInfo.Caption);
RegisterCallback<PointerEnterEvent>(OnPointerEnter);
RegisterCallback<PointerLeaveEvent>(OnPointerLeave);
}
internal override void Dispose()
{
base.Dispose();
UnregisterCallback<PointerEnterEvent>(OnPointerEnter);
UnregisterCallback<PointerLeaveEvent>(OnPointerLeave);
}
internal override bool HasContextMenu() => true;
public override bool ContainsPoint(Vector2 localPoint)
{
if (!DisplayOptions.DisplayBranches)
return false;
return mHitTestPolygon.ContainsPoint(localPoint);
}
protected override void GenerateVisualContent(Painter2D painter)
{
if (!DisplayOptions.DisplayBranches)
return;
Rect geometryRect = new Rect(
0, 0,
BranchDrawInfo.Bounds.Width,
BranchDrawInfo.Bounds.Height);
SubBranchContainerDrawInfo[] containers = TranslateSubBranchContainers(
BranchDrawInfo.SubBranchContainers,
BranchDrawInfo.Bounds);
Color branchColor = mColorProvider.GetBranchColor(this, IsMultiBranchSelected());
Color borderColor = BrExColors.Branch.GetBorderColor(
IsSelected, IsMultiBranchSelected(), IsCurrentSearchResult);
if (mIsHovered)
{
branchColor = BrightenColor(branchColor, HoverBrightenAmount);
borderColor = BrightenColor(borderColor, HoverBrightenAmount);
}
mResolvedColor = branchColor;
painter.fillColor = branchColor;
painter.strokeColor = borderColor;
painter.lineWidth = mIsHovered
? BrExLineWidths.Branch.GetBorderWidth()
: BrExLineWidths.Branch.GetBorderWidth();
BranchGeometry.Draw(
painter,
geometryRect,
containers,
out mHitTestPolygon);
painter.Stroke();
painter.Fill();
if (BranchDrawInfo.IsWorkspaceBranch && BranchDrawInfo.IsEmpty())
{
DrawHomeGlyph(painter, geometryRect);
}
}
static void DrawHomeGlyph(Painter2D painter, Rect branchBounds)
{
float scale = 0.825f;
float glyphWidth = HomeGeometry.WIDTH * scale;
float glyphHeight = HomeGeometry.HEIGHT * scale;
float offsetX = (branchBounds.width / 2) - (glyphWidth / 2);
float offsetY = (branchBounds.height / 2) - (glyphHeight / 2);
painter.fillColor = BrExColors.Branch.GetHomeGlyphFillColor();
HomeGeometry.Draw(painter, offsetX, offsetY, scale);
painter.Fill();
}
static SubBranchContainerDrawInfo[] TranslateSubBranchContainers(
SubBranchContainerDrawInfo[] subBranchContainers,
BrExRectangle relativeTo)
{
if (subBranchContainers == null || subBranchContainers.Length == 0)
return subBranchContainers;
List<SubBranchContainerDrawInfo> translatedSubBranchContainers = new List<SubBranchContainerDrawInfo>();
foreach (var subBranchContainer in subBranchContainers)
{
translatedSubBranchContainers.Add(new SubBranchContainerDrawInfo()
{
Bounds = new BrExRectangle(
subBranchContainer.Bounds.X - relativeTo.X,
subBranchContainer.Bounds.Y - relativeTo.Y,
subBranchContainer.Bounds.Width,
subBranchContainer.Bounds.Height),
CaptionBounds = subBranchContainer.CaptionBounds,
Depth = subBranchContainer.Depth,
IniChangeset = subBranchContainer.IniChangeset,
EndChangeset = subBranchContainer.EndChangeset,
Tag = subBranchContainer.Tag,
Visual = subBranchContainer.Visual,
Hidden = subBranchContainer.Hidden
});
}
return translatedSubBranchContainers.ToArray();
}
bool IsMultiBranchSelected()
{
BranchExplorerViewer brExView = this.GetFirstAncestorOfType<BranchExplorerViewer>();
if (brExView == null)
return false;
return brExView.Selection.GetSelectedBranches().Count > 1;
}
// internal for testing purposes
internal void OnPointerEnter(PointerEnterEvent evt)
{
if (evt.pressedButtons != 0)
return;
mIsHovered = true;
MarkDirtyRepaint();
}
// internal for testing purposes
internal void OnPointerLeave(PointerLeaveEvent evt)
{
mIsHovered = false;
MarkDirtyRepaint();
}
static Color BrightenColor(Color color, float amount)
{
return new Color(
Mathf.Min(1f, color.r + amount),
Mathf.Min(1f, color.g + amount),
Mathf.Min(1f, color.b + amount),
Mathf.Clamp01(color.a + amount * 0.5f));
}
bool mIsHovered;
Color mResolvedColor;
List<Vector2> mHitTestPolygon;
readonly ColorProvider mColorProvider;
const float HoverBrightenAmount = 0.08f;
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 7f5193b7e776436a9f838cd480cb7460
timeCreated: 1768387965
@@ -0,0 +1,457 @@
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;
using Codice.Client.BaseCommands.BranchExplorer;
using PlasticGui;
using PlasticGui.WorkspaceWindow.BranchExplorer;
using Unity.PlasticSCM.Editor.UI;
using Unity.PlasticSCM.Editor.Views.BranchExplorer.Drawing.Shapes.Colors;
using Unity.PlasticSCM.Editor.Views.BranchExplorer.Virtualization;
namespace Unity.PlasticSCM.Editor.Views.BranchExplorer.Drawing.Shapes
{
internal class ChangesetCommentShape : BrExShape
{
// internal for testing purposes
internal bool IsExpanded { get { return mIsExpanded; } }
internal ChangesetDrawInfo ChangesetDraw
{
get { return VirtualShape.DrawInfo as ChangesetDrawInfo; }
}
internal ChangesetCommentShape(
VirtualShape virtualShape,
AsyncChangesetCommentResolver commentResolver) : base(virtualShape)
{
mCommentResolver = commentResolver;
mCommentContainer = new VisualElement();
mCommentContainer.style.position = Position.Absolute;
mCommentContainer.style.overflow = Overflow.Hidden;
mCommentContainer.style.borderTopLeftRadius = CornerRadius;
mCommentContainer.style.borderTopRightRadius = CornerRadius;
mCommentContainer.style.borderBottomLeftRadius = CornerRadius;
mCommentContainer.style.borderBottomRightRadius = CornerRadius;
mCommentContainer.style.paddingLeft = 0;
mCommentContainer.style.paddingRight = 0;
mCommentContainer.style.paddingTop = 0;
mCommentContainer.style.paddingBottom = 0;
mCommentContainer.style.width = CollapsedWidth;
mCommentLabel = new Label();
mCommentLabel.style.fontSize = DefaultFontSize;
mCommentLabel.style.color = UnityStyles.Colors.SecondaryLabel;
mCommentLabel.style.marginBottom = 0;
mCommentLabel.style.marginTop = 0;
mCommentLabel.style.paddingBottom = 0;
mCommentLabel.style.paddingTop = 0;
mCommentLabel.style.whiteSpace = WhiteSpace.NoWrap;
mCommentLabel.style.textOverflow = TextOverflow.Ellipsis;
mCommentLabel.style.overflow = Overflow.Hidden;
mCommentLabel.pickingMode = PickingMode.Ignore;
mCommentLabel.style.transitionProperty =
new List<StylePropertyName> { new StylePropertyName("color") };
mCommentLabel.style.transitionDuration =
new List<TimeValue> { new TimeValue(ColorTransitionMs, TimeUnit.Millisecond) };
mScrollView = new ScrollView(ScrollViewMode.Vertical);
mScrollView.verticalScrollerVisibility = ScrollerVisibility.Hidden;
mScrollView.horizontalScrollerVisibility = ScrollerVisibility.Hidden;
mScrollView.Add(mCommentLabel);
mCommentContainer.Add(mScrollView);
Add(mCommentContainer);
mHitTestOverlay = new VisualElement();
mHitTestOverlay.style.position = Position.Absolute;
mHitTestOverlay.pickingMode = PickingMode.Position;
Add(mHitTestOverlay);
mHitTestOverlay.RegisterCallback<PointerEnterEvent>(OnPointerEnter);
mHitTestOverlay.RegisterCallback<PointerLeaveEvent>(OnPointerLeave);
mCommentContainer.RegisterCallback<PointerEnterEvent>(OnPointerEnter);
mCommentContainer.RegisterCallback<PointerLeaveEvent>(OnPointerLeave);
mCommentContainer.RegisterCallback<WheelEvent>(OnWheelEvent);
mCommentContainer.RegisterCallback<GeometryChangedEvent>(OnContainerGeometryChanged);
RegisterCallback<AttachToPanelEvent>(OnAttachToPanel);
}
internal override void Dispose()
{
CancelScheduledCollapse();
mHitTestOverlay.UnregisterCallback<PointerEnterEvent>(OnPointerEnter);
mHitTestOverlay.UnregisterCallback<PointerLeaveEvent>(OnPointerLeave);
mCommentContainer.UnregisterCallback<PointerEnterEvent>(OnPointerEnter);
mCommentContainer.UnregisterCallback<PointerLeaveEvent>(OnPointerLeave);
mCommentContainer.UnregisterCallback<WheelEvent>(OnWheelEvent);
mCommentContainer.UnregisterCallback<GeometryChangedEvent>(OnContainerGeometryChanged);
UnregisterCallback<AttachToPanelEvent>(OnAttachToPanel);
base.Dispose();
}
internal override void Redraw()
{
UpdateCommentText();
UpdateLayout();
UpdateVisibilityForZoom();
base.Redraw();
}
protected override void GenerateVisualContent(Painter2D painter)
{
if (!DisplayOptions.DisplayChangesetComments)
return;
RequestResolveComment();
}
internal override bool HasContextMenu() => false;
public override bool ContainsPoint(Vector2 localPoint)
{
return mCommentContainer.localBound.Contains(localPoint);
}
internal override void OnScrollChanged()
{
UpdateVisibilityForZoom();
}
protected internal override VirtualShape GetVirtualShapeForSelection()
{
VirtualCanvas canvas = GetFirstAncestorOfType<VirtualCanvas>();
if (canvas == null)
return null;
foreach (BrExShape brExShape in canvas.GetShapes())
{
if (brExShape is ChangesetShape changesetShape &&
changesetShape.ChangesetDraw == ChangesetDraw)
return brExShape.VirtualShape;
}
return null;
}
void OnAttachToPanel(AttachToPanelEvent evt)
{
if (!DisplayOptions.DisplayChangesetComments)
return;
RequestResolveComment();
UpdateCommentText();
UpdateLayout();
UpdateVisibilityForZoom();
}
void OnContainerGeometryChanged(GeometryChangedEvent evt)
{
UpdateHitTestOverlaySize();
}
// internal for testing purposes
internal void OnPointerEnter(PointerEnterEvent evt)
{
// don't expand while dragging
if (evt.pressedButtons != 0)
return;
Expand();
}
// internal for testing purposes
internal void OnPointerLeave(PointerLeaveEvent evt)
{
// Don't collapse while dragging (e.g. scrollbar thumb drag
// that moves the pointer outside the container bounds).
if (mIsExpanded && evt.pressedButtons != 0)
return;
ScheduleCollapse();
}
void OnWheelEvent(WheelEvent evt)
{
if (!mIsExpanded)
return;
float contentHeight = mScrollView.contentContainer.layout.height;
float viewportHeight = mScrollView.contentViewport.layout.height;
if (contentHeight <= viewportHeight)
return;
evt.StopPropagation();
}
internal void Expand()
{
CancelScheduledCollapse();
if (mIsExpanded)
return;
if (string.IsNullOrEmpty(mCommentLabel.text))
return;
if (!IsVisibleForZoomLevel())
return;
mIsExpanded = true;
mCommentLabel.text = mOriginalComment;
mCommentLabel.style.color = UnityStyles.Colors.Label;
mCommentLabel.style.whiteSpace = WhiteSpace.Normal;
mCommentLabel.style.textOverflow = TextOverflow.Clip;
mCommentLabel.style.overflow = Overflow.Visible;
mCommentContainer.style.backgroundColor =
UnityStyles.Colors.BranchExplorer.ControlBackgroundColor;
Color borderColor = BrExColors.Label.GetCaptionBorderColor();
mCommentContainer.style.borderTopColor = borderColor;
mCommentContainer.style.borderBottomColor = borderColor;
mCommentContainer.style.borderLeftColor = borderColor;
mCommentContainer.style.borderRightColor = borderColor;
mCommentContainer.style.borderTopWidth = ExpandedBorderWidth;
mCommentContainer.style.borderBottomWidth = ExpandedBorderWidth;
mCommentContainer.style.borderLeftWidth = ExpandedBorderWidth;
mCommentContainer.style.borderRightWidth = ExpandedBorderWidth;
mCommentContainer.style.paddingLeft = ExpandedPadding;
mCommentContainer.style.paddingRight = ExpandedPadding;
mCommentContainer.style.paddingTop = ExpandedPadding;
mCommentContainer.style.paddingBottom = ExpandedPadding;
mCommentContainer.style.width = StyleKeyword.Auto;
mCommentContainer.style.maxWidth = MaxExpandedWidth + 2 * ExpandedPadding;
mCommentContainer.style.maxHeight = MaxExpandedHeight;
mScrollView.verticalScrollerVisibility = ScrollerVisibility.Auto;
mScrollView.style.maxHeight =
MaxExpandedHeight - 2 * (ExpandedPadding + ExpandedBorderWidth);
// Let pointer events pass through the overlay so the
// ScrollView and its scrollbar receive clicks/drags directly.
// The container's own enter/leave callbacks handle collapse.
mHitTestOverlay.pickingMode = PickingMode.Ignore;
UpdateLayout();
BringToFront();
}
internal void ScheduleCollapse()
{
CancelScheduledCollapse();
mScheduledCollapse = schedule.Execute(Collapse).StartingIn(CollapseDelayMs);
}
void Collapse()
{
if (!mIsExpanded)
return;
mIsExpanded = false;
mCommentLabel.text = CommentFormatter.GetFormattedComment(mOriginalComment);
mCommentLabel.style.color = UnityStyles.Colors.SecondaryLabel;
mCommentLabel.style.whiteSpace = WhiteSpace.NoWrap;
mCommentLabel.style.textOverflow = TextOverflow.Ellipsis;
mCommentLabel.style.overflow = Overflow.Hidden;
mCommentContainer.style.paddingLeft = 0;
mCommentContainer.style.paddingRight = 0;
mCommentContainer.style.paddingTop = 0;
mCommentContainer.style.paddingBottom = 0;
mCommentContainer.style.borderTopWidth = 0;
mCommentContainer.style.borderBottomWidth = 0;
mCommentContainer.style.borderLeftWidth = 0;
mCommentContainer.style.borderRightWidth = 0;
mCommentContainer.style.backgroundColor = Color.clear;
mCommentContainer.style.width = CollapsedWidth;
mCommentContainer.style.maxWidth = new StyleLength(StyleKeyword.None);
mCommentContainer.style.maxHeight = CollapsedHeight;
mCommentContainer.style.overflow = Overflow.Hidden;
mScrollView.verticalScrollerVisibility = ScrollerVisibility.Hidden;
mScrollView.style.maxHeight = new StyleLength(StyleKeyword.None);
mScrollView.scrollOffset = Vector2.zero;
// Restore the overlay so it captures enter/leave for
// the collapsed state hit testing.
mHitTestOverlay.pickingMode = PickingMode.Position;
UpdateLayout();
VirtualCanvas canvas = parent as VirtualCanvas;
canvas?.RestoreZOrder(this);
}
void CancelScheduledCollapse()
{
if (mScheduledCollapse == null)
return;
mScheduledCollapse.Pause();
mScheduledCollapse = null;
}
void UpdateCommentText()
{
if (!DisplayOptions.DisplayChangesetComments)
{
mCommentLabel.text = string.Empty;
mOriginalComment = string.Empty;
return;
}
BrExChangeset changeset = ChangesetDraw.Tag as BrExChangeset;
if (changeset == null)
{
mCommentLabel.text = string.Empty;
mOriginalComment = string.Empty;
return;
}
string comment = mCommentResolver.GetResolvedComment(changeset.Id);
mOriginalComment = comment ?? string.Empty;
mCommentLabel.text = mIsExpanded
? mOriginalComment
: CommentFormatter.GetFormattedComment(mOriginalComment);
}
void UpdateLayout()
{
float shapeWidth = VirtualShape.Bounds.width;
// always use the collapsed width for the text origin so the
// text stays at the exact same position in both states.
float textOriginX = (shapeWidth - CollapsedWidth) / 2f;
float textOriginY = 0;
float containerX = textOriginX;
float containerY = textOriginY;
// when expanded, offset by the padding + border so the
// background/border grow outward and text doesn't shift.
if (mIsExpanded)
{
containerX -= ExpandedPadding + ExpandedBorderWidth;
containerY -= ExpandedPadding + ExpandedBorderWidth;
}
mCommentContainer.style.left = containerX;
mCommentContainer.style.top = containerY;
mHitTestOverlay.style.left = containerX;
mHitTestOverlay.style.top = containerY;
UpdateHitTestOverlaySize();
}
void UpdateHitTestOverlaySize()
{
if (!mIsExpanded)
{
mHitTestOverlay.style.width = CollapsedWidth;
mHitTestOverlay.style.height = CollapsedHeight;
return;
}
float containerWidth = mCommentContainer.resolvedStyle.width;
float containerHeight = mCommentContainer.resolvedStyle.height;
float hitWidth = !float.IsNaN(containerWidth) && containerWidth > 0
? containerWidth
: CollapsedWidth;
float hitHeight = !float.IsNaN(containerHeight) && containerHeight > 0
? containerHeight
: CollapsedHeight;
float offset = ExpandedPadding + ExpandedBorderWidth;
float minExpandedHeight = CollapsedHeight + offset + HitTestMargin;
float minExpandedWidth = CollapsedWidth + offset + HitTestMargin;
if (hitHeight < minExpandedHeight)
hitHeight = minExpandedHeight;
if (hitWidth < minExpandedWidth)
hitWidth = minExpandedWidth;
mHitTestOverlay.style.width = hitWidth;
mHitTestOverlay.style.height = hitHeight;
}
void UpdateVisibilityForZoom()
{
bool isVisible = IsVisibleForZoomLevel();
if (!visible && mIsExpanded)
Collapse();
visible = isVisible;
}
void RequestResolveComment()
{
BrExChangeset changeset = ChangesetDraw.Tag as BrExChangeset;
if (changeset == null)
return;
mCommentResolver.RequestComment(changeset.Id);
}
internal static ChangesetCommentShape FindForChangeset(
VirtualCanvas canvas, ChangesetDrawInfo changesetDraw)
{
if (canvas == null)
return null;
foreach (BrExShape shape in canvas.GetShapes())
{
if (shape is ChangesetCommentShape commentShape &&
commentShape.ChangesetDraw == changesetDraw)
return commentShape;
}
return null;
}
bool IsVisibleForZoomLevel()
{
VirtualCanvas canvas = GetFirstAncestorOfType<VirtualCanvas>();
return canvas != null && canvas.ZoomLevel >= BrExShape.MinZoomToShowText;
}
IVisualElementScheduledItem mScheduledCollapse;
bool mIsExpanded;
string mOriginalComment = string.Empty;
readonly AsyncChangesetCommentResolver mCommentResolver;
readonly VisualElement mCommentContainer;
readonly ScrollView mScrollView;
readonly Label mCommentLabel;
readonly VisualElement mHitTestOverlay;
const float CollapsedWidth = BrExDrawProperties.ChangesetWidth;
const float CollapsedHeight = 20;
const float MaxExpandedWidth = 250;
const float MaxExpandedHeight = 120;
const float ExpandedPadding = 4;
const float CornerRadius = 4;
const float ExpandedBorderWidth = 1;
const float HitTestMargin = 4;
const int DefaultFontSize = 10;
const long CollapseDelayMs = 100;
const int ColorTransitionMs = 250;
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: c7d6a678a5bdb45c9b91c35d33ad597d
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,294 @@
using System.Globalization;
using Codice.Client.BaseCommands.BranchExplorer;
using Unity.PlasticSCM.Editor.UI;
using Unity.PlasticSCM.Editor.Views.BranchExplorer.Drawing.Shapes.Colors;
using Unity.PlasticSCM.Editor.Views.BranchExplorer.Virtualization;
using UnityEditor;
using UnityEngine;
using UnityEngine.UIElements;
namespace Unity.PlasticSCM.Editor.Views.BranchExplorer.Drawing.Shapes
{
internal class ChangesetNumberShape : BrExShape
{
internal ChangesetDrawInfo ChangesetDraw
{
get { return VirtualShape.DrawInfo as ChangesetDrawInfo; }
}
internal static string BuildName(long changesetId)
{
return "changeset-number-" + changesetId;
}
internal ChangesetNumberShape(VirtualShape virtualShape) : base(virtualShape)
{
name = BuildName(GetChangesetId(ChangesetDraw));
mContainer = new VisualElement();
mContainer.style.position = Position.Absolute;
mContainer.style.left = 0;
mContainer.style.top = 0;
mContainer.style.width = Length.Percent(100);
mContainer.style.height = Length.Percent(100);
mContainer.style.overflow = Overflow.Hidden;
mContainer.style.borderTopLeftRadius = CornerRadius;
mContainer.style.borderTopRightRadius = CornerRadius;
mContainer.style.borderBottomLeftRadius = CornerRadius;
mContainer.style.borderBottomRightRadius = CornerRadius;
Color borderColor = BrExColors.Label.GetCaptionBorderColor();
mContainer.style.borderTopColor = borderColor;
mContainer.style.borderBottomColor = borderColor;
mContainer.style.borderLeftColor = borderColor;
mContainer.style.borderRightColor = borderColor;
mContainer.style.borderTopWidth = ExpandedBorderWidth;
mContainer.style.borderBottomWidth = ExpandedBorderWidth;
mContainer.style.borderLeftWidth = ExpandedBorderWidth;
mContainer.style.borderRightWidth = ExpandedBorderWidth;
mContainer.style.paddingLeft = ExpandedPadding;
mContainer.style.paddingRight = ExpandedPadding;
mContainer.style.paddingTop = ExpandedPadding;
mContainer.style.paddingBottom = ExpandedPadding;
mContainer.style.backgroundColor =
UnityStyles.Colors.BranchExplorer.ControlBackgroundColor;
mNumberLabel = new Label();
mNumberLabel.style.fontSize = DefaultFontSize;
mNumberLabel.style.color = UnityStyles.Colors.Label;
mNumberLabel.style.whiteSpace = WhiteSpace.NoWrap;
mNumberLabel.style.unityTextAlign = TextAnchor.MiddleCenter;
mNumberLabel.style.marginLeft = 0;
mNumberLabel.style.marginRight = 0;
mNumberLabel.style.marginTop = 0;
mNumberLabel.style.marginBottom = 0;
mNumberLabel.pickingMode = PickingMode.Ignore;
mContainer.Add(mNumberLabel);
Add(mContainer);
pickingMode = PickingMode.Position;
RegisterCallback<AttachToPanelEvent>(OnAttachToPanel);
RegisterCallback<PointerEnterEvent>(OnPointerEnter);
RegisterCallback<PointerLeaveEvent>(OnPointerLeave);
Redraw();
}
internal static ChangesetNumberShape FindForChangeset(
VirtualCanvas canvas, ChangesetDrawInfo changesetDraw)
{
if (canvas == null)
return null;
foreach (BrExShape shape in canvas.GetShapes())
{
if (shape is ChangesetNumberShape numberShape &&
numberShape.ChangesetDraw == changesetDraw)
return numberShape;
}
return null;
}
internal static Vector2 MeasureNumberBoxSize(string text)
{
if (string.IsNullOrEmpty(text))
return Vector2.zero;
GUIStyle style = new GUIStyle(EditorStyles.label);
style.fontSize = DefaultFontSize;
Vector2 textSize = style.CalcSize(new GUIContent(text));
float edge = (ExpandedPadding + ExpandedBorderWidth) * 2f;
return new Vector2(textSize.x + edge, textSize.y + edge);
}
static long GetChangesetId(ChangesetDrawInfo changesetDraw)
{
BrExChangeset changeset = changesetDraw.Tag as BrExChangeset;
return changeset != null ? changeset.Id : 0;
}
internal static string GetNumberText(ChangesetDrawInfo drawInfo)
{
if (drawInfo == null)
return null;
BrExChangeset changeset = drawInfo.Tag as BrExChangeset;
if (changeset == null || changeset.IsCheckoutChangeset)
return null;
return changeset.Id.ToString(CultureInfo.InvariantCulture);
}
internal void Expand()
{
CancelScheduledCollapse();
if (mIsExpanded)
return;
if (!IsVisibleForZoomLevel())
return;
mIsExpanded = true;
UpdateVisibilityForZoom();
}
internal void ScheduleCollapse()
{
CancelScheduledCollapse();
mScheduledCollapse = schedule.Execute(Collapse).StartingIn(CollapseDelayMs);
}
internal void CancelScheduledCollapse()
{
if (mScheduledCollapse == null)
return;
mScheduledCollapse.Pause();
mScheduledCollapse = null;
}
internal override void Dispose()
{
CancelScheduledCollapse();
UnregisterCallback<AttachToPanelEvent>(OnAttachToPanel);
UnregisterCallback<PointerEnterEvent>(OnPointerEnter);
UnregisterCallback<PointerLeaveEvent>(OnPointerLeave);
base.Dispose();
}
internal override void Redraw()
{
if (!DisplayOptions.DisplayChangesetNumbers)
{
mIsExpanded = false;
CancelScheduledCollapse();
}
UpdateNumberText();
UpdateVisibilityForZoom();
base.Redraw();
}
protected override void GenerateVisualContent(Painter2D painter)
{
}
internal override bool HasContextMenu()
{
return false;
}
internal override void OnScrollChanged()
{
UpdateVisibilityForZoom();
}
protected internal override VirtualShape GetVirtualShapeForSelection()
{
VirtualCanvas canvas = GetFirstAncestorOfType<VirtualCanvas>();
if (canvas == null)
return null;
foreach (BrExShape brExShape in canvas.GetShapes())
{
if (brExShape is ChangesetShape changesetShape &&
changesetShape.ChangesetDraw == ChangesetDraw)
return brExShape.VirtualShape;
}
return null;
}
void OnAttachToPanel(AttachToPanelEvent evt)
{
UpdateVisibilityForZoom();
}
void OnPointerEnter(PointerEnterEvent evt)
{
if (evt.pressedButtons != 0)
return;
Expand();
}
void OnPointerLeave(PointerLeaveEvent evt)
{
if (mIsExpanded && evt.pressedButtons != 0)
return;
ScheduleCollapse();
}
void Collapse()
{
mScheduledCollapse = null;
if (!mIsExpanded)
return;
mIsExpanded = false;
UpdateVisibilityForZoom();
}
void UpdateNumberText()
{
string text = GetNumberText(ChangesetDraw);
mNumberLabel.text = text ?? string.Empty;
}
void UpdateVisibilityForZoom()
{
bool zoomOk = IsVisibleForZoomLevel();
if (!zoomOk && mIsExpanded)
{
mIsExpanded = false;
CancelScheduledCollapse();
}
visible = zoomOk && DisplayOptions.DisplayChangesetNumbers;
SyncContainerVisibility();
MarkDirtyRepaint();
}
void SyncContainerVisibility()
{
string text = GetNumberText(ChangesetDraw);
bool showCaption =
visible &&
mIsExpanded &&
!string.IsNullOrEmpty(text);
mContainer.style.display = showCaption ? DisplayStyle.Flex : DisplayStyle.None;
}
bool IsVisibleForZoomLevel()
{
VirtualCanvas canvas = GetFirstAncestorOfType<VirtualCanvas>();
return canvas != null && canvas.ZoomLevel >= BrExShape.MinZoomToShowText;
}
readonly VisualElement mContainer;
readonly Label mNumberLabel;
IVisualElementScheduledItem mScheduledCollapse;
bool mIsExpanded;
const float ExpandedPadding = 4;
const float ExpandedBorderWidth = 1;
const float CornerRadius = 4;
const int DefaultFontSize = 10;
const long CollapseDelayMs = 100;
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 733cdcd5219de8f4192fa7fc20da99ac
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,530 @@
using System.Collections.Generic;
using Codice.Client.BaseCommands.BranchExplorer;
using Codice.Client.BaseCommands.BranchExplorer.Layout;
using Codice.CM.Common;
using CodiceApp.Gravatar;
using PlasticGui;
using PlasticGui.WorkspaceWindow.BranchExplorer;
using Unity.PlasticSCM.Editor.UI;
using Unity.PlasticSCM.Editor.UI.Avatar;
using Unity.PlasticSCM.Editor.Views.BranchExplorer.Drawing.Shapes.Colors;
using Unity.PlasticSCM.Editor.Views.BranchExplorer.Virtualization;
using UnityEngine;
using UnityEngine.UIElements;
namespace Unity.PlasticSCM.Editor.Views.BranchExplorer.Drawing.Shapes
{
internal class ChangesetShape : BrExShape
{
// internal for testing purposes
internal bool IsHovered { get { return mIsHovered; } }
internal ChangesetDrawInfo ChangesetDraw { get { return VirtualShape.DrawInfo as ChangesetDrawInfo; } }
internal Color ResolvedColor { get { return mResolvedColor; } }
internal static string BuildName(long changesetId)
{
return "changeset-" + changesetId;
}
internal ChangesetShape(
VirtualShape virtualShape,
ColorProvider colorProvider,
AsyncUserNameResolver userNameResolver) : base(virtualShape)
{
mColorProvider = colorProvider;
mUserNameResolver = userNameResolver;
name = BuildName(GetChangesetId(ChangesetDraw));
if (DisplayOptions.DisplayUserAvatar)
{
UpdateAvatar();
}
if (ChangesetDraw.IsWorkspaceChangeset && ChangesetDraw.Branch.IsWorkspaceBranch)
{
CreateHomeImage();
}
SetupHoverEffects();
RegisterCallback<AttachToPanelEvent>(OnAttachToPanel);
RegisterCallback<PointerEnterEvent>(OnPointerEnter);
RegisterCallback<PointerLeaveEvent>(OnPointerLeave);
}
void CreateHomeImage()
{
mHomeImage = new HomeImageOverlay(
HomeGeometry.WIDTH,
HomeGeometry.HEIGHT);
UpdateHomeImageBorder();
mHomeImage.style.position = Position.Absolute;
mHomeImage.style.right = -3;
mHomeImage.style.bottom = -3;
Add(mHomeImage);
}
internal override void Dispose()
{
base.Dispose();
mIsHovered = false;
mHomeImage?.Dispose();
UnregisterCallback<AttachToPanelEvent>(OnAttachToPanel);
UnregisterCallback<PointerEnterEvent>(OnPointerEnter);
UnregisterCallback<PointerLeaveEvent>(OnPointerLeave);
}
internal override void Redraw()
{
base.Redraw();
UpdateHomeImageBorder();
UpdateGlowColor();
if (!DisplayOptions.DisplayUserAvatar)
{
HideAvatarControls();
return;
}
UpdateAvatar();
}
void UpdateHomeImageBorder()
{
if (mHomeImage == null)
return;
Color borderColor = mColorProvider.GetChangesetColor(
this, IsMultiChangesetSelected());
mHomeImage.style.borderLeftColor = borderColor;
mHomeImage.style.borderRightColor = borderColor;
mHomeImage.style.borderTopColor = borderColor;
mHomeImage.style.borderBottomColor = borderColor;
}
internal override bool HasContextMenu() => true;
public override bool ContainsPoint(Vector2 localPoint)
{
Vector2 center = new Vector2(
BrExDrawProperties.ChangesetRadius,
BrExDrawProperties.ChangesetRadius);
float strokeWidth = BrExLineWidths.Changeset.GetOuterBorderWidth(
ChangesetDraw.IsCheckoutChangeset);
return Vector2.Distance(localPoint, center) <= BrExDrawProperties.ChangesetRadius + strokeWidth;
}
protected override void GenerateVisualContent(Painter2D painter)
{
Color changesetColor = mColorProvider.GetChangesetColor(
this, IsMultiChangesetSelected());
mResolvedColor = changesetColor;
if (DrawWithOpacity())
{
//context.DrawGeometry(ThemeBrushes.Name.ControlBrush.GetBrush(), null, DefiningGeometry);
//opacity = context.PushOpacity(0.3);
}
// outer fill
painter.fillColor = UnityStyles.Colors.BranchExplorer.ControlBackgroundColor;
painter.DrawCircle(
new Vector2(BrExDrawProperties.ChangesetRadius, BrExDrawProperties.ChangesetRadius),
BrExDrawProperties.ChangesetRadius);
painter.Fill();
// outer border
painter.strokeColor = changesetColor;
painter.lineWidth = BrExLineWidths.Changeset.GetOuterBorderWidth(ChangesetDraw.IsCheckoutChangeset);
painter.StrokeCircle(
new Vector2(BrExDrawProperties.ChangesetRadius, BrExDrawProperties.ChangesetRadius),
BrExDrawProperties.ChangesetRadius,
BrExDashes.GetChangesetDashPattern(ChangesetDraw.IsCheckoutChangeset));
if (ChangesetDraw.IsHead && !ChangesetDraw.IsCheckoutChangeset)
{
// head border
painter.strokeColor = changesetColor;
painter.lineWidth = BrExLineWidths.Changeset.GetHeadBorderWidth();
painter.DrawCircle(
new Vector2(BrExDrawProperties.ChangesetRadius, BrExDrawProperties.ChangesetRadius),
BrExDrawProperties.ChangesetHeadRadius);
painter.Stroke();
}
if (!ChangesetDraw.IsCheckoutChangeset)
{
// changeset fill
painter.fillColor = changesetColor;
painter.DrawCircle(
new Vector2(BrExDrawProperties.ChangesetRadius, BrExDrawProperties.ChangesetRadius),
BrExDrawProperties.ChangesetFillRadius);
painter.Fill();
if (mIsHovered)
{
painter.fillColor = new Color(1f, 1f, 1f, HoverHighlightAlpha);
painter.DrawCircle(
new Vector2(BrExDrawProperties.ChangesetRadius, BrExDrawProperties.ChangesetRadius),
BrExDrawProperties.ChangesetFillRadius);
painter.Fill();
}
}
}
bool IsMultiChangesetSelected()
{
BranchExplorerViewer brExView = this.GetFirstAncestorOfType<BranchExplorerViewer>();
if (brExView == null)
return false;
return brExView.Selection.GetSelectedChangesets().Count > 1;
}
static long GetChangesetId(ChangesetDrawInfo changesetDraw)
{
BrExChangeset changeset = changesetDraw.Tag as BrExChangeset;
return changeset != null ? changeset.Id : 0;
}
bool DrawWithOpacity()
{
if (IsSearchResult || IsSelected)
return false;
if (DisplayOptions.UserFilter == null)
return false;
// draw with opacity if the user is filtered
return !DisplayOptions.UserFilter.Contains(((BrExChangeset)ChangesetDraw.Tag).Owner);
}
void OnAttachToPanel(AttachToPanelEvent evt)
{
if (!DisplayOptions.DisplayUserAvatar)
return;
UpdateAvatar();
}
void UpdateAvatar()
{
SEID owner = ((BrExChangeset)ChangesetDraw.Tag).Owner;
if (owner == null)
{
HideAvatarControls();
return;
}
string resolvedUserName = mUserNameResolver.GetResolvedUserName(owner);
if (string.IsNullOrEmpty(resolvedUserName))
{
mUserNameResolver.RequestUserName(owner);
HideAvatarControls();
return;
}
VirtualCanvas canvas = GetFirstAncestorOfType<VirtualCanvas>();
if (canvas == null)
return;
GetAvatar.ForEmail(resolvedUserName, canvas.RedrawChangesetShapes);
if (AvatarImages.HasDownloadedGravatar(resolvedUserName))
{
CreateAvatarImage();
UpdateAvatarImage(AvatarImages.GetAvatar(resolvedUserName));
HideAvatarLabel();
return;
}
CreateAvatarLabel();
UpdateAvatarLabel(resolvedUserName);
HideAvatarImage();
}
void CreateAvatarLabel()
{
if (mAvatarLabel != null)
return;
int radius = BrExDrawProperties.ChangesetFillRadius;
mAvatarLabel = new Label();
mAvatarLabel.style.position = Position.Absolute;
mAvatarLabel.style.paddingLeft = 1;
mAvatarLabel.style.paddingRight = 1;
mAvatarLabel.style.borderBottomLeftRadius = radius;
mAvatarLabel.style.borderBottomRightRadius = radius;
mAvatarLabel.style.borderTopLeftRadius = radius;
mAvatarLabel.style.borderTopRightRadius = radius;
mAvatarLabel.style.color = Color.white;
mAvatarLabel.style.unityTextAlign = TextAnchor.MiddleCenter;
int offset = BrExDrawProperties.ChangesetRadius - radius;
mAvatarLabel.style.left = offset;
mAvatarLabel.style.top = offset;
mAvatarLabel.style.width = radius * 2;
mAvatarLabel.style.height = radius * 2;
Add(mAvatarLabel);
mHomeImage?.BringToFront();
}
void CreateAvatarImage()
{
if (mGravatarImage != null)
return;
int radius = BrExDrawProperties.ChangesetFillRadius;
int offset = BrExDrawProperties.ChangesetRadius - radius;
mGravatarImage = new Image();
mGravatarImage.style.borderBottomLeftRadius = radius;
mGravatarImage.style.borderBottomRightRadius = radius;
mGravatarImage.style.borderTopLeftRadius = radius;
mGravatarImage.style.borderTopRightRadius = radius;
mGravatarImage.style.overflow = Overflow.Hidden;
mGravatarImage.style.left = offset;
mGravatarImage.style.top = offset;
mGravatarImage.style.width = radius * 2;
mGravatarImage.style.height = radius * 2;
Add(mGravatarImage);
mHomeImage?.BringToFront();
}
void UpdateAvatarLabel(string resolvedUserName)
{
if (mAvatarLabel == null)
return;
mAvatarLabel.visible = true;
schedule.Execute(() =>
{
// check the element is still valid and attached
if (mAvatarLabel != null && panel != null)
{
mAvatarLabel.text = GetAvatarInitial.ForUserName(resolvedUserName);
mAvatarLabel.style.backgroundColor = AvatarColor.FromUserName(resolvedUserName);
}
});
}
void UpdateAvatarImage(Texture2D avatarImage)
{
if (mGravatarImage == null)
return;
mGravatarImage.visible = true;
schedule.Execute(() =>
{
// check the element is still valid and attached
if (mGravatarImage != null && panel != null)
mGravatarImage.image = avatarImage;
});
}
void HideAvatarControls()
{
HideAvatarLabel();
HideAvatarImage();
}
void HideAvatarLabel()
{
if (mAvatarLabel != null)
mAvatarLabel.visible = false;
}
void HideAvatarImage()
{
if (mGravatarImage != null)
mGravatarImage.visible = false;
}
// internal for testing purposes
internal void OnPointerEnter(PointerEnterEvent evt)
{
// don't expand while dragging
if (evt.pressedButtons != 0)
return;
mIsHovered = true;
style.scale = new Scale(new Vector3(HoverScale, HoverScale, 1f));
UpdateGlowColor();
mGlowRing.style.opacity = 1;
mGlowRing.style.scale = new Scale(Vector3.one);
MarkDirtyRepaint();
VirtualCanvas canvas = GetFirstAncestorOfType<VirtualCanvas>();
ChangesetCommentShape commentShape =
ChangesetCommentShape.FindForChangeset(canvas, ChangesetDraw);
commentShape?.Expand();
ChangesetNumberShape numberShape =
ChangesetNumberShape.FindForChangeset(canvas, ChangesetDraw);
numberShape?.Expand();
}
void UpdateGlowColor()
{
Color changesetColor = mColorProvider.GetChangesetColor(
this, IsMultiChangesetSelected());
Color glowColor = new Color(
changesetColor.r, changesetColor.g, changesetColor.b, GlowAlpha);
mGlowRing.style.borderLeftColor = glowColor;
mGlowRing.style.borderRightColor = glowColor;
mGlowRing.style.borderTopColor = glowColor;
mGlowRing.style.borderBottomColor = glowColor;
}
// internal for testing purposes
internal void OnPointerLeave(PointerLeaveEvent evt)
{
mIsHovered = false;
style.scale = new Scale(Vector3.one);
// Fade out and shrink glow ring
mGlowRing.style.opacity = 0;
mGlowRing.style.scale = new Scale(
new Vector3(GlowStartScale, GlowStartScale, 1f));
MarkDirtyRepaint();
VirtualCanvas canvas = GetFirstAncestorOfType<VirtualCanvas>();
if (canvas == null)
return;
// use the comment shape's delayed collapse so that if the mouse
// moves from the changeset directly onto the comment, the
// comment's Expand() cancels this scheduled collapse.
ChangesetCommentShape commentShape =
ChangesetCommentShape.FindForChangeset(canvas, ChangesetDraw);
commentShape?.ScheduleCollapse();
ChangesetNumberShape numberShape =
ChangesetNumberShape.FindForChangeset(canvas, ChangesetDraw);
numberShape?.ScheduleCollapse();
}
void SetupHoverEffects()
{
style.overflow = Overflow.Visible;
style.transitionProperty = new List<StylePropertyName>
{
new StylePropertyName("scale"),
};
style.transitionDuration = new List<TimeValue>
{
new TimeValue(HoverAnimationMs, TimeUnit.Millisecond),
};
style.transitionTimingFunction = new List<EasingFunction>
{
new EasingFunction(EasingMode.EaseOutCubic),
};
style.transformOrigin = new TransformOrigin(
Length.Percent(50), Length.Percent(50));
float glowDiameter = BrExDrawProperties.ChangesetRadius * 2 + GlowExtent * 2;
float glowRadius = glowDiameter / 2f;
mGlowRing = new VisualElement();
mGlowRing.style.position = Position.Absolute;
mGlowRing.style.width = glowDiameter;
mGlowRing.style.height = glowDiameter;
mGlowRing.style.left = -GlowExtent;
mGlowRing.style.top = -GlowExtent;
mGlowRing.style.borderBottomLeftRadius = glowRadius;
mGlowRing.style.borderBottomRightRadius = glowRadius;
mGlowRing.style.borderTopLeftRadius = glowRadius;
mGlowRing.style.borderTopRightRadius = glowRadius;
mGlowRing.style.backgroundColor = Color.clear;
mGlowRing.style.borderLeftWidth = GlowThickness;
mGlowRing.style.borderRightWidth = GlowThickness;
mGlowRing.style.borderTopWidth = GlowThickness;
mGlowRing.style.borderBottomWidth = GlowThickness;
mGlowRing.style.opacity = 0;
mGlowRing.pickingMode = PickingMode.Ignore;
mGlowRing.style.transitionProperty = new List<StylePropertyName>
{
new StylePropertyName("opacity"),
new StylePropertyName("scale"),
};
mGlowRing.style.transitionDuration = new List<TimeValue>
{
new TimeValue(HoverAnimationMs, TimeUnit.Millisecond),
new TimeValue(GlowExpandMs, TimeUnit.Millisecond),
};
mGlowRing.style.transitionTimingFunction = new List<EasingFunction>
{
new EasingFunction(EasingMode.EaseOutCubic),
new EasingFunction(EasingMode.EaseOutCubic),
};
mGlowRing.style.transformOrigin = new TransformOrigin(
Length.Percent(50), Length.Percent(50));
mGlowRing.style.scale = new Scale(
new Vector3(GlowStartScale, GlowStartScale, 1f));
Insert(0, mGlowRing);
}
bool mIsHovered;
Color mResolvedColor;
VisualElement mGlowRing;
Label mAvatarLabel;
Image mGravatarImage;
HomeImageOverlay mHomeImage;
readonly AsyncUserNameResolver mUserNameResolver;
readonly ColorProvider mColorProvider;
const int HoverAnimationMs = 200;
const int GlowExpandMs = 350;
const float HoverScale = 1.15f;
const float GlowExtent = 8f;
const float GlowThickness = 4f;
const float GlowAlpha = 0.35f;
const float GlowStartScale = 0.7f;
const float HoverHighlightAlpha = 0.12f;
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 839307907e7a41f7af4d60bf8eef2218
timeCreated: 1768388009
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 1047700d0d5e4572882e66f9c6420fc1
timeCreated: 1768810881
@@ -0,0 +1,182 @@
using Codice.Client.BaseCommands.BranchExplorer;
using Codice.CM.Common;
using Unity.PlasticSCM.Editor.UI;
using Unity.PlasticSCM.Editor.UI.UIElements;
using UnityEngine;
namespace Unity.PlasticSCM.Editor.Views.BranchExplorer.Drawing.Shapes.Colors
{
internal class BrExColors
{
internal static class Branch
{
internal static Color GetBackgroundColor(
bool isSelected,
bool isMultipleSelected,
bool isCurrentSearchResult,
bool isSearchResult)
{
Color baseColor = GetBaseBackgroundColor(
isSelected, isMultipleSelected, isCurrentSearchResult, isSearchResult);
float alpha = GetBackgroundAlpha(
isSelected, isCurrentSearchResult, isSearchResult);
return new Color(baseColor.r, baseColor.g, baseColor.b, alpha);
}
internal static Color GetBorderColor(
bool isSelected,
bool isMultipleSelected,
bool isCurrentSearchResult)
{
if (isCurrentSearchResult)
return UnityStyles.Colors.BranchExplorer.BranchDefaultColor;
if (isSelected)
{
return isMultipleSelected
? UnityStyles.Colors.BranchExplorer.MultipleSelectedObjectsColor
: UnityStyles.Colors.BranchExplorer.SingleSelectedObjectColor;
}
return UnityStyles.Colors.BranchExplorer.BranchDefaultColor;
}
internal static Color GetHomeGlyphFillColor()
{
return UnityStyles.Colors.ImageForeground;
}
static Color GetBaseBackgroundColor(
bool isSelected,
bool isMultipleSelected,
bool isCurrentSearchResult,
bool isSearchResult)
{
if (isCurrentSearchResult)
return UnityStyles.Colors.BranchExplorer.CurrentSearchResultColor;
if (isSelected)
{
return isMultipleSelected
? UnityStyles.Colors.BranchExplorer.MultipleSelectedObjectsColor
: UnityStyles.Colors.BranchExplorer.SingleSelectedObjectColor;
}
if (isSearchResult)
return UnityStyles.Colors.BranchExplorer.SearchResultColor;
return UnityStyles.Colors.BranchExplorer.BranchDefaultColor;
}
static float GetBackgroundAlpha(
bool isSelected,
bool isCurrentSearchResult,
bool isSearchResult)
{
if (isCurrentSearchResult || isSearchResult)
return 1;
if (isSelected)
return 0.39f;
return 0.12f;
}
internal static Color GetCaptionBackgroundBrush()
{
return UnityStyles.Colors.BranchExplorer.CaptionBackgroundColor;
}
}
internal static class Changeset
{
internal static Color GetFillColor(
bool isSelected,
bool isMultipleSelected,
bool isCurrentSearchResult,
bool isSearchResult)
{
if (isCurrentSearchResult)
return UnityStyles.Colors.BranchExplorer.CurrentSearchResultColor;
if (isSelected)
{
return isMultipleSelected
? UnityStyles.Colors.BranchExplorer.MultipleSelectedObjectsColor
: UnityStyles.Colors.BranchExplorer.SingleSelectedObjectColor;
}
if (isSearchResult)
return UnityStyles.Colors.BranchExplorer.SearchResultColor;
return UnityStyles.Colors.BranchExplorer.ChangesetDefaultColor;
}
}
internal static class Label
{
internal static Color GetColor(
bool isSelected,
bool isMultipleSelected,
bool isCurrentSearchResult,
bool isSearchResult)
{
if (isCurrentSearchResult)
return UnityStyles.Colors.BranchExplorer.CurrentSearchResultColor;
if (isSelected)
{
return isMultipleSelected
? UnityStyles.Colors.BranchExplorer.MultipleSelectedObjectsColor
: UnityStyles.Colors.BranchExplorer.SingleSelectedObjectColor;
}
if (isSearchResult)
return UnityStyles.Colors.BranchExplorer.SearchResultColor;
return UnityStyles.Colors.BranchExplorer.LabelColor;
}
internal static Color GetCaptionBorderColor()
{
return UnityStyles.Colors.BranchExplorer.CaptionBorderColor;
}
}
internal static class ParentLink
{
internal static Color GetLineColor()
{
return UnityStyles.Colors.BranchExplorer.ParentLinkColor;
}
}
internal static class MergeLink
{
internal static Color GetLineColor(MergeType mergeType, bool isSelected)
{
switch (mergeType)
{
case MergeType.Merge:
return isSelected ?
UnityStyles.Colors.BranchExplorer.MergeLinkSelectedColor :
UnityStyles.Colors.BranchExplorer.MergeLinkColor;
case MergeType.Cherrypicking:
case MergeType.IntervalCherrypick:
return isSelected ?
UnityStyles.Colors.BranchExplorer.CherryPickLinkSelectedColor :
UnityStyles.Colors.BranchExplorer.CherryPickLinkColor;
case MergeType.CherrypickSubtractive:
case MergeType.IntervalCherrypickSubtractive:
return isSelected ?
UnityStyles.Colors.BranchExplorer.SubstractiveLinkSelectedColor :
UnityStyles.Colors.BranchExplorer.SubstractiveLinkColor;
}
return Color.red;
}
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 4805ac0c590d4c9a8134f0df52d0fb7c
timeCreated: 1768812893
@@ -0,0 +1,27 @@
namespace Unity.PlasticSCM.Editor.Views.BranchExplorer.Drawing.Shapes.Colors
{
internal static class BrExDashes
{
internal static float[] GetParentLinkDashPattern(bool isRelevant)
{
return isRelevant ?
RelevantParentLink : null;
}
internal static float[] GetMergeLinkDashPattern(bool isPendingMergeLink)
{
return isPendingMergeLink ?
PendingMergeLink : null;
}
internal static float[] GetChangesetDashPattern(bool isCheckoutChangeset)
{
return isCheckoutChangeset ?
CheckoutChangeset : null;
}
static float[] RelevantParentLink = new float[] { 7, 2 };
static float[] PendingMergeLink = new float[] { 4, 5 };
static float[] CheckoutChangeset = new float[] { 9, 3 };
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 9bce97fab0964d528edee0fae8663c95
timeCreated: 1768815171
@@ -0,0 +1,78 @@
using Codice.Client.BaseCommands.BranchExplorer;
namespace Unity.PlasticSCM.Editor.Views.BranchExplorer.Drawing.Shapes.Colors
{
internal static class BrExLineWidths
{
internal static class Branch
{
internal static float GetBorderWidth()
{
return BRANCH_BORDER_THICKNESS;
}
internal static float GetHomeGlyphBorderWidth()
{
return BRANCH_HOME_BORDER_THICKNESS;
}
const float BRANCH_BORDER_THICKNESS = 1.5f;
const float BRANCH_HOME_BORDER_THICKNESS = 1;
}
internal static class Changeset
{
internal static float GetHeadBorderWidth()
{
return CSET_HEAD_BORDER_THICKNESS;
}
internal static float GetOuterBorderWidth(bool isCheckoutChangeset)
{
return isCheckoutChangeset ?
CSET_CHECKOUT_BORDER_THICKNESS :
CSET_BORDER_THICKNESS;
}
internal static float GetParentLinkThickness()
{
return PARENT_LINK_THICKNESS;
}
internal static float GetHomeGlyphBorderWidth()
{
return CSET_HOME_BORDER_THICKNESS;
}
const float CSET_BORDER_THICKNESS = 3f;
const float CSET_CHECKOUT_BORDER_THICKNESS = 3f;
const float CSET_HEAD_BORDER_THICKNESS = 1.5f;
const float CSET_HOME_BORDER_THICKNESS = 1.6f;
const float PARENT_LINK_THICKNESS = 2.2f;
}
internal static class Label
{
internal static float GetWidth()
{
return BrExDrawProperties.LabelThickness;
}
}
internal static class MergeLink
{
internal static float GetWidth()
{
return MERGE_LINK_THICKNESS;
}
internal static float GetIntervalHighlightWidth()
{
return INTERVAL_MERGE_PARENT_LINK_HIGHLIGHT_THICKNESS;
}
const float MERGE_LINK_THICKNESS = 2.2f;
const float INTERVAL_MERGE_PARENT_LINK_HIGHLIGHT_THICKNESS = 7;
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 22fddd1dbabe4f35b6d26dd7691d9882
timeCreated: 1768813577
@@ -0,0 +1,206 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Codice.Client.BaseCommands.BranchExplorer;
using Codice.Client.BaseCommands.BranchExplorer.ExplorerTree;
using Codice.CM.Common;
using PlasticGui.WorkspaceWindow.Configuration;
using UnityEngine;
namespace Unity.PlasticSCM.Editor.Views.BranchExplorer.Drawing.Shapes.Colors
{
internal class ColorProvider
{
internal ColorProvider(
RepositorySpec repSpec,
WorkspaceInfo wkInfo,
BrExTree explTree)
{
mRepSpec = repSpec;
mWkInfo = wkInfo;
mExplorerTree = explTree;
}
internal void SetRulesConfiguration(List<Rule> rules)
{
if (mExplorerTree == null)
return;
FillRulesCache(rules);
}
void FillRulesCache(List<Rule> rulesToApply)
{
mRuleColors.Clear();
foreach (Rule rule in rulesToApply)
{
if (!rule.Enabled)
continue;
switch (rule.RuleType)
{
case Rule.Type.NonIntegrated:
ProcessNonIntegratedRule(rule);
break;
case Rule.Type.ConditionalFormat:
ProcessConditionalFormatRule(rule);
break;
case Rule.Type.CurrentBranchFormat:
ProcessCurrentBranchFormatRule(rule);
break;
default:
break;
}
}
}
internal Color GetBranchColor(BranchShape brShape, bool isMultipleSelected)
{
Color result = Color.red;
if (brShape.IsSearchResult
|| brShape.IsSelected
|| !mRuleColors.TryGetValue(brShape.BranchDrawInfo.BranchId, out result))
{
return BrExColors.Branch.GetBackgroundColor(
brShape.IsSelected,
isMultipleSelected,
brShape.IsCurrentSearchResult,
brShape.IsSearchResult);
}
return result;
}
internal Color GetChangesetColor(ChangesetShape csShape, bool isMultipleSelected)
{
Color result;
if (!csShape.IsSearchResult && !csShape.IsSelected)
{
if (mRuleColors.TryGetValue(csShape.ChangesetDraw.Id, out result))
return result;
}
return BrExColors.Changeset.GetFillColor(
csShape.IsSelected,
isMultipleSelected,
csShape.IsCurrentSearchResult,
csShape.IsSearchResult);
}
internal Color GetLabelColor(LabelShape lbShape, bool isMultipleSelected)
{
Color result;
if (lbShape.IsSearchResult
|| lbShape.IsSelected
|| !TryGetLabelColor(lbShape.LabelDraw.Labels.Select(x => x.Guid), out result))
{
return BrExColors.Label.GetColor(
lbShape.IsSelected,
isMultipleSelected,
lbShape.IsCurrentSearchResult,
lbShape.IsSearchResult);
}
return result;
}
void ProcessConditionalFormatRule(Rule rule)
{
HashSet<Guid> guids = RuleObjectGuids.GetForRule(rule, mRepSpec, mWkInfo);
foreach (Guid guid in guids)
mRuleColors[guid] = GetRuleColor(rule);
}
void ProcessCurrentBranchFormatRule(Rule rule)
{
BranchInfo brInfo = PlasticGui.Plastic.API.GetWorkingBranch(mWkInfo);
if (brInfo == null)
return;
mRuleColors[brInfo.GUID] = GetRuleColor(rule);
}
void ProcessNonIntegratedRule(Rule rule)
{
foreach (BrExBranch br in mExplorerTree.GetBranches())
{
if (br.ParentId == Guid.Empty)
continue;
long lastOutChangeset = GetLastLinkChangeset(br);
long lastBranchChangeset = GetLastBranchChangeset(br);
if (lastOutChangeset < lastBranchChangeset)
mRuleColors[br.Guid] = GetRuleColor(rule);
}
}
long GetLastLinkChangeset(BrExBranch br)
{
long result = -1;
if (br.OutgoingLinks == null)
return result;
foreach (BrExLink link in br.OutgoingLinks)
{
BrExChangeset cs = link.DestinationChangeset;
if (cs != null && cs.Id > result)
result = cs.Id;
}
return result;
}
long GetLastBranchChangeset(BrExBranch br)
{
long result = -1;
if (br.Changesets == null)
return result;
foreach (BrExChangeset cs in br.Changesets)
{
if (cs.Id > result)
result = cs.Id;
}
return result;
}
internal Color GetRuleColor(Rule rule)
{
if (rule.FormatTarget == Rule.FormattedObject.Branch)
{
return new Color(
rule.Color.R,
rule.Color.G,
rule.Color.B,
0.63f);
}
return new Color(rule.Color.R, rule.Color.G, rule.Color.B, rule.Color.A);
}
bool TryGetLabelColor(IEnumerable<Guid> guids, out Color result)
{
foreach (Guid guid in guids)
{
if (mRuleColors.TryGetValue(guid, out result))
return true;
}
result = new Color();
return false;
}
readonly RepositorySpec mRepSpec;
readonly WorkspaceInfo mWkInfo;
readonly BrExTree mExplorerTree;
readonly Dictionary<Guid, Color> mRuleColors = new Dictionary<Guid, Color>();
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 0da29ddb8a5144b1b4f1bd9922a3669a
timeCreated: 1768810887
@@ -0,0 +1,92 @@
using Codice.Client.BaseCommands.BranchExplorer;
using Unity.PlasticSCM.Editor.UI;
using Unity.PlasticSCM.Editor.Views.BranchExplorer.Virtualization;
using UnityEngine;
using UnityEngine.UIElements;
namespace Unity.PlasticSCM.Editor.Views.BranchExplorer.Drawing.Shapes
{
internal class ColumnHeaderShape : BrExShape
{
internal ColumnDrawInfo ColumnDraw { get { return VirtualShape.DrawInfo as ColumnDrawInfo; } }
internal ColumnHeaderShape(VirtualShape virtualShape) : base(virtualShape)
{
mHeaderBackground = new VisualElement();
mHeaderBackground.style.position = Position.Absolute;
mHeaderBackground.style.width = ColumnDraw.Bounds.Width;
mHeaderBackground.style.height = BrExDrawProperties.DateHeaderHeight;
mHeaderBackground.style.backgroundColor =
UnityStyles.Colors.BranchExplorer.ColumnHeaderBackgroundColor;
mCaptionLabel = new Label();
mCaptionLabel.style.position = Position.Absolute;
mCaptionLabel.style.unityFontStyleAndWeight = FontStyle.Bold;
mCaptionLabel.style.fontSize = 11;
mCaptionLabel.style.color = UnityStyles.Colors.SecondaryLabel;
mCaptionLabel.style.unityTextAlign = TextAnchor.MiddleCenter;
mCaptionLabel.style.marginBottom = 0;
mCaptionLabel.style.marginTop = 0;
mCaptionLabel.style.paddingBottom = 0;
mCaptionLabel.style.paddingTop = 0;
mCaptionLabel.style.paddingLeft = TextPaddingX;
mCaptionLabel.style.paddingRight = TextPaddingX;
mCaptionLabel.style.height = BrExDrawProperties.DateHeaderHeight;
mCaptionLabel.text = ColumnDraw.Caption;
Add(mHeaderBackground);
Add(mCaptionLabel);
}
internal override void Redraw()
{
UpdateLayout();
base.Redraw();
}
internal override void OnScrollChanged()
{
UpdateLayout();
}
void UpdateLayout()
{
VirtualCanvas canvas = this.GetFirstAncestorOfType<VirtualCanvas>();
CanvasScrollView scrollView = this.GetFirstAncestorOfType<CanvasScrollView>();
if (canvas == null || scrollView == null)
return;
float scrollY = canvas.ScrollOffset.y / canvas.ZoomLevel;
mHeaderBackground.style.translate = new Translate(0, scrollY);
float columnLeft = ColumnDraw.Bounds.X;
float columnRight = columnLeft + ColumnDraw.Bounds.Width;
float viewportLeft = canvas.ScrollOffset.x / canvas.ZoomLevel;
float viewportRight = viewportLeft + scrollView.Viewport.contentRect.width / canvas.ZoomLevel;
float labelWidth = mCaptionLabel.resolvedStyle.width;
if (float.IsNaN(labelWidth) || labelWidth == 0)
labelWidth = mCaptionLabel.text.Length * 7 + 2 * TextPaddingX;
// Center label in visible portion of column (intersection of column and viewport)
float visibleLeft = Mathf.Max(columnLeft, viewportLeft);
float visibleRight = Mathf.Min(columnRight, viewportRight);
float labelLeft = (visibleLeft + visibleRight - labelWidth) / 2;
// Clamp to column bounds
labelLeft = Mathf.Clamp(labelLeft, columnLeft, columnRight - labelWidth);
float captionX = labelLeft - columnLeft;
mCaptionLabel.style.translate = new Translate(captionX, scrollY);
}
readonly VisualElement mHeaderBackground;
readonly Label mCaptionLabel;
const float TextPaddingX = 8;
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: da7fb61f9c56463093c257eaaabf46b5
timeCreated: 1768387820
@@ -0,0 +1,33 @@
using Codice.Client.BaseCommands.BranchExplorer;
using Unity.PlasticSCM.Editor.UI;
using Unity.PlasticSCM.Editor.Views.BranchExplorer.Virtualization;
using UnityEngine;
using UnityEngine.UIElements;
namespace Unity.PlasticSCM.Editor.Views.BranchExplorer.Drawing.Shapes
{
internal class ColumnShape : BrExShape
{
internal ColumnDrawInfo ColumnDraw { get { return VirtualShape.DrawInfo as ColumnDrawInfo; } }
internal ColumnShape(VirtualShape virtualShape) : base(virtualShape) { }
protected override void GenerateVisualContent(Painter2D painter)
{
int columnIndex = (int)ColumnDraw.Tag;
bool isTransparentColumn =
((ColumnDraw.TotalColumns - columnIndex) % 2) != 0;
Color color = (isTransparentColumn) ?
UnityStyles.Colors.BranchExplorer.ControlBackgroundColor :
UnityStyles.Colors.BranchExplorer.ColumnBackgroundColor;
painter.fillColor = color;
painter.DrawRect(new Rect(0, 0,
ColumnDraw.Bounds.Width, ColumnDraw.Bounds.Height));
painter.Fill();
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 67042b0a735b4e9a9e1f047045048baa
timeCreated: 1768388079
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: a7816f8f0b844c4faf3b7c5f4a231f0d
timeCreated: 1768388168
@@ -0,0 +1,130 @@
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;
namespace Unity.PlasticSCM.Editor.Views.BranchExplorer.Drawing.Shapes.Connections
{
internal static class BezierCurveExtensions
{
internal static void DrawCubicBezier(
this Painter2D painter,
Vector2 start,
Vector2 controlPoint1,
Vector2 controlPoint2,
Vector2 end,
List<Vector2> hitTestPath)
{
painter.BeginPath();
painter.MoveTo(start);
painter.AppendCubicBezier(start,
controlPoint1,
controlPoint2,
end,
hitTestPath,
true);
}
internal static void AppendCubicBezier(
this Painter2D painter,
Vector2 start,
Vector2 controlPoint1,
Vector2 controlPoint2,
Vector2 end,
List<Vector2> hitTestPath,
bool includeStart)
{
if (includeStart && hitTestPath != null)
AddPointIfNeeded(hitTestPath, start);
float toleranceSqr = DEFAULT_TOLERANCE * DEFAULT_TOLERANCE;
List<BezierSegment> stack = GetSegmentStack();
stack.Add(new BezierSegment(start, controlPoint1, controlPoint2, end, 0));
while (stack.Count > 0)
{
int lastIndex = stack.Count - 1;
BezierSegment segment = stack[lastIndex];
stack.RemoveAt(lastIndex);
if (segment.Depth >= MAX_SUBDIVISION_DEPTH ||
IsFlatEnough(segment, toleranceSqr))
{
painter.LineTo(segment.P3);
if (hitTestPath != null)
hitTestPath.Add(segment.P3);
continue;
}
Vector2 p01 = (segment.P0 + segment.P1) * 0.5f;
Vector2 p12 = (segment.P1 + segment.P2) * 0.5f;
Vector2 p23 = (segment.P2 + segment.P3) * 0.5f;
Vector2 p012 = (p01 + p12) * 0.5f;
Vector2 p123 = (p12 + p23) * 0.5f;
Vector2 p0123 = (p012 + p123) * 0.5f;
stack.Add(new BezierSegment(p0123, p123, p23, segment.P3, segment.Depth + 1));
stack.Add(new BezierSegment(segment.P0, p01, p012, p0123, segment.Depth + 1));
}
}
static bool IsFlatEnough(BezierSegment segment, float toleranceSqr)
{
float d1 = DistancePointToLineSqr(segment.P1, segment.P0, segment.P3);
float d2 = DistancePointToLineSqr(segment.P2, segment.P0, segment.P3);
return Mathf.Max(d1, d2) <= toleranceSqr;
}
static float DistancePointToLineSqr(Vector2 point, Vector2 lineStart, Vector2 lineEnd)
{
Vector2 line = lineEnd - lineStart;
float lenSq = line.sqrMagnitude;
if (lenSq < MIN_LINE_LENGTH_SQR)
return (point - lineStart).sqrMagnitude;
float t = Vector2.Dot(point - lineStart, line) / lenSq;
Vector2 projection = lineStart + t * line;
return (point - projection).sqrMagnitude;
}
static void AddPointIfNeeded(List<Vector2> path, Vector2 point)
{
if (path.Count == 0 || path[path.Count - 1] != point)
path.Add(point);
}
static List<BezierSegment> GetSegmentStack()
{
if (mSegmentStack == null)
mSegmentStack = new List<BezierSegment>(64);
else
mSegmentStack.Clear();
return mSegmentStack;
}
const float DEFAULT_TOLERANCE = 0.15f;
const int MAX_SUBDIVISION_DEPTH = 12;
const float MIN_LINE_LENGTH_SQR = 0.0001f;
static List<BezierSegment> mSegmentStack;
readonly struct BezierSegment
{
internal readonly Vector2 P0;
internal readonly Vector2 P1;
internal readonly Vector2 P2;
internal readonly Vector2 P3;
internal readonly int Depth;
internal BezierSegment(Vector2 p0, Vector2 p1, Vector2 p2, Vector2 p3, int depth)
{
P0 = p0;
P1 = p1;
P2 = p2;
P3 = p3;
Depth = depth;
}
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 83fb50776194245ea981ff3a8c412370
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,10 @@
using UnityEngine;
namespace Unity.PlasticSCM.Editor.Views.BranchExplorer.Drawing.Shapes.Connections
{
internal class ConnectionPoints
{
internal Vector2 Source;
internal Vector2 Destination;
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 9d30f19d4b52413f8c6f4b107a28350e
timeCreated: 1768388433
@@ -0,0 +1,18 @@
using System;
using UnityEngine;
namespace Unity.PlasticSCM.Editor.Views.BranchExplorer.Drawing.Shapes.Connections
{
internal static class Degrees
{
internal static float ToRadians(float angle)
{
return (Mathf.PI / 180) * angle;
}
internal static float FromRadians(float radians)
{
return radians * (180 / Mathf.PI);
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 339bb0bea15547279a13171ebf92c4e9
timeCreated: 1768388563
@@ -0,0 +1,80 @@
using System;
using UnityEngine;
namespace Unity.PlasticSCM.Editor.Views.BranchExplorer.Drawing.Shapes.Connections
{
internal class Ellipse
{
internal Ellipse(float x, float y, float width, float height)
{
mBounds = new Rect(x, y, width, height);
a = Bounds.width / 2;
b = Bounds.height / 2;
x0 = Bounds.x + Bounds.width / 2;
y0 = Bounds.y + Bounds.height / 2;
ox = (Bounds.width / 2) * KAPPA;
oy = (Bounds.height / 2) * KAPPA;
xm = Bounds.x + Bounds.width / 2;
ym = Bounds.y + Bounds.height / 2;
}
internal float X { get { return Bounds.x; } }
internal float Y { get { return Bounds.y; } }
internal float OX { get { return ox; } }
internal float OY { get { return oy; } }
internal float XW { get { return Bounds.xMax; } }
internal float YH { get { return Bounds.yMax; } }
internal float XM { get { return xm; } }
internal float YM { get { return ym; } }
internal float CalculateXPoint(float py)
{
float apow = Mathf.Pow(a, 2);
float bpow = Mathf.Pow(b, 2);
float yminusy0pow = Mathf.Pow(py - y0, 2);
return Mathf.Sqrt((1 - (yminusy0pow / bpow)) * apow) + x0;
}
internal float GetSymmetricXPoint(float px)
{
return Bounds.x + (Bounds.x + Bounds.width - px);
}
internal float CalculateAngleAtPoint(float px, float py)
{
float numerator = a * (py - y0);
float denominator = b * (px - x0);
float result = Mathf.Atan(numerator / denominator);
return Degrees.FromRadians(result);
}
internal Rect Bounds
{
get
{
return mBounds;
}
}
const float KAPPA = 0.5522848f;
Rect mBounds;
float a;
float b;
float x0;
float y0;
float ox;
float oy;
float xm;
float ym;
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: e953ea4cb7dc46e0866cb1b475c70072
timeCreated: 1768388461
@@ -0,0 +1,687 @@
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;
namespace Unity.PlasticSCM.Editor.Views.BranchExplorer.Drawing.Shapes.Connections
{
internal static class MergeLinkGeometry
{
internal static void CalculateHitTestPath(
Rect source,
Rect destination,
out List<Vector2> hitTestPath)
{
Draw(null, source, destination, null, false, default, out hitTestPath);
}
internal static void Draw(
Painter2D painter,
Rect normalizedSource,
Rect normalizedDestination)
{
Draw(painter, normalizedSource, normalizedDestination, null, false, default, out _);
}
internal static void Draw(
Painter2D painter,
Rect normalizedSource,
Rect normalizedDestination,
float[] dashPattern)
{
Draw(painter, normalizedSource, normalizedDestination, dashPattern, false, default, out _);
}
internal static void Draw(
Painter2D painter,
Rect normalizedSource,
Rect normalizedDestination,
float[] dashPattern,
Rect clipRect)
{
Draw(painter, normalizedSource, normalizedDestination, dashPattern, true, clipRect, out _);
}
static void Draw(
Painter2D painter,
Rect normalizedSource,
Rect normalizedDestination,
float[] dashPattern,
bool useClip,
Rect clipRect,
out List<Vector2> hitTestPath)
{
hitTestPath = new List<Vector2>();
if (normalizedSource.y == normalizedDestination.y)
{
DrawHorizontalCurve(
painter,
normalizedSource,
normalizedDestination,
dashPattern,
useClip,
clipRect,
hitTestPath);
return;
}
if (normalizedSource.x == normalizedDestination.x)
{
DrawVerticalLine(
painter,
normalizedSource,
normalizedDestination,
dashPattern,
useClip,
clipRect,
hitTestPath);
return;
}
DrawCurve(
painter,
normalizedSource,
normalizedDestination,
dashPattern,
useClip,
clipRect,
hitTestPath);
}
static void DrawHorizontalCurve(
Painter2D painter,
Rect source,
Rect destination,
float[] dashPattern,
bool useClip,
Rect clipRect,
List<Vector2> hitTestPath)
{
float sourceRadius = source.height / 2;
float destRadius = destination.height / 2;
float sourcex, sourcey, destx, desty;
if (source.x < destination.x)
{
sourcex = source.x + source.width - sourceRadius;
sourcey = source.y;
destx = destination.x + destRadius;
desty = destination.y;
}
else
{
sourcex = source.x + sourceRadius;
sourcey = source.y;
destx = destination.x + destination.width - destRadius;
desty = destination.y;
}
float offsetX = sourcex - destx;
float middle = sourcex - offsetX / 2;
float tension = 20 + Mathf.Abs(offsetX) * 0.05f;
float i1x = middle - 10;
float i1y = sourcey - tension;
float i2x = middle + 10;
float i2y = sourcey - tension;
float srcx, srcy, middlex, middley;
if (offsetX < 0)
{
srcx = i1x;
srcy = i1y;
middlex = i2x;
middley = i2y;
}
else
{
srcx = i2x;
srcy = i2y;
middlex = i1x;
middley = i1y;
}
Vector2[] vertex = GetArrowVertex(
middlex, middley, destx, desty, DEFAULT_HEAD_ANGLE, MERGE_LINK_HEAD_SIZE);
float lineEndX = Mathf.Round((vertex[0].x + vertex[1].x) / 2);
float lineEndY = Mathf.Round((vertex[0].y + vertex[1].y) / 2);
Vector2 start = new Vector2(sourcex, sourcey);
Vector2 cp1 = new Vector2(srcx, srcy);
Vector2 cp2 = new Vector2(middlex, middley);
Vector2 end = new Vector2(lineEndX, lineEndY);
Vector2 arrowTip = new Vector2(destx, desty);
DrawBezierCurve(painter, start, cp1, cp2, end, dashPattern, useClip, clipRect, hitTestPath);
DrawArrowHead(painter, arrowTip, vertex, hitTestPath);
}
static void DrawVerticalLine(
Painter2D painter,
Rect source,
Rect dest,
float[] dashPattern,
bool useClip,
Rect clipRect,
List<Vector2> hitTestPath)
{
float x = source.x + source.width / 2;
float sx, sy, dx, dy;
if (source.y < dest.y)
{
sx = x;
sy = source.y + source.height;
dx = x;
dy = dest.y;
}
else
{
sx = x;
sy = source.y;
dx = x;
dy = dest.y + dest.height;
}
Vector2[] vertex = GetArrowVertex(
sx, sy, dx, dy, DEFAULT_HEAD_ANGLE, MERGE_LINK_HEAD_SIZE);
float lineEndX = (vertex[0].x + vertex[1].x) / 2;
float lineEndY = (vertex[0].y + vertex[1].y) / 2;
Vector2 start = new Vector2(sx, sy);
Vector2 end = new Vector2(lineEndX, lineEndY);
Vector2 arrowTip = new Vector2(dx, dy);
DrawLine(painter, start, end, dashPattern, useClip, clipRect, hitTestPath);
DrawArrowHead(painter, arrowTip, vertex, hitTestPath);
}
static void DrawCurve(
Painter2D painter,
Rect source,
Rect dest,
float[] dashPattern,
bool useClip,
Rect clipRect,
List<Vector2> hitTestPath)
{
bool offsetVertically = GetYGrowingRatio(source, dest) < MIN_VERTICAL_OFFSET_RATIO;
if (4 * VERTICAL_SOURCE_OFFSET >= Mathf.Abs(source.y - dest.y))
{
// not allowed -> generates an empty rectangle
offsetVertically = false;
}
float sourcex, sourcey, destx, desty, rectanglex, rectangley, rectangleWidth, rectangleHeight;
float verticalSourceOffset = 0;
float sourceRadius = source.height / 2;
float destRadius = dest.height / 2;
EllipseQuadrant quadrant;
float vectorDestinationx;
float factor = 13;
float angleMultiplicity = 1;
bool symmetricCase = false;
if (dest.x > source.x && dest.y < source.y)
{
// right top
sourcex = source.x + source.width - sourceRadius;
sourcey = source.y;
// left bottom
destx = dest.x + destRadius;
desty = dest.y + dest.height;
rectanglex = sourcex - Mathf.Abs(destx - sourcex);
rectangley = desty - Mathf.Abs(desty - sourcey);
rectangleWidth = Mathf.Abs(destx - sourcex) * 2;
rectangleHeight = Mathf.Abs(desty - sourcey) * 2;
vectorDestinationx = rectanglex + rectangleWidth;
angleMultiplicity = -angleMultiplicity;
if (offsetVertically)
{
verticalSourceOffset = -GetVerticalSourceOffset(source, dest);
rectangley = rectangley + Mathf.Abs(verticalSourceOffset);
rectangleHeight = rectangleHeight - 2 * Mathf.Abs(verticalSourceOffset);
}
quadrant = EllipseQuadrant.First;
}
else if (dest.x < source.x && dest.y > source.y)
{
// left bottom
sourcex = source.x + sourceRadius;
sourcey = source.y + source.height;
// right top
destx = dest.x + dest.width - sourceRadius;
desty = dest.y;
rectanglex = sourcex - Mathf.Abs(destx - sourcex);
rectangley = sourcey;
rectangleWidth = Mathf.Abs(destx - sourcex) * 2;
rectangleHeight = Mathf.Abs(desty - sourcey) * 2;
vectorDestinationx = rectanglex;
factor = -factor;
symmetricCase = true;
if (offsetVertically)
{
verticalSourceOffset = GetVerticalSourceOffset(source, dest);
rectangley = sourcey + verticalSourceOffset;
rectangleHeight = rectangleHeight - 2 * verticalSourceOffset;
}
quadrant = EllipseQuadrant.Third;
}
else if (dest.x > source.x && dest.y > source.y)
{
// right bottom
sourcex = source.x + source.width - sourceRadius;
sourcey = source.y + source.height;
// left top
destx = dest.x + destRadius;
desty = dest.y;
rectanglex = sourcex - Mathf.Abs(destx - sourcex);
rectangley = sourcey;
rectangleWidth = Mathf.Abs(destx - sourcex) * 2;
rectangleHeight = Mathf.Abs(desty - sourcey) * 2;
vectorDestinationx = rectanglex + rectangleWidth;
factor = -factor;
angleMultiplicity = -angleMultiplicity;
if (offsetVertically)
{
verticalSourceOffset = GetVerticalSourceOffset(source, dest);
rectangley = rectangley + verticalSourceOffset;
rectangleHeight = rectangleHeight - 2 * verticalSourceOffset;
}
quadrant = EllipseQuadrant.Fourth;
}
else
{
// left top
sourcex = source.x + sourceRadius;
sourcey = source.y;
// right bottom
destx = dest.x + dest.width - destRadius;
desty = dest.y + dest.height;
rectanglex = sourcex - Mathf.Abs(destx - sourcex);
rectangley = desty - Mathf.Abs(desty - sourcey);
rectangleWidth = Mathf.Abs(destx - sourcex) * 2;
rectangleHeight = Mathf.Abs(desty - sourcey) * 2;
vectorDestinationx = rectanglex;
symmetricCase = true;
if (offsetVertically)
{
verticalSourceOffset = -GetVerticalSourceOffset(source, dest);
rectangley = rectangley + Mathf.Abs(verticalSourceOffset);
rectangleHeight = rectangleHeight - 2 * Mathf.Abs(verticalSourceOffset);
}
quadrant = EllipseQuadrant.Second;
}
float vectordestinationy = rectangley + rectangleHeight / 2;
float vectorsourcey = ClampValue(rectangley + (rectangleHeight / 2) + factor,
rectangley, rectangley + rectangleHeight);
Ellipse outerEllipse = new Ellipse(rectanglex, rectangley, rectangleWidth, rectangleHeight);
float vectorsourcex = outerEllipse.CalculateXPoint(vectorsourcey);
if (symmetricCase)
vectorsourcex = outerEllipse.GetSymmetricXPoint(vectorsourcex);
Vector2[] vertex = GetArrowVertex(
vectorsourcex, vectorsourcey, vectorDestinationx, vectordestinationy,
DEFAULT_HEAD_ANGLE, MERGE_LINK_HEAD_SIZE);
float lineEndX = Mathf.Round((vertex[0].x + vertex[1].x) / 2);
float lineEndY = Mathf.Round((vertex[0].y + vertex[1].y) / 2);
Vector2 start = new Vector2(sourcex, sourcey);
Vector2 verticalOffsetPoint = new Vector2(sourcex, sourcey + verticalSourceOffset);
Vector2 end = new Vector2(lineEndX, lineEndY);
Vector2 arrowTip = new Vector2(vectorDestinationx, vectordestinationy);
DrawEllipticalArc(
painter,
start,
verticalOffsetPoint,
end,
offsetVertically,
quadrant,
dashPattern,
useClip,
clipRect,
hitTestPath);
DrawArrowHead(painter, arrowTip, vertex, hitTestPath);
}
static void DrawLine(
Painter2D painter,
Vector2 start,
Vector2 end,
float[] dashPattern,
bool useClip,
Rect clipRect,
List<Vector2> hitTestPath)
{
if (painter != null)
{
if (useClip)
painter.StrokeLine(start, end, dashPattern, clipRect);
else
painter.StrokeLine(start, end, dashPattern);
}
hitTestPath.Add(start);
hitTestPath.Add(end);
}
static void DrawBezierCurve(
Painter2D painter,
Vector2 start,
Vector2 controlPoint1,
Vector2 controlPoint2,
Vector2 end,
float[] dashPattern,
bool useClip,
Rect clipRect,
List<Vector2> hitTestPath)
{
if (painter != null)
{
if (dashPattern == null || dashPattern.Length == 0)
{
painter.DrawCubicBezier(
start,
controlPoint1,
controlPoint2,
end,
hitTestPath);
painter.Stroke();
}
else
{
Painter2DExtensions.AppendCubicBezierToPath(
start,
controlPoint1,
controlPoint2,
end,
hitTestPath);
if (useClip)
painter.StrokePath(hitTestPath, dashPattern, clipRect);
else
painter.StrokePath(hitTestPath, dashPattern);
}
}
else
{
Painter2DExtensions.AppendCubicBezierToPath(
start,
controlPoint1,
controlPoint2,
end,
hitTestPath);
}
}
static void DrawEllipticalArc(
Painter2D painter,
Vector2 start,
Vector2 verticalOffsetPoint,
Vector2 end,
bool offsetVertically,
EllipseQuadrant quadrant,
float[] dashPattern,
bool useClip,
Rect clipRect,
List<Vector2> hitTestPath)
{
hitTestPath.Add(start);
if (offsetVertically)
{
hitTestPath.Add(verticalOffsetPoint);
}
Vector2 arcStart = offsetVertically ? verticalOffsetPoint : start;
float ax = start.x;
float ay = arcStart.y;
float bx = end.x;
float bby = end.y;
Ellipse innerEllipse = new Ellipse(
ax - Mathf.Abs(ax - bx), bby - Mathf.Abs(ay - bby),
2 * Mathf.Abs(ax - bx), 2 * Mathf.Abs(ay - bby));
Vector2 cp1, cp2;
switch (quadrant)
{
case EllipseQuadrant.First:
cp1 = new Vector2(
Mathf.Round(innerEllipse.XM + innerEllipse.OX),
Mathf.Round(innerEllipse.YH));
cp2 = new Vector2(
Mathf.Round(innerEllipse.XW),
Mathf.Round(innerEllipse.YM + innerEllipse.OY));
break;
case EllipseQuadrant.Second:
cp1 = new Vector2(
Mathf.Round(innerEllipse.XM - innerEllipse.OX),
Mathf.Round(innerEllipse.YH));
cp2 = new Vector2(
Mathf.Round(innerEllipse.X),
Mathf.Round(innerEllipse.YM + innerEllipse.OY));
break;
case EllipseQuadrant.Third:
cp1 = new Vector2(
Mathf.Round(innerEllipse.XM - innerEllipse.OX),
Mathf.Round(innerEllipse.Y));
cp2 = new Vector2(
Mathf.Round(innerEllipse.X),
Mathf.Round(innerEllipse.YM - innerEllipse.OY));
break;
case EllipseQuadrant.Fourth:
default:
cp1 = new Vector2(
Mathf.Round(innerEllipse.XM + innerEllipse.OX),
Mathf.Round(innerEllipse.Y));
cp2 = new Vector2(
Mathf.Round(innerEllipse.XW),
Mathf.Round(innerEllipse.YM - innerEllipse.OY));
break;
}
if (painter != null)
{
if (dashPattern == null || dashPattern.Length == 0)
{
painter.BeginPath();
painter.MoveTo(start);
if (offsetVertically)
{
painter.LineTo(verticalOffsetPoint);
}
painter.AppendCubicBezier(
arcStart,
cp1,
cp2,
end,
hitTestPath,
false);
painter.Stroke();
}
else
{
Painter2DExtensions.AppendCubicBezierToPath(
arcStart,
cp1,
cp2,
end,
hitTestPath);
if (useClip)
painter.StrokePath(hitTestPath, dashPattern, clipRect);
else
painter.StrokePath(hitTestPath, dashPattern);
}
}
else
{
Painter2DExtensions.AppendCubicBezierToPath(
arcStart,
cp1,
cp2,
end,
hitTestPath);
}
}
static void DrawArrowHead(
Painter2D painter,
Vector2 tip,
Vector2[] vertex,
List<Vector2> hitTestPath)
{
if (painter != null)
{
Color fillColor = painter.strokeColor;
painter.fillColor = fillColor;
painter.BeginPath();
painter.MoveTo(tip);
painter.LineTo(vertex[0]);
painter.LineTo(vertex[1]);
painter.ClosePath();
painter.Stroke();
painter.Fill();
}
hitTestPath.Add(tip);
}
// internal for testing
internal static float GetYGrowingRatio(Rect source, Rect dest)
{
float ydistance = Mathf.Abs(source.y - dest.y);
float xdistance = Mathf.Abs(source.x - dest.x);
float ratio;
if (xdistance == 0)
{
ratio = float.MaxValue;
}
else
{
ratio = ydistance / xdistance;
}
return ratio;
}
// internal for testing
internal static float GetVerticalSourceOffset(Rect source, Rect dest)
{
float result = VERTICAL_SOURCE_OFFSET;
float yDistance = Mathf.Abs(source.y - dest.y);
if (yDistance < VERTICAL_SOURCE_OFFSET)
{
result = yDistance / 2;
}
return result;
}
// internal for testing
internal static float ClampValue(float value, float minValue, float maxValue)
{
if (value < minValue)
return minValue;
if (value > maxValue)
return maxValue;
return value;
}
// internal for testing
internal static Vector2[] GetArrowVertex(
float startx, float starty, float endx, float endy, int headAngle, int headSize)
{
float phi = Degrees.ToRadians(headAngle);
float dy = endy - starty;
float dx = endx - startx;
float theta = Mathf.Atan2(dy, dx);
float x, y, rho = theta + phi;
Vector2[] vertex = new Vector2[2];
for (int j = 0; j < 2; j++)
{
x = (endx - headSize * Mathf.Cos(rho));
y = (endy - headSize * Mathf.Sin(rho));
vertex[j] = new Vector2(x, y);
rho = theta - phi;
}
return vertex;
}
const int VERTICAL_SOURCE_OFFSET = 10;
const float MIN_VERTICAL_OFFSET_RATIO = 0.5f; // 0 never - 1 always
const int MERGE_LINK_HEAD_SIZE = 4;
const int DEFAULT_HEAD_ANGLE = 26;
enum EllipseQuadrant
{
First, // from 3 o'clock to 6 o'clock
Second, // from 6 o'clock to 9 o'clock
Third, // from 9 o'clock to 12 o'clock
Fourth // from 12 o'clock to 3 o'clock
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 1db38f8fca654faa9d306e57e639e4a1
timeCreated: 1768842444
@@ -0,0 +1,47 @@
using System;
using Codice.Client.BaseCommands.BranchExplorer;
using UnityEngine;
namespace Unity.PlasticSCM.Editor.Views.BranchExplorer.Drawing.Shapes.Connections
{
internal static class ParentLinkConnectionPoints
{
internal static ConnectionPoints Build(Rect source, Rect destination)
{
ConnectionPoints result = new ConnectionPoints();
result.Source = BuildSourcePoint(source);
result.Destination = BuildDestinationPoint(source, destination);
return result;
}
static Vector2 BuildSourcePoint(Rect source)
{
return new Vector2(
source.x,
source.y + source.height / 2);
}
static Vector2 BuildDestinationPoint(Rect source, Rect destination)
{
if (Math.Abs(destination.y - source.y) < BrExDrawProperties.ChangesetDrawingHeight)
{
return new Vector2(
destination.x + destination.width + START_PADDING,
destination.y + destination.height / 2);
}
if (destination.y > source.y)
{
return new Vector2(
destination.x + destination.width / 2,
destination.y - START_PADDING);
}
return new Vector2(
destination.x + destination.width / 2,
destination.y + source.height + START_PADDING);
}
const float START_PADDING = 3;
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: d29601c53f414c2090f0a65c04a0d011
timeCreated: 1768388782
@@ -0,0 +1,37 @@
using UnityEngine;
using Unity.PlasticSCM.Editor.Views.BranchExplorer.Virtualization;
namespace Unity.PlasticSCM.Editor.Views.BranchExplorer.Drawing.Shapes.Connections
{
internal static class ShapeConnectionBuilder
{
internal static ParentLinkShape BuildParentLinkConnection(
VirtualShape shape,
VirtualShape src,
VirtualShape dst,
bool isRelevant)
{
ParentLinkShape result = new ParentLinkShape(shape, isRelevant);
result.Source = new Rect(
src.Bounds.x, src.Bounds.y,
src.Bounds.width, src.Bounds.height);
result.Destination = new Rect(
dst.Bounds.x, dst.Bounds.y,
dst.Bounds.width, dst.Bounds.height);
return result;
}
internal static MergeLinkShape BuildMergeLinkConnection(
VirtualShape shape, VirtualShape src, VirtualShape dst)
{
return new MergeLinkShape(
shape,
src.Bounds,
dst.Bounds);
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: e68a46ad78cc4cec9266e64ae51c807f
timeCreated: 1768388179
@@ -0,0 +1,389 @@
// Copyright © 2003-2004, Luc Maisonobe
// 2015 - Alexey Rozanov <thehdotx@gmail.com> - Adaptations for oval center computations
// 2022 - Alexey Rozanov <thehdotx@gmail.com> - Fix for arcs sometimes drawn in inverted order.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with
// or without modification, are permitted provided that
// the following conditions are met:
//
// Redistributions of source code must retain the
// above copyright notice, this list of conditions and
// the following disclaimer.
// Redistributions in binary form must reproduce the
// above copyright notice, this list of conditions and
// the following disclaimer in the documentation
// and/or other materials provided with the
// distribution.
// Neither the names of spaceroots.org, spaceroots.com
// nor the names of their contributors may be used to
// endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
// CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
// THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
// USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
// IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
// UIElements adaptation by Alexey Rozanov <thehdotx@gmail.com>, 2015.
// I do not mind if anyone would find this adaptation useful, but
// please retain the above disclaimer made by the original class
// author Luc Maisonobe. He worked really hard on this subject, so
// please respect him by at least keeping the above disclaimer intact
// if you use his code.
//
// Commented out some unused values calculations.
// These are not supposed to be removed from the source code,
// as these may be helpful for debugging.
//
// Adapted from http://www.spaceroots.org/documents/ellipse/EllipticalArc.java
using UnityEngine;
using UnityEngine.UIElements;
namespace Unity.PlasticSCM.Editor.Views.BranchExplorer.Drawing.Shapes
{
internal class EllipticalArc
{
const float TwoPi = 2 * Mathf.PI;
/// <summary>
/// Coefficients for error estimation while using cubic Bezier curves for approximation,
/// 0 &lt;= b/a &lt;= 0.25
/// </summary>
static readonly float[][][] Coeffs3Low = {
new[]
{
new[] {3.85268f, -21.229f, -0.330434f, 0.0127842f},
new[] {-1.61486f, 0.706564f, 0.225945f, 0.263682f},
new[] {-0.910164f, 0.388383f, 0.00551445f, 0.00671814f},
new[] {-0.630184f, 0.192402f, 0.0098871f, 0.0102527f}
},
new[]
{
new[] {-0.162211f, 9.94329f, 0.13723f, 0.0124084f},
new[] {-0.253135f, 0.00187735f, 0.0230286f, 0.01264f},
new[] {-0.0695069f, -0.0437594f, 0.0120636f, 0.0163087f},
new[] {-0.0328856f, -0.00926032f, -0.00173573f, 0.00527385f}
}
};
/// <summary>
/// Coefficients for error estimation while using cubic Bezier curves for approximation,
/// 0.25 &lt;= b/a &lt;= 1
/// </summary>
static readonly float[][][] Coeffs3High = {
new[]
{
new[] {0.0899116f, -19.2349f, -4.11711f, 0.183362f},
new[] {0.138148f, -1.45804f, 1.32044f, 1.38474f},
new[] {0.230903f, -0.450262f, 0.219963f, 0.414038f},
new[] {0.0590565f, -0.101062f, 0.0430592f, 0.0204699f}
},
new[]
{
new[] {0.0164649f, 9.89394f, 0.0919496f, 0.00760802f},
new[] {0.0191603f, -0.0322058f, 0.0134667f, -0.0825018f},
new[] {0.0156192f, -0.017535f, 0.00326508f, -0.228157f},
new[] {-0.0236752f, 0.0405821f, -0.0173086f, 0.176187f}
}
};
/// <summary>
/// Safety factor to convert the "best" error approximation into a "max bound" error
/// </summary>
static readonly float[] Safety3 = { 0.0010f, 4.98f, 0.207f, 0.0067f };
float mCx;
float mCy;
float mA;
float mB;
float mCosTheta;
float mSinTheta;
float mEta1;
float mEta2;
float mX1;
float mY1;
float mX2;
float mY2;
bool mDrawInOppositeDirection;
const int MaxDegree = 3;
const double DefaultFlatness = 0.5;
internal EllipticalArc(
float cx, float cy,
float a, float b,
float theta,
float lambda1, float lambda2)
{
mCx = cx;
mCy = cy;
mA = a;
mB = b;
mCosTheta = Mathf.Cos(theta);
mSinTheta = Mathf.Sin(theta);
mEta1 = Mathf.Atan2(Mathf.Sin(lambda1) / b, Mathf.Cos(lambda1) / a);
mEta2 = Mathf.Atan2(Mathf.Sin(lambda2) / b, Mathf.Cos(lambda2) / a);
// Make sure we have eta1 <= eta2 <= eta1 + 2*PI
mEta2 -= TwoPi * Mathf.Floor((mEta2 - mEta1) / TwoPi);
// The preceding correction fails if we have exactly eta2-eta1 == 2*PI
// it reduces the interval to zero length
if (lambda2 - lambda1 > Mathf.PI && mEta2 - mEta1 < Mathf.PI)
{
mEta2 += TwoPi;
}
ComputeEndPoints();
}
void ComputeEndPoints()
{
float aCosEta1 = mA * Mathf.Cos(mEta1);
float bSinEta1 = mB * Mathf.Sin(mEta1);
mX1 = mCx + aCosEta1 * mCosTheta - bSinEta1 * mSinTheta;
mY1 = mCy + aCosEta1 * mSinTheta + bSinEta1 * mCosTheta;
float aCosEta2 = mA * Mathf.Cos(mEta2);
float bSinEta2 = mB * Mathf.Sin(mEta2);
mX2 = mCx + aCosEta2 * mCosTheta - bSinEta2 * mSinTheta;
mY2 = mCy + aCosEta2 * mSinTheta + bSinEta2 * mCosTheta;
}
// internal for testing
internal static float RationalFunction(float x, float[] c)
{
return (x * (x * c[0] + c[1]) + c[2]) / (x + c[3]);
}
float EstimateError(float etaA, float etaB)
{
float x = mB / mA;
float dEta = etaB - etaA;
float eta = 0.5f * (etaA + etaB);
float cos2 = Mathf.Cos(2 * eta);
float cos4 = Mathf.Cos(4 * eta);
float cos6 = Mathf.Cos(6 * eta);
float[][][] coeffs = x < 0.25 ? Coeffs3Low : Coeffs3High;
float c0 = RationalFunction(x, coeffs[0][0]) +
cos2 * RationalFunction(x, coeffs[0][1]) +
cos4 * RationalFunction(x, coeffs[0][2]) +
cos6 * RationalFunction(x, coeffs[0][3]);
float c1 = RationalFunction(x, coeffs[1][0]) +
cos2 * RationalFunction(x, coeffs[1][1]) +
cos4 * RationalFunction(x, coeffs[1][2]) +
cos6 * RationalFunction(x, coeffs[1][3]);
return RationalFunction(x, Safety3) * mA * Mathf.Exp(c0 + c1 * dEta);
}
void BuildArc(Painter2D painter)
{
// Find the number of Bezier curves needed
bool found = false;
int n = 1;
float dEta;
float etaB;
while (!found && n < 1024)
{
dEta = (mEta2 - mEta1) / n;
if (dEta <= 0.5 * Mathf.PI)
{
etaB = mEta1;
found = true;
for (int i = 0; found && i < n; ++i)
{
float etaA = etaB;
etaB += dEta;
found = EstimateError(etaA, etaB) <= DefaultFlatness;
}
}
n = n << 1;
}
if (!mDrawInOppositeDirection)
{
dEta = (mEta2 - mEta1) / n;
etaB = mEta1;
}
else
{
dEta = (mEta1 - mEta2) / n;
etaB = mEta2;
}
float cosEtaB = Mathf.Cos(etaB);
float sinEtaB = Mathf.Sin(etaB);
float aCosEtaB = mA * cosEtaB;
float bSinEtaB = mB * sinEtaB;
float aSinEtaB = mA * sinEtaB;
float bCosEtaB = mB * cosEtaB;
float xB = mCx + aCosEtaB * mCosTheta - bSinEtaB * mSinTheta;
float yB = mCy + aCosEtaB * mSinTheta + bSinEtaB * mCosTheta;
float xBDot = -aSinEtaB * mCosTheta - bCosEtaB * mSinTheta;
float yBDot = -aSinEtaB * mSinTheta + bCosEtaB * mCosTheta;
float t = Mathf.Tan(0.5f * dEta);
float alpha = Mathf.Sin(dEta) * (Mathf.Sqrt(4 + 3 * t * t) - 1) / 3;
for (int i = 0; i < n; ++i)
{
float xA = xB;
float yA = yB;
float xADot = xBDot;
float yADot = yBDot;
etaB += dEta;
cosEtaB = Mathf.Cos(etaB);
sinEtaB = Mathf.Sin(etaB);
aCosEtaB = mA * cosEtaB;
bSinEtaB = mB * sinEtaB;
aSinEtaB = mA * sinEtaB;
bCosEtaB = mB * cosEtaB;
xB = mCx + aCosEtaB * mCosTheta - bSinEtaB * mSinTheta;
yB = mCy + aCosEtaB * mSinTheta + bSinEtaB * mCosTheta;
xBDot = -aSinEtaB * mCosTheta - bCosEtaB * mSinTheta;
yBDot = -aSinEtaB * mSinTheta + bCosEtaB * mCosTheta;
// Use cubic Bezier curves
painter.BezierCurveTo(
new Vector2((float)(xA + alpha * xADot), (float)(yA + alpha * yADot)),
new Vector2((float)(xB - alpha * xBDot), (float)(yB - alpha * yBDot)),
new Vector2((float)xB, (float)yB));
}
}
// internal for testing
internal static float GetAngle(Vector2 v1, Vector2 v2)
{
return Mathf.Atan2(v1.x * v2.y - v2.x * v1.y, v1.x * v2.x + v1.y * v2.y);
}
// internal for testing
internal readonly struct SimpleMatrix
{
readonly float mA, mB, mC, mD;
internal SimpleMatrix(float a, float b, float c, float d)
{
mA = a;
mB = b;
mC = c;
mD = d;
}
public static Vector2 operator *(SimpleMatrix m, Vector2 p)
{
return new Vector2(
(m.mA * p.x + m.mB * p.y),
(m.mC * p.x + m.mD * p.y));
}
}
/// <summary>
/// ArcTo Helper - builds an elliptical arc using the endpoint parameterization
/// </summary>
internal static void BuildArc(
Painter2D painter,
Vector2 p1,
Vector2 p2,
Vector2 size,
float theta,
bool isLargeArc,
bool clockwise)
{
var orth = new SimpleMatrix(
Mathf.Cos(theta), Mathf.Sin(theta),
-Mathf.Sin(theta), Mathf.Cos(theta));
var rest = new SimpleMatrix(
Mathf.Cos(theta), -Mathf.Sin(theta),
Mathf.Sin(theta), Mathf.Cos(theta));
Vector2 p1S = orth * new Vector2((p1.x - p2.x) / 2, (p1.y - p2.y) / 2);
float rx = size.x;
float ry = size.y;
float rx2 = rx * rx;
float ry2 = ry * ry;
float y1S2 = p1S.y * p1S.y;
float x1S2 = p1S.x * p1S.x;
float numerator = rx2 * ry2 - rx2 * y1S2 - ry2 * x1S2;
float denominator = rx2 * y1S2 + ry2 * x1S2;
if (Mathf.Abs(denominator) < 1e-8)
{
painter.LineTo(p2);
return;
}
if ((numerator / denominator) < 0)
{
float lambda = x1S2 / rx2 + y1S2 / ry2;
float lambdaSqrt = Mathf.Sqrt(lambda);
if (lambda > 1)
{
rx *= lambdaSqrt;
ry *= lambdaSqrt;
rx2 = rx * rx;
ry2 = ry * ry;
numerator = rx2 * ry2 - rx2 * y1S2 - ry2 * x1S2;
if (numerator < 0)
numerator = 0;
denominator = rx2 * y1S2 + ry2 * x1S2;
}
}
float multiplier = Mathf.Sqrt(Mathf.Abs(numerator / denominator));
Vector2 mulVec = new Vector2((float)(rx * p1S.y / ry), (float)(-ry * p1S.x / rx));
int sign = (clockwise != isLargeArc) ? 1 : -1;
Vector2 cs = new Vector2(mulVec.x * multiplier * sign, mulVec.y * multiplier * sign);
Vector2 translation = new Vector2((p1.x + p2.x) / 2, (p1.y + p2.y) / 2);
Vector2 c = rest * cs + translation;
var p1NoOffset = orth * (p1 - c);
var p2NoOffset = orth * (p2 - c);
var revisedP1 = clockwise ? p1NoOffset : p2NoOffset;
var revisedP2 = clockwise ? p2NoOffset : p1NoOffset;
var thetaStart = GetAngle(new Vector2(1, 0), revisedP1);
var thetaEnd = GetAngle(new Vector2(1, 0), revisedP2);
var arc = new EllipticalArc(c.x, c.y, rx, ry, theta, thetaStart, thetaEnd);
float ManhattanDistance(Vector2 a, Vector2 b) => Mathf.Abs(a.x - b.x) + Mathf.Abs(a.y - b.y);
if (ManhattanDistance(p2, new Vector2((float)arc.mX2, (float)arc.mY2)) >
ManhattanDistance(p2, new Vector2((float)arc.mX1, (float)arc.mY1)))
{
arc.mDrawInOppositeDirection = true;
}
arc.BuildArc(painter);
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 97d25960402b4e1e98351c7168ef189f
timeCreated: 1768819510
@@ -0,0 +1,71 @@
using UnityEngine;
using UnityEngine.UIElements;
namespace Unity.PlasticSCM.Editor.Views.BranchExplorer.Drawing.Shapes
{
internal static class HomeGeometry
{
internal const float WIDTH = 16f;
internal const float HEIGHT = 16f;
internal static void Draw(Painter2D painter, float offsetX, float offsetY, float scale = 1)
{
painter.BeginPath();
// Start at right eave
painter.MoveTo(Scale(14f, 9f, offsetX, offsetY, scale));
// Right wall top
painter.LineTo(Scale(13f, 9f, offsetX, offsetY, scale));
// Right wall down
painter.LineTo(Scale(13f, 13f, offsetX, offsetY, scale));
// Bottom right corner curve
painter.BezierCurveTo(
Scale(13f, 13.5523f, offsetX, offsetY, scale),
Scale(12.5523f, 14f, offsetX, offsetY, scale),
Scale(12f, 14f, offsetX, offsetY, scale));
// Bottom to door right
painter.LineTo(Scale(9f, 14f, offsetX, offsetY, scale));
// Door right side up
painter.LineTo(Scale(9f, 10f, offsetX, offsetY, scale));
// Door top
painter.LineTo(Scale(7f, 10f, offsetX, offsetY, scale));
// Door left side down
painter.LineTo(Scale(7f, 14f, offsetX, offsetY, scale));
// Bottom to left wall
painter.LineTo(Scale(4f, 14f, offsetX, offsetY, scale));
// Bottom left corner curve
painter.BezierCurveTo(
Scale(3.44772f, 14f, offsetX, offsetY, scale),
Scale(3f, 13.5523f, offsetX, offsetY, scale),
Scale(3f, 13f, offsetX, offsetY, scale));
// Left wall up
painter.LineTo(Scale(3f, 9f, offsetX, offsetY, scale));
// Left eave
painter.LineTo(Scale(2f, 9f, offsetX, offsetY, scale));
// Left side of roof to top
painter.LineTo(Scale(8.04688f, 2f, offsetX, offsetY, scale));
// Right side of roof back to start
painter.LineTo(Scale(14f, 9f, offsetX, offsetY, scale));
painter.ClosePath();
}
static Vector2 Scale(float x, float y, float offsetX, float offsetY, float scale)
{
return new Vector2(offsetX + x * scale, offsetY + y * scale);
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 254497d6403494baa8cf3544ec92749d
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,50 @@
using Unity.PlasticSCM.Editor.UI;
using UnityEditor;
using UnityEngine;
using UnityEngine.UIElements;
namespace Unity.PlasticSCM.Editor.Views.BranchExplorer.Drawing.Shapes
{
internal class HomeImageOverlay : VisualElement
{
internal HomeImageOverlay(
float width,
float height)
{
style.width = width;
style.height = height;
style.backgroundColor = UnityStyles.Colors.BranchExplorer.ControlBackgroundColor;
style.borderLeftWidth = 1;
style.borderRightWidth = 1;
style.borderTopWidth = 1;
style.borderBottomWidth = 1;
style.borderBottomLeftRadius = width / 2;
style.borderBottomRightRadius = width / 2;
style.borderTopLeftRadius = height / 2;
style.borderTopRightRadius = height / 2;
generateVisualContent += OnGenerateVisualContent;
}
internal void Dispose()
{
generateVisualContent -= OnGenerateVisualContent;
}
void OnGenerateVisualContent(MeshGenerationContext obj)
{
Painter2D painter = obj.painter2D;
painter.fillColor = UnityStyles.Colors.ImageForeground;
float scale = 0.65f;
float glyphWidth = HomeGeometry.WIDTH * scale;
float glyphHeight = HomeGeometry.HEIGHT * scale;
float offsetX = (localBound.width - glyphWidth) * 0.5f;
float offsetY = (localBound.height - glyphHeight) * 0.5f;
HomeGeometry.Draw(painter, offsetX, offsetY - 0.5f, scale);
painter.Fill();
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 654349dfd493477d9aeb2dd5bd80b566
timeCreated: 1769766288

Some files were not shown because too many files have changed in this diff Show More