Compare commits

...

4 commits

Author SHA1 Message Date
leo
0d565f84c3
Merge pull request #504 from Gama11/feature/statistics-mailmap
Some checks are pending
Continuous Integration / Build (push) Waiting to run
Continuous Integration / Prepare version string (push) Waiting to run
Continuous Integration / Package (push) Blocked by required conditions
Respect .mailmap files in statistics
2024-09-23 22:54:52 +08:00
Jens Fischer
49d5b679fc Respect .mailmap files in statistics
see https://git-scm.com/docs/gitmailmap
2024-09-23 16:28:07 +02:00
leo
308445fa81
ux: fill brush for line chart (#493) 2024-09-23 21:54:02 +08:00
leo
af57c56cd7
feature: enhanced statistics panel (#493)
* replace the `YEAR` tab with `OVERVIEW` tab, which will analyze most recent 20K commits
* use `LiveChartsCore.SkiaSharpView.Avalonia` instead of a custom chart view
2024-09-23 21:45:44 +08:00
13 changed files with 148 additions and 310 deletions

View file

@ -6,21 +6,35 @@ namespace SourceGit.Commands
{ {
public Statistics(string repo) public Statistics(string repo)
{ {
_statistics = new Models.Statistics();
WorkingDirectory = repo; WorkingDirectory = repo;
Context = repo; Context = repo;
Args = $"log --date-order --branches --remotes --since=\"{_statistics.Since()}\" --pretty=format:\"%ct$%an\""; Args = $"log --date-order --branches --remotes -20000 --pretty=format:\"%ct$%aN\"";
} }
public Models.Statistics Result() public Models.Statistics Result()
{ {
Exec(); var statistics = new Models.Statistics();
_statistics.Complete(); var rs = ReadToEnd();
return _statistics; if (!rs.IsSuccess)
return statistics;
var start = 0;
var end = rs.StdOut.IndexOf('\n', start);
while (end > 0)
{
ParseLine(statistics, rs.StdOut.Substring(start, end - start));
start = end + 1;
end = rs.StdOut.IndexOf('\n', start);
}
if (start < rs.StdOut.Length)
ParseLine(statistics, rs.StdOut.Substring(start));
statistics.Complete();
return statistics;
} }
protected override void OnReadline(string line) private void ParseLine(Models.Statistics statistics, string line)
{ {
var dateEndIdx = line.IndexOf('$', StringComparison.Ordinal); var dateEndIdx = line.IndexOf('$', StringComparison.Ordinal);
if (dateEndIdx == -1) if (dateEndIdx == -1)
@ -28,9 +42,7 @@ namespace SourceGit.Commands
var dateStr = line.Substring(0, dateEndIdx); var dateStr = line.Substring(0, dateEndIdx);
if (double.TryParse(dateStr, out var date)) if (double.TryParse(dateStr, out var date))
_statistics.AddCommit(line.Substring(dateEndIdx + 1), date); statistics.AddCommit(line.Substring(dateEndIdx + 1), date);
} }
private readonly Models.Statistics _statistics = null;
} }
} }

View file

