-
Notifications
You must be signed in to change notification settings - Fork 31
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
base: master
Are you sure you want to change the base?
Зиновьева Милана #13
Changes from 6 commits
30e4e30
14620e5
301b059
360b777
d08b4ac
825ab62
5a4160d
28ca5d5
18b0f48
08a02a8
586002f
90e440c
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -41,3 +41,4 @@ bld/ | |
msbuild.log | ||
msbuild.err | ||
msbuild.wrn | ||
FractalPainter/ |
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> |
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) |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
да | ||
о | ||
кошка | ||
кошка | ||
большой | ||
большой | ||
большой | ||
дом | ||
дом | ||
красиво | ||
красиво | ||
красиво | ||
красиво | ||
и | ||
книга | ||
книга | ||
азбука | ||
азбука | ||
кружка | ||
кружка | ||
кружка | ||
алгебра | ||
алгебра | ||
алгебра | ||
носок | ||
носок | ||
не |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
да | ||
о | ||
кошка | ||
кошка | ||
большой | ||
большой | ||
большой | ||
дом | ||
дом | ||
дом | ||
красиво | ||
красиво | ||
красиво | ||
красиво | ||
и | ||
книга | ||
книга | ||
азбука | ||
азбука | ||
кружка | ||
кружка | ||
кружка | ||
алгебра | ||
алгебра | ||
алгебра | ||
носок | ||
носок | ||
носок | ||
не | ||
говно | ||
говно | ||
говно | ||
хуй | ||
хуй | ||
хуй | ||
залупа | ||
залупа | ||
мошонник | ||
мошонник | ||
мошонник | ||
мошонник | ||
говнохуй | ||
говнохуй | ||
говнохуй | ||
говнохуй |
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; } | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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; } | ||
} |
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); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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(); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. А, ещё тут прямо логика в инициализации. Так нельзя. У тебя в отрисовщике в зависимости данные. Для ISpiral так можно делать, тк нам надо понимать, кого конкретно использовать. А здесь надо чтобы либо IWordHandler был в зависимости RectangleGenerator, а он в зависимости у отрисовщика, либо чтобы сама Program резолвила все зависимости по очереди и в нужном порядке обрабатывала. Я бы вообще сделал чтобы был какой-то TagsCloudDrawingFacade, у которого в зависимостях вообще все модули, он в нужном порядке их вызывает, а в Program просто была строчка |
||
|
||
var container = builder.Build(); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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("Ошибка при обработке аргументов командной строки."); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Вот тут бы обработать коллекцию ошибок, чтобы пользователя не оставить в недоумении |
||
} | ||
} |
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); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. По именованию
Для обработчиков есть окончание-заглушка: 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; | ||
} | ||
} |
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> |
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) |
This file was deleted.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Нраица