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

Зиновьева Милана #13

Open
wants to merge 12 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 6 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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -41,3 +41,4 @@ bld/
msbuild.log
msbuild.err
msbuild.wrn
FractalPainter/
21 changes: 21 additions & 0 deletions ConsoleClient/ConsoleClient.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Autofac" Version="8.2.0" />
<PackageReference Include="CommandLineParser" Version="2.5.0" />
<PackageReference Include="System.ComponentModel.Composition" Version="4.0.1" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="../DrawingTagsCloudVisualization/DrawingTagsCloudVisualization.csproj" />
<ProjectReference Include="../TagsCloudVisualization/TagsCloudVisualization.csproj" />
</ItemGroup>

</Project>
23 changes: 23 additions & 0 deletions ConsoleClient/Examples/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# 1 example:

Agrs: dotnet run
![alt text](example.png)

# 2 example:

Args: dotnet run -- -o Examples/example1.png -l 500 -w 500
![alt text](example1.png)

# 3 example:

Args: dotnet run -- -o Examples/example2.png -x 150 -y 300
![alt text](example2.png)

# 4 example:

Args: dotnet run -- -c pink -o Examples/example3.png
![alt text](example3.png)

# 5 example:
Args: dotnet run -- -a Fermat -o Examples/example4.png
![alt text](example4.png)
Binary file added ConsoleClient/Examples/example.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
27 changes: 27 additions & 0 deletions ConsoleClient/Examples/example.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
да
о
кошка
кошка
большой
большой
большой
дом
дом
красиво
красиво
красиво
красиво
и
книга
книга
азбука
азбука
кружка
кружка
кружка
алгебра
алгебра
алгебра
носок
носок
не
Binary file added ConsoleClient/Examples/example1.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
45 changes: 45 additions & 0 deletions ConsoleClient/Examples/example1.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
да
о
кошка
кошка
большой
большой
большой
дом
дом
дом
красиво
красиво
красиво
красиво
и
книга
книга
азбука
азбука
кружка
кружка
кружка
алгебра
алгебра
алгебра
носок
носок
носок
не
говно
говно
говно
хуй
хуй
хуй
залупа
залупа
мошонник
мошонник
мошонник
мошонник
говнохуй
говнохуй
говнохуй
говнохуй
Binary file added ConsoleClient/Examples/example2.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added ConsoleClient/Examples/example3.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added ConsoleClient/Examples/example4.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added ConsoleClient/Examples/example6.png
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Нраица

Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
29 changes: 29 additions & 0 deletions ConsoleClient/Options.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
using CommandLine;
namespace ConsoleClient;

public class Options
{
[Option('i', "input", Default = "Examples/example.txt", HelpText = "Путь к входному текстовому файлу.")]
public required string InputFilePath { get; set; }

[Option('o', "output", Default = "Examples/example.png", HelpText = "Путь к выходному изображению.")]
public required string OutputFilePath { get; set; }

[Option('x', "centerX", Default = 200, HelpText = "Координата X центра.")]
public int CenterX { get; set; }

[Option('y', "centerY", Default = 200, HelpText = "Координата Y центра.")]
public int CenterY { get; set; }

[Option('l', "lenght", Default = 400, HelpText = "Длина изображения")]
public int Lenght { get; set; }
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lenght


[Option('w', "width", Default = 400, HelpText = "Ширина изображения")]
public int Width{ get; set; }

[Option('c', "color", Default = "black", HelpText = "Цвет текста")]
public string Color{ get; set; }

[Option('a', "algoritm", Default = "Circle", HelpText = "Алгоритм(квадрат, круг)")]
public string Algorithm{ get; set; }
}
87 changes: 87 additions & 0 deletions ConsoleClient/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
using System.Drawing;
using Autofac;
using CommandLine;
using DrawingTagsCloudVisualization;
using TagsCloudVisualization;
using TagsCloudVisualization.FilesProcessing;
using TagsCloudVisualization.ManagingRendering;