@ -1,122 +1,166 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using LiveChartsCore;
using LiveChartsCore.Defaults;
using LiveChartsCore.SkiaSharpView;
using LiveChartsCore.SkiaSharpView.Painting;
using SkiaSharp;
namespace SourceGit.Models namespace SourceGit.Models
{ {
public class StatisticsSample(string name) public enum StaticsticsMode
{
All,
ThisMonth,
ThisWeek,
}
public class StaticsticsAuthor(string name, int count)
{ {
public string Name { get; set; } = name; public string Name { get; set; } = name;
public int Count { get; set; } = 0; public int Count { get; set; } = count;
}
public class StaticsticsSample(DateTime time, int count)
{
public DateTime Time { get; set; } = time;
public int Count { get; set; } = count;
} }
public class StatisticsReport public class StatisticsReport
{ {
public static readonly string[] WEEKDAYS = ["SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT"];
public int Total { get; set; } = 0; public int Total { get; set; } = 0;
public List<StatisticsSample> Samples { get; set; } = new List<StatisticsSample>(); public List<StaticsticsAuthor> Authors { get; set; } = new List<StaticsticsAuthor>();
public List<StatisticsSample> ByAuthor { get; set; } = new List<StatisticsSample>(); public List<ISeries> Series { get; set; } = new List<ISeries>();
public List<Axis> XAxes { get; set; } = new List<Axis>();
public List<Axis> YAxes { get; set; } = new List<Axis>();
public void AddCommit(int index, string author) public StatisticsReport(StaticsticsMode mode, DateTime start)
{ {
Total++; _mode = mode;
Samples[index].Count++;
if (_mapUsers.TryGetValue(author, out var value)) YAxes = [new Axis() {
TextSize = 10,
MinLimit = 0,
SeparatorsPaint = new SolidColorPaint(SKColors.LightSlateGray) { StrokeThickness = .6f }
}];
if (mode == StaticsticsMode.ThisWeek)
{ {
value.Count++; for (int i = 0; i < 7; i++)
_mapSamples.Add(start.AddDays(i), 0);
XAxes.Add(new DateTimeAxis(TimeSpan.FromDays(1), v => WEEKDAYS[(int)v.DayOfWeek]) { TextSize = 10 });
}
else if (mode == StaticsticsMode.ThisMonth)
{
var now = DateTime.Now;
var maxDays = DateTime.DaysInMonth(now.Year, now.Month);
for (int i = 0; i < maxDays; i++)
_mapSamples.Add(start.AddDays(i), 0);
XAxes.Add(new DateTimeAxis(TimeSpan.FromDays(1), v => $"{v:MM/dd}") { TextSize = 10 });
} }
else else
{ {
var sample = new StatisticsSample(author); XAxes.Add(new DateTimeAxis(TimeSpan.FromDays(365), v => $"{v:yyyy/MM}") { TextSize = 10 });
sample.Count++;
_mapUsers.Add(author, sample);
ByAuthor.Add(sample);
} }
} }
public void AddCommit(DateTime time, string author)
{
Total++;
var normalized = DateTime.MinValue;
if (_mode == StaticsticsMode.ThisWeek || _mode == StaticsticsMode.ThisMonth)
normalized = time.Date;
else
normalized = new DateTime(time.Year, time.Month, 1).ToLocalTime();
if (_mapSamples.TryGetValue(normalized, out var vs))
_mapSamples[normalized] = vs + 1;
else
_mapSamples.Add(normalized, 1);
if (_mapUsers.TryGetValue(author, out var vu))
_mapUsers[author] = vu + 1;
else
_mapUsers.Add(author, 1);
}
public void Complete() public void Complete()
{ {
ByAuthor.Sort((l, r) => r.Count - l.Count); var samples = new List<DateTimePoint>();
foreach (var kv in _mapSamples)
samples.Add(new DateTimePoint(kv.Key, kv.Value));
Series.Add(
new LineSeries<DateTimePoint>()
{
Values = samples,
Stroke = new SolidColorPaint(SKColors.Green) { StrokeThickness = 1 },
Fill = new SolidColorPaint(SKColors.SkyBlue.WithAlpha(90)),
GeometrySize = 8,
GeometryStroke = new SolidColorPaint(SKColors.Green) { StrokeThickness = 2 }
}
);
foreach (var kv in _mapUsers)
Authors.Add(new StaticsticsAuthor(kv.Key, kv.Value));
Authors.Sort((l, r) => r.Count - l.Count);
_mapUsers.Clear(); _mapUsers.Clear();
_mapSamples.Clear();
} }
private readonly Dictionary<string, StatisticsSample> _mapUsers = new Dictionary<string, StatisticsSample>(); private StaticsticsMode _mode = StaticsticsMode.All;
private Dictionary<string, int> _mapUsers = new Dictionary<string, int>();
private Dictionary<DateTime, int> _mapSamples = new Dictionary<DateTime, int>();
} }
public class Statistics public class Statistics
{ {
public StatisticsReport Year { get; set; } = new StatisticsReport(); public StatisticsReport All { get; set; }
public StatisticsReport Month { get; set; } = new StatisticsReport(); public StatisticsReport Month { get; set; }
public StatisticsReport Week { get; set; } = new StatisticsReport(); public StatisticsReport Week { get; set; }
public Statistics() public Statistics()
{ {
_today = DateTime.Today; _today = DateTime.Now.ToLocalTime().Date;
_thisWeekStart = _today.AddSeconds(-(int)_today.DayOfWeek * 3600 * 24 - _today.Hour * 3600 - _today.Minute * 60 - _today.Second); _thisWeekStart = _today.AddSeconds(-(int)_today.DayOfWeek * 3600 * 24);
_thisWeekEnd = _thisWeekStart.AddDays(7); _thisMonthStart = _today.AddDays(1 - _today.Day);
for (int i = 0; i < 12; i++) All = new StatisticsReport(StaticsticsMode.All, DateTime.MinValue);
Year.Samples.Add(new StatisticsSample("")); Month = new StatisticsReport(StaticsticsMode.ThisMonth, _thisMonthStart);
Week = new StatisticsReport(StaticsticsMode.ThisWeek, _thisWeekStart);
var monthDays = DateTime.DaysInMonth(_today.Year, _today.Month);
for (int i = 0; i < monthDays; i++)
Month.Samples.Add(new StatisticsSample($"{i + 1}"));
string[] weekDayNames = ["SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT"];
for (int i = 0; i < weekDayNames.Length; i++)
Week.Samples.Add(new StatisticsSample(weekDayNames[i]));
}
public string Since()
{
return _today.AddMonths(-11).ToString("yyyy-MM-01 00:00:00");
} }
public void AddCommit(string author, double timestamp) public void AddCommit(string author, double timestamp)
{ {
var time = DateTime.UnixEpoch.AddSeconds(timestamp).ToLocalTime(); var time = DateTime.UnixEpoch.AddSeconds(timestamp).ToLocalTime();
if (time.CompareTo(_thisWeekStart) >= 0 && time.CompareTo(_thisWeekEnd) < 0) if (time >= _thisWeekStart)
Week.AddCommit((int)time.DayOfWeek, author); Week.AddCommit(time, author);
if (time.Month == _today.Month) if (time >= _thisMonthStart)
Month.AddCommit(time.Day - 1, author); Month.AddCommit(time, author);
Year.AddCommit(time.Month - 1, author); All.AddCommit(time, author);
} }
public void Complete() public void Complete()
{ {
Year.Complete(); All.Complete();
Month.Complete(); Month.Complete();
Week.Complete(); Week.Complete();
// Year is start from 11 months ago from now.
var thisYear = _today.Year;
var start = _today.AddMonths(-11);
if (start.Month == 1)
{
for (int i = 0; i < 12; i++)
Year.Samples[i].Name = $"{thisYear}/{i + 1:00}";
}
else
{
var lastYearIdx = start.Month - 1;
var lastYearMonths = Year.Samples.GetRange(lastYearIdx, 12 - lastYearIdx);
for (int i = 0; i < lastYearMonths.Count; i++)
lastYearMonths[i].Name = $"{thisYear - 1}/{lastYearIdx + i + 1:00}";
var thisYearMonths = Year.Samples.GetRange(0, lastYearIdx);
for (int i = 0; i < thisYearMonths.Count; i++)
thisYearMonths[i].Name = $"{thisYear}/{i + 1:00}";
Year.Samples.Clear();
Year.Samples.AddRange(lastYearMonths);
Year.Samples.AddRange(thisYearMonths);
}
} }
private readonly DateTime _today; private readonly DateTime _today;
private readonly DateTime _thisMonthStart;
private readonly DateTime _thisWeekStart; private readonly DateTime _thisWeekStart;
private readonly DateTime _thisWeekEnd;
} }
} }

