Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Шестопалов Андрей #33

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
123 changes: 123 additions & 0 deletions TagsCloudContainer.Tests/CircularCloudContainerTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
using System.Drawing;
using FluentAssertions;
using NUnit.Framework;
using TagsCloudContainer.CloudLayouters;
using TagsCloudContainer.Extensions;

namespace TagsCloudContainer.Tests;

[TestFixture]
public class CircularCloudContainerTests
{
private CircularCloudLayouter circularCloudLayouter;

[SetUp]
public void Setup()
{
var spiral = new ArchimedeanSpiral(Point.Empty);
circularCloudLayouter = new CircularCloudLayouter(Point.Empty, spiral);
}

[Test]
public void Constructor_SetCenterCorrectly_WhenInitialized()
{
var center = Point.Empty;
var cloudCenter = circularCloudLayouter.Center;

cloudCenter.Should().Be(center);
}

[Test]
public void CloudSizeIsZero_WhenInitialized()
{
var actualSize = circularCloudLayouter.Tags.CalculateSize();

actualSize.Should().Be(Size.Empty);
}

[Test]
public void CloudSizeEqualsFirstTagSize_WhenPuttingFirstTag()
{
var font = new Font("Arial", 25);
const string text = "text";

SizeF expectsdRectangleSize;
using (var bitmap = new Bitmap(1, 1))
using (var graphics = Graphics.FromImage(bitmap))
{
graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
expectsdRectangleSize = graphics.MeasureString(text, font);
}

circularCloudLayouter.PutNextTag(text, 3);
var actualRectangleSize = circularCloudLayouter.Tags.CalculateSize();

actualRectangleSize.Should().Be(expectsdRectangleSize.ToSize());
}

[Test]
public void CloudSizeIsCloseToCircleShape_WhenPuttingManyTags()
{
for (var i = 0; i < 100; i++)
{
circularCloudLayouter.PutNextTag("test", 4);
}

var actualSize = circularCloudLayouter.Tags.CalculateSize();
var aspectRatio = (double)actualSize.Width / actualSize.Height;

aspectRatio.Should().BeInRange(0.5, 2.0);
}

[TestCase(0, TestName = "NoTags_WhenInitialized")]
[TestCase(1, TestName = "SingleTag_WhenPuttingFirstTag")]
[TestCase(10, TestName = "MultipleTags_WhenPuttingALotOfTags")]
public void CloudContains(int rectangleCount)
{
for (var i = 0; i < rectangleCount; i++)
{
circularCloudLayouter.PutNextTag("test", 2);
}

circularCloudLayouter.Tags.Count.Should().Be(rectangleCount);
}

[Test]
public void PutNextRectangle_ThrowException_WhenCountIsNotPositive()
{
var putIncorrectRectangle = () => circularCloudLayouter.PutNextTag("test", -5);

putIncorrectRectangle.Should().Throw<ArgumentException>();
}

[Test]
public void PutNextRectangle_PlacesFirstRectangleInCenter()
{
var center = Point.Empty;
var firstRectangle = circularCloudLayouter.PutNextTag("text", 3);

var rectangleCenter = new Point(
firstRectangle.Left + firstRectangle.Width / 2,
firstRectangle.Top - firstRectangle.Height / 2);

rectangleCenter.Should().Be(center);
}

[Test]
public void PutNextRectangle_CloudTagsIsNotIntersect_WhenPuttingALotOfTags()
{
circularCloudLayouter.PutNextTag("test", 3);
circularCloudLayouter.PutNextTag("test", 2);
circularCloudLayouter.PutNextTag("test", 1);

var tags = circularCloudLayouter.Tags;
for (var i = 0; i < tags.Count; i++)
{
var currentRectangle = tags[i].Rectangle;
tags
.Where((_, j) => j != i)
.All(otherTag => !currentRectangle.IntersectsWith(otherTag.Rectangle))
.Should().BeTrue();
}
}
}
23 changes: 23 additions & 0 deletions TagsCloudContainer.Tests/TagsCloudContainer.Tests.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<LangVersion>12</LangVersion>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="FluentAssertions" Version="7.0.0" />
<PackageReference Include="NUnit" Version="4.3.1" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\TagsCloudContainer\TagsCloudContainer.csproj" />
</ItemGroup>

<ItemGroup>
<Reference Include="System.Windows.Forms" />
</ItemGroup>

</Project>
217 changes: 217 additions & 0 deletions TagsCloudContainer/App.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,217 @@
using System.Drawing;
using TagsCloudContainer.Extensions;

namespace TagsCloudContainer;

