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,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
@@ -0,0 +1,516 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Codice.Client.BaseCommands.BranchExplorer;
using PlasticGui;
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 LabelShape : BrExShape
{
// internal for testing purposes
internal bool IsHovered { get { return mIsHovered; } }
internal LabelDrawInfo LabelDraw => VirtualShape.DrawInfo as LabelDrawInfo;
internal Color ResolvedColor { get { return mResolvedColor; } }
internal static string BuildName(string labelName)
{
return "label-" + labelName;
}
internal LabelShape(VirtualShape virtualShape, ColorProvider colorProvider) : base(virtualShape)
{
mColorProvider = colorProvider;
name = BuildName(GetFirstLabelName(LabelDraw));
CreateHitTestOverlay();
CreateSummaryCaptionContainer();
CreateExpandedCaptionContainer();
SetupHoverEffects();
mHitTestOverlay.RegisterCallback<PointerMoveEvent>(OnOverlayPointerMove);
mHitTestOverlay.RegisterCallback<PointerLeaveEvent>(OnOverlayPointerLeave);
mSummaryCaptionContainer.RegisterCallback<GeometryChangedEvent>(OnSummaryContainerGeometryChanged);
mExpandedCaptionLabel.RegisterCallback<GeometryChangedEvent>(OnExpandedLabelGeometryChanged);
RegisterCallback<PointerEnterEvent>(OnPointerEnter);
RegisterCallback<PointerLeaveEvent>(OnPointerLeave);
}
internal override void Dispose()
{
mHitTestOverlay.UnregisterCallback<PointerMoveEvent>(OnOverlayPointerMove);
mHitTestOverlay.UnregisterCallback<PointerLeaveEvent>(OnOverlayPointerLeave);
mSummaryCaptionContainer.UnregisterCallback<GeometryChangedEvent>(OnSummaryContainerGeometryChanged);
mExpandedCaptionLabel.UnregisterCallback<GeometryChangedEvent>(OnExpandedLabelGeometryChanged);
UnregisterCallback<PointerEnterEvent>(OnPointerEnter);
UnregisterCallback<PointerLeaveEvent>(OnPointerLeave);
base.Dispose();
}
internal override bool HasContextMenu() => true;
protected override void GenerateVisualContent(Painter2D painter)
{
if (!DisplayOptions.DisplayLabels)
return;
Color labelColor = mColorProvider.GetLabelColor(this, IsMultiLabelSelected());
if (mIsHovered)
labelColor = BrightenColor(labelColor, HoverBrightenAmount);
mResolvedColor = labelColor;
painter.strokeColor = labelColor;
painter.lineWidth = mIsHovered
? BrExLineWidths.Label.GetWidth() + HoverExtraLineWidth
: BrExLineWidths.Label.GetWidth();
painter.DrawCircle(
new Vector2(BrExDrawProperties.LabelRadius, BrExDrawProperties.LabelRadius),
BrExDrawProperties.LabelRadius);
painter.Stroke();
}
void CreateHitTestOverlay()
{
// create a transparent overlay that covers both the label shape and caption area
// this is needed because captions are positioned with negative Y (above the shape),
// and pointer events only fire within an element's bounds
// width matches the summary container for better usability
mHitTestOverlay = new VisualElement();
mHitTestOverlay.style.position = Position.Absolute;
mHitTestOverlay.style.left = -CaptionExtraMargin / 2;
mHitTestOverlay.style.width = BrExDrawProperties.LabelRadius * 2 + CaptionExtraMargin;
mHitTestOverlay.pickingMode = PickingMode.Position;
Add(mHitTestOverlay);
}
void CreateSummaryCaptionContainer()
{
mSummaryCaptionContainer = new VisualElement();
mSummaryCaptionContainer.style.position = Position.Absolute;
mSummaryCaptionContainer.style.width = BrExDrawProperties.LabelRadius * 2 + CaptionExtraMargin;
mSummaryCaptionContainer.style.left = -CaptionExtraMargin / 2;
mSummaryCaptionContainer.pickingMode = PickingMode.Ignore;
mSummaryCaptionLabels = new List<Label>();
string[] captions = GetLabelCaptionsArray(LabelDraw.Labels, MaxLabelCaptions);
foreach (string caption in captions)
{
Label label = CreateSummaryCaptionLabel(caption);
mSummaryCaptionLabels.Add(label);
mSummaryCaptionContainer.Add(label);
}
Add(mSummaryCaptionContainer);
}
Label CreateSummaryCaptionLabel(string text)
{
Label label = new Label();
label.style.color = GetCaptionForegroundColor(IsSelected);
label.style.fontSize = 11;
label.style.unityTextAlign = TextAnchor.UpperCenter;
label.style.whiteSpace = WhiteSpace.NoWrap;
label.style.overflow = Overflow.Hidden;
label.style.textOverflow = TextOverflow.Ellipsis;
label.style.marginBottom = 0;
label.style.marginTop = 0;
label.style.paddingBottom = 0;
label.style.paddingTop = 0;
label.pickingMode = PickingMode.Ignore;
label.text = text;
return label;
}
void CreateExpandedCaptionContainer()
{
mExpandedCaptionContainer = new VisualElement();
mExpandedCaptionContainer.style.position = Position.Absolute;
mExpandedCaptionContainer.style.backgroundColor = UnityStyles.Colors.BranchExplorer.ControlBackgroundColor;
mExpandedCaptionContainer.style.borderTopLeftRadius = CornerRadius;
mExpandedCaptionContainer.style.borderTopRightRadius = CornerRadius;
mExpandedCaptionContainer.style.borderBottomLeftRadius = CornerRadius;
mExpandedCaptionContainer.style.borderBottomRightRadius = CornerRadius;
mExpandedCaptionContainer.style.paddingLeft = ExpandedPadding;
mExpandedCaptionContainer.style.paddingRight = ExpandedPadding;
mExpandedCaptionContainer.style.paddingTop = ExpandedPadding;
mExpandedCaptionContainer.style.paddingBottom = ExpandedPadding;
mExpandedCaptionContainer.style.display = DisplayStyle.None;
mExpandedCaptionContainer.style.borderTopWidth = ExpandedBorderWidth;
mExpandedCaptionContainer.style.borderBottomWidth = ExpandedBorderWidth;
mExpandedCaptionContainer.style.borderLeftWidth = ExpandedBorderWidth;
mExpandedCaptionContainer.style.borderRightWidth = ExpandedBorderWidth;
mExpandedCaptionContainer.style.borderTopColor = BrExColors.Label.GetCaptionBorderColor();
mExpandedCaptionContainer.style.borderBottomColor = BrExColors.Label.GetCaptionBorderColor();
mExpandedCaptionContainer.style.borderLeftColor = BrExColors.Label.GetCaptionBorderColor();
mExpandedCaptionContainer.style.borderRightColor = BrExColors.Label.GetCaptionBorderColor();
mExpandedCaptionContainer.pickingMode = PickingMode.Ignore;
mExpandedCaptionLabel = new Label();
mExpandedCaptionLabel.style.color = GetCaptionForegroundColor(true);
mExpandedCaptionLabel.style.fontSize = 11;
mExpandedCaptionLabel.style.unityTextAlign = TextAnchor.UpperCenter;
mExpandedCaptionLabel.style.whiteSpace = WhiteSpace.Normal;
mExpandedCaptionLabel.style.marginBottom = 0;
mExpandedCaptionLabel.style.marginTop = 0;
mExpandedCaptionLabel.style.paddingBottom = 0;
mExpandedCaptionLabel.style.paddingTop = 0;
mExpandedCaptionLabel.pickingMode = PickingMode.Ignore;
mExpandedCaptionLabel.text = GetAllLabelCaptions(LabelDraw.Labels);
mExpandedCaptionContainer.Add(mExpandedCaptionLabel);
Add(mExpandedCaptionContainer);
}
void OnSummaryContainerGeometryChanged(GeometryChangedEvent evt)
{
UpdateSummaryCaptionPosition();
UpdateCaptionHitArea();
}
void OnExpandedLabelGeometryChanged(GeometryChangedEvent evt)
{
UpdateExpandedCaptionPosition();
}
void OnOverlayPointerMove(PointerMoveEvent evt)
{
bool isInsideCaptionArea = mCaptionHitAreaInOverlay.Contains(evt.localPosition);
if (isInsideCaptionArea)
{
ShowExpandedCaption();
return;
}
ShowSummaryCaption();
}
void OnOverlayPointerLeave(PointerLeaveEvent evt)
{
ShowSummaryCaption();
}
void ShowExpandedCaption()
{
if (mIsExpanded)
return;
if (!DisplayOptions.DisplayLabels)
return;
mIsExpanded = true;
mSummaryCaptionContainer.style.display = DisplayStyle.None;
mExpandedCaptionContainer.style.display = DisplayStyle.Flex;
BringToFront();
}
void ShowSummaryCaption()
{
if (!mIsExpanded)
return;
mIsExpanded = false;
mExpandedCaptionContainer.style.display = DisplayStyle.None;
mSummaryCaptionContainer.style.display = DisplayStyle.Flex;
VirtualCanvas canvas = parent as VirtualCanvas;
canvas?.RestoreZOrder(this);
}
void UpdateCaptionHitArea()
{
float containerHeight = mSummaryCaptionContainer.resolvedStyle.height;
if (float.IsNaN(containerHeight) || containerHeight <= 0)
return;
float captionTop = containerHeight + CaptionMargin;
mHitTestOverlay.style.top = -captionTop;
mHitTestOverlay.style.height = captionTop + BrExDrawProperties.LabelRadius * 2;
mCaptionHitAreaInOverlay = new Rect(
0,
0,
BrExDrawProperties.LabelRadius * 2 + CaptionExtraMargin,
containerHeight);
}
void UpdateSummaryCaptionPosition()
{
float containerHeight = mSummaryCaptionContainer.resolvedStyle.height;
if (float.IsNaN(containerHeight) || containerHeight <= 0)
return;
mSummaryCaptionContainer.style.top = -containerHeight - CaptionMargin;
}
void UpdateExpandedCaptionPosition()
{
float textHeight = mExpandedCaptionLabel.resolvedStyle.height;
float textWidth = mExpandedCaptionLabel.resolvedStyle.width;
if (float.IsNaN(textHeight) || textHeight <= 0)
return;
if (float.IsNaN(textWidth) || textWidth <= 0)
return;
float textY = -textHeight - CaptionMargin;
float textX = (BrExDrawProperties.LabelRadius * 2 - textWidth) / 2;
mExpandedCaptionContainer.style.left = textX - ExpandedPadding - ExpandedBorderWidth;
mExpandedCaptionContainer.style.top = textY - ExpandedPadding - ExpandedBorderWidth;
}
internal override void Redraw()
{
UpdateSummaryCaptionLabels();
mExpandedCaptionLabel.text = GetAllLabelCaptions(LabelDraw.Labels);
bool displayLabels = DisplayOptions.DisplayLabels;
mSummaryCaptionContainer.style.display =
displayLabels ? DisplayStyle.Flex : DisplayStyle.None;
mHitTestOverlay.style.display =
displayLabels ? DisplayStyle.Flex : DisplayStyle.None;
if (!displayLabels)
{
mExpandedCaptionContainer.style.display = DisplayStyle.None;
mIsExpanded = false;
}
base.Redraw();
}
void UpdateSummaryCaptionLabels()
{
string[] captions = GetLabelCaptionsArray(LabelDraw.Labels, MaxLabelCaptions);
Color captionColor = GetCaptionForegroundColor(IsSelected);
// Remove excess labels if needed
while (mSummaryCaptionLabels.Count > captions.Length)
{
Label labelToRemove = mSummaryCaptionLabels[mSummaryCaptionLabels.Count - 1];
mSummaryCaptionContainer.Remove(labelToRemove);
mSummaryCaptionLabels.RemoveAt(mSummaryCaptionLabels.Count - 1);
}
// Update existing labels and add new ones if needed
for (int i = 0; i < captions.Length; i++)
{
if (i < mSummaryCaptionLabels.Count)
{
mSummaryCaptionLabels[i].text = captions[i];
mSummaryCaptionLabels[i].style.color = captionColor;
}
else
{
Label label = CreateSummaryCaptionLabel(captions[i]);
mSummaryCaptionLabels.Add(label);
mSummaryCaptionContainer.Add(label);
}
}
}
static string GetAllLabelCaptions(BrExLabel[] labels)
{
return GetLabelCaptions(labels, 10000);
}
static string GetLabelCaptions(BrExLabel[] labels, int maxCaptions)
{
return string.Join(Environment.NewLine, GetLabelCaptionsArray(labels, maxCaptions));
}
static string[] GetLabelCaptionsArray(BrExLabel[] labels, int maxCaptions)
{
IEnumerable<BrExLabel> sortedLabels = labels.Reverse();
if (labels.Length <= maxCaptions)
return sortedLabels.Select(x => x.Name).ToArray();
List<string> result = sortedLabels.Take(maxCaptions - 1).Select(x => x.Name).ToList();
result.Add(PlasticLocalization.GetString(
PlasticLocalization.Name.PlusMore, labels.Length - maxCaptions + 1));
return result.ToArray();
}
static Color GetCaptionForegroundColor(bool isSelected)
{
return isSelected ? UnityStyles.Colors.Label : UnityStyles.Colors.SecondaryLabel;
}
// internal for testing purposes
internal void OnPointerEnter(PointerEnterEvent evt)
{
if (evt.pressedButtons != 0)
return;
mIsHovered = true;
style.scale = new Scale(new Vector3(HoverScale, HoverScale, 1f));
Color labelColor = mColorProvider.GetLabelColor(this, IsMultiLabelSelected());
Color glowColor = new Color(
labelColor.r, labelColor.g, labelColor.b, GlowAlpha);
mGlowRing.style.borderLeftColor = glowColor;
mGlowRing.style.borderRightColor = glowColor;
mGlowRing.style.borderTopColor = glowColor;
mGlowRing.style.borderBottomColor = glowColor;
mGlowRing.style.opacity = 1;
mGlowRing.style.scale = new Scale(Vector3.one);
MarkDirtyRepaint();
}
// internal for testing purposes
internal void OnPointerLeave(PointerLeaveEvent evt)
{
mIsHovered = false;
style.scale = new Scale(Vector3.one);
mGlowRing.style.opacity = 0;
mGlowRing.style.scale = new Scale(
new Vector3(GlowStartScale, GlowStartScale, 1f));
MarkDirtyRepaint();
if (!mIsExpanded)
{
VirtualCanvas canvas = parent as VirtualCanvas;
canvas?.RestoreZOrder(this);
}
}
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.LabelRadius * 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);
}
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 IsMultiLabelSelected()
{
return false;
}
static string GetFirstLabelName(LabelDrawInfo labelDraw)
{
if (labelDraw.Labels == null || labelDraw.Labels.Length == 0)
return string.Empty;
return labelDraw.Labels[0].Name;
}
bool mIsHovered;
Color mResolvedColor;
VisualElement mGlowRing;
VisualElement mHitTestOverlay;
VisualElement mSummaryCaptionContainer;
List<Label> mSummaryCaptionLabels;
VisualElement mExpandedCaptionContainer;
Label mExpandedCaptionLabel;
Rect mCaptionHitAreaInOverlay;
bool mIsExpanded;
readonly ColorProvider mColorProvider;
const float CaptionMargin = 3;
const float CaptionExtraMargin = 18;
const float ExpandedPadding = 5;
const float ExpandedBorderWidth = 1;
const float CornerRadius = 4;
const int MaxLabelCaptions = 3;
const float HoverBrightenAmount = 0.1f;
const float HoverExtraLineWidth = 0f;
const int HoverAnimationMs = 200;
const int GlowExpandMs = 300;
const float HoverScale = 1.02f;
const float GlowExtent = 6f;
const float GlowThickness = 3f;
const float GlowAlpha = 0.3f;
const float GlowStartScale = 0.75f;
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 065cbcefa4134632ae7680ab429e988f
timeCreated: 1768388023
@@ -0,0 +1,167 @@
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;
using Codice.Client.BaseCommands.BranchExplorer;
using Codice.CM.Common;
using Unity.PlasticSCM.Editor.Views.BranchExplorer.Virtualization;
using Unity.PlasticSCM.Editor.Views.BranchExplorer.Drawing.Shapes.Colors;
using Unity.PlasticSCM.Editor.Views.BranchExplorer.Drawing.Shapes.Connections;
namespace Unity.PlasticSCM.Editor.Views.BranchExplorer.Drawing.Shapes
{
internal class MergeLinkShape : BrExShape
{
internal LinkDrawInfo LinkDraw { get { return VirtualShape.DrawInfo as LinkDrawInfo; } }
internal Rect Source { get; }
internal Rect Destination { get; }
internal static string BuildName(long sourceChangesetId, long destinationChangesetId)
{
return "merge-link-" + sourceChangesetId + "-" + destinationChangesetId;
}
internal MergeLinkShape(
VirtualShape virtualShape,
Rect source,
Rect dst) : base(virtualShape)
{
Source = source;
Destination = dst;
name = BuildName(
GetChangesetId(LinkDraw.SourceChangeset),
GetChangesetId(LinkDraw.DestinationChangeset));
SetupBounds();
}
internal override bool HasContextMenu() => true;
internal override void OnScrollChanged()
{
if (!LinkDraw.Pending)
return;
MarkDirtyRepaint();
}
public override bool ContainsPoint(Vector2 localPoint)
{
if (!DisplayOptions.DisplayMergeLinks)
return false;
return mHitTestPath != null &&
mHitTestPath.IsPointNear(localPoint, HIT_TEST_TOLERANCE);
}
void SetupBounds()
{
MergeLinkGeometry.CalculateHitTestPath(Source, Destination, out mHitTestPath);
Rect boundingBox = mHitTestPath.CalculateBoundingBox()
.Inflate(HIT_TEST_TOLERANCE);
style.left = boundingBox.x;
style.top = boundingBox.y;
style.width = boundingBox.width;
style.height = boundingBox.height;
mBoundsOffset = new Vector2(boundingBox.x, boundingBox.y);
TranslateHitTestPath(mHitTestPath, mBoundsOffset);
mLocalSource = TranslateRect(Source, mBoundsOffset);
mLocalDestination = TranslateRect(Destination, mBoundsOffset);
}
protected override void GenerateVisualContent(Painter2D painter)
{
if (!DisplayOptions.DisplayMergeLinks)
return;
painter.strokeColor = BrExColors.MergeLink.GetLineColor(
LinkDraw.MergeType,
IsSelected);
painter.lineWidth = BrExLineWidths.MergeLink.GetWidth();
painter.lineCap = LineCap.Round;
painter.lineJoin = LineJoin.Round;
if (LinkDraw.Pending && TryGetLocalVisibleRect(out Rect localVisibleRect))
{
// use clipping when drawing pending links
// as they use dashes and could exceed the
// UIElements limit of 65535 vertices
MergeLinkGeometry.Draw(
painter,
mLocalSource,
mLocalDestination,
BrExDashes.GetMergeLinkDashPattern(true),
localVisibleRect);
return;
}
MergeLinkGeometry.Draw(
painter,
mLocalSource,
mLocalDestination,
null);
}
static void TranslateHitTestPath(List<Vector2> hitTestPath, Vector2 offset)
{
for (int i = 0; i < hitTestPath.Count; i++)
hitTestPath[i] -= offset;
}
Rect TranslateRect(Rect rect, Vector2 offset)
{
return new Rect(
rect.x - offset.x,
rect.y - offset.y,
rect.width,
rect.height);
}
static long GetChangesetId(ChangesetDrawInfo changesetDraw)
{
if (changesetDraw == null)
return -1;
BrExChangeset changeset = changesetDraw.Tag as BrExChangeset;
return changeset != null ? changeset.Id : -1;
}
bool TryGetLocalVisibleRect(out Rect localVisibleRect)
{
VirtualCanvas virtualCanvas = this.GetFirstAncestorOfType<VirtualCanvas>();
if (virtualCanvas == null)
{
localVisibleRect = default;
return false;
}
Rect visibleRect = virtualCanvas.GetVisibleRectStrict();
localVisibleRect = new Rect(
visibleRect.x - mBoundsOffset.x,
visibleRect.y - mBoundsOffset.y,
visibleRect.width,
visibleRect.height);
return true;
}
const float HIT_TEST_TOLERANCE = 6f;
Rect mLocalSource;
Rect mLocalDestination;
List<Vector2> mHitTestPath;
Vector2 mBoundsOffset;
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 0b4508d282e94f37a6429cd6a3468e8e
timeCreated: 1768382316
@@ -0,0 +1,518 @@
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;
namespace Unity.PlasticSCM.Editor.Views.BranchExplorer.Drawing.Shapes
{
internal static class PolygonExtensions
{
internal static bool ContainsPoint(this List<Vector2> polygon, Vector2 point)
{
if (polygon == null || polygon.Count < 3)
return false;
// ray casting algorithm for point-in-polygon
bool inside = false;
int j = polygon.Count - 1;
for (int i = 0; i < polygon.Count; i++)
{
// check if edge crosses horizontal ray from point
bool edgeCrossesRay = (polygon[i].y > point.y) != (polygon[j].y > point.y);
if (edgeCrossesRay)
{
float intersectionX = (polygon[j].x - polygon[i].x) * (point.y - polygon[i].y) /
(polygon[j].y - polygon[i].y) + polygon[i].x;
// if the intersection is to the right of point, toggle inside
if (point.x < intersectionX)
inside = !inside;
}
j = i;
}
return inside;
}
}
internal static class PathExtensions
{
internal static bool IsPointNear(this List<Vector2> path, Vector2 point, float tolerance)
{
if (path == null || path.Count < 2)
return false;
for (int i = 0; i < path.Count - 1; i++)
{
float distance = DistanceToSegment(point, path[i], path[i + 1]);
if (distance <= tolerance)
return true;
}
return false;
}
internal static Rect CalculateBoundingBox(this List<Vector2> path)
{
if (path == null || path.Count == 0)
return new Rect(0, 0, 0, 0);
float minX = path[0].x;
float minY = path[0].y;
float maxX = path[0].x;
float maxY = path[0].y;
for (int i = 1; i < path.Count; i++)
{
Vector2 p = path[i];
if (p.x < minX) minX = p.x;
else if (p.x > maxX) maxX = p.x;
if (p.y < minY) minY = p.y;
else if (p.y > maxY) maxY = p.y;
}
return new Rect(minX, minY, maxX - minX, maxY - minY);
}
static float DistanceToSegment(Vector2 point, Vector2 segmentStart, Vector2 segmentEnd)
{
Vector2 segment = segmentEnd - segmentStart;
float segmentLengthSquared = segment.sqrMagnitude;
if (segmentLengthSquared == 0)
return Vector2.Distance(point, segmentStart);
// project point onto the line, clamping to segment
float t = Mathf.Clamp01(Vector2.Dot(point - segmentStart, segment) / segmentLengthSquared);
Vector2 projection = segmentStart + t * segment;
return Vector2.Distance(point, projection);
}
}
internal static class Painter2DExtensions
{
internal static void DrawRect(
this Painter2D painter,
Rect rect)
{
painter.BeginPath();
painter.MoveTo(new Vector2(rect.xMin, rect.yMin));
painter.LineTo(new Vector2(rect.xMax, rect.yMin));
painter.LineTo(new Vector2(rect.xMax, rect.yMax));
painter.LineTo(new Vector2(rect.xMin, rect.yMax));
painter.ClosePath();
}
internal static void DrawPoligon(
this Painter2D painter,
List<Vector2> poligon)
{
painter.BeginPath();
for (int i = 0; i < poligon.Count; i++)
{
if (i == 0)
painter.MoveTo(poligon[i]);
else
painter.LineTo(poligon[i]);
}
}
internal static void DrawCircle(
this Painter2D painter,
Vector2 center,
float radius)
{
painter.BeginPath();
painter.Arc(
center,
radius,
0,
360);
painter.ClosePath();
}
internal static void StrokeLine(
this Painter2D painter,
Vector2 start,
Vector2 end,
float[] dashPattern)
{
StrokeLine(painter, start, end, dashPattern, false, default);
}
internal static void StrokeLine(
this Painter2D painter,
Vector2 start,
Vector2 end,
float[] dashPattern,
Rect clipRect)
{
StrokeLine(painter, start, end, dashPattern, true, clipRect);
}
internal static void StrokeCircle(
this Painter2D painter,
Vector2 vector2,
int changesetRadius,
float[] dashPattern)
{
if (dashPattern == null || dashPattern.Length == 0)
{
painter.DrawCircle(vector2, changesetRadius);
painter.Stroke();
return;
}
// Calculate the circumference to determine how to distribute dashes
float circumference = 2 * Mathf.PI * changesetRadius;
// Calculate total pattern length
float patternLength = 0;
foreach (float segment in dashPattern)
{
if (segment > 0)
patternLength += segment;
}
if (patternLength <= 0 || circumference <= 0)
{
painter.DrawCircle(vector2, changesetRadius);
painter.Stroke();
return;
}
// Draw dashed circle using arc segments
float currentAngle = 0;
float distanceCovered = 0;
int patternIndex = 0;
bool isDash = true; // Start with a dash
while (distanceCovered < circumference)
{
float segmentLength = dashPattern[patternIndex % dashPattern.Length];
if (segmentLength <= 0)
{
patternIndex++;
isDash = !isDash;
continue;
}
float angleIncrement = (segmentLength / circumference) * 360f;
if (isDash)
{
// Draw the dash as an arc
painter.BeginPath();
painter.Arc(vector2, changesetRadius, currentAngle, currentAngle + angleIncrement);
painter.Stroke();
}
currentAngle += angleIncrement;
distanceCovered += segmentLength;
patternIndex++;
isDash = !isDash; // Alternate between dash and gap
}
}
internal static void StrokePath(
this Painter2D painter,
List<Vector2> path,
float[] dashPattern)
{
StrokePath(painter, path, dashPattern, false, default);
}
internal static void StrokePath(
this Painter2D painter,
List<Vector2> path,
float[] dashPattern,
Rect clipRect)
{
StrokePath(painter, path, dashPattern, true, clipRect);
}
static void StrokeLine(
Painter2D painter,
Vector2 start,
Vector2 end,
float[] dashPattern,
bool useClip,
Rect clipRect)
{
if (dashPattern == null || dashPattern.Length == 0)
{
Vector2 clippedStart = default;
Vector2 clippedEnd = default;
if (!useClip || TryClipSegment.ToRect(start, end, clipRect, out clippedStart, out clippedEnd))
{
Vector2 from = useClip ? clippedStart : start;
Vector2 to = useClip ? clippedEnd : end;
painter.BeginPath();
painter.MoveTo(from);
painter.LineTo(to);
painter.Stroke();
}
return;
}
Vector2 direction = end - start;
float totalLength = direction.magnitude;
if (totalLength <= 0f)
return;
direction /= totalLength;
float patternLength = 0f;
foreach (float segment in dashPattern)
{
if (segment > 0)
patternLength += segment;
}
if (patternLength <= 0f)
{
Vector2 clippedStart = default;
Vector2 clippedEnd = default;
if (!useClip || TryClipSegment.ToRect(start, end, clipRect, out clippedStart, out clippedEnd))
{
Vector2 from = useClip ? clippedStart : start;
Vector2 to = useClip ? clippedEnd : end;
painter.BeginPath();
painter.MoveTo(from);
painter.LineTo(to);
painter.Stroke();
}
return;
}
float distanceCovered = 0f;
int patternIndex = 0;
bool isDash = true;
while (distanceCovered < totalLength)
{
float segmentLength = dashPattern[patternIndex % dashPattern.Length];
if (segmentLength <= 0f)
{
patternIndex++;
isDash = !isDash;
continue;
}
float remaining = totalLength - distanceCovered;
float lengthToUse = Mathf.Min(segmentLength, remaining);
if (isDash)
{
Vector2 segmentStart = start + direction * distanceCovered;
Vector2 segmentEnd = start + direction * (distanceCovered + lengthToUse);
Vector2 clippedStart = default;
Vector2 clippedEnd = default;
if (!useClip || TryClipSegment.ToRect(segmentStart, segmentEnd, clipRect, out clippedStart, out clippedEnd))
{
Vector2 from = useClip ? clippedStart : segmentStart;
Vector2 to = useClip ? clippedEnd : segmentEnd;
painter.BeginPath();
painter.MoveTo(from);
painter.LineTo(to);
painter.Stroke();
}
}
distanceCovered += segmentLength;
patternIndex++;
isDash = !isDash;
}
}
static void StrokePath(
Painter2D painter,
List<Vector2> path,
float[] dashPattern,
bool useClip,
Rect clipRect)
{
if (path == null || path.Count < 2)
return;
if (dashPattern == null || dashPattern.Length == 0)
{
painter.BeginPath();
painter.MoveTo(path[0]);
for (int i = 1; i < path.Count; i++)
painter.LineTo(path[i]);
painter.Stroke();
return;
}
float totalLength = 0f;
for (int i = 0; i < path.Count - 1; i++)
totalLength += Vector2.Distance(path[i], path[i + 1]);
if (totalLength <= 0f)
return;
float patternLength = 0f;
foreach (float segment in dashPattern)
{
if (segment > 0)
patternLength += segment;
}
if (patternLength <= 0f)
{
painter.BeginPath();
painter.MoveTo(path[0]);
for (int i = 1; i < path.Count; i++)
painter.LineTo(path[i]);
painter.Stroke();
return;
}
int patternIndex = 0;
bool isDash = true;
float segmentRemaining = dashPattern[patternIndex % dashPattern.Length];
for (int i = 0; i < path.Count - 1; i++)
{
Vector2 segmentStart = path[i];
Vector2 segmentEnd = path[i + 1];
Vector2 segmentVector = segmentEnd - segmentStart;
float segmentLength = segmentVector.magnitude;
if (segmentLength <= 0f)
continue;
Vector2 direction = segmentVector / segmentLength;
float distanceCovered = 0f;
while (distanceCovered < segmentLength)
{
if (segmentRemaining <= 0f)
{
patternIndex++;
isDash = !isDash;
segmentRemaining = dashPattern[patternIndex % dashPattern.Length];
continue;
}
float remainingInSegment = segmentLength - distanceCovered;
float lengthToUse = Mathf.Min(segmentRemaining, remainingInSegment);
if (isDash)
{
Vector2 dashStart = segmentStart + direction * distanceCovered;
Vector2 dashEnd = dashStart + direction * lengthToUse;
Vector2 clippedStart = default;
Vector2 clippedEnd = default;
if (!useClip || TryClipSegment.ToRect(dashStart, dashEnd, clipRect, out clippedStart, out clippedEnd))
{
Vector2 from = useClip ? clippedStart : dashStart;
Vector2 to = useClip ? clippedEnd : dashEnd;
painter.BeginPath();
painter.MoveTo(from);
painter.LineTo(to);
painter.Stroke();
}
}
distanceCovered += lengthToUse;
segmentRemaining -= lengthToUse;
}
}
}
internal static void PreciseArcTo(
this Painter2D painter,
Vector2 currentPoint,
Vector2 targetPoint,
Vector2 size,
float rotationAngle,
bool isLargeArc,
ArcDirection direction)
{
EllipticalArc.BuildArc(
painter,
currentPoint,
targetPoint,
size,
rotationAngle * Mathf.Deg2Rad,
isLargeArc,
direction == ArcDirection.Clockwise);
}
internal static void AppendCubicBezierToPath(
Vector2 start,
Vector2 controlPoint1,
Vector2 controlPoint2,
Vector2 end,
List<Vector2> hitTestPath)
{
if (hitTestPath.Count == 0 || hitTestPath[hitTestPath.Count - 1] != start)
hitTestPath.Add(start);
float toleranceSqr = DEFAULT_TOLERANCE * DEFAULT_TOLERANCE;
Stack<(Vector2 p0, Vector2 p1, Vector2 p2, Vector2 p3, int depth)> stack =
new Stack<(Vector2, Vector2, Vector2, Vector2, int)>();
stack.Push((start, controlPoint1, controlPoint2, end, 0));
while (stack.Count > 0)
{
var segment = stack.Pop();
if (segment.depth >= MAX_SUBDIVISION_DEPTH ||
IsBezierFlatEnough(segment.p0, segment.p1, segment.p2, segment.p3, toleranceSqr))
{
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;
// Push in reverse order so first half is processed first
stack.Push((p0123, p123, p23, segment.p3, segment.depth + 1));
stack.Push((segment.p0, p01, p012, p0123, segment.depth + 1));
}
}
internal static bool IsBezierFlatEnough(Vector2 p0, Vector2 p1, Vector2 p2, Vector2 p3, float toleranceSqr)
{
float d1 = DistancePointToLineSqr(p1, p0, p3);
float d2 = DistancePointToLineSqr(p2, p0, p3);
return Mathf.Max(d1, d2) <= toleranceSqr;
}
internal static float DistancePointToLineSqr(Vector2 point, Vector2 lineStart, Vector2 lineEnd)
{
Vector2 line = lineEnd - lineStart;
float lenSq = line.sqrMagnitude;
if (lenSq < 0.0001f)
return (point - lineStart).sqrMagnitude;
float t = Vector2.Dot(point - lineStart, line) / lenSq;
Vector2 projection = lineStart + t * line;
return (point - projection).sqrMagnitude;
}
const float DEFAULT_TOLERANCE = 1.0f;
const int MAX_SUBDIVISION_DEPTH = 10;
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 90c35417a995402084cf69d05578c8de
timeCreated: 1768819438
@@ -0,0 +1,187 @@
using UnityEngine;
using UnityEngine.UIElements;
using Codice.CM.Common;
using Unity.PlasticSCM.Editor.Views.BranchExplorer.Drawing.Shapes.Colors;
using Unity.PlasticSCM.Editor.Views.BranchExplorer.Drawing.Shapes.Connections;
using Unity.PlasticSCM.Editor.Views.BranchExplorer.Virtualization;
namespace Unity.PlasticSCM.Editor.Views.BranchExplorer.Drawing.Shapes
{
internal class ParentLinkShape : BrExShape
{
internal Rect Source { get; set; }
internal Rect Destination { get; set; }
internal bool IsHighlightedByMergeLinkInterval { get; set; }
internal MergeType MergeLinkInvervalType { get; set; }
internal ParentLinkShape(
VirtualShape virtualShape,
bool isRelevant) : base(virtualShape)
{
mIsRelevant = isRelevant;
}
internal override void OnScrollChanged()
{
float opacity = IsPartiallyVisible() ? 0.7f : 1;
style.opacity = opacity;
}
protected override void SetVirtualShape(VirtualShape virtualShape)
{
base.SetVirtualShape(virtualShape);
if (!(virtualShape is ChangesetParentLinkVirtualShape))
return;
IsHighlightedByMergeLinkInterval = ((ChangesetParentLinkVirtualShape)virtualShape).IsHighlightedByMergeLinkInterval;
MergeLinkInvervalType = ((ChangesetParentLinkVirtualShape)virtualShape).MergeLinkInvervalType;
}
protected override void GenerateVisualContent(Painter2D painter)
{
if (IsCrossBranchParentLink() && !DisplayOptions.DisplayCrossBranchChangesetLinks)
return;
ConnectionPoints connection = ParentLinkConnectionPoints.
Build(Source, Destination);
if (IsHighlightedByMergeLinkInterval)
{
DrawMergeIntervalHighlight(painter, connection);
}
// arrow line
painter.strokeColor = BrExColors.ParentLink.GetLineColor();
painter.lineWidth = BrExLineWidths.Changeset.GetParentLinkThickness();
DrawLineArrow(
painter,
connection.Source,
connection.Destination,
out var arrowStartPoint);
painter.Stroke();
painter.strokeColor = BrExColors.ParentLink.GetLineColor();
painter.fillColor = BrExColors.ParentLink.GetLineColor();
painter.lineWidth = BrExLineWidths.Changeset.GetParentLinkThickness();
painter.lineCap = LineCap.Round;
painter.lineJoin = LineJoin.Round;
// arrow head
DrawHeadArrow(
painter,
arrowStartPoint,
connection.Destination);
painter.Stroke();
painter.Fill();
}
void DrawHeadArrow(
Painter2D painter,
Vector2 arrowStartPoint,
Vector2 arrowEndPoint)
{
float theta = Mathf.Atan2(
arrowStartPoint.y - arrowEndPoint.y,
arrowStartPoint.x - arrowEndPoint.x);
float sint = Mathf.Sin(theta);
float cost = Mathf.Cos(theta);
Vector2 p3 = new Vector2(
arrowEndPoint.x + (ARROW_WIDTH * cost - ARROW_HEIGHT * sint),
arrowEndPoint.y + (ARROW_WIDTH * sint + ARROW_HEIGHT * cost));
Vector2 p4 = new Vector2(
arrowEndPoint.x + (ARROW_WIDTH * cost + ARROW_HEIGHT * sint),
arrowEndPoint.y - (ARROW_HEIGHT * cost - ARROW_WIDTH * sint));
painter.BeginPath();
painter.MoveTo(p3);
painter.LineTo(p4);
painter.LineTo(arrowEndPoint);
painter.ClosePath();
}
void DrawLineArrow(
Painter2D painter,
Vector2 start,
Vector2 end,
out Vector2 arrowStartPoint)
{
Vector2 normal = (end - start).normalized;
float distance = ARROW_HEIGHT + 3; // give some extra for the pen thickness
Vector2 endLinePoint = new Vector2(
end.x - (distance * normal.x),
end.y - (distance * normal.y));
arrowStartPoint = start;
painter.StrokeLine(
start,
endLinePoint,
BrExDashes.GetParentLinkDashPattern(mIsRelevant));
}
void DrawMergeIntervalHighlight(
Painter2D painter,
ConnectionPoints connection)
{
// arrow line
painter.strokeColor = BrExColors.MergeLink.GetLineColor(MergeLinkInvervalType, false);
painter.lineCap = LineCap.Round;
painter.lineJoin = LineJoin.Round;
painter.lineWidth = BrExLineWidths.MergeLink.GetIntervalHighlightWidth();
DrawLineArrow(
painter,
connection.Source,
connection.Destination,
out _);
painter.Stroke();
}
bool IsPartiallyVisible()
{
VirtualCanvas virtualCanvas = this.GetFirstAncestorOfType<VirtualCanvas>();
return !IsVisibleRect(Source, virtualCanvas) || !IsVisibleRect(Destination, virtualCanvas);
}
bool IsCrossBranchParentLink()
{
return !Mathf.Approximately(Source.y, Destination.y);
}
static bool IsVisibleRect(Rect source, VirtualCanvas virtualCanvas)
{
if (virtualCanvas == null)
return false;
Rect visibleRect = virtualCanvas.GetVisibleRectStrict();
Vector2 topLeft = new Vector2(source.xMin, source.yMin);
Vector2 bottomRight = new Vector2(source.xMax, source.yMax);
Vector2 topRight = new Vector2(source.xMax, source.yMax);
Vector2 bottomLeft = new Vector2(source.xMin, source.yMax);
return visibleRect.Contains(topLeft) || visibleRect.Contains(bottomRight) ||
visibleRect.Contains(topRight) || visibleRect.Contains(bottomLeft);
}
readonly bool mIsRelevant;
const float ARROW_WIDTH = 4;
const float ARROW_HEIGHT = 2;
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: c24fdb91749740eea5515d6db87aafd9
timeCreated: 1768382293
@@ -0,0 +1,110 @@
using UnityEngine;
namespace Unity.PlasticSCM.Editor.Views.BranchExplorer.Drawing.Shapes
{
internal static class TryClipSegment
{
internal static bool ToRect(
Vector2 start,
Vector2 end,
Rect rect,
out Vector2 clippedStart,
out Vector2 clippedEnd)
{
const int Left = 1;
const int Right = 2;
const int Bottom = 4;
const int Top = 8;
float xMin = rect.xMin;
float xMax = rect.xMax;
float yMin = rect.yMin;
float yMax = rect.yMax;
Vector2 p0 = start;
Vector2 p1 = end;
int outCode0 = ComputeOutCode(p0, xMin, xMax, yMin, yMax, Left, Right, Bottom, Top);
int outCode1 = ComputeOutCode(p1, xMin, xMax, yMin, yMax, Left, Right, Bottom, Top);
bool accept = false;
while (true)
{
if ((outCode0 | outCode1) == 0)
{
accept = true;
break;
}
if ((outCode0 & outCode1) != 0)
break;
int outCodeOut = outCode0 != 0 ? outCode0 : outCode1;
float x = 0f;
float y = 0f;
if ((outCodeOut & Top) != 0)
{
x = p0.x + (p1.x - p0.x) * (yMax - p0.y) / (p1.y - p0.y);
y = yMax;
}
else if ((outCodeOut & Bottom) != 0)
{
x = p0.x + (p1.x - p0.x) * (yMin - p0.y) / (p1.y - p0.y);
y = yMin;
}
else if ((outCodeOut & Right) != 0)
{
y = p0.y + (p1.y - p0.y) * (xMax - p0.x) / (p1.x - p0.x);
x = xMax;
}
else if ((outCodeOut & Left) != 0)
{
y = p0.y + (p1.y - p0.y) * (xMin - p0.x) / (p1.x - p0.x);
x = xMin;
}
if (outCodeOut == outCode0)
{
p0 = new Vector2(x, y);
outCode0 = ComputeOutCode(p0, xMin, xMax, yMin, yMax, Left, Right, Bottom, Top);
}
else
{
p1 = new Vector2(x, y);
outCode1 = ComputeOutCode(p1, xMin, xMax, yMin, yMax, Left, Right, Bottom, Top);
}
}
clippedStart = p0;
clippedEnd = p1;
return accept;
}
static int ComputeOutCode(
Vector2 point,
float xMin,
float xMax,
float yMin,
float yMax,
int left,
int right,
int bottom,
int top)
{
int code = 0;
if (point.x < xMin)
code |= left;
else if (point.x > xMax)
code |= right;
if (point.y < yMin)
code |= bottom;
else if (point.y > yMax)
code |= top;
return code;
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: bddb6813a13a4bf892c0927184324e20
timeCreated: 1772441078
@@ -0,0 +1,103 @@
using Codice.Client.BaseCommands.BranchExplorer;
using PlasticGui.WorkspaceWindow.BranchExplorer;
using Unity.PlasticSCM.Editor.Views.BranchExplorer.Virtualization;
namespace Unity.PlasticSCM.Editor.Views.BranchExplorer.Drawing.Shapes
{
internal static class ZIndex
{
// Base multiplier for position calculation.
// Positions are calculated as: (zIndex * BASE_MULTIPLIER) + originalIndex
// This ensures proper z-ordering while maintaining relative order within each z-index level.
internal const int BASE_MULTIPLIER = 1000000;
internal static int GetZIndex(VirtualShape virtualShape)
{
switch (virtualShape.ShapeType)
{
case ShapeType.Column:
return COLUMN_ZINDEX;
case ShapeType.ColumnHeader:
return COLUMN_HEADER_ZINDEX;
case ShapeType.ChangesetParentLink:
return GetChangesetParentLinkZIndex(virtualShape);
case ShapeType.BranchParentLink:
return DEFAULT_ZINDEX;
case ShapeType.Branch:
case ShapeType.EmptyBranch:
return BRANCH_ZINDEX;
case ShapeType.BranchCaption:
return BRANCH_CAPTION_ZINDEX;
case ShapeType.Changeset:
return CHANGESET_ZINDEX;
case ShapeType.ChangesetComment:
return CHANGESET_COMMENT_ZINDEX;
case ShapeType.ChangesetNumber:
return CHANGESET_NUMBER_ZINDEX;
case ShapeType.Label:
return LABEL_ZINDEX;
case ShapeType.MergeLink:
return DEFAULT_ZINDEX;
default:
return DEFAULT_ZINDEX;
}
}
static int GetParentLinkShapeZIndex(ParentLinkShape shape)
{
if (shape.VirtualShape.DrawInfo is ChangesetDrawInfo)
{
ChangesetDrawInfo commitDraw =
(ChangesetDrawInfo)shape.VirtualShape.DrawInfo;
ChangesetDrawInfo parent = commitDraw.Parent ?? commitDraw.RelevantParent;
if (parent == null)
return DEFAULT_ZINDEX;
return commitDraw.Branch == parent.Branch ?
PARENT_LINK_ON_SAME_BRANCH_ZINDEX : DEFAULT_ZINDEX;
}
return DEFAULT_ZINDEX;
}
static int GetChangesetParentLinkZIndex(VirtualShape virtualShape)
{
if (!(virtualShape.DrawInfo is ChangesetDrawInfo))
return DEFAULT_ZINDEX;
ChangesetDrawInfo commitDraw = (ChangesetDrawInfo)virtualShape.DrawInfo;
ChangesetDrawInfo parent = commitDraw.Parent ?? commitDraw.RelevantParent;
if (parent == null)
return DEFAULT_ZINDEX;
return commitDraw.Branch == parent.Branch ?
PARENT_LINK_ON_SAME_BRANCH_ZINDEX : DEFAULT_ZINDEX;
}
const int COLUMN_ZINDEX = 0;
internal const int DEFAULT_ZINDEX = 1;
const int BRANCH_ZINDEX = 2;
const int CHANGESET_COMMENT_ZINDEX = 3;
const int LABEL_ZINDEX = 4;
const int CHANGESET_ZINDEX = 5;
internal const int PARENT_LINK_ON_SAME_BRANCH_ZINDEX = 6;
const int BRANCH_CAPTION_ZINDEX = 7;
const int CHANGESET_NUMBER_ZINDEX = 8;
const int COLUMN_HEADER_ZINDEX = 9;
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 4a3f57b0c1c9343bf9b378276e7db640
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,37 @@
using System;
using UnityEngine.UIElements;
using PlasticGui;
namespace Unity.PlasticSCM.Editor.Views.BranchExplorer
{
internal class EmptyStateView : VisualElement
{
internal EmptyStateView(Action onCreateWorkspaceClicked)
{
CreateGUI(onCreateWorkspaceClicked);
}
void CreateGUI(Action onCreateWorkspaceClicked)
{
style.flexGrow = 1;
style.alignItems = Align.Center;
style.justifyContent = Justify.Center;
var emptyStateLabel = new Label(
PlasticLocalization.Name.BranchExplorerNoWorkspaceMessage.GetString());
emptyStateLabel.style.unityTextAlign = UnityEngine.TextAnchor.MiddleCenter;
emptyStateLabel.style.whiteSpace = WhiteSpace.Normal;
var createWorkspaceButton = new Button(onCreateWorkspaceClicked)
{
text = PlasticLocalization.Name.CreateWorkspace.GetString()
};
createWorkspaceButton.style.marginTop = 10;
Add(emptyStateLabel);
Add(createWorkspaceButton);
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 42dc3be94f914d4c886ba488248b16b2
timeCreated: 1768304400
@@ -0,0 +1,60 @@
using Unity.PlasticSCM.Editor.Views.BranchExplorer.Drawing.Shapes;
using System.Collections.Generic;
using Codice.Client.BaseCommands.BranchExplorer;
namespace Unity.PlasticSCM.Editor.Views.BranchExplorer
{
internal static class FindReferenceChangeset
{
internal static ChangesetDrawInfo FromChangesetShapes(List<ChangesetShape> shapes)
{
BrExRectangle mostRightChangesetBounds = new BrExRectangle();
ChangesetDrawInfo mostRightChangeset = null;
foreach (ChangesetShape changesetShape in shapes)
{
if (changesetShape.ChangesetDraw.IsWorkspaceChangeset)
return changesetShape.ChangesetDraw;
if (changesetShape.IsSelected)
return GetRelevantSelfOrParent(changesetShape.ChangesetDraw);
if (changesetShape.ChangesetDraw.Bounds.X <= mostRightChangesetBounds.X)
continue;
mostRightChangesetBounds = changesetShape.ChangesetDraw.Bounds;
mostRightChangeset = changesetShape.ChangesetDraw;
}
return mostRightChangeset;
}
static ChangesetDrawInfo GetRelevantSelfOrParent(ChangesetDrawInfo changesetDrawInfo)
{
ChangesetDrawInfo current = changesetDrawInfo;
while (current != null && !IsRelevant(current))
{
current = GetParentOrRelevantParent(current);
}
return current;
}
static ChangesetDrawInfo GetParentOrRelevantParent(ChangesetDrawInfo changesetDrawInfo)
{
if (changesetDrawInfo.Parent != null)
return changesetDrawInfo.Parent;
if (changesetDrawInfo.RelevantParent != null)
return changesetDrawInfo.RelevantParent;
return null;
}
static bool IsRelevant(ChangesetDrawInfo changesetDrawInfo)
{
return ((BrExChangeset)changesetDrawInfo.Tag).IsRelevant;
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 06643e3404d14375af98fc02b7314141
timeCreated: 1769691148
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 55c9ef176d464ba492d271e2b2c6cef1
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 5ea6fbde01fc74fd9aef36edf64214a7
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,74 @@
using UnityEngine;
namespace Unity.PlasticSCM.Editor.Views.BranchExplorer.Game
{
internal class EasterEggDetector
{
internal bool ProcessKeyCode(KeyCode keyCode)
{
if (keyCode == KeyCode.None)
return false;
bool konamiMatch = ProcessSequence(
keyCode, KONAMI_CODE, ref mKonamiIndex);
bool playMatch = ProcessSequence(
keyCode, PLAY_CODE, ref mPlayIndex);
bool gameMatch = ProcessSequence(
keyCode, GAME_CODE, ref mGameIndex);
return konamiMatch || playMatch || gameMatch;
}
internal void Reset()
{
mKonamiIndex = 0;
mPlayIndex = 0;
mGameIndex = 0;
}
static bool ProcessSequence(
KeyCode keyCode, KeyCode[] sequence, ref int index)
{
if (keyCode == sequence[index])
{
index++;
if (index >= sequence.Length)
{
index = 0;
return true;
}
}
else
{
index = keyCode == sequence[0] ? 1 : 0;
}
return false;
}
static readonly KeyCode[] KONAMI_CODE =
{
KeyCode.UpArrow, KeyCode.UpArrow,
KeyCode.DownArrow, KeyCode.DownArrow,
KeyCode.LeftArrow, KeyCode.RightArrow,
KeyCode.LeftArrow, KeyCode.RightArrow,
KeyCode.B, KeyCode.A
};
static readonly KeyCode[] PLAY_CODE =
{
KeyCode.P, KeyCode.L, KeyCode.A, KeyCode.Y
};
static readonly KeyCode[] GAME_CODE =
{
KeyCode.G, KeyCode.A, KeyCode.M, KeyCode.E
};
int mKonamiIndex;
int mPlayIndex;
int mGameIndex;
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: ae954cba0516d43c5b81c92cdb63d0c3
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,78 @@
using UnityEngine.UIElements;
namespace Unity.PlasticSCM.Editor.Views.BranchExplorer.Game
{
internal class Launcher
{
internal static Launcher Install(
VisualElement parent,
BranchExplorerView branchExplorerView)
{
return new Launcher(parent, branchExplorerView);
}
internal void Dispose()
{
Stop();
mParent.UnregisterCallback<KeyDownEvent>(
OnKeyDown, TrickleDown.TrickleDown);
}
Launcher(
VisualElement parent,
BranchExplorerView branchExplorerView)
{
mParent = parent;
mBranchExplorerView = branchExplorerView;
mDetector = new EasterEggDetector();
mParent.RegisterCallback<KeyDownEvent>(
OnKeyDown, TrickleDown.TrickleDown);
}
void OnKeyDown(KeyDownEvent evt)
{
if (mGame != null)
return;
if (mDetector.ProcessKeyCode(evt.keyCode))
Start();
}
void Start()
{
if (mBranchExplorerView == null)
return;
BranchExplorerViewer viewer = mBranchExplorerView.BranchExplorerViewer;
if (viewer == null || viewer.ExplorerLayout == null)
return;
mGame = new BranchRunnerGame();
mGame.OnExit += Stop;
mParent.Add(mGame);
mGame.StartWithLayout(
viewer.ExplorerLayout,
viewer.Zoom.Offset,
viewer.Zoom.ZoomLevel);
}
void Stop()
{
if (mGame == null)
return;
mGame.Stop();
mGame.OnExit -= Stop;
mParent.Remove(mGame);
mGame = null;
mDetector.Reset();
}
readonly VisualElement mParent;
readonly BranchExplorerView mBranchExplorerView;
readonly EasterEggDetector mDetector;
BranchRunnerGame mGame;
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: b048016cba8a4416cb18b2e78eb1705e
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,74 @@
using Codice.Utils;
using Unity.PlasticSCM.Editor.UI.UIElements;
using UnityEngine;
using UnityEngine.UIElements;
namespace Unity.PlasticSCM.Editor.Views.BranchExplorer
{
internal static class KeyboardActions
{
internal enum SearchAction
{
None,
Clean,
NextSearch,
PreviousSearch
}
internal enum NavigationAction
{
None,
MoveUp,
MoveDown,
MoveRight,
MoveLeft,
Escape,
Home,
End
}
internal static SearchAction GetSearchAction(KeyDownEvent evt)
{
if (KeyboardEvents.IsEscapePressed(evt))
return SearchAction.Clean;
if (PlatformIdentifier.IsMac() &&
evt.commandKey &&
KeyboardEvents.IsEnterPressed(evt))
return SearchAction.PreviousSearch;
if (PlatformIdentifier.IsWindows() &&
KeyboardEvents.IsControlPressed(evt) &&
KeyboardEvents.IsEnterPressed(evt))
return SearchAction.PreviousSearch;
if (KeyboardEvents.IsEnterPressed(evt))
return SearchAction.NextSearch;
return SearchAction.None;
}
internal static NavigationAction GetNavigationAction(KeyDownEvent evt)
{
switch (evt.keyCode)
{
case KeyCode.UpArrow:
return NavigationAction.MoveUp;
case KeyCode.DownArrow:
return NavigationAction.MoveDown;
case KeyCode.RightArrow:
return NavigationAction.MoveRight;
case KeyCode.LeftArrow:
return NavigationAction.MoveLeft;
case KeyCode.Escape:
return NavigationAction.Escape;
case KeyCode.Home:
return NavigationAction.Home;
case KeyCode.End:
return NavigationAction.End;
}
return NavigationAction.None;
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: b6b66fe771b04a66a438c93ccea06aa4
timeCreated: 1769416843
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 4198868b7a6f4b29aee31bc2cd593c1e
timeCreated: 1769006618
@@ -0,0 +1,294 @@
using System;
using System.Linq;
using UnityEditor;
using UnityEngine;
using Codice.Client.BaseCommands.BranchExplorer;
using Codice.CM.Common;
using PlasticGui;
using PlasticGui.Help;
using PlasticGui.WorkspaceWindow;
using PlasticGui.WorkspaceWindow.BranchExplorer;
using Unity.PlasticSCM.Editor.AssetsOverlays.Cache;
using Unity.PlasticSCM.Editor.Tool;
using Unity.PlasticSCM.Editor.Views.Labels;
namespace Unity.PlasticSCM.Editor.Views.BranchExplorer.Menu
{
internal class BranchExplorerLabelMenu :
BranchExplorerViewLabelMenuOperations.ISelectionResolver
//BranchExplorerViewExternalToolsMenuOperations.ISelectionResolver
{
internal BranchExplorerLabelMenu(
WorkspaceInfo wkInfo,
RepositorySpec repSpec,
EditorWindow window,
IWorkspaceWindow workspaceWindow,
IViewSwitcher switcher,
IMergeViewLauncher mergeViewLauncher,
BranchExplorerView branchExplorerView,
BranchExplorerSelection selectionHandler,
IProgressControls progressControls,
GuiHelpEvents guiHelpEvents,
IAssetStatusCache assetStatusCache,
IPendingChangesUpdater pendingChangesUpdater,
IIncomingChangesUpdater incomingChangesUpdater,
IShelvedChangesUpdater shelvedChangesUpdater,
LaunchTool.IProcessExecutor processExecutor,
LaunchTool.IShowDownloadPlasticExeWindow showDownloadPlasticExeWindow)
{
mRepSpec = repSpec;
mSelectionHandler = selectionHandler;
mLabelOperations = new BranchExplorerViewLabelMenuOperations(
wkInfo,
repSpec,
window,
workspaceWindow,
switcher,
mergeViewLauncher,
branchExplorerView,
selectionHandler,
this,
progressControls,
guiHelpEvents,
assetStatusCache,
pendingChangesUpdater,
incomingChangesUpdater,
shelvedChangesUpdater,
processExecutor,
showDownloadPlasticExeWindow);
/*
mExternalToolsMenuOperations = new BranchExplorerViewExternalToolsMenuOperations(
wkInfo, repSpec, selectionHandler, this, progressControls);
*/
mLabelsViewMenu = LabelsViewMenu.BuildForContextMenu(mLabelOperations);
}
internal void BrowseRepositoryOnLabel()
{
mLabelOperations.BrowseRepositoryOnLabel();
}
internal void Popup()
{
mSubmenuLabel = null;
if (!mSelectionHandler.HasSelectedLabels())
return;
LabelDrawInfo currentLabelDrawInfo = GetSelectedLabel(mSelectionHandler);
if (currentLabelDrawInfo.Labels.Length == 1 ||
mSelectionHandler.GetSelectedLabels().Count > 2)
{
mLabelsViewMenu.Popup();
return;
}
PopupMultipleLabelMenu(currentLabelDrawInfo.Labels);
}
internal bool ProcessKeyActionIfNeeded(Event e)
{
return mLabelsViewMenu.ProcessKeyActionIfNeeded(e);
}
internal void UpdateRepositorySpec(RepositorySpec repSpec)
{
mRepSpec = repSpec;
//mExternalToolsMenuOperations.UpdateRepositorySpec(repSpec);
}
void PopupMultipleLabelMenu(BrExLabel[] labels)
{
GenericMenu menu = new GenericMenu();
for (int i = 0; i < labels.Length; i++)
{
if (NeedsSeparator(
i, labels.Length, BrExDrawProperties.MaxLabelsPerChangeset))
{
menu.AddSeparator(string.Empty);
}
string escapedLabelName = EscapeLabelName(labels[i].Name);
BrExLabel label = labels[i];
LabelSpecificMenuOperations labelSpecificOperations =
new LabelSpecificMenuOperations(
mLabelOperations, () => { mSubmenuLabel = label; });
LabelsViewMenu labelsViewMenu = LabelsViewMenu.BuildForSubMenu(
labelSpecificOperations,
escapedLabelName);
labelsViewMenu.UpdateMenuItems(menu);
}
menu.ShowAsContext();
}
static bool NeedsSeparator(
int position,
int labelCount,
int maxLabelsForSeparator)
{
if (labelCount == maxLabelsForSeparator)
return false;
if (position >= labelCount || position == 0)
return false;
return position % maxLabelsForSeparator == 0;
}
MarkerExtendedInfo BranchExplorerViewLabelMenuOperations.ISelectionResolver.ResolveSelectedLabel()
{
LabelDrawInfo currentLabelDrawInfo = GetSelectedLabel(mSelectionHandler);
return BranchExplorerObjectResolver.GetMarkerExtendedInfo(
currentLabelDrawInfo,
PlasticGui.Plastic.API.GetMarkerInfo(mRepSpec, GetCurrentLabel(currentLabelDrawInfo).Id));
}
MarkerExtendedInfo BranchExplorerViewLabelMenuOperations.ISelectionResolver.ResolveLabel(
long labelId, LabelDrawInfo labelInfo)
{
return BranchExplorerObjectResolver.GetMarkerExtendedInfo(
labelInfo, PlasticGui.Plastic.API.GetMarkerInfo(mRepSpec, labelId));
}
/*
List<RepObjectInfo> BranchExplorerViewExternalToolsMenuOperations.ISelectionResolver.ResolveSelectedObjects()
{
return new List<RepObjectInfo>()
{
((BranchExplorerViewLabelMenuOperations.ISelectionResolver)this)
.ResolveSelectedLabel()
};
}
*/
BrExLabel GetCurrentLabel(LabelDrawInfo currentLabelDrawInfo)
{
return mSubmenuLabel ?? currentLabelDrawInfo.Labels[0];
}
static LabelDrawInfo GetSelectedLabel(BranchExplorerSelection selectionHandler)
{
return selectionHandler.GetSelectedLabels().
Aggregate((l1, l2) => l1.Labels.Count() > l2.Labels.Count() ? l1 : l2);
}
static string EscapeLabelName(string name)
{
if (string.IsNullOrEmpty(name))
return name;
return name.Replace("_", "__");
}
BrExLabel mSubmenuLabel;
RepositorySpec mRepSpec;
readonly BranchExplorerSelection mSelectionHandler;
readonly BranchExplorerViewLabelMenuOperations mLabelOperations;
//readonly BranchExplorerViewExternalToolsMenuOperations mExternalToolsMenuOperations;
readonly LabelsViewMenu mLabelsViewMenu;
}
internal class LabelSpecificMenuOperations : PlasticGui.WorkspaceWindow.QueryViews.Labels.ILabelMenuOperations
{
internal LabelSpecificMenuOperations(
BranchExplorerViewLabelMenuOperations labelOperations,
Action selectSpecificLabel)
{
mLabelOperations = labelOperations;
mSelectSpecificLabel = selectSpecificLabel;
}
int PlasticGui.WorkspaceWindow.QueryViews.Labels.ILabelMenuOperations.GetSelectedLabelsCount()
{
mSelectSpecificLabel();
return mLabelOperations.GetSelectedLabelsCount();
}
void PlasticGui.WorkspaceWindow.QueryViews.Labels.ILabelMenuOperations.CreateLabel()
{
mSelectSpecificLabel();
mLabelOperations.CreateLabel();
}
void PlasticGui.WorkspaceWindow.QueryViews.Labels.ILabelMenuOperations.ApplyLabelToWorkspace()
{
mSelectSpecificLabel();
mLabelOperations.ApplyLabelToWorkspace();
}
void PlasticGui.WorkspaceWindow.QueryViews.Labels.ILabelMenuOperations.SwitchToLabel()
{
mSelectSpecificLabel();
mLabelOperations.SwitchToLabel();
}
void PlasticGui.WorkspaceWindow.QueryViews.Labels.ILabelMenuOperations.DiffWithAnotherLabel()
{
mSelectSpecificLabel();
mLabelOperations.DiffWithAnotherLabel();
}
void PlasticGui.WorkspaceWindow.QueryViews.Labels.ILabelMenuOperations.DiffSelectedLabels()
{
mSelectSpecificLabel();
mLabelOperations.DiffSelectedLabels();
}
void PlasticGui.WorkspaceWindow.QueryViews.Labels.ILabelMenuOperations.MergeLabel()
{
mSelectSpecificLabel();
mLabelOperations.MergeLabel();
}
void PlasticGui.WorkspaceWindow.QueryViews.Labels.ILabelMenuOperations.MergeToLabel()
{
mSelectSpecificLabel();
mLabelOperations.MergeToLabel();
}
void PlasticGui.WorkspaceWindow.QueryViews.Labels.ILabelMenuOperations.CreateBranchFromLabel()
{
mSelectSpecificLabel();
mLabelOperations.CreateBranchFromLabel();
}
void PlasticGui.WorkspaceWindow.QueryViews.Labels.ILabelMenuOperations.RenameLabel()
{
mSelectSpecificLabel();
mLabelOperations.RenameLabel();
}
void PlasticGui.WorkspaceWindow.QueryViews.Labels.ILabelMenuOperations.DeleteLabel()
{
mSelectSpecificLabel();
mLabelOperations.DeleteLabel();
}
void PlasticGui.WorkspaceWindow.QueryViews.Labels.ILabelMenuOperations.ViewPermissions()
{
mSelectSpecificLabel();
mLabelOperations.ViewPermissions();
}
void PlasticGui.WorkspaceWindow.QueryViews.Labels.ILabelMenuOperations.BrowseRepositoryOnLabel()
{
mSelectSpecificLabel();
mLabelOperations.ViewPermissions();
}
readonly Action mSelectSpecificLabel;
readonly BranchExplorerViewLabelMenuOperations mLabelOperations;
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: f90d4c194bf143c5a6ca86108b35d4c8
timeCreated: 1769161133
@@ -0,0 +1,791 @@
using System.Collections.Generic;
using UnityEditor;
using Codice.Client.BaseCommands.BranchExplorer;
using Codice.Client.BaseCommands.BranchExplorer.Layout;
using Codice.Client.Common;
using Codice.Client.Common.EventTracking;
using Codice.Client.Common.Threading;
using Codice.Client.Common.WebApi;
using Codice.CM.Common;
using PlasticGui;
using PlasticGui.Help;
using PlasticGui.WorkspaceWindow;
using PlasticGui.WorkspaceWindow.BranchExplorer;
using PlasticGui.WorkspaceWindow.MergeRequest;
using PlasticGui.WorkspaceWindow.QueryViews.Branches;
using Unity.PlasticSCM.Editor.AssetsOverlays.Cache;
using Unity.PlasticSCM.Editor.AssetUtils;
using Unity.PlasticSCM.Editor.Tool;
using Unity.PlasticSCM.Editor.Headless;
using Unity.PlasticSCM.Editor.Views.Branches.Dialogs;
using Unity.PlasticSCM.Editor.Views.BranchExplorer.Virtualization;
using Unity.PlasticSCM.Editor.Views.Merge;
namespace Unity.PlasticSCM.Editor.Views.BranchExplorer.Menu
{
class BranchExplorerViewBranchMenuOperations :
IBranchMenuOperations,
IBranchExplorerBranchMenuOperations,
ILaunchCodeReviewWindow
{
internal BranchExplorerViewBranchMenuOperations(
IPlasticWebRestApi restApi,
WorkspaceInfo wkInfo,
RepositorySpec repSpec,
EditorWindow window,
IWorkspaceWindow workspaceWindow,
IViewSwitcher switcher,
IMergeViewLauncher mergeViewLauncher,
BranchExplorerView branchExplorerView,
IBrExNavigate brExNavigate,
BranchExplorerSelection selection,
BranchExplorerSelectedObjectResolver selectedObjectResolver,
IProgressControls progressControls,
GuiHelpEvents guiHelpEvents,
OpenedCodeReviewWindows openedCodeReviewWindows,
IAssetStatusCache assetStatusCache,
IPendingChangesUpdater pendingChangesUpdater,
IIncomingChangesUpdater incomingChangesUpdater,
IShelvedChangesUpdater shelvedChangesUpdater,
IWorkspaceModeNotificationUpdater workspaceModeNotificationUpdater,
LaunchTool.IProcessExecutor processExecutor,
LaunchTool.IShowDownloadPlasticExeWindow showDownloadPlasticExeWindow)
{
mRestApi = restApi;
mWkInfo = wkInfo;
mRepSpec = repSpec;
mWindow = window;
mSwitcher = switcher;
mMergeViewLauncher = mergeViewLauncher;
mBranchExplorerView = branchExplorerView;
mBrExNavigate = brExNavigate;
mSelectionHandler = selection;
mSelectedObjectResolver = selectedObjectResolver;
mProgressControl = progressControls;
mGuiHelpEvents = guiHelpEvents;
mOpenedCodeReviewWindows = openedCodeReviewWindows;
mAssetStatusCache = assetStatusCache;
mPendingChangesUpdater = pendingChangesUpdater;
mIncomingChangesUpdater = incomingChangesUpdater;
mShelvedChangesUpdater = shelvedChangesUpdater;
mWorkspaceModeNotificationUpdater = workspaceModeNotificationUpdater;
mProcessExecutor = processExecutor;
mShowDownloadPlasticExeWindow = showDownloadPlasticExeWindow;
mBranchOperations = new BranchOperations(
wkInfo,
workspaceWindow,
mergeViewLauncher,
branchExplorerView,
ViewType.BranchExplorerView,
progressControls,
new HeadlessUpdateReport(),
new ApplyShelveReport(window),
new ContinueWithPendingChangesQuestionerBuilder(switcher, window),
new ShelvePendingChangesQuestionerBuilder(window),
new ApplyShelveWithConflictsQuestionerBuilder(),
pendingChangesUpdater,
incomingChangesUpdater,
shelvedChangesUpdater,
new EnableSwitchAndShelveFeature(repSpec, window));
}
public void UpdateRepositorySpec(RepositorySpec repSpec)
{
mRepSpec = repSpec;
}
public BranchInfo GetSelectedBranch()
{
List<BranchInfo> selectedBranches = mSelectedObjectResolver.GetSelectedBranches();
if (selectedBranches.Count == 0)
return null;
return selectedBranches[0];
}
public int GetSelectedBranchesCount()
{
return mSelectedObjectResolver.GetSelectedObjectsCount();
}
public bool AreHiddenBranchesShown()
{
return false;
}
public void CreateBranch()
{
BranchInfo branch = null;
IThreadWaiter waiter = ThreadWaiter.GetWaiter();
waiter.Execute(
threadOperationDelegate: delegate
{
branch = ResolveSelectedBranch();
},
afterOperationDelegate: delegate
{
if (!HasOperationSucceeded(waiter))
return;
BranchCreationData branchCreationData =
CreateBranchDialog.CreateBranchFromLastParentBranchChangeset(
mWindow, mRepSpec, branch, string.Empty);
mBranchOperations.CreateBranch(
branchCreationData,
RefreshAsset.BeforeLongAssetOperation,
items => RefreshAsset.AfterLongAssetOperation(
mAssetStatusCache,
ProjectPackages.ShouldBeResolvedFromUpdateReport(mWkInfo, items)));
});
}
public void CreateTopLevelBranch()
{
BranchInfo branch = null;
IThreadWaiter waiter = ThreadWaiter.GetWaiter();
waiter.Execute(
threadOperationDelegate: delegate
{
branch = ResolveSelectedBranch();
},
afterOperationDelegate: /*async*/ delegate
{
if (!HasOperationSucceeded(waiter))
return;
/*
BranchCreationData branchCreationData =
await CreateBranchDialog.CreateTopLevelBranch(
GlobalConfig.Instance, mRepSpec, branch, mWindow, !mWkInfo.IsTemporary);
mBranchOperations.CreateBranch(branchCreationData, null, null);
*/
});
}
public void SwitchToBranch()
{
BranchInfo branch = null;
IThreadWaiter waiter = ThreadWaiter.GetWaiter();
waiter.Execute(
threadOperationDelegate: delegate
{
branch = ResolveSelectedBranch();
},
afterOperationDelegate: delegate
{
if (!HasOperationSucceeded(waiter))
return;
mBranchOperations.SwitchToBranch(
mRepSpec,
branch,
RefreshAsset.BeforeLongAssetOperation,
items => RefreshAsset.AfterLongAssetOperation(
mAssetStatusCache,
ProjectPackages.ShouldBeResolvedFromUpdateReport(mWkInfo, items)));
});
}
public void MergeBranch()
{
BranchInfo branch = null;
IThreadWaiter waiter = ThreadWaiter.GetWaiter();
waiter.Execute(
threadOperationDelegate: delegate
{
branch = ResolveSelectedBranch();
},
afterOperationDelegate: delegate
{
if (!HasOperationSucceeded(waiter))
return;
mBranchOperations.MergeBranch(mRepSpec, branch);
});
}
public void CherrypickBranch()
{
BranchInfo branch = null;
IThreadWaiter waiter = ThreadWaiter.GetWaiter();
waiter.Execute(
threadOperationDelegate: delegate
{
branch = ResolveSelectedBranch();
},
afterOperationDelegate: delegate
{
if (!HasOperationSucceeded(waiter))
return;
mBranchOperations.CherrypickBranch(mRepSpec, branch);
});
}
public void MergeToBranch()
{
BranchInfo branch = null;
IThreadWaiter waiter = ThreadWaiter.GetWaiter();
waiter.Execute(
threadOperationDelegate: delegate
{
branch = ResolveSelectedBranch();
},
afterOperationDelegate: /*async*/ delegate
{
if (!HasOperationSucceeded(waiter))
return;
/*
mBranchOperations.MergeToBranch(
mRepSpec,
branch,
await MergeToDestinationBranch.GetAsync(
mRepSpec, mWindow, mGuiHelpEvents));
*/
});
}
public void PullBranch()
{
BranchInfo branch = null;
IThreadWaiter waiter = ThreadWaiter.GetWaiter();
waiter.Execute(
threadOperationDelegate: delegate
{
branch = ResolveSelectedBranch();
},
afterOperationDelegate: delegate
{
if (!HasOperationSucceeded(waiter))
return;
/*
ReplicationOperations.PullBranch(
mRestApi,
mWindow,
mWindow.WorkspacePanel.WorkspaceView,
mRepSpec,
branch,
mGuiHelpEvents);
*/
});
}
public void PullRemoteBranch()
{
/*
ReplicationOperations.PullRemoteBranch(
mRestApi,
mWindow,
mWindow.WorkspacePanel.WorkspaceView,
mRepSpec,
mGuiHelpEvents);
*/
}
public void SyncWithGit()
{
/*
ReplicationOperations.SyncWithGit(
mWindow,
mIncomingChangesUpdater,
mShelvedChangesUpdater,
mRepSpec);
*/
}
public void PushBranch()
{
BranchInfo branch = null;
IThreadWaiter waiter = ThreadWaiter.GetWaiter();
waiter.Execute(
threadOperationDelegate: delegate
{
branch = ResolveSelectedBranch();
},
afterOperationDelegate: delegate
{
if (!HasOperationSucceeded(waiter))
return;
/*
ReplicationOperations.PushBranch(
mRestApi,
mWindow,
mWindow.WorkspacePanel.WorkspaceView,
mRepSpec,
branch,
mGuiHelpEvents);
*/
});
}
public void DiffBranch()
{
BranchInfo branch = null;
IThreadWaiter waiter = ThreadWaiter.GetWaiter();
waiter.Execute(
threadOperationDelegate: delegate
{
branch = ResolveSelectedBranch();
},
afterOperationDelegate: delegate
{
if (!HasOperationSucceeded(waiter))
return;
LaunchDiffOperations.DiffBranch(
mShowDownloadPlasticExeWindow,
mProcessExecutor,
mRepSpec,
branch,
PlasticGui.Plastic.API.IsGluonWorkspace(mWkInfo));
});
}
public void DiffWithAnotherBranch()
{
BranchInfo branch = null;
IThreadWaiter waiter = ThreadWaiter.GetWaiter();
waiter.Execute(
threadOperationDelegate: delegate
{
branch = ResolveSelectedBranch();
},
afterOperationDelegate: /*async*/ delegate
{
if (!HasOperationSucceeded(waiter))
return;
/*
BranchInfo targetBranch = await BranchesExplorerDialog.AskForBranchAsync(
mWindow, string.Format("find branch on repository '{0}'", mRepSpec),
mGuiHelpEvents);
if (targetBranch == null)
return;
DiffWindow.DiffBranches(
mWkInfo,
mRepSpec,
mWindow.WorkspacePanel.WorkspaceView,
mWindow.WorkspacePanel.WorkspaceView,
mWindow.WorkspacePanel.WorkspaceView.PendingChangesUpdater,
mWindow.WorkspacePanel.WorkspaceView.IncomingChangesUpdater,
mWindow.WorkspacePanel.WorkspaceView.ShelvedChangesUpdater,
mWindow.WorkspacePanel.WorkspaceView,
mProgressControl,
branch,
targetBranch);
*/
});
}
public void ViewChangesets()
{
BranchInfo branch = null;
IThreadWaiter waiter = ThreadWaiter.GetWaiter();
waiter.Execute(
threadOperationDelegate: delegate
{
branch = ResolveSelectedBranch();
},
afterOperationDelegate: delegate
{
if (!HasOperationSucceeded(waiter))
return;
/*
DynamicViewHandler.ShowChangesetsDynamicView(
mWkInfo,
mWindow,
mSwitcher,
mMergeViewLauncher,
mOverlappedView,
SettingSerializationName.BRANCHES_VIEW_NAME,
branch,
mRepSpec,
mGuiHelpEvents,
mOpenedCodeReviewWindows,
mPendingChangesUpdater,
mIncomingChangesUpdater,
mShelvedChangesUpdater,
mWorkspaceModeNotificationUpdater,
mNotifyStatusBar);
*/
});
}
public void RenameBranch()
{
BranchInfo branch = null;
IThreadWaiter waiter = ThreadWaiter.GetWaiter();
waiter.Execute(
threadOperationDelegate: delegate
{
branch = ResolveSelectedBranch();
},
afterOperationDelegate: delegate
{
if (!HasOperationSucceeded(waiter))
return;
BranchRenameData data = RenameBranchDialog.GetBranchRenameData(
mRepSpec, branch, mWindow);
mBranchOperations.RenameBranch(data);
});
}
public void HideUnhideBranch()
{
IList<BranchInfo> branches = null;
IThreadWaiter waiter = ThreadWaiter.GetWaiter();
waiter.Execute(
threadOperationDelegate: delegate
{
branches = ResolveSelectedBranches();
},
afterOperationDelegate: delegate
{
if (!HasOperationSucceeded(waiter))
return;
mBranchOperations.HideBranch(
GetRepositoryList(branches.Count),
branches);
});
}
public void DeleteBranch()
{
IList<BranchInfo> branches = null;
IThreadWaiter waiter = ThreadWaiter.GetWaiter();
waiter.Execute(
threadOperationDelegate: delegate
{
branches = ResolveSelectedBranches();
},
afterOperationDelegate: delegate
{
if (!HasOperationSucceeded(waiter))
return;
if (!DeleteBranchDialog.ConfirmDelete(mWindow, branches))
return;
mBranchOperations.DeleteBranch(
GetRepositoryList(branches.Count),
branches,
DeleteBranchOptions.IncludeChangesets);
});
}
public void CreateCodeReview()
{
BranchInfo branch = null;
IThreadWaiter waiter = ThreadWaiter.GetWaiter();
waiter.Execute(
threadOperationDelegate: delegate
{
branch = ResolveSelectedBranch();
},
afterOperationDelegate: delegate
{
if (!HasOperationSucceeded(waiter))
return;
NewCodeReviewBehavior choice = SelectNewCodeReviewBehavior.For(mRepSpec.Server);
switch (choice)
{
case NewCodeReviewBehavior.CreateAndOpenInDesktop:
mBranchOperations.CreateReview(mRepSpec, branch, this);
break;
case NewCodeReviewBehavior.RequestFromUnityCloud:
OpenRequestReviewPage.ForBranch(mRepSpec, branch.BranchId);
break;
case NewCodeReviewBehavior.Ask:
default:
break;
}
});
}
public void CreateMergeRequest() { }
public void ViewPermissions()
{
BranchInfo branch = null;
IThreadWaiter waiter = ThreadWaiter.GetWaiter();
waiter.Execute(
threadOperationDelegate: delegate
{
branch = ResolveSelectedBranch();
},
afterOperationDelegate: delegate
{
if (!HasOperationSucceeded(waiter))
return;
/*
PermissionsDialog.ShowPermissions(
mRepSpec,
branch,
mRepSpec.Server,
mGuiHelpEvents,
mWindow,
new PlasticGuiMessage(mWindow));
*/
});
}
public void NavigateToBase()
{
ChangesetDrawInfo branchBaseChangeset =
ResolveSelectedBranchBaseChangeset();
if (branchBaseChangeset == null)
return;
mBrExNavigate.NavigateToShape(
(VirtualShape)branchBaseChangeset.Visual);
}
public void FilterSelectedBranches()
{
TrackFeatureUseEvent.For(
mRepSpec,
TrackFeatureUseEvent.Features.DesktopGUI.Filters.FilterSelectedBranches);
/*
mBranchExplorerView.FilterBySelectedBranches(
ResolveSelectedBranches(),
showRelatedBranches: false,
displayOnlyPendingToMergeBranches: false);
*/
}
public void FilterSelectedAndRelatedBranches()
{
TrackFeatureUseEvent.For(
mRepSpec,
TrackFeatureUseEvent.Features.DesktopGUI.Filters.FilterSelectedAndRelatedBranches);
/*
mBranchExplorerView.FilterBySelectedBranches(
ResolveSelectedBranches(),
showRelatedBranches: true,
displayOnlyPendingToMergeBranches: false);
*/
}
public void FilterSelectedBranchesPendingMerges()
{
TrackFeatureUseEvent.For(
mRepSpec,
TrackFeatureUseEvent.Features.DesktopGUI.Filters.FilterSelectedBranchesPendingMerges);
/*
mBranchExplorerView.FilterBySelectedBranches(
ResolveSelectedBranches(),
showRelatedBranches: true,
displayOnlyPendingToMergeBranches: true);
*/
}
void IBranchExplorerBranchMenuOperations.MoveBranchUp()
{
TrackFeatureUseEvent.For(
mRepSpec,
TrackFeatureUseEvent.Features.BranchExplorer.Relayout.MoveBranchUp);
List<BranchDrawInfo> selectedBranches = mSelectionHandler.GetSelectedBranches();
foreach (BranchDrawInfo selectedBranch in selectedBranches)
{
if (selectedBranch.Row <= 0)
continue;
PersistentBranchLayout.Get().SetPreallocatedIndex(
selectedBranch.BranchId, selectedBranch.Row - 1);
}
mBranchExplorerView.RecalculateLayout();
}
void IBranchExplorerBranchMenuOperations.MoveBranchDown()
{
TrackFeatureUseEvent.For(
mRepSpec,
TrackFeatureUseEvent.Features.BranchExplorer.Relayout.MoveBranchDown);
List<BranchDrawInfo> selectedBranches = mSelectionHandler.GetSelectedBranches();
foreach (BranchDrawInfo selectedBranch in selectedBranches)
{
if (selectedBranch.Row >=
mBranchExplorerView.BranchExplorerViewer.ExplorerLayout.SlotCount - 1)
continue;
PersistentBranchLayout.Get().SetPreallocatedIndex(
selectedBranch.BranchId, selectedBranch.Row + 1);
}
mBranchExplorerView.RecalculateLayout();
}
void IBranchExplorerBranchMenuOperations.MoveBranchTop()
{
TrackFeatureUseEvent.For(
mRepSpec,
TrackFeatureUseEvent.Features.BranchExplorer.Relayout.MoveBranchTop);
List<BranchDrawInfo> selectedBranches = mSelectionHandler.GetSelectedBranches();
foreach (BranchDrawInfo selectedBranch in selectedBranches)
{
PersistentBranchLayout.Get().SetPreallocatedIndex(selectedBranch.BranchId, 0);
}
mBranchExplorerView.RecalculateLayout();
}
void IBranchExplorerBranchMenuOperations.MoveBranchBottom()
{
TrackFeatureUseEvent.For(
mRepSpec,
TrackFeatureUseEvent.Features.BranchExplorer.Relayout.MoveBranchBottom);
List<BranchDrawInfo> selectedBranches = mSelectionHandler.GetSelectedBranches();
foreach (BranchDrawInfo selectedBranch in selectedBranches)
{
PersistentBranchLayout.Get().SetPreallocatedIndex(
selectedBranch.BranchId,
mBranchExplorerView.BranchExplorerViewer.ExplorerLayout.SlotCount);
}
mBranchExplorerView.RecalculateLayout();
}
void IBranchExplorerBranchMenuOperations.ClearBranchRelayout()
{
TrackFeatureUseEvent.For(
mRepSpec,
TrackFeatureUseEvent.Features.BranchExplorer.Relayout.ClearBranchRelayout);
List<BranchDrawInfo> selectedBranches = mSelectionHandler.GetSelectedBranches();
foreach (BranchDrawInfo selectedBranch in selectedBranches)
{
PersistentBranchLayout.Get().Clear(selectedBranch.BranchId);
}
mBranchExplorerView.RecalculateLayout();
}
void IBranchExplorerBranchMenuOperations.ResetRelayoutData()
{
if (!GuiMessage.ShowYesNoQuestion(
PlasticLocalization.Name.ResetRelayoutData.GetString(),
PlasticLocalization.Name.ClearAllBranchRelayoutsDialogExplanation.GetString()))
{
return;
}
TrackFeatureUseEvent.For(
mRepSpec,
TrackFeatureUseEvent.Features.BranchExplorer.Relayout.ResetRelayoutData);
PersistentBranchLayout.Get().ClearAll();
mBranchExplorerView.RecalculateLayout();
}
void ILaunchCodeReviewWindow.Show(
WorkspaceInfo wkInfo,
RepositorySpec repSpec,
ReviewInfo reviewInfo,
RepObjectInfo repObjectInfo,
bool bShowReviewChangesTab)
{
LaunchTool.OpenCodeReview(
mShowDownloadPlasticExeWindow,
mProcessExecutor,
repSpec,
reviewInfo.Id,
PlasticGui.Plastic.API.IsGluonWorkspace(mWkInfo));
}
IList<BranchInfo> ResolveSelectedBranches()
{
return mSelectedObjectResolver.GetSelectedBranches();
}
BranchInfo ResolveSelectedBranch()
{
return ResolveSelectedBranches()[0];
}
ChangesetDrawInfo ResolveSelectedBranchBaseChangeset()
{
if (mSelectionHandler.GetSelectedBranchesCount() != 1)
return null;
BranchDrawInfo selectedBranch = mSelectionHandler.GetSelectedBranches()[0];
if (selectedBranch.EndChangeset == null)
return selectedBranch.HeadChangeset;
return selectedBranch.InitChangeset.Parent;
}
IList<RepositorySpec> GetRepositoryList(int count)
{
RepositorySpec[] repositories = new RepositorySpec[count];
for (int i = 0; i < repositories.Length; i++)
repositories[i] = mRepSpec;
return repositories;
}
bool HasOperationSucceeded(IThreadWaiter waiter)
{
if (waiter.Exception == null)
return true;
ExceptionsHandler.DisplayException(waiter.Exception);
return false;
}
readonly IProgressControls mProgressControl;
readonly IAssetStatusCache mAssetStatusCache;
readonly LaunchTool.IProcessExecutor mProcessExecutor;
readonly LaunchTool.IShowDownloadPlasticExeWindow mShowDownloadPlasticExeWindow;
readonly BranchOperations mBranchOperations;
readonly BranchExplorerView mBranchExplorerView;
readonly IBrExNavigate mBrExNavigate;
readonly BranchExplorerSelection mSelectionHandler;
readonly BranchExplorerSelectedObjectResolver mSelectedObjectResolver;
readonly IViewSwitcher mSwitcher;
readonly IMergeViewLauncher mMergeViewLauncher;
readonly EditorWindow mWindow;
RepositorySpec mRepSpec;
readonly WorkspaceInfo mWkInfo;
readonly GuiHelpEvents mGuiHelpEvents;
readonly OpenedCodeReviewWindows mOpenedCodeReviewWindows;
readonly IPendingChangesUpdater mPendingChangesUpdater;
readonly IIncomingChangesUpdater mIncomingChangesUpdater;
readonly IShelvedChangesUpdater mShelvedChangesUpdater;
readonly IWorkspaceModeNotificationUpdater mWorkspaceModeNotificationUpdater;
readonly IPlasticWebRestApi mRestApi;
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 91af864187ea4d65841241cea79c3f71
timeCreated: 1769082195
@@ -0,0 +1,644 @@
using System.Collections.Generic;
using UnityEditor;
using Codice.Client.BaseCommands.BranchExplorer;
using Codice.Client.Common;
using Codice.Client.Common.Threading;
using Codice.CM.Common;
using GluonGui;
using GluonGui.WorkspaceWindow.Views.WorkspaceExplorer.Explorer;
using PlasticGui;
using PlasticGui.Gluon;
using PlasticGui.Help;
using PlasticGui.WorkspaceWindow;
using PlasticGui.WorkspaceWindow.BranchExplorer;
using PlasticGui.WorkspaceWindow.MergeRequest;
using PlasticGui.WorkspaceWindow.QueryViews.Branches;
using PlasticGui.WorkspaceWindow.QueryViews.Changesets;
using Unity.PlasticSCM.Editor.AssetsOverlays.Cache;
using Unity.PlasticSCM.Editor.AssetUtils;
using Unity.PlasticSCM.Editor.Tool;
using Unity.PlasticSCM.Editor.Headless;
using Unity.PlasticSCM.Editor.UI;
using Unity.PlasticSCM.Editor.Views.Branches.Dialogs;
using Unity.PlasticSCM.Editor.Views.BranchExplorer.Virtualization;
using Unity.PlasticSCM.Editor.Views.Changesets.Dialogs;
using Unity.PlasticSCM.Editor.Views.Merge;
namespace Unity.PlasticSCM.Editor.Views.BranchExplorer.Menu
{
class BranchExplorerViewChangesetMenuOperations :
IChangesetMenuOperations,
IBranchExplorerChangesetMenuOperations,
ICheckoutChangesetMenuOperations,
ILaunchCodeReviewWindow
{
internal BranchExplorerViewChangesetMenuOperations(
WorkspaceInfo wkInfo,
RepositorySpec repSpec,
EditorWindow window,
IWorkspaceWindow workspaceView,
IViewSwitcher switcher,
IMergeViewLauncher mergeViewLauncher,
BranchExplorerView branchExplorerView,
IBrExNavigate brExNavigate,
BranchExplorerSelection selection,
BranchExplorerSelectedObjectResolver selectedObjectResolver,
IProgressControls progressControls,
GuiHelpEvents guiHelpEvents,
OpenedCodeReviewWindows openedCodeReviewWindows,
IAssetStatusCache assetStatusCache,
IPendingChangesUpdater pendingChangesUpdater,
IIncomingChangesUpdater incomingChangesUpdater,
IShelvedChangesUpdater shelvedChangesUpdater,
IWorkspaceModeNotificationUpdater workspaceModeNotificationUpdater,
LaunchTool.IProcessExecutor processExecutor,
LaunchTool.IShowDownloadPlasticExeWindow showDownloadPlasticExeWindow,
ViewHost viewHost,
SwitchAndShelve.IEnableSwitchAndShelveFeatureDialog enableSwitchAndShelveFeatureDialog,
IShelvePendingChangesQuestionerBuilder shelvePendingChangesQuestionerBuilder,
IUpdateProgress updateProgressNotifier,
IUpdateReport updateReport,
IWorkspaceStatusChangeListener workspaceStatusChangeListener)
{
mWkInfo = wkInfo;
mRepSpec = repSpec;
mWindow = window;
mBrExNavigate = brExNavigate;
mSelectionHandler = selection;
mSelectedObjectResolver = selectedObjectResolver;
mWorkspaceWindow = workspaceView;
mSwitcher = switcher;
mGuiHelpEvents = guiHelpEvents;
mOpenedCodeReviewWindows = openedCodeReviewWindows;
mAssetStatusCache = assetStatusCache;
mPendingChangesUpdater = pendingChangesUpdater;
mIncomingChangesUpdater = incomingChangesUpdater;
mShelvedChangesUpdater = shelvedChangesUpdater;
mProcessExecutor = processExecutor;
mShowDownloadPlasticExeWindow = showDownloadPlasticExeWindow;
mProgressControls = progressControls;
mViewHost = viewHost;
mEnableSwitchAndShelveFeatureDialog = enableSwitchAndShelveFeatureDialog;
mShelvePendingChangesQuestionerBuilder = shelvePendingChangesQuestionerBuilder;
mUpdateProgressNotifier = updateProgressNotifier;
mUpdateReport = updateReport;
mWorkspaceStatusChangeListener = workspaceStatusChangeListener;
mChangesetOperations = new ChangesetOperations(
wkInfo,
workspaceView,
switcher,
mergeViewLauncher,
progressControls,
new HeadlessUpdateReport(),
new ApplyShelveReport(window),
new ContinueWithPendingChangesQuestionerBuilder(switcher, window),
new ShelvePendingChangesQuestionerBuilder(window),
new ApplyShelveWithConflictsQuestionerBuilder(),
pendingChangesUpdater,
incomingChangesUpdater,
shelvedChangesUpdater,
workspaceModeNotificationUpdater,
openedCodeReviewWindows,
new EnableSwitchAndShelveFeature(repSpec, window));
}
public void UpdateRepositorySpec(RepositorySpec repSpec)
{
mRepSpec = repSpec;
}
public int GetSelectedChangesetsCount()
{
return mSelectedObjectResolver.GetSelectedObjectsCount();
}
public void DiffChangeset()
{
ChangesetInfo changeset = null;
IThreadWaiter waiter = ThreadWaiter.GetWaiter();
waiter.Execute(
threadOperationDelegate: delegate
{
changeset = ResolveSelectedChangeset();
},
afterOperationDelegate: delegate
{
if (!HasOperationSucceeded(waiter))
return;
LaunchDiffOperations.DiffChangeset(
mShowDownloadPlasticExeWindow,
mProcessExecutor,
mRepSpec,
changeset,
PlasticGui.Plastic.API.IsGluonWorkspace(mWkInfo));
});
}
public void DiffWithAnotherChangeset()
{
ChangesetInfo currentCset = null;
IThreadWaiter waiter = ThreadWaiter.GetWaiter();
waiter.Execute(
threadOperationDelegate: delegate
{
currentCset = ResolveSelectedChangeset();
},
afterOperationDelegate: /*async*/ delegate
{
if (!HasOperationSucceeded(waiter))
return;
/*
ChangesetInfo targetedCset = await ChangesetExplorerDialog.AskForChangesetAsync(
mWindow, mWkInfo, mRepSpec, mGuiHelpEvents);
if (targetedCset == null)
return;
DiffWindowParameters diffParams = DiffWindowParametersBuilder.Build(
mWkInfo,
mRepSpec,
mWindow.WorkspacePanel.WorkspaceView,
mWindow.WorkspacePanel.WorkspaceView.PendingChangesUpdater,
mWindow.WorkspacePanel.WorkspaceView.IncomingChangesUpdater,
mWindow.WorkspacePanel.WorkspaceView.ShelvedChangesUpdater,
mWindow.WorkspacePanel.WorkspaceView,
currentCset,
targetedCset);
DiffWindow.Diff(
diffParams, mWindow.WorkspacePanel.WorkspaceView);
*/
});
}
public void DiffSelectedChangesets()
{
IList<ChangesetInfo> changesets = null;
IThreadWaiter waiter = ThreadWaiter.GetWaiter();
waiter.Execute(
threadOperationDelegate: delegate
{
changesets = ResolveSelectedChangesets();
},
afterOperationDelegate: delegate
{
if (!HasOperationSucceeded(waiter))
return;
if (changesets.Count < 2)
return;
LaunchDiffOperations.DiffSelectedChangesets(
mShowDownloadPlasticExeWindow,
mProcessExecutor,
mRepSpec,
(ChangesetExtendedInfo)changesets[0],
(ChangesetExtendedInfo)changesets[1],
PlasticGui.Plastic.API.IsGluonWorkspace(mWkInfo));
});
}
public void BrowseRepositoryOnChangeset()
{
ChangesetInfo changeset = null;
IThreadWaiter waiter = ThreadWaiter.GetWaiter();
waiter.Execute(
threadOperationDelegate: delegate
{
changeset = ResolveSelectedChangeset();
},
afterOperationDelegate: delegate
{
if (!HasOperationSucceeded(waiter))
return;
/*
DynamicViewHandler.ShowBrowseRepositoryView(
mWkInfo,
mWindow,
mPendingChangesUpdater,
mIncomingChangesUpdater,
mShelvedChangesUpdater,
mRepSpec,
mOverlappedView,
changeset.ChangesetId,
SettingSerializationName.CHANGESETS_VIEW_NAME,
mNotifyStatusBar);
*/
});
}
public void CreateCodeReview()
{
ChangesetInfo changeset = null;
IThreadWaiter waiter = ThreadWaiter.GetWaiter();
waiter.Execute(
threadOperationDelegate: delegate
{
changeset = ResolveSelectedChangeset();
},
afterOperationDelegate: delegate
{
if (!HasOperationSucceeded(waiter))
return;
NewCodeReviewBehavior choice = SelectNewCodeReviewBehavior.For(mRepSpec.Server);
switch (choice)
{
case NewCodeReviewBehavior.CreateAndOpenInDesktop:
mChangesetOperations.CreateCodeReview(mRepSpec, changeset, this);
break;
case NewCodeReviewBehavior.RequestFromUnityCloud:
OpenRequestReviewPage.ForChangeset(mRepSpec, changeset.ChangesetId);
break;
case NewCodeReviewBehavior.Ask:
default:
break;
}
});
}
public void CreateBranch()
{
ChangesetInfo changeset = null;
IThreadWaiter waiter = ThreadWaiter.GetWaiter();
waiter.Execute(
threadOperationDelegate: delegate
{
changeset = ResolveSelectedChangeset();
},
afterOperationDelegate: delegate
{
if (!HasOperationSucceeded(waiter))
return;
EditorApplication.delayCall += () =>
{
BranchCreationData branchCreationData = CreateBranchDialog.CreateBranchFromChangeset(
mWindow,
mRepSpec,
changeset,
null);
mChangesetOperations.CreateBranch(
branchCreationData,
RefreshAsset.BeforeLongAssetOperation,
items => RefreshAsset.AfterLongAssetOperation(
mAssetStatusCache,
ProjectPackages.ShouldBeResolvedFromUpdateReport(mWkInfo, items)));
};
});
}
public void LabelChangeset()
{
ChangesetInfo changeset = null;
IThreadWaiter waiter = ThreadWaiter.GetWaiter();
waiter.Execute(
threadOperationDelegate: delegate
{
changeset = ResolveSelectedChangeset();
},
afterOperationDelegate: /*async*/ delegate
{
if (!HasOperationSucceeded(waiter))
return;
EditorApplication.delayCall += () =>
{
ChangesetLabelData changesetLabelData = LabelChangesetDialog.Label(
mWindow,
mRepSpec,
changeset);
mChangesetOperations.LabelChangeset(changesetLabelData);
};
});
}
public void SwitchToChangeset()
{
ChangesetInfo changeset = null;
IThreadWaiter waiter = ThreadWaiter.GetWaiter();
waiter.Execute(
threadOperationDelegate: delegate
{
changeset = ResolveSelectedChangeset();
},
afterOperationDelegate: delegate
{
if (!HasOperationSucceeded(waiter))
return;
mChangesetOperations.SwitchToChangeset(
mRepSpec,
changeset,
RefreshAsset.BeforeLongAssetOperation,
items => RefreshAsset.AfterLongAssetOperation(
mAssetStatusCache,
ProjectPackages.ShouldBeResolvedFromUpdateReport(mWkInfo, items)));
});
}
public void MergeChangeset()
{
ChangesetInfo changeset = null;
IThreadWaiter waiter = ThreadWaiter.GetWaiter();
waiter.Execute(
threadOperationDelegate: delegate
{
changeset = ResolveSelectedChangeset();
},
afterOperationDelegate: delegate
{
if (!HasOperationSucceeded(waiter))
return;
mChangesetOperations.MergeChangeset(mRepSpec, changeset);
});
}
public void CherryPickChangeset()
{
ChangesetInfo changeset = null;
IThreadWaiter waiter = ThreadWaiter.GetWaiter();
waiter.Execute(
threadOperationDelegate: delegate
{
changeset = ResolveSelectedChangeset();
},
afterOperationDelegate: delegate
{
if (!HasOperationSucceeded(waiter))
return;
mChangesetOperations.CherryPickChangeset(mRepSpec, changeset);
});
}
public void SubtractiveChangeset()
{
ChangesetInfo changeset = null;
IThreadWaiter waiter = ThreadWaiter.GetWaiter();
waiter.Execute(
threadOperationDelegate: delegate
{
changeset = ResolveSelectedChangeset();
},
afterOperationDelegate: delegate
{
if (!HasOperationSucceeded(waiter))
return;
mChangesetOperations.SubtractiveChangeset(mRepSpec, changeset);
});
}
public void SubtractiveChangesetInterval()
{
IList<ChangesetInfo> changesets = null;
IThreadWaiter waiter = ThreadWaiter.GetWaiter();
waiter.Execute(
threadOperationDelegate: delegate
{
changesets = ResolveSelectedChangesets();
},
afterOperationDelegate: delegate
{
if (!HasOperationSucceeded(waiter))
return;
mChangesetOperations.SubtractiveChangesetInterval(
mRepSpec, changesets[0], changesets[1]);
});
}
public void CherryPickChangesetInterval()
{
IList<ChangesetInfo> changesets = null;
IThreadWaiter waiter = ThreadWaiter.GetWaiter();
waiter.Execute(
threadOperationDelegate: delegate
{
changesets = ResolveSelectedChangesets();
},
afterOperationDelegate: delegate
{
if (!HasOperationSucceeded(waiter))
return;
mChangesetOperations.CherryPickChangesetInterval(
mRepSpec, changesets[0], changesets[1]);
});
}
public void MergeToChangeset()
{
ChangesetInfo changeset = null;
IThreadWaiter waiter = ThreadWaiter.GetWaiter();
waiter.Execute(
threadOperationDelegate: delegate
{
changeset = ResolveSelectedChangeset();
},
afterOperationDelegate: /*async*/ delegate
{
if (!HasOperationSucceeded(waiter))
return;
/*
mChangesetOperations.MergeToChangeset(
mRepSpec,
changeset,
await MergeToDestinationBranch.GetAsync(mRepSpec, mWindow, mGuiHelpEvents));
*/
});
}
public void MoveChangeset()
{
ChangesetInfo changeset = null;
IThreadWaiter waiter = ThreadWaiter.GetWaiter();
waiter.Execute(
threadOperationDelegate: delegate
{
changeset = ResolveSelectedChangeset();
},
afterOperationDelegate: /*async*/ delegate
{
if (!HasOperationSucceeded(waiter))
return;
/*
MoveChangesetsToBranchResult selectionResult = await
MoveChangesetsToBranchDialog.MoveChangesetsToBranchAsync(
mWindow, mWkInfo, mRepSpec, changeset, mGuiHelpEvents);
if (!selectionResult.Result)
return;
mChangesetOperations.MoveChangeset(
mRepSpec,
changeset,
selectionResult.TargetBranch,
null,
null);
*/
});
}
public void DeleteChangeset()
{
ChangesetInfo changeset = null;
IThreadWaiter waiter = ThreadWaiter.GetWaiter();
waiter.Execute(
threadOperationDelegate: delegate
{
changeset = ResolveSelectedChangeset();
},
afterOperationDelegate: delegate
{
if (!HasOperationSucceeded(waiter))
return;
mChangesetOperations.DeleteChangeset(
mRepSpec,
changeset,
null,
null);
});
}
void IChangesetMenuOperations.RevertToChangeset()
{
ChangesetInfo changeset = null;
IThreadWaiter waiter = ThreadWaiter.GetWaiter();
waiter.Execute(
threadOperationDelegate: delegate
{
changeset = ResolveSelectedChangeset();
},
afterOperationDelegate: /*async*/ delegate
{
RevertToChangesetOperation.RevertTo(
mWkInfo,
mSwitcher,
mWorkspaceWindow,
mProgressControls,
mGetStatusForWorkspace,
mUndoCheckoutOperation,
mRevertToChangesetMergeController,
GuiMessage.Get(),
changeset,
mPendingChangesUpdater,
RefreshAsset.BeforeLongAssetOperation,
() => RefreshAsset.AfterLongAssetOperation(mAssetStatusCache),
() => { });
});
}
void ILaunchCodeReviewWindow.Show(
WorkspaceInfo wkInfo,
RepositorySpec repSpec,
ReviewInfo reviewInfo,
RepObjectInfo repObjectInfo,
bool bShowReviewChangesTab)
{
LaunchTool.OpenCodeReview(
mShowDownloadPlasticExeWindow,
mProcessExecutor,
repSpec,
reviewInfo.Id,
PlasticGui.Plastic.API.IsGluonWorkspace(mWkInfo));
}
public void NavigateToParent()
{
ChangesetDrawInfo parentChangeset =
ResolveSelectedChangesetParent();
if (parentChangeset == null)
return;
mBrExNavigate.NavigateToShape(
(VirtualShape)parentChangeset.Visual);
}
public void ShowPendingChangesView()
{
ShowWindow.UVCS();
mSwitcher.ShowPendingChanges();
}
IList<ChangesetInfo> ResolveSelectedChangesets()
{
return mSelectedObjectResolver.GetSelectedChangesets();
}
ChangesetInfo ResolveSelectedChangeset()
{
return ResolveSelectedChangesets()[0];
}
ChangesetDrawInfo ResolveSelectedChangesetParent()
{
if (mSelectionHandler.GetSelectedChangesetsCount() != 1)
return null;
ChangesetDrawInfo selectedChangeset =
mSelectionHandler.GetSelectedChangesets()[0];
return selectedChangeset.Parent;
}
bool HasOperationSucceeded(IThreadWaiter waiter)
{
if (waiter.Exception == null)
return true;
ExceptionsHandler.DisplayException(waiter.Exception);
return false;
}
readonly RevertToChangesetOperation.IGetStatusForWorkspace mGetStatusForWorkspace =
new RevertToChangesetOperation.GetStatusFromWorkspace();
readonly RevertToChangesetOperation.IUndoCheckoutOperation mUndoCheckoutOperation =
new RevertToChangesetOperation.UndoCheckout();
readonly RevertToChangesetOperation.IRevertToChangesetMergeController mRevertToChangesetMergeController =
new RevertToChangesetOperation.RevertToChangesetMergeController();
readonly ViewHost mViewHost;
readonly IProgressControls mProgressControls;
readonly SwitchAndShelve.IEnableSwitchAndShelveFeatureDialog mEnableSwitchAndShelveFeatureDialog;
readonly IShelvePendingChangesQuestionerBuilder mShelvePendingChangesQuestionerBuilder;
readonly IUpdateProgress mUpdateProgressNotifier;
readonly IUpdateReport mUpdateReport;
readonly IWorkspaceStatusChangeListener mWorkspaceStatusChangeListener;
readonly LaunchTool.IProcessExecutor mProcessExecutor;
readonly LaunchTool.IShowDownloadPlasticExeWindow mShowDownloadPlasticExeWindow;
readonly ChangesetOperations mChangesetOperations;
readonly IBrExNavigate mBrExNavigate;
readonly BranchExplorerSelection mSelectionHandler;
readonly BranchExplorerSelectedObjectResolver mSelectedObjectResolver;
readonly EditorWindow mWindow;
RepositorySpec mRepSpec;
readonly WorkspaceInfo mWkInfo;
readonly IWorkspaceWindow mWorkspaceWindow;
readonly IViewSwitcher mSwitcher;
readonly GuiHelpEvents mGuiHelpEvents;
readonly OpenedCodeReviewWindows mOpenedCodeReviewWindows;
readonly IAssetStatusCache mAssetStatusCache;
readonly IPendingChangesUpdater mPendingChangesUpdater;
readonly IIncomingChangesUpdater mIncomingChangesUpdater;
readonly IShelvedChangesUpdater mShelvedChangesUpdater;
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: c9b4bc0669b544cb9b754dc80d82e74c
timeCreated: 1769097332
@@ -0,0 +1,412 @@
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using Codice.Client.BaseCommands.BranchExplorer;
using Codice.Client.Common.Threading;
using Codice.CM.Common;
using PlasticGui;
using PlasticGui.Help;
using PlasticGui.WorkspaceWindow;
using PlasticGui.WorkspaceWindow.BranchExplorer;
using PlasticGui.WorkspaceWindow.QueryViews.Branches;
using PlasticGui.WorkspaceWindow.QueryViews.Labels;
using Unity.PlasticSCM.Editor.AssetsOverlays.Cache;
using Unity.PlasticSCM.Editor.AssetUtils;
using Unity.PlasticSCM.Editor.Tool;
using Unity.PlasticSCM.Editor.Headless;
using Unity.PlasticSCM.Editor.Views.Branches.Dialogs;
using Unity.PlasticSCM.Editor.Views.Labels.Dialogs;
using Unity.PlasticSCM.Editor.Views.Merge;
namespace Unity.PlasticSCM.Editor.Views.BranchExplorer.Menu
{
class BranchExplorerViewLabelMenuOperations : ILabelMenuOperations
{
internal interface ISelectionResolver
{
MarkerExtendedInfo ResolveSelectedLabel();
MarkerExtendedInfo ResolveLabel(long labelId, LabelDrawInfo labelInfo);
}
internal BranchExplorerViewLabelMenuOperations(
WorkspaceInfo wkInfo,
RepositorySpec repSpec,
EditorWindow window,
IWorkspaceWindow workspaceWindow,
IViewSwitcher switcher,
IMergeViewLauncher mergeViewLauncher,
BranchExplorerView branchExplorerView,
BranchExplorerSelection selectionHandler,
ISelectionResolver selectedLabelResolver,
IProgressControls progressControls,
GuiHelpEvents guiHelpEvents,
IAssetStatusCache assetStatusCache,
IPendingChangesUpdater pendingChangesUpdater,
IIncomingChangesUpdater incomingChangesUpdater,
IShelvedChangesUpdater shelvedChangesUpdater,
LaunchTool.IProcessExecutor processExecutor,
LaunchTool.IShowDownloadPlasticExeWindow showDownloadPlasticExeWindow)
{
mWkInfo = wkInfo;
mRepSpec = repSpec;
mWindow = window;
mSelectionHandler = selectionHandler;
mSelectedLabelResolver = selectedLabelResolver;
mGuiHelpEvents = guiHelpEvents;
mAssetStatusCache = assetStatusCache;
mPendingChangesUpdater = pendingChangesUpdater;
mIncomingChangesUpdater = incomingChangesUpdater;
mShelvedChangesUpdater = shelvedChangesUpdater;
mProcessExecutor = processExecutor;
mShowDownloadPlasticExeWindow = showDownloadPlasticExeWindow;
mLabelOperations = new LabelOperations(
wkInfo,
workspaceWindow,
mergeViewLauncher,
branchExplorerView,
ViewType.BranchExplorerView,
progressControls,
new HeadlessUpdateReport(),
new ApplyShelveReport(window),
new ContinueWithPendingChangesQuestionerBuilder(switcher, window),
new ShelvePendingChangesQuestionerBuilder(window),
new ApplyShelveWithConflictsQuestionerBuilder(),
pendingChangesUpdater,
incomingChangesUpdater,
shelvedChangesUpdater,
new EnableSwitchAndShelveFeature(repSpec, window));
}
public int GetSelectedLabelsCount()
{
if (!mSelectionHandler.HasSelectedLabels())
return 0;
return mSelectionHandler.GetSelectedLabels().Count;
}
public void CreateLabel()
{
LabelCreationData labelCreationData = CreateLabelDialog.CreateLabel(
mWindow, mWkInfo);
mLabelOperations.CreateLabel(
labelCreationData,
null,
null);
}
public void ApplyLabelToWorkspace()
{
MarkerInfo label = null;
IThreadWaiter waiter = ThreadWaiter.GetWaiter();
waiter.Execute(
threadOperationDelegate: delegate
{
label = ResolveSelectedLabel();
},
afterOperationDelegate: delegate
{
if (!HasOperationSucceeded(waiter))
return;
mLabelOperations.ApplyLabelToWorkspace(mRepSpec, label);
});
}
public void SwitchToLabel()
{
MarkerInfo label = null;
IThreadWaiter waiter = ThreadWaiter.GetWaiter();
waiter.Execute(
threadOperationDelegate: delegate
{
label = ResolveSelectedLabel();
},
afterOperationDelegate: delegate
{
if (!HasOperationSucceeded(waiter))
return;
mLabelOperations.SwitchToLabel(
mRepSpec,
label,
RefreshAsset.BeforeLongAssetOperation,
items => RefreshAsset.AfterLongAssetOperation(
mAssetStatusCache,
ProjectPackages.ShouldBeResolvedFromUpdateReport(mWkInfo, items)));
});
}
public void BrowseRepositoryOnLabel()
{
MarkerInfo label = null;
IThreadWaiter waiter = ThreadWaiter.GetWaiter();
waiter.Execute(
threadOperationDelegate: delegate
{
label = ResolveSelectedLabel();
},
afterOperationDelegate: delegate
{
if (!HasOperationSucceeded(waiter))
return;
/*
DynamicViewHandler.ShowBrowseRepositoryView(
mWkInfo,
mWindow,
mPendingChangesUpdater,
mIncomingChangesUpdater,
mShelvedChangesUpdater,
mRepSpec,
mOverlappedView,
label.Changeset,
SettingSerializationName.BRANCH_EXPLORER_VIEW_NAME,
mNotifyStatusBar);
*/
});
}
public void DiffWithAnotherLabel()
{
MarkerInfo currentLabel = null;
IThreadWaiter waiter = ThreadWaiter.GetWaiter();
waiter.Execute(
threadOperationDelegate: delegate
{
currentLabel = ResolveSelectedLabel();
},
afterOperationDelegate: /*async*/ delegate
{
if (!HasOperationSucceeded(waiter))
return;
/*
MarkerInfo targetedLabel = await LabelExplorerDialog.AskForLabelAsync(
mWindow, mWkInfo, mRepSpec, mGuiHelpEvents);
DiffLabels(currentLabel, targetedLabel);
*/
});
}
public void DiffSelectedLabels()
{
IList<MarkerExtendedInfo> labels = null;
IThreadWaiter waiter = ThreadWaiter.GetWaiter();
waiter.Execute(
threadOperationDelegate: delegate
{
labels = ResolveSelectedLabels();
},
afterOperationDelegate: delegate
{
if (!HasOperationSucceeded(waiter))
return;
DiffLabels(labels[0], labels[1]);
});
}
public void MergeLabel()
{
MarkerInfo label = null;
IThreadWaiter waiter = ThreadWaiter.GetWaiter();
waiter.Execute(
threadOperationDelegate: delegate
{
label = ResolveSelectedLabel();
},
afterOperationDelegate: delegate
{
if (!HasOperationSucceeded(waiter))
return;
mLabelOperations.MergeLabel(mRepSpec, label);
});
}
public void MergeToLabel()
{
MarkerInfo label = null;
IThreadWaiter waiter = ThreadWaiter.GetWaiter();
waiter.Execute(
threadOperationDelegate: delegate
{
label = ResolveSelectedLabel();
},
afterOperationDelegate: delegate
{
if (!HasOperationSucceeded(waiter))
return;
/*
mLabelOperations.MergeToLabel(
mRepSpec,
label,
MergeToDestinationBranch.GetAsync(mRepSpec, mWindow, mGuiHelpEvents));
*/
});
}
public void CreateBranchFromLabel()
{
MarkerExtendedInfo label = null;
IThreadWaiter waiter = ThreadWaiter.GetWaiter();
waiter.Execute(
threadOperationDelegate: delegate
{
label = ResolveSelectedLabel();
},
afterOperationDelegate: delegate
{
if (!HasOperationSucceeded(waiter))
return;
BranchCreationData branchCreationData = CreateBranchDialog.CreateBranchFromLabel(
mWindow,
mRepSpec,
label);
mLabelOperations.CreateBranchFromLabel(
branchCreationData,
RefreshAsset.BeforeLongAssetOperation,
items => RefreshAsset.AfterLongAssetOperation(
mAssetStatusCache,
ProjectPackages.ShouldBeResolvedFromPaths(mWkInfo, items)));
});
}
public void RenameLabel()
{
MarkerInfo label = null;
IThreadWaiter waiter = ThreadWaiter.GetWaiter();
waiter.Execute(
threadOperationDelegate: delegate
{
label = ResolveSelectedLabel();
},
afterOperationDelegate: delegate
{
if (!HasOperationSucceeded(waiter))
return;
LabelRenameData renameLabelData = RenameLabelDialog.GetLabelRenameData(
mRepSpec, label, mWindow);
mLabelOperations.RenameLabel(renameLabelData);
});
}
public void DeleteLabel()
{
MarkerExtendedInfo label = null;
IThreadWaiter waiter = ThreadWaiter.GetWaiter();
waiter.Execute(
threadOperationDelegate: delegate
{
label = ResolveSelectedLabel();
},
afterOperationDelegate: delegate
{
if (!HasOperationSucceeded(waiter))
return;
mLabelOperations.DeleteLabel(
new List<RepositorySpec>() { mRepSpec },
new List<MarkerExtendedInfo>() { label });
});
}
public void ViewPermissions()
{
MarkerInfo label = null;
IThreadWaiter waiter = ThreadWaiter.GetWaiter();
waiter.Execute(
threadOperationDelegate: delegate
{
label = ResolveSelectedLabel();
},
afterOperationDelegate: delegate
{
if (!HasOperationSucceeded(waiter))
return;
/*
PermissionsDialog.ShowPermissions(
mRepSpec,
label,
mRepSpec.Server,
mGuiHelpEvents,
mWindow,
new PlasticGuiMessage(mWindow));
*/
});
}
MarkerExtendedInfo ResolveSelectedLabel()
{
return mSelectedLabelResolver.ResolveSelectedLabel();
}
IList<MarkerExtendedInfo> ResolveSelectedLabels()
{
MarkerExtendedInfo selectedLabel = mSelectedLabelResolver.ResolveSelectedLabel();
List<LabelDrawInfo> labels = mSelectionHandler.GetSelectedLabels();
List<MarkerExtendedInfo> selectedLabels = labels.
Where(li => !li.Labels.Any(x => x.Id == selectedLabel.Id)).
Select(l => mSelectedLabelResolver.ResolveLabel(l.Labels[0].Id, l)).ToList();
selectedLabels.Insert(0, selectedLabel);
return selectedLabels;
}
bool HasOperationSucceeded(IThreadWaiter waiter)
{
if (waiter.Exception == null)
return true;
ExceptionsHandler.DisplayException(waiter.Exception);
return false;
}
void DiffLabels(
MarkerInfo currentLabel,
MarkerInfo targetedLabel)
{
if (targetedLabel == null)
return;
LaunchDiffOperations.DiffSelectedLabels(
mShowDownloadPlasticExeWindow,
mProcessExecutor,
mRepSpec,
currentLabel,
targetedLabel,
PlasticGui.Plastic.API.IsGluonWorkspace(mWkInfo));
}
readonly LaunchTool.IProcessExecutor mProcessExecutor;
readonly LaunchTool.IShowDownloadPlasticExeWindow mShowDownloadPlasticExeWindow;
readonly LabelOperations mLabelOperations;
readonly ISelectionResolver mSelectedLabelResolver;
readonly BranchExplorerSelection mSelectionHandler;
readonly IAssetStatusCache mAssetStatusCache;
readonly IPendingChangesUpdater mPendingChangesUpdater;
readonly IIncomingChangesUpdater mIncomingChangesUpdater;
readonly IShelvedChangesUpdater mShelvedChangesUpdater;
readonly EditorWindow mWindow;
readonly RepositorySpec mRepSpec;
readonly WorkspaceInfo mWkInfo;
readonly GuiHelpEvents mGuiHelpEvents;
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 11b2026af4f74d51a4ac170e12c3b888
timeCreated: 1769161153
@@ -0,0 +1,49 @@
using Codice.Client.BaseCommands.BranchExplorer;
using PlasticGui.WorkspaceWindow.BranchExplorer;
using Unity.PlasticSCM.Editor.Views.BranchExplorer.Virtualization;
namespace Unity.PlasticSCM.Editor.Views.BranchExplorer.Menu
{
class BranchExplorerViewLinkMenuOperations : ILinkMenuOperations
{
internal BranchExplorerViewLinkMenuOperations(
IBrExNavigate brExNavigate,
BranchExplorerSelection selection)
{
mBrExNavigate = brExNavigate;
mSelectionHandler = selection;
}
void ILinkMenuOperations.GoToSourcechangeset()
{
NavigateToChangeset(GetSelectedLink().SourceChangeset);
}
void ILinkMenuOperations.GoToDestinationChangeset()
{
NavigateToChangeset(GetSelectedLink().DestinationChangeset);
}
int ILinkMenuOperations.GetSelectedLinksCount()
{
return mSelectionHandler.GetSelectedLinksCount();
}
LinkDrawInfo GetSelectedLink()
{
return mSelectionHandler.GetSelectedLinks()[0];
}
void NavigateToChangeset(ChangesetDrawInfo changeset)
{
VirtualShape commitShape = (VirtualShape)changeset.Visual;
commitShape.IsLinkNavigationTarget = true;
mBrExNavigate.NavigateToShape(commitShape);
}
readonly IBrExNavigate mBrExNavigate;
readonly BranchExplorerSelection mSelectionHandler;
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: dc1bc6a318004247a55e4f3fbf74309a
timeCreated: 1769166026
@@ -0,0 +1,345 @@
using UnityEditor;
using UnityEngine;
using Codice.Client.Common.WebApi;
using Codice.CM.Common;
using GluonGui;
using PlasticGui;
using PlasticGui.Help;
using PlasticGui.WorkspaceWindow;
using PlasticGui.WorkspaceWindow.BranchExplorer;
using PlasticGui.WorkspaceWindow.MergeRequest;
using PlasticGui.WorkspaceWindow.QueryViews;
using PlasticGui.WorkspaceWindow.Topbar;
using Unity.PlasticSCM.Editor.AssetsOverlays.Cache;
using Unity.PlasticSCM.Editor.Tool;
using Unity.PlasticSCM.Editor.Headless;
using Unity.PlasticSCM.Editor.Toolbar;
using Unity.PlasticSCM.Editor.Views.Branches;
using Unity.PlasticSCM.Editor.Views.Changesets;
namespace Unity.PlasticSCM.Editor.Views.BranchExplorer.Menu
{
internal class BranchExplorerViewMenu : ChangesetsViewMenu.IMenuOperations, IGetWorkingObject
{
internal BranchExplorerViewMenu(
IPlasticWebRestApi restApi,
WorkspaceInfo wkInfo,
RepositorySpec repSpec,
EditorWindow window,
IWorkspaceWindow workspaceWindow,
IViewSwitcher switcher,
IMergeViewLauncher mergeViewLauncher,
BranchExplorerView branchExplorerView,
IBrExNavigate brExNavigate,
BranchExplorerSelection selection,
BranchExplorerSelectedObjectResolver selectedObjectResolver,
IProgressControls progressControls,
GuiHelpEvents guiHelpEvents,
OpenedCodeReviewWindows openedCodeReviewWindows,
IAssetStatusCache assetStatusCache,
IPendingChangesUpdater pendingChangesUpdater,
IIncomingChangesUpdater incomingChangesUpdater,
IShelvedChangesUpdater shelvedChangesUpdater,
IWorkspaceModeNotificationUpdater workspaceModeNotificationUpdater,
LaunchTool.IProcessExecutor processExecutor,
LaunchTool.IShowDownloadPlasticExeWindow showDownloadPlasticExeWindow)
{
mWkInfo = wkInfo;
mRepSpec = repSpec;
mWindow = window;
mWorkspaceWindow = workspaceWindow;
mSwitcher = switcher;
mMergeViewLauncher = mergeViewLauncher;
mBranchExplorerView = branchExplorerView;
mSelectionHandler = selection;
mSelectedObjectResolver = selectedObjectResolver;
mProgressControls = progressControls;
mGuiHelpEvents = guiHelpEvents;
mAssetStatusCache = assetStatusCache;
mPendingChangesUpdater = pendingChangesUpdater;
mIncomingChangesUpdater = incomingChangesUpdater;
mShelvedChangesUpdater = shelvedChangesUpdater;
mProcessExecutor = processExecutor;
mShowDownloadPlasticExeWindow = showDownloadPlasticExeWindow;
mBranchOperations = new BranchExplorerViewBranchMenuOperations(
restApi,
wkInfo,
repSpec,
window,
workspaceWindow,
switcher,
mergeViewLauncher,
branchExplorerView,
brExNavigate,
mSelectionHandler,
selectedObjectResolver,
progressControls,
guiHelpEvents,
openedCodeReviewWindows,
assetStatusCache,
pendingChangesUpdater,
incomingChangesUpdater,
shelvedChangesUpdater,
workspaceModeNotificationUpdater,
processExecutor,
showDownloadPlasticExeWindow);
mChangesetOperations = new BranchExplorerViewChangesetMenuOperations(
wkInfo,
repSpec,
window,
workspaceWindow,
switcher,
mergeViewLauncher,
branchExplorerView,
brExNavigate,
mSelectionHandler,
selectedObjectResolver,
progressControls,
guiHelpEvents,
openedCodeReviewWindows,
assetStatusCache,
pendingChangesUpdater,
incomingChangesUpdater,
shelvedChangesUpdater,
workspaceModeNotificationUpdater,
processExecutor,
showDownloadPlasticExeWindow,
new ViewHost(),
new EnableSwitchAndShelveFeature(repSpec, window),
new ShelvePendingChangesQuestionerBuilder(window),
new HeadlessGluonUpdateProgress(),
new HeadlessGluonUpdateReport(),
new HeadlessWorkspaceStatusChangeListener(RefreshWorkspaceWorkingInfo));
mLinkOperations = new BranchExplorerViewLinkMenuOperations(brExNavigate, selection);
}
internal void UpdateRepositorySpec(RepositorySpec repSpec)
{
mRepSpec = repSpec;
mBranchOperations.UpdateRepositorySpec(repSpec);
mChangesetOperations.UpdateRepositorySpec(repSpec);
//mExternalToolsOperations.UpdateRepositorySpec(repSpec);
if (mLabelsMenu != null)
mLabelsMenu.UpdateRepositorySpec(repSpec);
}
void RefreshWorkspaceWorkingInfo()
{
if (mWkInfo == null)
return;
UpdateWorkspaceInfoBar.UpdateWorkspaceInfo(
mWkInfo,
null,
UVCSToolbar.Controller);
}
internal void Popup()
{
if (mSelectionHandler.HasSelectedBranches())
{
GetBranchesViewMenu().Popup();
return;
}
if (mSelectionHandler.IsCheckoutChangesetSelected())
{
GetCheckoutChangesetViewMenu().Popup();
return;
}
if (mSelectionHandler.HasSelectedChangesets())
{
GetChangesetsViewMenu().Popup();
return;
}
if (mSelectionHandler.HasSelectedLabels())
{
GetLabelsViewMenu().Popup();
return;
}
if (mSelectionHandler.HasSelectedLinks())
{
GetLinkMenu().Popup();
return;
}
}
internal bool ProcessKeyActionIfNeeded(Event e)
{
if (mSelectionHandler.HasSelectedBranches())
{
return GetBranchesViewMenu().ProcessKeyActionIfNeeded(e);
}
if (mSelectionHandler.IsCheckoutChangesetSelected())
{
// the checkout changeset menu hasn't shortcuts
return false;
}
if (mSelectionHandler.HasSelectedChangesets())
{
return GetChangesetsViewMenu().ProcessKeyActionIfNeeded(e);
}
if (mSelectionHandler.HasSelectedLabels())
{
return GetLabelsViewMenu().ProcessKeyActionIfNeeded(e);
}
if (mSelectionHandler.HasSelectedLinks())
{
// the merge link menu hasn't shortcuts
return false;
}
return false;
}
internal void ExecuteDefaultAction()
{
if (mSelectionHandler.HasSelectedBranches())
{
mBranchOperations.DiffBranch();
return;
}
if (mSelectionHandler.HasSelectedChangesets())
{
mChangesetOperations.DiffChangeset();
return;
}
if (mSelectionHandler.HasSelectedLabels())
{
GetLabelsViewMenu().BrowseRepositoryOnLabel();
return;
}
}
void ChangesetsViewMenu.IMenuOperations.DiffBranch()
{
}
ChangesetInfo ChangesetsViewMenu.IMenuOperations.GetSelectedChangeset()
{
RepObjectInfo selectedObject = mSelectedObjectResolver.GetFirstSelectedObject();
if (selectedObject is not ChangesetInfo)
return null;
return (ChangesetInfo)selectedObject;
}
object IGetWorkingObject.Get()
{
return mSelectedObjectResolver.GetFirstSelectedObject();
}
BranchesViewMenu GetBranchesViewMenu()
{
if (mBranchesViewMenu == null)
{
mBranchesViewMenu = new BranchesViewMenu(
mBranchOperations,
PlasticGui.Plastic.API.IsGluonWorkspace(mWkInfo));
}
return mBranchesViewMenu;
}
CheckoutChangesetViewMenu GetCheckoutChangesetViewMenu()
{
if (mCheckoutChangesetViewMenu == null)
mCheckoutChangesetViewMenu = new CheckoutChangesetViewMenu(mChangesetOperations);
return mCheckoutChangesetViewMenu;
}
ChangesetsViewMenu GetChangesetsViewMenu()
{
if (mChangesetsViewMenu == null)
{
mChangesetsViewMenu = new ChangesetsViewMenu(
mChangesetOperations,
this,
this,
PlasticGui.Plastic.API.IsGluonWorkspace(mWkInfo));
}
return mChangesetsViewMenu;
}
BranchExplorerLabelMenu GetLabelsViewMenu()
{
if (mLabelsMenu == null)
{
mLabelsMenu = new BranchExplorerLabelMenu(
mWkInfo,
mRepSpec,
mWindow,
mWorkspaceWindow,
mSwitcher,
mMergeViewLauncher,
mBranchExplorerView,
mSelectionHandler,
mProgressControls,
mGuiHelpEvents,
mAssetStatusCache,
mPendingChangesUpdater,
mIncomingChangesUpdater,
mShelvedChangesUpdater,
mProcessExecutor,
mShowDownloadPlasticExeWindow);
}
return mLabelsMenu;
}
LinkMenu GetLinkMenu()
{
if (mLinkMenu == null)
mLinkMenu = new LinkMenu(mLinkOperations);
return mLinkMenu;
}
BranchesViewMenu mBranchesViewMenu;
CheckoutChangesetViewMenu mCheckoutChangesetViewMenu;
ChangesetsViewMenu mChangesetsViewMenu;
BranchExplorerLabelMenu mLabelsMenu;
LinkMenu mLinkMenu;
RepositorySpec mRepSpec;
readonly LaunchTool.IProcessExecutor mProcessExecutor;
readonly LaunchTool.IShowDownloadPlasticExeWindow mShowDownloadPlasticExeWindow;
readonly WorkspaceInfo mWkInfo;
readonly EditorWindow mWindow;
readonly IWorkspaceWindow mWorkspaceWindow;
readonly IViewSwitcher mSwitcher;
readonly IMergeViewLauncher mMergeViewLauncher;
readonly BranchExplorerView mBranchExplorerView;
readonly BranchExplorerSelection mSelectionHandler;
readonly BranchExplorerSelectedObjectResolver mSelectedObjectResolver;
readonly IProgressControls mProgressControls;
readonly GuiHelpEvents mGuiHelpEvents;
readonly IAssetStatusCache mAssetStatusCache;
readonly IPendingChangesUpdater mPendingChangesUpdater;
readonly IIncomingChangesUpdater mIncomingChangesUpdater;
readonly IShelvedChangesUpdater mShelvedChangesUpdater;
readonly BranchExplorerViewBranchMenuOperations mBranchOperations;
readonly BranchExplorerViewChangesetMenuOperations mChangesetOperations;
readonly BranchExplorerViewLinkMenuOperations mLinkOperations;
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 8f5b967c51ec477bb1f1b6aad7b6839f
timeCreated: 1769006631

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