View file

@ -567,7 +567,6 @@
<x:String x:Key="Text.Statistics.Committer" xml:space="preserve">COMMITTER</x:String> <x:String x:Key="Text.Statistics.Committer" xml:space="preserve">COMMITTER</x:String>
<x:String x:Key="Text.Statistics.ThisMonth" xml:space="preserve">MONAT</x:String> <x:String x:Key="Text.Statistics.ThisMonth" xml:space="preserve">MONAT</x:String>
<x:String x:Key="Text.Statistics.ThisWeek" xml:space="preserve">WOCHE</x:String> <x:String x:Key="Text.Statistics.ThisWeek" xml:space="preserve">WOCHE</x:String>
<x:String x:Key="Text.Statistics.MostRecentYear" xml:space="preserve">JAHR</x:String>
<x:String x:Key="Text.Statistics.TotalCommits" xml:space="preserve">COMMITS: </x:String> <x:String x:Key="Text.Statistics.TotalCommits" xml:space="preserve">COMMITS: </x:String>
<x:String x:Key="Text.Statistics.TotalAuthors" xml:space="preserve">AUTOREN: </x:String> <x:String x:Key="Text.Statistics.TotalAuthors" xml:space="preserve">AUTOREN: </x:String>
<x:String x:Key="Text.Submodule" xml:space="preserve">SUBMODULE</x:String> <x:String x:Key="Text.Submodule" xml:space="preserve">SUBMODULE</x:String>

View file

