-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBaseGraphControl.cs
More file actions
482 lines (419 loc) · 16.7 KB
/
BaseGraphControl.cs
File metadata and controls
482 lines (419 loc) · 16.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
using System;
using System.Drawing;
using System.Windows.Forms;
namespace WinFormsApp1
{
public abstract class BaseGraphControl : UserControl
{
protected WeightedGraph graph;
protected DoubleBufferedPanel drawPanel;
protected TextBox logTextBox;
protected Panel controlPanel;
protected TextBox txtMatrix;
protected SplitContainer mainSplitter;
protected SplitContainer leftSplitter;
protected SplitContainer rightSplitter;
protected int animationDelay = 500;
protected bool isRunning = false;
protected WeightedGraph.Node selectedNode = null;
// Для перетаскивания
protected WeightedGraph.Node draggingNode = null;
protected bool isDragging = false;
protected Point dragOffset;
private bool isInitialized = false;
protected BaseGraphControl()
{
this.AutoScaleMode = AutoScaleMode.Dpi;
this.BackColor = Color.WhiteSmoke;
this.Dock = DockStyle.Fill;
InitializeBasicLayout();
// Настраиваем сплиттеры после полной загрузки
this.Load += BaseGraphControl_Load;
this.Resize += BaseGraphControl_Resize;
}
private void BaseGraphControl_Load(object sender, EventArgs e)
{
// Откладываем инициализацию до первого показа
if (!isInitialized)
{
BeginInvoke(new Action(() => InitializeSplitters()));
}
}
private void BaseGraphControl_Resize(object sender, EventArgs e)
{
if (!isInitialized && this.Width > 100 && this.Height > 100)
{
InitializeSplitters();
}
}
private void InitializeSplitters()
{
if (isInitialized) return;
if (this.Width < 100 || this.Height < 100) return;
try
{
// Устанавливаем минимальные размеры
mainSplitter.Panel1MinSize = 200;
mainSplitter.Panel2MinSize = 150;
leftSplitter.Panel1MinSize = 100;
leftSplitter.Panel2MinSize = 50;
rightSplitter.Panel1MinSize = 100;
rightSplitter.Panel2MinSize = 50;
// Устанавливаем позиции сплиттеров
int mainDist = (int)(mainSplitter.Width * 0.65);
if (mainDist > mainSplitter.Panel1MinSize &&
mainDist < mainSplitter.Width - mainSplitter.Panel2MinSize)
{
mainSplitter.SplitterDistance = mainDist;
}
int leftDist = (int)(leftSplitter.Height * 0.75);
if (leftDist > leftSplitter.Panel1MinSize &&
leftDist < leftSplitter.Height - leftSplitter.Panel2MinSize)
{
leftSplitter.SplitterDistance = leftDist;
}
int rightDist = (int)(rightSplitter.Height * 0.7);
if (rightDist > rightSplitter.Panel1MinSize &&
rightDist < rightSplitter.Height - rightSplitter.Panel2MinSize)
{
rightSplitter.SplitterDistance = rightDist;
}
isInitialized = true;
}
catch
{
// Игнорируем ошибки инициализации
}
}
private void InitializeBasicLayout()
{
// Создаём сплиттеры БЕЗ установки минимальных размеров и SplitterDistance
mainSplitter = new SplitContainer
{
Dock = DockStyle.Fill,
Orientation = Orientation.Vertical,
SplitterWidth = 6,
BackColor = Color.LightGray,
BorderStyle = BorderStyle.None
};
leftSplitter = new SplitContainer
{
Dock = DockStyle.Fill,
Orientation = Orientation.Horizontal,
SplitterWidth = 6,
BackColor = Color.LightGray,
BorderStyle = BorderStyle.None
};
rightSplitter = new SplitContainer
{
Dock = DockStyle.Fill,
Orientation = Orientation.Horizontal,
SplitterWidth = 6,
BackColor = Color.LightGray,
BorderStyle = BorderStyle.None
};
// Панель рисования
drawPanel = new DoubleBufferedPanel
{
Dock = DockStyle.Fill,
BackColor = Color.White,
BorderStyle = BorderStyle.FixedSingle
};
drawPanel.Paint += DrawPanel_Paint;
drawPanel.MouseDown += DrawPanel_MouseDown;
drawPanel.MouseMove += DrawPanel_MouseMove;
drawPanel.MouseUp += DrawPanel_MouseUp;
drawPanel.Resize += (s, e) => drawPanel.Invalidate();
// Лог
logTextBox = new TextBox
{
Dock = DockStyle.Fill,
Multiline = true,
ScrollBars = ScrollBars.Both,
ReadOnly = true,
Font = new Font("Consolas", 9.5f),
BackColor = Color.FromArgb(250, 250, 250),
BorderStyle = BorderStyle.FixedSingle,
WordWrap = false
};
// Панель управления
controlPanel = new Panel
{
Dock = DockStyle.Fill,
AutoScroll = true,
BackColor = Color.White,
BorderStyle = BorderStyle.FixedSingle,
Padding = new Padding(5)
};
// Матрица
Label lblMatrixTitle = new Label
{
Text = "Матрица смежности:",
Dock = DockStyle.Top,
Height = 22,
Font = new Font("Segoe UI", 9, FontStyle.Bold),
BackColor = Color.WhiteSmoke,
Padding = new Padding(3)
};
txtMatrix = new TextBox
{
Dock = DockStyle.Fill,
Multiline = true,
ScrollBars = ScrollBars.Both,
ReadOnly = true,
Font = new Font("Consolas", 9),
BackColor = Color.FromArgb(250, 250, 250),
BorderStyle = BorderStyle.FixedSingle,
WordWrap = false
};
Panel matrixPanel = new Panel
{
Dock = DockStyle.Fill,
BorderStyle = BorderStyle.None
};
matrixPanel.Controls.Add(txtMatrix);
matrixPanel.Controls.Add(lblMatrixTitle);
// Сборка
leftSplitter.Panel1.Controls.Add(drawPanel);
leftSplitter.Panel2.Controls.Add(logTextBox);
rightSplitter.Panel1.Controls.Add(controlPanel);
rightSplitter.Panel2.Controls.Add(matrixPanel);
mainSplitter.Panel1.Controls.Add(leftSplitter);
mainSplitter.Panel2.Controls.Add(rightSplitter);
this.Controls.Add(mainSplitter);
}
protected abstract void DrawPanel_Paint(object sender, PaintEventArgs e);
protected virtual void DrawPanel_MouseDown(object sender, MouseEventArgs e)
{
if (isRunning) return;
OnMouseDownHandler(e);
}
protected virtual void DrawPanel_MouseMove(object sender, MouseEventArgs e)
{
if (isRunning) return;
if (isDragging && draggingNode != null)
{
int newX = e.X - dragOffset.X;
int newY = e.Y - dragOffset.Y;
int margin = 30;
newX = Math.Max(margin, Math.Min(drawPanel.Width - margin, newX));
newY = Math.Max(margin, Math.Min(drawPanel.Height - margin, newY));
draggingNode.Position = new Point(newX, newY);
RefreshGraph();
drawPanel.Cursor = Cursors.SizeAll;
}
else
{
var node = FindNodeAtPosition(e.Location);
drawPanel.Cursor = node != null ? Cursors.Hand : Cursors.Default;
}
}
protected virtual void DrawPanel_MouseUp(object sender, MouseEventArgs e)
{
if (isDragging && draggingNode != null)
{
Log($"Узел {draggingNode.Id} перемещён в ({draggingNode.Position.X}, {draggingNode.Position.Y})");
isDragging = false;
draggingNode = null;
drawPanel.Cursor = Cursors.Default;
RefreshGraph();
}
}
protected abstract void OnMouseDownHandler(MouseEventArgs e);
protected void StartDragging(WeightedGraph.Node node, Point mousePosition)
{
if (node == null) return;
draggingNode = node;
isDragging = true;
dragOffset = new Point(mousePosition.X - node.Position.X, mousePosition.Y - node.Position.Y);
selectedNode = node;
drawPanel.Cursor = Cursors.SizeAll;
}
protected WeightedGraph.Node FindNodeAtPosition(Point pos)
{
if (graph == null) return null;
foreach (var node in graph.Nodes)
{
double dist = Math.Sqrt(
Math.Pow(pos.X - node.Position.X, 2) +
Math.Pow(pos.Y - node.Position.Y, 2));
if (dist <= 25)
return node;
}
return null;
}
protected void RefreshGraph() => drawPanel.Invalidate();
protected void UpdateMatrix()
{
if (graph != null)
txtMatrix.Text = graph.GetAdjacencyMatrixString();
}
protected void Log(string message)
{
if (logTextBox.InvokeRequired)
{
logTextBox.BeginInvoke(new Action(() => Log(message)));
return;
}
logTextBox.AppendText($"[{DateTime.Now:HH:mm:ss}] {message}\r\n");
logTextBox.SelectionStart = logTextBox.Text.Length;
logTextBox.ScrollToCaret();
}
protected Button CreateButton(string text, Color backColor, EventHandler onClick)
{
var btn = new Button
{
Text = text,
Size = new Size(135, 32),
BackColor = backColor,
FlatStyle = FlatStyle.Flat,
Font = new Font("Segoe UI", 9),
Cursor = Cursors.Hand,
Margin = new Padding(3),
TextAlign = ContentAlignment.MiddleCenter
};
btn.FlatAppearance.BorderSize = 1;
btn.FlatAppearance.BorderColor = Color.Gray;
btn.Click += onClick;
return btn;
}
protected Label CreateLabel(string text, bool isBold = false, int fontSize = 9)
{
return new Label
{
Text = text,
AutoSize = true,
Font = new Font("Segoe UI", fontSize, isBold ? FontStyle.Bold : FontStyle.Regular),
Margin = new Padding(3, 8, 3, 3)
};
}
protected TrackBar CreateSpeedTrackBar(Label lblSpeed)
{
var trackBar = new TrackBar
{
Minimum = 100,
Maximum = 2000,
Value = 500,
TickFrequency = 200,
Size = new Size(260, 45),
Margin = new Padding(3)
};
trackBar.ValueChanged += (s, e) =>
{
animationDelay = trackBar.Value;
lblSpeed.Text = $"Скорость анимации: {animationDelay}мс";
};
return trackBar;
}
protected void SaveGraph()
{
if (graph == null || graph.Nodes.Count == 0)
{
MessageBox.Show("Нет графа для сохранения!", "Предупреждение",
MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
using (SaveFileDialog sfd = new SaveFileDialog())
{
sfd.Filter = "Graph files (*.graph)|*.graph|CSV files (*.csv)|*.csv|All files (*.*)|*.*";
sfd.DefaultExt = "graph";
if (sfd.ShowDialog() == DialogResult.OK)
{
try
{
if (sfd.FileName.EndsWith(".csv", StringComparison.OrdinalIgnoreCase))
graph.SaveToCsv(sfd.FileName);
else
graph.SaveToFile(sfd.FileName);
Log($"Граф сохранён: {sfd.FileName}");
}
catch (Exception ex)
{
MessageBox.Show($"Ошибка сохранения: {ex.Message}", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
protected void LoadGraph()
{
using (OpenFileDialog ofd = new OpenFileDialog())
{
ofd.Filter = "Graph files (*.graph)|*.graph|CSV files (*.csv)|*.csv|All files (*.*)|*.*";
if (ofd.ShowDialog() == DialogResult.OK)
{
try
{
if (ofd.FileName.EndsWith(".csv", StringComparison.OrdinalIgnoreCase))
graph = WeightedGraph.LoadFromCsv(ofd.FileName);
else
graph = WeightedGraph.LoadFromFile(ofd.FileName);
if (drawPanel.Width > 100 && drawPanel.Height > 100)
graph.AdjustPositions(drawPanel.Width, drawPanel.Height);
Log($"Граф загружен: {ofd.FileName}");
UpdateMatrix();
RefreshGraph();
OnGraphLoaded();
}
catch (Exception ex)
{
MessageBox.Show($"Ошибка загрузки: {ex.Message}", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
protected virtual void OnGraphLoaded() { }
protected string ShowInputDialog(string prompt, string title, string defaultValue)
{
Form inputForm = new Form
{
Width = 320,
Height = 160,
Text = title,
StartPosition = FormStartPosition.CenterParent,
FormBorderStyle = FormBorderStyle.FixedDialog,
MaximizeBox = false,
MinimizeBox = false
};
Label label = new Label
{
Left = 15,
Top = 15,
Width = 270,
Text = prompt,
Font = new Font("Segoe UI", 9)
};
TextBox textBox = new TextBox
{
Left = 15,
Top = 45,
Width = 270,
Text = defaultValue,
Font = new Font("Segoe UI", 10)
};
Button okButton = new Button
{
Text = "OK",
Left = 120,
Top = 85,
Width = 80,
Height = 28,
DialogResult = DialogResult.OK
};
Button cancelButton = new Button
{
Text = "Отмена",
Left = 205,
Top = 85,
Width = 80,
Height = 28,
DialogResult = DialogResult.Cancel
};
inputForm.Controls.AddRange(new Control[] { label, textBox, okButton, cancelButton });
inputForm.AcceptButton = okButton;
inputForm.CancelButton = cancelButton;
return inputForm.ShowDialog() == DialogResult.OK ? textBox.Text : null;
}
}
}