namespace ConsoleClient;

public class Program
{
static void Main(string[] args)
{
Parser.Default.ParseArguments<Options>(args)
.WithParsed(RunApplication)
.WithNotParsed(HandleErrors);
}

private static void RunApplication(Options options)
{
var builder = new ContainerBuilder();

builder.Register(c =>
{
var mystem = new MyStemWrapper.MyStem
{
PathToMyStem = "mystem",
Parameters = "-ni"
};
return mystem;
}).As<MyStemWrapper.MyStem>().SingleInstance();

builder.RegisterType<MorphologicalProcessing>()
.As<IMorphologicalAnalyzer>()
.InstancePerDependency();

builder.RegisterType<TxtFileProcessor>()
.As<IFileProcessor>()
.InstancePerDependency();

builder.RegisterType<RectangleGenerator>()
.As<IRectangleGenerator>()
.InstancePerDependency();

builder.Register<ISpiral>(c =>
{
if (options.Algorithm.Equals("Circle", StringComparison.OrdinalIgnoreCase))
{
return new ArchimedeanSpiral(new Point(options.CenterX, options.CenterY), 1);
}
return new FermatSpiral(new Point(options.CenterX, options.CenterY), 20);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Тут бы switch подошёл. Алгоритм А - А, алгоритм Б - Б, а какой-то другой - throw ArgumentOutOfRangeException или просто ошибку вывести вместо страшного ексепшна

Вообще по идее валидацией должен заниматься CommandLineParser, но раз не завезли валидацию значений, надо самим валидировать

}).As<ISpiral>().InstancePerDependency();

builder.RegisterType<WordHandler>()
.As<IWordHandler>()
.InstancePerDependency();

builder.Register(c =>
{
var wordHandler = c.Resolve<IWordHandler>();
var frequencyRectangles = wordHandler.ProcessFile(options.InputFilePath);
var arrRect = c.Resolve<IRectangleGenerator>().ExecuteRectangles(frequencyRectangles, new Point(options.CenterX, options.CenterY));
return new DrawingTagsCloud(arrRect);
}).As<IDrawingTagsCloud>().InstancePerDependency();
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

А, ещё тут прямо логика в инициализации. Так нельзя. У тебя в отрисовщике в зависимости данные. Для ISpiral так можно делать, тк нам надо понимать, кого конкретно использовать. А здесь надо чтобы либо IWordHandler был в зависимости RectangleGenerator, а он в зависимости у отрисовщика, либо чтобы сама Program резолвила все зависимости по очереди и в нужном порядке обрабатывала. Я бы вообще сделал чтобы был какой-то TagsCloudDrawingFacade, у которого в зависимостях вообще все модули, он в нужном порядке их вызывает, а в Program просто была строчка c.Resolve<ITagsCloudDrawingFacade>().DrawRectangle(options)


var container = builder.Build();
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Принято инициализацию контейнера уносить в отдельный класс. У тебя тут зависимостей чуть-чуть, но это уже занимает места на полтора экрана


using var scope = container.BeginLifetimeScope();
try
{
var drawingTagsCloud = scope.Resolve<IDrawingTagsCloud>();
drawingTagsCloud.SaveToFile(options.OutputFilePath, options.Lenght, options.Width, options.Color);

Console.WriteLine($"Облако тегов успешно сохранено в файл: {options.OutputFilePath}");
}
catch (Exception ex)
{
Console.WriteLine($"Произошла ошибка: {ex.Message}");
}
}

private static void HandleErrors(IEnumerable<Error> errors)
{
Console.WriteLine("Ошибка при обработке аргументов командной строки.");
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Вот тут бы обработать коллекцию ошибок, чтобы пользователя не оставить в недоумении

}
}
Binary file added ConsoleClient/mystem
Binary file not shown.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
67 changes: 67 additions & 0 deletions DrawingTagsCloudVisualization/DrawingTagsCloud.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
using System.Runtime.CompilerServices;
using Microsoft.Maui.Graphics;
using Microsoft.Maui.Graphics.Skia;
using Microsoft.VisualBasic;
using TagsCloudVisualization;