public static class App
{
private const string DefaultCommand = "default";
private const string ExitCommand = "exit";

private static int defaultImageWidth = 1000;
private static int defaultImageHeight = 1000;
private static string defaultFontName = "Arial";
private static Color defaultBackgroundColor = Color.White;
private static Color defaultTextColor = Color.Black;
private static string defaultWordsFilePath = Path.Combine("..", "..", "..", "WordProcessing", "cloud.txt");
private static string defaultExcludedWordsFilePath = Path.Combine("..", "..", "..", "WordProcessing", "excluded_words.txt");

private static readonly string imageDimensionsPrompt = $"Введите размер изображения (по умолчанию W: {defaultImageWidth}, H: {defaultImageHeight}):";
private static readonly string fileNamePrompt = "Введите название файла с текстом:";
private static readonly string excludedWordsFileNamePrompt = "Введите название файла с исключёнными словами:";
private static readonly string fontNamePrompt = $"Введите название шрифта (по умолчанию {defaultFontName}):";
private static readonly string backgroundColorPrompt = $"Введите цвет фона (по умолчанию {defaultBackgroundColor.Name}):";
private static readonly string textColorPrompt = $"Введите цвет текста (по умолчанию {defaultTextColor.Name}):";

public static string GetDefaultExcludedWordsFilePath()
{
return defaultExcludedWordsFilePath;
}

private static void ShowExitMessage()
{
Console.WriteLine($"Чтобы выйти из программы, напишите \"{ExitCommand}\", чтобы использовать значение по умолчанию, напишите \"{DefaultCommand}\"");
Console.WriteLine();
}

public static string GetFileNameFromUser()
{
return GetFileName(fileNamePrompt, defaultWordsFilePath);
}

public static string GetExcludedWordsFileNameFromUser()
{
return GetFileName(excludedWordsFileNamePrompt, string.Empty);
}

private static string GetFileName(string prompt, string defaultPath)
{
ShowExitMessage();

while (true)

This comment was marked as resolved.

{
Console.WriteLine(prompt);
var input = Console.ReadLine();

if (!string.IsNullOrEmpty(input) && File.Exists(input))
{
Console.Clear();
return input;
}

switch (input)
{
case ExitCommand:
Environment.Exit(0);
break;
case DefaultCommand:
Console.Clear();
return defaultPath;
}

Console.Clear();
ShowExitMessage();
Console.WriteLine("Файл не найден. Попробуйте снова.");
}
}

public static ImageDimensions GetImageDimensionsFromUser()
{
ShowExitMessage();

while (true)
{
Console.WriteLine(imageDimensionsPrompt);
Console.WriteLine("(в формате \"ширина высота\")");
var input = Console.ReadLine();
var size = input?.Split(' ');

if (size?.Length == 2 &&
int.TryParse(size[0], out var width) &&
int.TryParse(size[1], out var height) &&
width > 0 && height > 0)
{
Console.Clear();
return new ImageDimensions(width, height);
}

switch (input)
{
case ExitCommand:
Environment.Exit(0);
break;
case DefaultCommand:
Console.Clear();
return new ImageDimensions(defaultImageWidth, defaultImageHeight);
}

Console.Clear();
ShowExitMessage();
Console.WriteLine("Некорректный ввод. Убедитесь, что вы ввели два положительных целых числа.");
}
}

public static string GetFontNameFromUser()
{
ShowExitMessage();

while (true)
{
Console.WriteLine(fontNamePrompt);
var input = Console.ReadLine();

if (input!.FontExists())
{
Console.Clear();
return input!;
}

switch (input)
{
case ExitCommand:
Environment.Exit(0);
break;
case DefaultCommand:
Console.Clear();
return defaultFontName;
}

Console.Clear();
ShowExitMessage();
Console.WriteLine("Шрифт не найден. Попробуйте снова.");
}
}

public static (Color Primary, Color? Secondary) GetBackgroundColorsFromUser()
{
return GetColorsFromUser(backgroundColorPrompt, defaultBackgroundColor);
}

public static (Color Primary, Color? Secondary) GetTextColorsFromUser()
{
return GetColorsFromUser(textColorPrompt, defaultTextColor);
}

private static (Color Primary, Color? Secondary) GetColorsFromUser(string prompt, Color defaultColor)
{
ShowExitMessage();

while (true)
{
Console.WriteLine(prompt);
Console.WriteLine("(Чтобы использовать градиент введите 2 цвета через пробел)");
var input = Console.ReadLine();

switch (input)
{
case ExitCommand:
Environment.Exit(0);
break;
case DefaultCommand:
Console.Clear();
return (defaultColor, null);
}

var colorInputs = input?.Split(' ', StringSplitOptions.RemoveEmptyEntries);

if (colorInputs is { Length: > 0 })
{
try
{
var primaryColor = ParseColor(colorInputs[0].Trim());

if (colorInputs.Length > 1)
{
var secondaryColor = ParseColor(colorInputs[1].Trim());
Console.Clear();
return (primaryColor, secondaryColor);
}

Console.Clear();
return (primaryColor, null);
}
catch (ArgumentException ex)
{
Console.Clear();
ShowExitMessage();
Console.WriteLine(ex.Message);
continue;
}
}

Console.Clear();
ShowExitMessage();
Console.WriteLine("Некорректное значение. Попробуйте снова.");
}
}

private static Color ParseColor(string input)
{
if (Enum.TryParse(input, true, out KnownColor knownColor))
{
return Color.FromKnownColor(knownColor);
}

throw new ArgumentException($"Некорректное название цвета: {input}");
}
}
Loading