@ -571,9 +571,9 @@
<x:String x:Key="Text.Statistics.Committer" xml:space="preserve">COMMITTER</x:String> <x:String x:Key="Text.Statistics.Committer" xml:space="preserve">COMMITTER</x:String>
<x:String x:Key="Text.Statistics.ThisMonth" xml:space="preserve">MONTH</x:String> <x:String x:Key="Text.Statistics.ThisMonth" xml:space="preserve">MONTH</x:String>
<x:String x:Key="Text.Statistics.ThisWeek" xml:space="preserve">WEEK</x:String> <x:String x:Key="Text.Statistics.ThisWeek" xml:space="preserve">WEEK</x:String>
<x:String x:Key="Text.Statistics.MostRecentYear" xml:space="preserve">YEAR</x:String>
<x:String x:Key="Text.Statistics.TotalCommits" xml:space="preserve">COMMITS: </x:String> <x:String x:Key="Text.Statistics.TotalCommits" xml:space="preserve">COMMITS: </x:String>
<x:String x:Key="Text.Statistics.TotalAuthors" xml:space="preserve">AUTHORS: </x:String> <x:String x:Key="Text.Statistics.TotalAuthors" xml:space="preserve">AUTHORS: </x:String>
<x:String x:Key="Text.Statistics.Overview" xml:space="preserve">OVERVIEW</x:String>
<x:String x:Key="Text.Submodule" xml:space="preserve">SUBMODULES</x:String> <x:String x:Key="Text.Submodule" xml:space="preserve">SUBMODULES</x:String>
<x:String x:Key="Text.Submodule.Add" xml:space="preserve">Add Submodule</x:String> <x:String x:Key="Text.Submodule.Add" xml:space="preserve">Add Submodule</x:String>
<x:String x:Key="Text.Submodule.CopyPath" xml:space="preserve">Copy Relative Path</x:String> <x:String x:Key="Text.Submodule.CopyPath" xml:space="preserve">Copy Relative Path</x:String>

View file

@ -552,7 +552,6 @@
<x:String x:Key="Text.Statistics.Committer" xml:space="preserve">COMMITTER</x:String> <x:String x:Key="Text.Statistics.Committer" xml:space="preserve">COMMITTER</x:String>
<x:String x:Key="Text.Statistics.ThisMonth" xml:space="preserve">MONTH</x:String> <x:String x:Key="Text.Statistics.ThisMonth" xml:space="preserve">MONTH</x:String>
<x:String x:Key="Text.Statistics.ThisWeek" xml:space="preserve">WEEK</x:String> <x:String x:Key="Text.Statistics.ThisWeek" xml:space="preserve">WEEK</x:String>
<x:String x:Key="Text.Statistics.MostRecentYear" xml:space="preserve">YEAR</x:String>
<x:String x:Key="Text.Statistics.TotalCommits" xml:space="preserve">COMMITS: </x:String> <x:String x:Key="Text.Statistics.TotalCommits" xml:space="preserve">COMMITS: </x:String>
<x:String x:Key="Text.Statistics.TotalAuthors" xml:space="preserve">AUTHORS: </x:String> <x:String x:Key="Text.Statistics.TotalAuthors" xml:space="preserve">AUTHORS: </x:String>
<x:String x:Key="Text.Submodule" xml:space="preserve">SUBMODULES</x:String> <x:String x:Key="Text.Submodule" xml:space="preserve">SUBMODULES</x:String>

View file

@ -545,7 +545,6 @@
<x:String x:Key="Text.Statistics.Committer" xml:space="preserve">COMMITTER</x:String> <x:String x:Key="Text.Statistics.Committer" xml:space="preserve">COMMITTER</x:String>
<x:String x:Key="Text.Statistics.ThisMonth" xml:space="preserve">MÊS</x:String> <x:String x:Key="Text.Statistics.ThisMonth" xml:space="preserve">MÊS</x:String>
<x:String x:Key="Text.Statistics.ThisWeek" xml:space="preserve">SEMANA</x:String> <x:String x:Key="Text.Statistics.ThisWeek" xml:space="preserve">SEMANA</x:String>
<x:String x:Key="Text.Statistics.MostRecentYear" xml:space="preserve">ANO</x:String>
<x:String x:Key="Text.Statistics.TotalCommits" xml:space="preserve">COMMITS: </x:String> <x:String x:Key="Text.Statistics.TotalCommits" xml:space="preserve">COMMITS: </x:String>
<x:String x:Key="Text.Statistics.TotalAuthors" xml:space="preserve">AUTORES: </x:String> <x:String x:Key="Text.Statistics.TotalAuthors" xml:space="preserve">AUTORES: </x:String>
<x:String x:Key="Text.Submodule" xml:space="preserve">SUBMÓDULOS</x:String> <x:String x:Key="Text.Submodule" xml:space="preserve">SUBMÓDULOS</x:String>

View file