namespace DrawingTagsCloudVisualization;

public interface IDrawingTagsCloud
{
public void SaveToFile(string filePath, int lenght, int width, string color);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

По именованию

  1. файл обработчик должен называться как файл обработчик. А здесь название будто класс хранит данные
  2. Имя метода не соответствует имени класса. Вроде бы мы рисуем, а по факту ещё и сохраняем куда-то

Для обработчиков есть окончание-заглушка: Handler. Если ты начнёшь читать чужой код и увидишь это слово, значит автор не смог придумать внятное название

В твоём случае ты генерируешь файл и сохраняешь. Тогда можешь создать ITagsCloudDrawer и IImageSaver, в одном метод Draw, а во втором SaveToFile, и оба по очереди вызываются из Program

А ну и принято интерфейсы в отдельные файлы убирать, но это по вкусу. Просто в контуре все так делают

}
public class DrawingTagsCloud(List<RectangleInformation> rectangleInformation) : IDrawingTagsCloud
{
private readonly List<RectangleInformation> rectangleInformation = rectangleInformation;

private readonly Dictionary<string, Color> dictColors = new(){
{ "white", Colors.White },
{ "red", Colors.Red },
{ "green", Colors.Green },
{ "yellow", Colors.Yellow },
{ "blue", Colors.Blue },
{ "pink", Colors.Pink },
{ "black", Colors.Black },
};

public void SaveToFile(string filePath, int lenght, int width, string color)
{
using var bitmapContext = new SkiaBitmapExportContext(lenght, width, 2.0f);
var canvas = bitmapContext.Canvas;
canvas.FontColor = Colors.Black;
canvas = Draw(canvas, color);
using var image = bitmapContext.Image;
using var stream = File.OpenWrite(filePath);
image.Save(stream);
}

private ICanvas Draw(ICanvas canvas, string color)
{
foreach (var rectInfo in rectangleInformation)
{
var rect = rectInfo.rectangle;
var text = rectInfo.word;
//canvas.FillRectangle(rect.X, rect.Y, rect.Width, rect.Height);

float fontSize = rect.Height;
if (!dictColors.TryGetValue(color, out var colorGet))
colorGet = Colors.Black;
canvas.FontColor = colorGet;
var textBounds = canvas.GetStringSize(text, Font.Default, fontSize);

while ((textBounds.Width > rect.Width || textBounds.Height > rect.Height) && fontSize > 1)
{
fontSize -= 1;
textBounds = canvas.GetStringSize(text, Font.Default, fontSize);
}

canvas.FontSize = fontSize;
var textX = rect.X + (rect.Width - textBounds.Width) / 2;
var textY = rect.Y + (rect.Height - textBounds.Height) / 2;

canvas.DrawString(text, textX, textY, HorizontalAlignment.Left);
}

return canvas;
}
}
21 changes: 21 additions & 0 deletions DrawingTagsCloudVisualization/DrawingTagsCloudVisualization.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<Project Sdk="Microsoft.NET.Sdk">

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

<IsPackable>false</IsPackable>
<IsTestProject>false</IsTestProject>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Maui.Graphics" Version="9.0.21" />
<PackageReference Include="Microsoft.Maui.Graphics.Skia" Version="9.0.21" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="../TagsCloudVisualization/TagsCloudVisualization.csproj" />
</ItemGroup>

</Project>
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
10 changes: 10 additions & 0 deletions DrawingTagsCloudVisualization/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
Увеличивающися по размеру прямоугольники
![alt text](DecreasingRectangles120.png)


Одинаковые прямоугольники
![alt text](EqualsRectangles250.png)


Прямоугольники разных размеров
![alt text](MixedRectangles320.png)
41 changes: 0 additions & 41 deletions FractalPainter/Application/Actions/DragonFractalAction.cs

This file was deleted.

Loading