mitushkin-infa/FigureList.cpp

423 lines
11 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include <vcl.h>
#pragma hdrstop
#include "FigureList.h"
#include "TriangleFigure.h"
#include "RectangleFigure.h"
#include "EllipseFigure.h"
#include <math.h>
#pragma package(smart_init)
const String FILE_HEADER = "FIGURES 1";
static String ColorToText(TColor c)
{
int rgb = ColorToRGB(c);
return "#" + IntToHex((int)GetRValue(rgb), 2) + IntToHex((int)GetGValue(rgb), 2) + IntToHex((int)GetBValue(rgb), 2);
}
static bool TextToColor(String s, TColor &c)
{
if (s.Length() != 7 || s[1] != '#')
return false;
int v;
if (!TryStrToInt("$" + s.SubString(2, 6), v))
return false;
int r = (v >> 16) & 0xFF;
int g = (v >> 8) & 0xFF;
int b = v & 0xFF;
c = (TColor)RGB(r, g, b);
return true;
}
TFigureManager::TFigureManager()
{
lastNum = 0;
}
TFigureManager::~TFigureManager()
{
FreeAll();
}
void TFigureManager::FreeAll()
{
for (unsigned i = 0; i < links.size(); i++)
delete links[i];
links.clear();
for (unsigned i = 0; i < list.size(); i++)
delete list[i];
list.clear();
}
TFigure* TFigureManager::MakeFigure(String type, int aNum)
{
if (type == "triangle") return new TTriangleFigure(aNum);
if (type == "rectangle") return new TRectangleFigure(aNum);
if (type == "ellipse") return new TEllipseFigure(aNum);
return NULL;
}
TFigure* TFigureManager::Add(String type, int ax, int ay, int aw, int ah, TColor fill, TColor line)
{
TFigure *f = MakeFigure(type, lastNum + 1);
if (!f)
return NULL;
lastNum++;
f->SetBounds(ax, ay, aw, ah);
f->SetFill(fill);
f->SetLine(line);
list.push_back(f);
return f;
}
void TFigureManager::Delete(TFigure *f)
{
for (int i = (int)links.size() - 1; i >= 0; i--)
{
if (links[i]->from == f || links[i]->to == f)
{
delete links[i];
links.erase(links.begin() + i);
}
}
for (unsigned i = 0; i < list.size(); i++)
{
if (list[i] == f)
{
delete f;
list.erase(list.begin() + i);
break;
}
}
}
void TFigureManager::Clear()
{
FreeAll();
lastNum = 0;
}
int TFigureManager::Count()
{
return (int)list.size();
}
TFigure* TFigureManager::FindAt(int px, int py)
{
for (int i = Count() - 1; i >= 0; i--)
if (list[i]->Contains(px, py))
return list[i];
return NULL;
}
void TFigureManager::FindInRect(TRect r, std::vector<TFigure*> &out)
{
out.clear();
for (unsigned i = 0; i < list.size(); i++)
{
TFigure *f = list[i];
if (f->GetX() > r.Right || f->GetX() + f->GetW() < r.Left)
continue;
if (f->GetY() > r.Bottom || f->GetY() + f->GetH() < r.Top)
continue;
out.push_back(f);
}
}
static bool InVector(std::vector<TFigure*> &v, TFigure *f)
{
for (unsigned i = 0; i < v.size(); i++)
if (v[i] == f)
return true;
return false;
}
bool TFigureManager::ToTop(std::vector<TFigure*> &figs)
{
std::vector<TFigure*> others, upper;
for (unsigned i = 0; i < list.size(); i++)
{
if (InVector(figs, list[i]))
upper.push_back(list[i]);
else
others.push_back(list[i]);
}
for (unsigned i = 0; i < upper.size(); i++)
others.push_back(upper[i]);
if (others == list)
return false;
list = others;
return true;
}
bool TFigureManager::Joined(TFigure *a, TFigure *b)
{
for (unsigned i = 0; i < links.size(); i++)
if ((links[i]->from == a && links[i]->to == b) || (links[i]->from == b && links[i]->to == a))
return true;
return false;
}
TFigLink* TFigureManager::JoinTwo(TFigure *a, TFigure *b, TColor color, int width)
{
if (a == b || Joined(a, b))
return NULL;
TFigLink *l = new TFigLink;
l->from = a;
l->to = b;
l->color = color;
l->width = InRange(width, 1, 10);
links.push_back(l);
return l;
}
bool TFigureManager::Join(std::vector<TFigure*> &figs, TColor color, int width)
{
bool any = false;
for (unsigned i = 1; i < figs.size(); i++)
if (JoinTwo(figs[i - 1], figs[i], color, width))
any = true;
return any;
}
bool TFigureManager::Unjoin(std::vector<TFigure*> &figs)
{
bool any = false;
for (int i = (int)links.size() - 1; i >= 0; i--)
{
bool a = InVector(figs, links[i]->from);
bool b = InVector(figs, links[i]->to);
if ((figs.size() == 1 && (a || b)) || (a && b))
{
delete links[i];
links.erase(links.begin() + i);
any = true;
}
}
return any;
}
bool TFigureManager::AnyLinks(std::vector<TFigure*> &figs)
{
for (unsigned i = 0; i < links.size(); i++)
if (InVector(figs, links[i]->from) || InVector(figs, links[i]->to))
return true;
return false;
}
static bool NearSegment(int px, int py, int x1, int y1, int x2, int y2, double tol)
{
double vx = x2 - x1, vy = y2 - y1;
double len2 = vx * vx + vy * vy;
double k = 0;
if (len2 > 0)
k = ((px - x1) * vx + (py - y1) * vy) / len2;
if (k < 0) k = 0;
if (k > 1) k = 1;
double qx = x1 + k * vx - px;
double qy = y1 + k * vy - py;
return sqrt(qx * qx + qy * qy) <= tol;
}
TFigLink* TFigureManager::LinkAt(int px, int py)
{
for (int i = (int)links.size() - 1; i >= 0; i--)
{
TFigLink *l = links[i];
if (NearSegment(px, py,
l->from->GetX() + l->from->GetW() / 2, l->from->GetY() + l->from->GetH() / 2,
l->to->GetX() + l->to->GetW() / 2, l->to->GetY() + l->to->GetH() / 2,
l->width / 2.0 + 4))
return l;
}
return NULL;
}
void TFigureManager::DeleteLink(TFigLink *l)
{
for (unsigned i = 0; i < links.size(); i++)
{
if (links[i] == l)
{
links.erase(links.begin() + i);
delete l;
break;
}
}
}
void TFigureManager::PaintAll(TCanvas *c)
{
c->Pen->Style = psSolid;
for (unsigned i = 0; i < links.size(); i++)
{
TFigLink *l = links[i];
c->Pen->Color = l->color;
c->Pen->Width = l->width;
c->MoveTo(l->from->GetX() + l->from->GetW() / 2, l->from->GetY() + l->from->GetH() / 2);
c->LineTo(l->to->GetX() + l->to->GetW() / 2, l->to->GetY() + l->to->GetH() / 2);
}
for (unsigned i = 0; i < list.size(); i++)
list[i]->Draw(c);
}
void TFigureManager::Save(String fileName)
{
TStringList *sl = new TStringList();
try
{
sl->Add(L"# Фигуры: вид номер X Y ширина высота заливка обводка");
sl->Add(L"# Линии: link номер_откуда номер_куда цвет толщина");
sl->Add(FILE_HEADER);
for (unsigned i = 0; i < list.size(); i++)
{
TFigure *f = list[i];
String s = f->TypeName();
s += " " + IntToStr(f->GetNum());
s += " " + IntToStr(f->GetX());
s += " " + IntToStr(f->GetY());
s += " " + IntToStr(f->GetW());
s += " " + IntToStr(f->GetH());
s += " " + ColorToText(f->GetFill());
s += " " + ColorToText(f->GetLine());
sl->Add(s);
}
for (unsigned i = 0; i < links.size(); i++)
{
TFigLink *l = links[i];
sl->Add("link " + IntToStr(l->from->GetNum()) + " " + IntToStr(l->to->GetNum())
+ " " + ColorToText(l->color) + " " + IntToStr(l->width));
}
sl->SaveToFile(fileName, TEncoding::UTF8);
}
__finally
{
delete sl;
}
}
static TFigure* ByNumber(std::vector<TFigure*> &v, int num)
{
for (unsigned i = 0; i < v.size(); i++)
if (v[i]->GetNum() == num)
return v[i];
return NULL;
}
void TFigureManager::Load(String fileName)
{
std::vector<TFigure*> temp;
std::vector<TFigLink*> tempLinks;
std::vector<int> fromNum, toNum, linkRow;
int maxNum = 0;
TStringList *lines = new TStringList();
TStringList *words = new TStringList();
words->Delimiter = ' ';
words->StrictDelimiter = true;
try
{
lines->LoadFromFile(fileName, TEncoding::UTF8);
bool headerFound = false;
for (int i = 0; i < lines->Count; i++)
{
String line = lines->Strings[i].Trim();
if (line.IsEmpty() || line[1] == '#')
continue;
String pos = L"Строка " + IntToStr(i + 1) + L": ";
if (!headerFound)
{
if (line != FILE_HEADER)
throw Exception(pos + L"нет заголовка \"" + FILE_HEADER + L"\"");
headerFound = true;
continue;
}
words->DelimitedText = line;
if (words->Strings[0] == "link")
{
if (words->Count != 5)
throw Exception(pos + L"у линии должно быть 5 значений: link откуда куда цвет толщина");
int a, b, w;
if (!TryStrToInt(words->Strings[1], a))
throw Exception(pos + L"\"" + words->Strings[1] + L"\" — не целое число");
if (!TryStrToInt(words->Strings[2], b))
throw Exception(pos + L"\"" + words->Strings[2] + L"\" — не целое число");
TFigLink *l = new TFigLink;
l->from = NULL;
l->to = NULL;
tempLinks.push_back(l);
if (!TextToColor(words->Strings[3], l->color))
throw Exception(pos + L"\"" + words->Strings[3] + L"\" — неверный цвет линии (нужно #RRGGBB)");
if (!TryStrToInt(words->Strings[4], w) || w < 1 || w > 10)
throw Exception(pos + L"\"" + words->Strings[4] + L"\" — толщина линии должна быть от 1 до 10");
l->width = w;
fromNum.push_back(a);
toNum.push_back(b);
linkRow.push_back(i + 1);
continue;
}
if (words->Count != 8)
throw Exception(pos + L"должно быть 8 значений, а их " + IntToStr(words->Count));
int n[5];
for (int j = 0; j < 5; j++)
{
String w = words->Strings[j + 1];
if (!TryStrToInt(w, n[j]))
throw Exception(pos + L"\"" + w + L"\" — не целое число");
}
TColor fill, stroke;
if (!TextToColor(words->Strings[6], fill))
throw Exception(pos + L"\"" + words->Strings[6] + L"\" — неверный цвет (нужно #RRGGBB)");
if (!TextToColor(words->Strings[7], stroke))
throw Exception(pos + L"\"" + words->Strings[7] + L"\" — неверный цвет (нужно #RRGGBB)");
if (n[0] <= 0)
throw Exception(pos + L"номер фигуры должен быть больше 0");
if (ByNumber(temp, n[0]))
throw Exception(pos + L"фигура с номером " + IntToStr(n[0]) + L" уже есть");
TFigure *f = MakeFigure(words->Strings[0], n[0]);
if (!f)
throw Exception(pos + L"неизвестный вид фигуры \"" + words->Strings[0] + L"\"");
f->SetBounds(n[1], n[2], n[3], n[4]);
f->SetFill(fill);
f->SetLine(stroke);
temp.push_back(f);
if (n[0] > maxNum)
maxNum = n[0];
}
if (!headerFound)
throw Exception(L"Это не файл фигур: нет заголовка \"" + FILE_HEADER + L"\"");
for (unsigned k = 0; k < tempLinks.size(); k++)
{
String pos = L"Строка " + IntToStr(linkRow[k]) + L": ";
tempLinks[k]->from = ByNumber(temp, fromNum[k]);
tempLinks[k]->to = ByNumber(temp, toNum[k]);
if (!tempLinks[k]->from)
throw Exception(pos + L"нет фигуры с номером " + IntToStr(fromNum[k]));
if (!tempLinks[k]->to)
throw Exception(pos + L"нет фигуры с номером " + IntToStr(toNum[k]));
if (tempLinks[k]->from == tempLinks[k]->to)
throw Exception(pos + L"линия не может соединять фигуру саму с собой");
}
}
catch (...)
{
for (unsigned k = 0; k < tempLinks.size(); k++)
delete tempLinks[k];
for (unsigned k = 0; k < temp.size(); k++)
delete temp[k];
delete lines;
delete words;
throw;
}
delete lines;
delete words;
FreeAll();
list = temp;
links = tempLinks;
lastNum = maxNum;
}