@ -571,7 +571,6 @@
<x:String x:Key="Text.Statistics.Committer" xml:space="preserve">ФИКСАТОРЫ</x:String> <x:String x:Key="Text.Statistics.Committer" xml:space="preserve">ФИКСАТОРЫ</x:String>
<x:String x:Key="Text.Statistics.ThisMonth" xml:space="preserve">МЕСЯЦ</x:String> <x:String x:Key="Text.Statistics.ThisMonth" xml:space="preserve">МЕСЯЦ</x:String>
<x:String x:Key="Text.Statistics.ThisWeek" xml:space="preserve">НЕДЕЛЯ</x:String> <x:String x:Key="Text.Statistics.ThisWeek" xml:space="preserve">НЕДЕЛЯ</x:String>
<x:String x:Key="Text.Statistics.MostRecentYear" xml:space="preserve">ГОД</x:String>
<x:String x:Key="Text.Statistics.TotalCommits" xml:space="preserve">ФИКСАЦИИ: </x:String> <x:String x:Key="Text.Statistics.TotalCommits" xml:space="preserve">ФИКСАЦИИ: </x:String>
<x:String x:Key="Text.Statistics.TotalAuthors" xml:space="preserve">АВТОРЫ: </x:String> <x:String x:Key="Text.Statistics.TotalAuthors" xml:space="preserve">АВТОРЫ: </x:String>
<x:String x:Key="Text.Submodule" xml:space="preserve">ПОДМОДУЛИ</x:String> <x:String x:Key="Text.Submodule" xml:space="preserve">ПОДМОДУЛИ</x:String>

View file

@ -569,9 +569,9 @@
<x:String x:Key="Text.Statistics.Committer" xml:space="preserve">提交者</x:String> <x:String x:Key="Text.Statistics.Committer" xml:space="preserve">提交者</x:String>
<x:String x:Key="Text.Statistics.ThisMonth" xml:space="preserve">本月</x:String> <x:String x:Key="Text.Statistics.ThisMonth" xml:space="preserve">本月</x:String>
<x:String x:Key="Text.Statistics.ThisWeek" xml:space="preserve">本周</x:String> <x:String x:Key="Text.Statistics.ThisWeek" xml:space="preserve">本周</x:String>
<x:String x:Key="Text.Statistics.MostRecentYear" xml:space="preserve">最近一年</x:String>
<x:String x:Key="Text.Statistics.TotalCommits" xml:space="preserve">提交次数: </x:String> <x:String x:Key="Text.Statistics.TotalCommits" xml:space="preserve">提交次数: </x:String>
<x:String x:Key="Text.Statistics.TotalAuthors" xml:space="preserve">贡献者人数: </x:String> <x:String x:Key="Text.Statistics.TotalAuthors" xml:space="preserve">贡献者人数: </x:String>
<x:String x:Key="Text.Statistics.Overview" xml:space="preserve">总览</x:String>
<x:String x:Key="Text.Submodule" xml:space="preserve">子模块</x:String> <x:String x:Key="Text.Submodule" xml:space="preserve">子模块</x:String>
<x:String x:Key="Text.Submodule.Add" xml:space="preserve">添加子模块</x:String> <x:String x:Key="Text.Submodule.Add" xml:space="preserve">添加子模块</x:String>
<x:String x:Key="Text.Submodule.CopyPath" xml:space="preserve">复制路径</x:String> <x:String x:Key="Text.Submodule.CopyPath" xml:space="preserve">复制路径</x:String>

View file

@ -574,9 +574,9 @@
<x:String x:Key="Text.Statistics.Committer" xml:space="preserve">提交者</x:String> <x:String x:Key="Text.Statistics.Committer" xml:space="preserve">提交者</x:String>
<x:String x:Key="Text.Statistics.ThisMonth" xml:space="preserve">本月</x:String> <x:String x:Key="Text.Statistics.ThisMonth" xml:space="preserve">本月</x:String>
<x:String x:Key="Text.Statistics.ThisWeek" xml:space="preserve">本週</x:String> <x:String x:Key="Text.Statistics.ThisWeek" xml:space="preserve">本週</x:String>
<x:String x:Key="Text.Statistics.MostRecentYear" xml:space="preserve">最近一年</x:String>
<x:String x:Key="Text.Statistics.TotalCommits" xml:space="preserve">提交次數:</x:String> <x:String x:Key="Text.Statistics.TotalCommits" xml:space="preserve">提交次數:</x:String>
<x:String x:Key="Text.Statistics.TotalAuthors" xml:space="preserve">貢獻者人數:</x:String> <x:String x:Key="Text.Statistics.TotalAuthors" xml:space="preserve">貢獻者人數:</x:String>
<x:String x:Key="Text.Statistics.Overview" xml:space="preserve">總覽</x:String>
<x:String x:Key="Text.Submodule" xml:space="preserve">子模組</x:String> <x:String x:Key="Text.Submodule" xml:space="preserve">子模組</x:String>
<x:String x:Key="Text.Submodule.Add" xml:space="preserve">新增子模組</x:String> <x:String x:Key="Text.Submodule.Add" xml:space="preserve">新增子模組</x:String>
<x:String x:Key="Text.Submodule.CopyPath" xml:space="preserve">複製路徑</x:String> <x:String x:Key="Text.Submodule.CopyPath" xml:space="preserve">複製路徑</x:String>

