#include #pragma hdrstop #include #include "ShapesUnit.h" #include "BoundsUnit.h" #pragma package(smart_init) #pragma resource "*.dfm" TfrmShapes *frmShapes; const int FIG_W = 110; // размер новой фигуры const int FIG_H = 90; const int GRIP = 5; // на сколько пикселей можно промахнуться мимо рамки // палитра из 8 цветов для новых фигур const TColor COLORS[8] = { (TColor)RGB(239, 83, 80), // красный (TColor)RGB(255, 167, 38), // оранжевый (TColor)RGB(255, 238, 88), // жёлтый (TColor)RGB(102, 187, 106), // зелёный (TColor)RGB(38, 198, 218), // бирюзовый (TColor)RGB(66, 103, 178), // синий (TColor)RGB(126, 87, 194), // фиолетовый (TColor)RGB(141, 110, 99) // коричневый }; __fastcall TfrmShapes::TfrmShapes(TComponent* Owner) : TForm(Owner) { } void __fastcall TfrmShapes::FormCreate(TObject *Sender) { Randomize(); figures = new TFigureManager(); current = NULL; fileName = ""; changed = false; action = actNone; // подсказка на кнопках появляется через 1 секунду Application->HintPause = 1000; Application->HintShortPause = 1000; DrawIcons(); UpdateView(); } void __fastcall TfrmShapes::FormDestroy(TObject *Sender) { delete figures; } // значки для кнопок панели рисуем прямо в программе void TfrmShapes::DrawIcons() { for (int i = 0; i < 3; i++) { Vcl::Graphics::TBitmap *bmp = new Vcl::Graphics::TBitmap(); bmp->SetSize(24, 24); TCanvas *c = bmp->Canvas; c->Brush->Color = clFuchsia; // прозрачный цвет c->FillRect(Rect(0, 0, 24, 24)); c->Pen->Color = (TColor)RGB(40, 40, 40); c->Pen->Width = 2; c->Brush->Color = COLORS[i * 2 + 1]; if (i == 0) { TPoint p[3] = { TPoint(12, 3), TPoint(21, 20), TPoint(3, 20) }; c->Polygon(p, 2); } if (i == 1) c->Rectangle(3, 5, 22, 20); if (i == 2) c->Ellipse(2, 5, 23, 20); imgShapes->AddMasked(bmp, clFuchsia); delete bmp; } } void TfrmShapes::MarkChanged() { changed = true; UpdateView(); } // заголовок окна, строка состояния и перерисовка поля void TfrmShapes::UpdateView() { String name = L"Без имени"; if (fileName != "") name = ExtractFileName(fileName); String star = ""; if (changed) star = " *"; Caption = L"Фигуры - " + name + star; sbInfo->Panels->Items[0]->Text = L"Фигур: " + IntToStr(figures->Count()); if (current) sbInfo->Panels->Items[1]->Text = L"Выбрана: " + current->RusName() + L" №" + IntToStr(current->GetNum()); else sbInfo->Panels->Items[1]->Text = L"Ничего не выбрано"; pbField->Invalidate(); } void TfrmShapes::Select(TFigure *f) { current = f; if (current && figures->ToTop(current)) changed = true; // порядок наложения тоже сохраняется в файл UpdateView(); } void TfrmShapes::NewFigure(String type) { int maxX = pbField->Width - FIG_W; int maxY = pbField->Height - FIG_H; if (maxX < 1) maxX = 1; if (maxY < 1) maxY = 1; TColor color = COLORS[Random(8)]; current = figures->Add(type, Random(maxX), Random(maxY), FIG_W, FIG_H, color, clBlack); MarkChanged(); } void TfrmShapes::DeleteCurrent() { if (!current) return; figures->Delete(current); current = NULL; MarkChanged(); } // ---------- рисование ---------- void __fastcall TfrmShapes::pbFieldPaint(TObject *Sender) { TCanvas *c = pbField->Canvas; c->Brush->Style = bsSolid; c->Brush->Color = clWhite; c->FillRect(pbField->ClientRect); figures->PaintAll(c); if (current) PaintFrame(c); } // пунктирная рамка и 8 маркеров вокруг выбранной фигуры void TfrmShapes::PaintFrame(TCanvas *c) { int l = current->GetX() - 2; int t = current->GetY() - 2; int r = current->GetX() + current->GetW() + 2; int b = current->GetY() + current->GetH() + 2; int mx = (l + r) / 2; int my = (t + b) / 2; c->Brush->Style = bsClear; c->Pen->Width = 1; c->Pen->Style = psDot; c->Pen->Color = (TColor)RGB(30, 90, 200); c->Rectangle(l, t, r + 1, b + 1); c->Pen->Style = psSolid; c->Brush->Style = bsSolid; c->Brush->Color = (TColor)RGB(30, 90, 200); TPoint marks[8] = { TPoint(l, t), TPoint(mx, t), TPoint(r, t), TPoint(r, my), TPoint(r, b), TPoint(mx, b), TPoint(l, b), TPoint(l, my) }; for (int i = 0; i < 8; i++) c->Rectangle(marks[i].x - 3, marks[i].y - 3, marks[i].x + 4, marks[i].y + 4); } // ---------- мышь ---------- // попала ли мышь на рамку выбранной фигуры и на какие стороны bool TfrmShapes::HitFrame(int px, int py, bool &l, bool &r, bool &t, bool &b) { l = r = t = b = false; if (!current) return false; int x1 = current->GetX(); int y1 = current->GetY(); int x2 = x1 + current->GetW(); int y2 = y1 + current->GetH(); if (px < x1 - GRIP || px > x2 + GRIP || py < y1 - GRIP || py > y2 + GRIP) return false; l = abs(px - x1) <= GRIP; r = !l && abs(px - x2) <= GRIP; t = abs(py - y1) <= GRIP; b = !t && abs(py - y2) <= GRIP; return l || r || t || b; } void __fastcall TfrmShapes::pbFieldMouseDown(TObject *Sender, TMouseButton Button, TShiftState Shift, int X, int Y) { startX = X; startY = Y; if (Button == mbLeft) { if (HitFrame(X, Y, sizeL, sizeR, sizeT, sizeB)) action = actResize; else { Select(figures->FindAt(X, Y)); if (current) action = actMove; } if (current) startRect = Rect(current->GetX(), current->GetY(), current->GetX() + current->GetW(), current->GetY() + current->GetH()); } if (Button == mbRight) { Select(figures->FindAt(X, Y)); if (!current) return; pmiCaption->Caption = current->RusName() + L" №" + IntToStr(current->GetNum()); TPoint p = pbField->ClientToScreen(TPoint(X, Y)); pmFigure->Popup(p.x, p.y); } } void __fastcall TfrmShapes::pbFieldMouseMove(TObject *Sender, TShiftState Shift, int X, int Y) { int dx = X - startX; int dy = Y - startY; if (action == actMove) { // фигура сдвигается на столько же, на сколько мышь - без рывка current->MoveTo(startRect.Left + dx, startRect.Top + dy); MarkChanged(); return; } if (action == actResize) { int l = startRect.Left; int t = startRect.Top; int w = startRect.Width(); int h = startRect.Height(); if (sizeR) w = InRange(w + dx, SIDE_MIN, SIDE_MAX); if (sizeB) h = InRange(h + dy, SIDE_MIN, SIDE_MAX); if (sizeL) { w = InRange(w - dx, SIDE_MIN, SIDE_MAX); l = startRect.Right - w; // правая сторона стоит на месте } if (sizeT) { h = InRange(h - dy, SIDE_MIN, SIDE_MAX); t = startRect.Bottom - h; // нижняя сторона стоит на месте } current->SetBounds(l, t, w, h); MarkChanged(); return; } // просто водим мышью - меняем курсор bool l, r, t, b; TCursor cur = crDefault; if (HitFrame(X, Y, l, r, t, b)) { if ((l && t) || (r && b)) cur = crSizeNWSE; else if ((r && t) || (l && b)) cur = crSizeNESW; else if (l || r) cur = crSizeWE; else cur = crSizeNS; } else if (figures->FindAt(X, Y)) cur = crHandPoint; pbField->Cursor = cur; } void __fastcall TfrmShapes::pbFieldMouseUp(TObject *Sender, TMouseButton Button, TShiftState Shift, int X, int Y) { action = actNone; } // ---------- клавиши и кнопки ---------- void __fastcall TfrmShapes::FormKeyDown(TObject *Sender, WORD &Key, TShiftState Shift) { switch (Key) { case '1': case VK_NUMPAD1: NewFigure("triangle"); break; case '2': case VK_NUMPAD2: NewFigure("rectangle"); break; case '3': case VK_NUMPAD3: NewFigure("ellipse"); break; case VK_DELETE: DeleteCurrent(); break; case VK_F1: mnuHelpClick(NULL); break; default: return; } Key = 0; } void __fastcall TfrmShapes::btnTriangleClick(TObject *Sender) { NewFigure("triangle"); } void __fastcall TfrmShapes::btnRectangleClick(TObject *Sender) { NewFigure("rectangle"); } void __fastcall TfrmShapes::btnEllipseClick(TObject *Sender) { NewFigure("ellipse"); } // ---------- меню фигуры ---------- void __fastcall TfrmShapes::pmiBoundsClick(TObject *Sender) { if (current && frmBounds->Edit(current)) MarkChanged(); } // стандартный диалог цвета, в нём сразу стоит текущий цвет bool TfrmShapes::PickColor(TColor &c) { dlgColor->Color = c; if (!dlgColor->Execute()) return false; c = dlgColor->Color; return true; } void __fastcall TfrmShapes::pmiFillClick(TObject *Sender) { if (!current) return; TColor c = current->GetFill(); if (PickColor(c)) { current->SetFill(c); MarkChanged(); } } void __fastcall TfrmShapes::pmiLineClick(TObject *Sender) { if (!current) return; TColor c = current->GetLine(); if (PickColor(c)) { current->SetLine(c); MarkChanged(); } } void __fastcall TfrmShapes::pmiDeleteClick(TObject *Sender) { DeleteCurrent(); } // ---------- файлы ---------- // вопрос "Сохранить изменения?" с кнопками Да / Нет / Отмена // возвращает true, если можно продолжать (сохранили или отказались) bool TfrmShapes::ConfirmSave() { if (!changed) return true; TForm *dlg = CreateMessageDialog(L"Сохранить изменения?", mtConfirmation, TMsgDlgButtons() << mbYes << mbNo << mbCancel); dlg->Caption = L"Фигуры"; for (int i = 0; i < dlg->ComponentCount; i++) { TButton *btn = dynamic_cast(dlg->Components[i]); if (!btn) continue; if (btn->ModalResult == mrYes) btn->Caption = L"Да"; if (btn->ModalResult == mrNo) btn->Caption = L"Нет"; if (btn->ModalResult == mrCancel) btn->Caption = L"Отмена"; } int res = dlg->ShowModal(); delete dlg; if (res == mrYes) return Save(); if (res == mrNo) return true; return false; } bool TfrmShapes::SaveFile(String name) { try { figures->Save(name); } catch (Exception &e) { Application->MessageBox((L"Не удалось сохранить файл.\n" + e.Message).c_str(), L"Ошибка", MB_OK | MB_ICONERROR); return false; } fileName = name; changed = false; UpdateView(); return true; } bool TfrmShapes::Save() { if (fileName == "") return SaveAs(); return SaveFile(fileName); } bool TfrmShapes::SaveAs() { dlgSave->FileName = fileName; if (dlgSave->Execute()) return SaveFile(dlgSave->FileName); return false; } void __fastcall TfrmShapes::mnuNewClick(TObject *Sender) { if (!ConfirmSave()) return; figures->Clear(); current = NULL; fileName = ""; changed = false; UpdateView(); } void __fastcall TfrmShapes::mnuOpenClick(TObject *Sender) { if (!ConfirmSave()) return; if (!dlgOpen->Execute()) return; try { figures->Load(dlgOpen->FileName); } catch (Exception &e) { // фигуры на поле остаются как были Application->MessageBox(e.Message.c_str(), L"Не удалось открыть файл", MB_OK | MB_ICONWARNING); return; } current = NULL; fileName = dlgOpen->FileName; changed = false; UpdateView(); } void __fastcall TfrmShapes::mnuSaveClick(TObject *Sender) { Save(); } void __fastcall TfrmShapes::mnuSaveAsClick(TObject *Sender) { SaveAs(); } void __fastcall TfrmShapes::mnuExitClick(TObject *Sender) { Close(); } void __fastcall TfrmShapes::FormCloseQuery(TObject *Sender, bool &CanClose) { CanClose = ConfirmSave(); } void __fastcall TfrmShapes::mnuHelpClick(TObject *Sender) { String s; s += L"ДОБАВЛЕНИЕ ФИГУР\n"; s += L"Кнопки на панели или клавиши:\n"; s += L" 1 - треугольник, 2 - прямоугольник, 3 - эллипс.\n\n"; s += L"МЫШЬ\n"; s += L" ЛКМ по фигуре - выбрать её (она поднимется наверх).\n"; s += L" ЛКМ по пустому месту - снять выбор.\n"; s += L" Тянуть фигуру - передвинуть.\n"; s += L" Тянуть за сторону или угол рамки - изменить размер (20...1000).\n"; s += L" ПКМ по фигуре - меню фигуры.\n\n"; s += L"МЕНЮ ФИГУРЫ\n"; s += L" Положение и размер, цвет заливки, цвет обводки, удалить.\n"; s += L" Del - удалить выбранную фигуру.\n\n"; s += L"ФАЙЛЫ (*.fig)\n"; s += L" Ctrl+N - создать, Ctrl+O - открыть,\n"; s += L" Ctrl+S - сохранить, Ctrl+Shift+S - сохранить как.\n\n"; s += L"F1 - эта справка."; Application->MessageBox(s.c_str(), L"Справка - Фигуры", MB_OK | MB_ICONINFORMATION); }