View file

@ -45,7 +45,8 @@
<PackageReference Include="Avalonia.Diagnostics" Version="11.1.3" Condition="'$(Configuration)' == 'Debug'" /> <PackageReference Include="Avalonia.Diagnostics" Version="11.1.3" Condition="'$(Configuration)' == 'Debug'" />
<PackageReference Include="Avalonia.AvaloniaEdit" Version="11.1.0" /> <PackageReference Include="Avalonia.AvaloniaEdit" Version="11.1.0" />
<PackageReference Include="AvaloniaEdit.TextMate" Version="11.1.0" /> <PackageReference Include="AvaloniaEdit.TextMate" Version="11.1.0" />
<PackageReference Include="CommunityToolkit.Mvvm" Version="8.2.2" /> <PackageReference Include="CommunityToolkit.Mvvm" Version="8.2.2" />
<PackageReference Include="LiveChartsCore.SkiaSharpView.Avalonia" Version="2.0.0-rc3.3" />
<PackageReference Include="TextMateSharp" Version="1.0.63" /> <PackageReference Include="TextMateSharp" Version="1.0.63" />
<PackageReference Include="TextMateSharp.Grammars" Version="1.0.63" /> <PackageReference Include="TextMateSharp.Grammars" Version="1.0.63" />
</ItemGroup> </ItemGroup>

View file

@ -50,7 +50,7 @@ namespace SourceGit.ViewModels
switch (_selectedIndex) switch (_selectedIndex)
{ {
case 0: case 0:
SelectedReport = _data.Year; SelectedReport = _data.All;
break; break;
case 1: case 1:
SelectedReport = _data.Month; SelectedReport = _data.Month;

View file

@ -5,6 +5,7 @@
xmlns:m="using:SourceGit.Models" xmlns:m="using:SourceGit.Models"
xmlns:vm="using:SourceGit.ViewModels" xmlns:vm="using:SourceGit.ViewModels"
xmlns:v="using:SourceGit.Views" xmlns:v="using:SourceGit.Views"
xmlns:lvc="using:LiveChartsCore.SkiaSharpView.Avalonia"
mc:Ignorable="d" d:DesignWidth="800" d:DesignHeight="450" mc:Ignorable="d" d:DesignWidth="800" d:DesignHeight="450"
x:Class="SourceGit.Views.Statistics" x:Class="SourceGit.Views.Statistics"
x:DataType="vm:Statistics" x:DataType="vm:Statistics"
@ -62,6 +63,7 @@
<ListBox.Styles> <ListBox.Styles>
<Style Selector="ListBoxItem"> <Style Selector="ListBoxItem">
<Setter Property="Width" Value="110"/>
<Setter Property="Height" Value="28"/> <Setter Property="Height" Value="28"/>
<Setter Property="Padding" Value="0"/> <Setter Property="Padding" Value="0"/>
<Setter Property="Background" Value="Transparent"/> <Setter Property="Background" Value="Transparent"/>
@ -90,6 +92,7 @@
<Style Selector="TextBlock.view_mode_switcher"> <Style Selector="TextBlock.view_mode_switcher">
<Setter Property="FontWeight" Value="Bold"/> <Setter Property="FontWeight" Value="Bold"/>
<Setter Property="Foreground" Value="{DynamicResource Brush.FG2}"/> <Setter Property="Foreground" Value="{DynamicResource Brush.FG2}"/>
<Setter Property="HorizontalAlignment" Value="Center"/>
</Style> </Style>
<Style Selector="ListBoxItem:pointerover TextBlock.view_mode_switcher"> <Style Selector="ListBoxItem:pointerover TextBlock.view_mode_switcher">
@ -103,7 +106,7 @@
<ListBoxItem> <ListBoxItem>
<Border Classes="switcher_bg"> <Border Classes="switcher_bg">
<TextBlock Classes="view_mode_switcher" Text="{DynamicResource Text.Statistics.MostRecentYear}"/> <TextBlock Classes="view_mode_switcher" Text="{DynamicResource Text.Statistics.Overview}"/>
</Border> </Border>
</ListBoxItem> </ListBoxItem>
@ -128,7 +131,7 @@
<Grid Grid.Column="0" RowDefinitions="*,16"> <Grid Grid.Column="0" RowDefinitions="*,16">
<!-- Table By Committer --> <!-- Table By Committer -->
<ListBox Grid.Column="0" <ListBox Grid.Column="0"
ItemsSource="{Binding ByAuthor}" ItemsSource="{Binding Authors}"
SelectionMode="Single" SelectionMode="Single"
BorderThickness="1" BorderThickness="1"
BorderBrush="{DynamicResource Brush.Border2}" BorderBrush="{DynamicResource Brush.Border2}"
@ -150,7 +153,7 @@
</ListBox.ItemsPanel> </ListBox.ItemsPanel>
<ListBox.ItemTemplate> <ListBox.ItemTemplate>
<DataTemplate DataType="m:StatisticsSample"> <DataTemplate DataType="m:StaticsticsAuthor">
<Border BorderThickness="0,0,0,1" BorderBrush="{DynamicResource Brush.Border2}"> <Border BorderThickness="0,0,0,1" BorderBrush="{DynamicResource Brush.Border2}">
<Grid ColumnDefinitions="*,100"> <Grid ColumnDefinitions="*,100">
<Border Grid.Column="0" Padding="8,0" ClipToBounds="True"> <Border Grid.Column="0" Padding="8,0" ClipToBounds="True">
@ -170,7 +173,7 @@
<!-- Total Committers --> <!-- Total Committers -->
<StackPanel Grid.Column="0" Orientation="Horizontal" VerticalAlignment="Bottom"> <StackPanel Grid.Column="0" Orientation="Horizontal" VerticalAlignment="Bottom">
<TextBlock Classes="primary" Text="{DynamicResource Text.Statistics.TotalAuthors}" FontSize="11" Foreground="{DynamicResource Brush.FG2}"/> <TextBlock Classes="primary" Text="{DynamicResource Text.Statistics.TotalAuthors}" FontSize="11" Foreground="{DynamicResource Brush.FG2}"/>
<TextBlock Classes="primary" Text="{Binding ByAuthor.Count}" FontSize="11" Margin="4,0,0,0"/> <TextBlock Classes="primary" Text="{Binding Authors.Count}" FontSize="11" Margin="4,0,0,0"/>
</StackPanel> </StackPanel>
<!-- Total Commits --> <!-- Total Commits -->
@ -182,12 +185,7 @@
</Grid> </Grid>
<!-- Graph --> <!-- Graph -->
<v:Chart Grid.Column="1" <lvc:CartesianChart Grid.Column="1" Margin="16" Series="{Binding Series}" XAxes="{Binding XAxes}" YAxes="{Binding YAxes}" ZoomMode="X"/>
Margin="16"
LabelBrush="{DynamicResource Brush.FG1}"
LineBrush="{DynamicResource Brush.Border2}"
ShapeBrush="{DynamicResource Brush.Accent}"
Samples="{Binding Samples}"/>
</Grid> </Grid>
</DataTemplate> </DataTemplate>
</ContentControl.DataTemplates> </ContentControl.DataTemplates>

View file

@ -1,220 +1,7 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Input; using Avalonia.Input;
using Avalonia.Media;
namespace SourceGit.Views namespace SourceGit.Views
{ {
public class Chart : Control
{
public static readonly StyledProperty<IBrush> LabelBrushProperty =
AvaloniaProperty.Register<Chart, IBrush>(nameof(LabelBrush), Brushes.Black);
public IBrush LabelBrush
{
get => GetValue(LabelBrushProperty);
set => SetValue(LabelBrushProperty, value);
}
public static readonly StyledProperty<IBrush> LineBrushProperty =
AvaloniaProperty.Register<Chart, IBrush>(nameof(LineBrush), Brushes.Gray);
public IBrush LineBrush
{
get => GetValue(LineBrushProperty);
set => SetValue(LineBrushProperty, value);
}
public static readonly StyledProperty<IBrush> ShapeBrushProperty =
AvaloniaProperty.Register<Chart, IBrush>(nameof(ShapeBrush), Brushes.Gray);
public IBrush ShapeBrush
{
get => GetValue(ShapeBrushProperty);
set => SetValue(ShapeBrushProperty, value);
}
public static readonly StyledProperty<List<Models.StatisticsSample>> SamplesProperty =
AvaloniaProperty.Register<Chart, List<Models.StatisticsSample>>(nameof(Samples));
public List<Models.StatisticsSample> Samples
{
get => GetValue(SamplesProperty);
set => SetValue(SamplesProperty, value);
}
static Chart()
{
SamplesProperty.Changed.AddClassHandler<Chart>((c, _) =>
{
c._hitBoxes.Clear();
c._lastHitIdx = -1;
c.InvalidateMeasure();
});
}
public override void Render(DrawingContext context)
{
if (Samples == null || Bounds.Width == 0)
return;
var samples = Samples;
int maxV = 0;
foreach (var s in samples)
{
if (maxV < s.Count)
maxV = s.Count;
}
if (maxV < 5)
maxV = 5;
else if (maxV < 10)
maxV = 10;
else if (maxV < 50)
maxV = 50;
else if (maxV < 100)
maxV = 100;
else if (maxV < 200)
maxV = 200;
else if (maxV < 500)
maxV = 500;
else
maxV = (int)Math.Ceiling(maxV / 500.0) * 500;
var typeface = new Typeface("fonts:SourceGit#JetBrains Mono");
var pen = new Pen(LineBrush);
var width = Bounds.Width;
var height = Bounds.Height;
// Draw coordinate
var maxLabel = new FormattedText($"{maxV}", CultureInfo.CurrentCulture, FlowDirection.LeftToRight, typeface, 12.0, LabelBrush);
var horizonStart = maxLabel.Width + 8;
var labelHeight = maxLabel.Height;
var bg = this.FindResource("Brush.Contents") as IBrush;
context.DrawText(maxLabel, new Point(0, -maxLabel.Height * 0.5));
context.DrawRectangle(bg, pen, new Rect(horizonStart, 0, width - horizonStart, height - labelHeight));
if (samples.Count == 0)
return;
// Draw horizontal lines
var stepX = (width - horizonStart) / samples.Count;
var stepV = (height - labelHeight) / 5;
var labelStepV = maxV / 5;
var gridPen = new Pen(LineBrush, 1, new DashStyle() { Dashes = [2, 2, 0, 2], Offset = 1 });
for (int i = 1; i < 5; i++)
{
var vLabel = new FormattedText(
$"{maxV - i * labelStepV}",
CultureInfo.CurrentCulture,
FlowDirection.LeftToRight,
typeface,
12.0,
LabelBrush);
var dashHeight = i * stepV;
var vy = Math.Max(0, dashHeight - vLabel.Height * 0.5);
using (context.PushOpacity(.1))
{
context.DrawLine(gridPen, new Point(horizonStart + 1, dashHeight), new Point(width, dashHeight));
}
context.DrawText(vLabel, new Point(horizonStart - vLabel.Width - 8, vy));
}
// Calculate hit boxes
if (_hitBoxes.Count == 0)
{
var shapeWidth = Math.Min(32, stepX - 4);
for (int i = 0; i < samples.Count; i++)
{
var h = samples[i].Count * (height - labelHeight) / maxV;
var x = horizonStart + 1 + stepX * i + (stepX - shapeWidth) * 0.5;
var y = height - labelHeight - h;
_hitBoxes.Add(new Rect(x, y, shapeWidth, h - 1));
}
}
// Draw shapes
for (int i = 0; i < samples.Count; i++)
{
var hLabel = new FormattedText(
samples[i].Name,
CultureInfo.CurrentCulture,
FlowDirection.LeftToRight,
typeface,
10.0,
LabelBrush);
var rect = _hitBoxes[i];
var xLabel = rect.X - (hLabel.Width - rect.Width) * 0.5;
var yLabel = height - labelHeight + 4;
context.DrawRectangle(ShapeBrush, null, rect);
var test = (stepX - 4) / hLabel.Width;
if (test < 1.0)
{
var matrix = Matrix.CreateRotation(Math.Acos(test)) * Matrix.CreateTranslation(xLabel + hLabel.Width * 0.5, yLabel);
using (context.PushTransform(matrix))
context.DrawText(hLabel, new Point(0, 0));
}
else
{
context.DrawText(hLabel, new Point(xLabel, yLabel));
}
}
// Draw labels on hover
if (_lastHitIdx >= 0 && _lastHitIdx < samples.Count)
{
var rect = _hitBoxes[_lastHitIdx];
var tooltip = new FormattedText(
$"{samples[_lastHitIdx].Count}",
CultureInfo.CurrentCulture,
FlowDirection.LeftToRight,
typeface,
12.0,
LabelBrush);
var tx = rect.X - (tooltip.Width - rect.Width) * 0.5;
var ty = rect.Y - tooltip.Height - 4;
context.DrawText(tooltip, new Point(tx, ty));
}
}
protected override void OnPointerMoved(PointerEventArgs e)
{
base.OnPointerMoved(e);
var p = e.GetPosition(this);
for (int i = 0; i < _hitBoxes.Count; i++)
{
if (_hitBoxes[i].Contains(p))
{
if (_lastHitIdx != i)
{
_lastHitIdx = i;
InvalidateVisual();
}
return;
}
}
if (_lastHitIdx != -1)
{
_lastHitIdx = -1;
InvalidateVisual();
}
}
private readonly List<Rect> _hitBoxes = new List<Rect>();
private int _lastHitIdx = -1;
}
public partial class Statistics : ChromelessWindow public partial class Statistics : ChromelessWindow
{ {
public Statistics() public Statistics()