Создание программы-интерпретатора блок-схем
Аналитический обзор существующих программ-редакторов схем (Microsoft Office Visio 2007, FCEditor, редактор блок-схем). Математическое описание программы и её интерпретатора. Описание системы и руководство пользователя, XML и текст редактора схем.
Рубрика | Программирование, компьютеры и кибернетика |
Вид | дипломная работа |
Язык | русский |
Дата добавления | 07.07.2012 |
Размер файла | 2,1 M |
Отправить свою хорошую работу в базу знаний просто. Используйте форму, расположенную ниже
Студенты, аспиранты, молодые ученые, использующие базу знаний в своей учебе и работе, будут вам очень благодарны.
marginRight = 16;
}
else if (this is LoopBlock)
{
marginTop = 80;
marginBottom = 80;
}
width = marginLeft + clientWidth + marginRight;
height = marginTop + clientHeight + marginBottom;
}
}
public void AdjustPosition(int ox, int oy)
{
X = ox;
Y = oy;
if (this is Branch)
{
int cy = Y;
foreach (Block item in Items)
{
item.AdjustPosition(ox + (width - item.width) / 2, cy);
cy += item.height;
}
}
else
{
int cx = X + marginLeft;
foreach (Block item in Items)
{
item.AdjustPosition(cx, Y + marginTop);
cx += item.width;
}
}
}
/// <summary>
/// Если открыть блок из файла, то информация о том какой ветке принадлежит каждый блок теряется
/// Метод устанавливает для каждого блока какой ветке он принадлежит
/// </summary>
public void SetBranches(Block branch)
{
this.Branch = branch;
if (this is RegularBLock)
return;
foreach (Block block in Items)
{
block.SetBranches(this);
}
}
public abstract void Draw(Graphics g);
}
}
2) RegularBlock.cs
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
namespace flowchart.blocks
{
[Serializable]
public class RegularBLock : Block
{
public RegularBLock() { }
public RegularBLock(string text) : base(text) { }
public override void Draw(Graphics g)
{
int containerCenter = X + width / 2;
Pen pen = isSelected ? new Pen(Color.Firebrick, 3) : new Pen(Color.Black, 1);
pen.EndCap = LineCap.ArrowAnchor;
g.DrawLine(pen, containerCenter, Y, containerCenter, Y + dy);
pen.EndCap = LineCap.NoAnchor;
g.DrawRectangle(pen, containerCenter - w/2, Y + dy, w, h);
Rectangle r = new Rectangle(containerCenter - w / 2, Y + dy, w, h);
g.DrawString(Text, drawFont, drawBrush, r, strFormat);
g.DrawLine(pen, containerCenter, Y + height - dy, containerCenter, Y + height);
}
}
}
3) Branch.cs
using System;
using System.Drawing;
namespace flowchart.blocks
{
[Serializable]
public class Branch : Block
{
public Branch() { }
public Branch(string text): base(text) { }
public override void Draw(Graphics g)
{
Pen pen = isSelected ? new Pen(Color.Firebrick, 3) : new Pen(Color.Black, 1);
int containerCenter = X + width / 2;
g.DrawLine(pen, containerCenter, Y, containerCenter, Y + dy);
return;
}
}
}
4) ChartMainBlock.cs
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Xml.Serialization;
namespace flowchart.blocks
{
[Serializable]
public class ChartMainBlock : Block
{
public ChartMainBlock() { }
public ChartMainBlock(string text) : base(text) { }
public override bool PointInsideBlock(int x, int y)
{
int blockX = X + width / 2 - w / 2;
int blockY = Y - dy;
return ((x > blockX && x < blockX + w) && (y > blockY && y < blockY + h));
}
public override void Draw(Graphics g)
{
//центр контейнера
int containerCenter = X + width / 2;
//центр контейнера минус половина ширины блока
int dx = X + width/2 - w/2;
Pen pen = isSelected ? new Pen(Color.Firebrick, 3) : new Pen(Color.Black, 1);
g.DrawLine(pen, dx + h / 2, Y - dy, dx + w - h / 2, Y - dy);
g.DrawLine(pen, dx + h / 2, Y + h - dy, dx + w - h / 2, Y + h - dy);
g.DrawArc(pen, dx, Y - dy, h, h, 90, 180);
g.DrawArc(pen, dx + w - h, Y - dy, h, h, 270, 180);
g.DrawLine(pen, containerCenter, Y + h - dy, containerCenter, Y + h);
Rectangle r = new Rectangle(dx, Y - dy, w, h);
g.DrawString("begin", drawFont, drawBrush, r, strFormat);
//блок в конце схемы
int downy = Y + height;
g.DrawLine(pen, dx + h / 2, downy, dx + w - h / 2, downy);
g.DrawLine(pen, dx + h / 2, downy + h, dx + w - h / 2, downy + h);
g.DrawArc(pen, dx, downy, h, h, 90, 180);
g.DrawArc(pen, dx + w - h, downy, h, h, 270, 180);
r = new Rectangle(dx, downy, w, h);
g.DrawString("end", drawFont, drawBrush, r, strFormat);
pen.EndCap = LineCap.ArrowAnchor;
g.DrawLine(pen, containerCenter, Y + height - dy, containerCenter, Y + height);
pen.EndCap = LineCap.NoAnchor;
}
public void SaveToXml(string path)
{
FileStream fStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None);
XmlSerializer xmlFormat = new XmlSerializer(
typeof(ChartMainBlock),
new Type[]
{
typeof (Block),
typeof (ConditionBlock),
typeof (RegularBLock),
typeof (Branch),
typeof (LoopBlock),
typeof (ChartMainBlock),
typeof (List<Block>),
typeof (List<ConditionBlock>),
typeof (List<RegularBLock>),
typeof (List<Branch>),
typeof (List<LoopBlock>),
typeof (List<ChartMainBlock>),
}
);
xmlFormat.Serialize(fStream, this);
fStream.Close();
}
}
}
5) ConditionBLock.cs
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
namespace flowchart.blocks
{
[Serializable]
public class ConditionBlock : Block
{
public ConditionBlock() { }
public ConditionBlock(string text) : base(text) { }
public override void Draw(Graphics g)
{
//центр контейнера
int containerCenter = X + width / 2;
//центр контейнера минус половина ширины блока
int dx = containerCenter - w / 2;
Pen pen = isSelected ? new Pen(Color.Firebrick, 3) : new Pen(Color.Black, 1);
//верхняя линия
pen.EndCap = LineCap.ArrowAnchor;
g.DrawLine(pen, containerCenter, Y, containerCenter, Y + dy);
pen.EndCap = LineCap.NoAnchor;
//сам блок в виде ромба
Point[] points = new Point[]
{
new Point(dx + w / 2, Y + dy),
new Point(dx + w, Y + h / 2 + dy),
new Point(dx + w / 2, Y + h + dy),
new Point(dx, Y + h / 2 + dy),
new Point(dx + w / 2, Y + dy),
};
g.DrawCurve(pen, points, 0);
Rectangle r = new Rectangle(dx, Y + dy, w, h);
g.DrawString(Text, drawFont, drawBrush, r, strFormat);
//подпись да
r = new Rectangle(dx - w/2, Y + dy, w/2, h/2);
g.DrawString("да", drawFont, drawBrush, r, strFormat);
//подпись нет
r = new Rectangle(dx + w , Y + dy, w / 2, h / 2);
g.DrawString("нет", drawFont, drawBrush, r, strFormat);
Block left = Items[0];
Block right = Items[1];
//левая линия
points = new Point[]
{
new Point(containerCenter - w / 2, Y + dy + h/2),
new Point(left.X + left.width/2, Y + dy + h/2),
new Point(left.X + left.width/2, left.Y),
};
g.DrawCurve(pen, points, 0);
//правая линия
points = new Point[]
{
new Point(containerCenter + w/2, Y + dy + h/2),
new Point(right.X + right.width/2, Y + dy + h/2),
new Point(right.X + right.width/2, right.Y),
};
g.DrawCurve(pen, points, 0);
//нижняя часть
points = new Point[]
{
new Point(left.X + left.width/2, left.Y + left.height),
new Point(left.X + left.width/2, Y + height - 20),
new Point(right.X + right.width/2, Y + height - 20),
new Point(right.X + right.width/2, right.Y + right.height),
};
g.DrawCurve(pen, points, 0);
g.DrawLine(pen, containerCenter, Y + height - 20, containerCenter, Y + height);
}
}
}
6) LoopBlock.cs
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
namespace flowchart.blocks
{
[Serializable]
public class LoopBlock : Block
{
public LoopBlock() { }
public LoopBlock(string text) : base(text) { }
public override void Draw(Graphics g)
{
int containerCenter = X + width / 2;
int dx = containerCenter - w / 2;
Pen pen = isSelected ? new Pen(Color.Firebrick, 3) : new Pen(Color.Black, 1);
pen.EndCap = LineCap.ArrowAnchor;
g.DrawLine(pen, containerCenter, Y, containerCenter, Y + dy);
pen.EndCap = LineCap.NoAnchor;
//начало цикла
Point[] points = new Point[]
{
new Point(dx + h / 3, Y + dy),
new Point(dx + w - h/3, Y + dy),
new Point(dx + w, Y + dy + h/3),
new Point(dx + w, Y + h + dy),
new Point(dx , Y + h + dy),
new Point(dx, Y + dy + h/3),
new Point(dx + h / 3, Y + dy),
};
g.DrawCurve(pen, points, 0);
g.DrawLine(pen, containerCenter, Y + h + dy*2, containerCenter, Y + h + dy);
Rectangle r = new Rectangle(containerCenter - w / 2, Y + dy, w, h);
g.DrawString(Text, drawFont, drawBrush, r, strFormat);
//смещение к низу контейнера
int delta = height - h - 35;
pen.EndCap = LineCap.ArrowAnchor;
g.DrawLine(pen, containerCenter, Y + delta, containerCenter, Y + dy + delta);
pen.EndCap = LineCap.NoAnchor;
//конец цикла
points = new Point[]
{
new Point(dx, Y + dy + delta),
new Point(dx + w, Y + dy+ delta),
new Point(dx + w, Y + dy + h - h/3+ delta),
new Point(dx + w - h/3, Y + h + dy+ delta),
new Point(dx + h/3, Y + h + dy+ delta),
new Point(dx, Y + dy + h - h/3+ delta),
new Point(dx, Y + dy + delta),
};
g.DrawCurve(pen, points, 0);
r = new Rectangle(containerCenter - w / 2, Y + dy + delta, w, h);
g.DrawString(TextAtTheEnd, drawFont, drawBrush, r, strFormat);
g.DrawLine(pen, containerCenter, Y + h + dy + delta, containerCenter, Y + h + dy*2 + delta);
}
}
}
7) MainForm.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;
using System.Xml.Serialization;
using Jint;
using flowchart.blocks;
namespace flowchart
{
public partial class MainForm : Form
{
private WorkAreaForm workAreaForm;
SaveFileDialog saveFileDialog = new SaveFileDialog { Filter = "xml files (*.xml)|*.xml|All files (*.*)|*.*" };
OpenFileDialog openFileDialog = new OpenFileDialog { Filter = "xml files (*.xml)|*.xml|All files (*.*)|*.*" };
private string filePath = String.Empty;
public MainForm()
{
InitializeComponent();
workAreaForm = new WorkAreaForm(codeTextBox);
workAreaForm.MdiParent = this;
workAreaForm.Clear();
workAreaForm.Show();
workAreaForm.Chart = new Chart();
workAreaForm.DrawChart();
codeTextBox.Text = workAreaForm.Chart.GetCode();
panel1.Height = ClientSize.Height;
panel1.Left = 0;
panel1.Top = menuStrip1.Height + 1;
codePanel.Height = ClientSize.Height - menuStrip1.Height;
codePanel.Left = ClientSize.Width - codePanel.Width;
codePanel.Top = menuStrip1.Height + 1;
codeTextBox.Left = 0;
codeTextBox.Width = codePanel.Width;
codeTextBox.Height = codePanel.Height- 200;
codeResultTextBox.Height = 130;
codeResultTextBox.Width = codePanel.Width;
codeResultTextBox.Left = 0;
codeResultTextBox.Top = codePanel.Top + codeTextBox.Height + 40;
label4.Top = codeResultTextBox.Top - 25;
}
private void button1_Click(object sender, EventArgs e)
{
workAreaForm.Insertion = true;
workAreaForm.BlockType = 1;
workAreaForm.UpdateChart(true);
}
private void button2_Click(object sender, EventArgs e)
{
workAreaForm.Insertion = true;
workAreaForm.BlockType = 2;
workAreaForm.UpdateChart(true);
}
private void loopButton_Click(object sender, EventArgs e)
{
workAreaForm.Insertion = true;
workAreaForm.BlockType = 3;
workAreaForm.UpdateChart(true);
}
private void deleteButton_Click(object sender, EventArgs e)
{
workAreaForm.DeleteBLock();
}
private void MainForm_Resize(object sender, EventArgs e)
{
panel1.Height = ClientSize.Height - menuStrip1.Height;
codePanel.Height = ClientSize.Height - menuStrip1.Height;
codePanel.Left = ClientSize.Width - codePanel.Width;
codeTextBox.Height = codePanel.Height - 200;
codeResultTextBox.Top = codePanel.Top + codeTextBox.Height + 40;
label4.Top = codeResultTextBox.Top - 25;
}
private void button3_Click(object sender, EventArgs e)
{
workAreaForm.ClearChart();
}
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (filePath != String.Empty)
{
workAreaForm.Chart.root.SaveToXml(filePath);
return;
}
string fileName = String.Empty;
if (saveFileDialog.ShowDialog() == DialogResult.OK)
fileName = saveFileDialog.FileName;
if (fileName == String.Empty)
return;
workAreaForm.Chart.root.SaveToXml(fileName);
filePath = fileName;
workAreaForm.Text = fileName;
}
private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
{
string fileName = String.Empty;
if (saveFileDialog.ShowDialog() == DialogResult.OK)
fileName = saveFileDialog.FileName;
if (fileName == String.Empty)
return;
workAreaForm.Chart.root.SaveToXml(fileName);
filePath = fileName;
workAreaForm.Text = fileName;
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Close();
}
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
string fileName = String.Empty;
if (openFileDialog.ShowDialog() == DialogResult.OK)
fileName = openFileDialog.FileName;
if (fileName == String.Empty)
return;
FileStream fStream = File.OpenRead(fileName);
XmlSerializer xmlFormat = new XmlSerializer(
typeof (ChartMainBlock),
new Type[]
{
typeof (Block),
typeof (ConditionBlock),
typeof (RegularBLock),
typeof (Branch),
typeof (LoopBlock),
typeof (ChartMainBlock),
typeof (List<Block>),
typeof (List<ConditionBlock>),
typeof (List<RegularBLock>),
typeof (List<Branch>),
typeof (List<LoopBlock>),
typeof (List<ChartMainBlock>),
}
);
ChartMainBlock rootBlockFromFile;
try
{
rootBlockFromFile = (ChartMainBlock)xmlFormat.Deserialize(fStream);
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при попытке открыть файл");
fStream.Close();
return;
}
fStream.Close();
filePath = fileName;
workAreaForm.Text = filePath;
rootBlockFromFile.Items[0].SetBranches(rootBlockFromFile);
workAreaForm.Chart.root = rootBlockFromFile;
workAreaForm.Chart.codeGen = new CodeGenerator(rootBlockFromFile);
workAreaForm.Chart.RealignBlocks();
workAreaForm.Chart.RegenerateInsertionPoints();
workAreaForm.Chart.UpdateAllBlocksList();
workAreaForm.UpdateChart();
workAreaForm.UpdateCode();
}
private void newChartToolStripMenuItem_Click(object sender, EventArgs e)
{
workAreaForm.ClearChart();
filePath = String.Empty;
workAreaForm.Text = "Новая схема";
}
private void executeToolStripMenuItem_Click(object sender, EventArgs e)
{
string script = @codeTextBox.Text;
JsCodeInterpreter engine = new JsCodeInterpreter(codeResultTextBox);
try
{
engine.RunScript(script);
}
catch (JintException ex)
{
MessageBox.Show(ex.Message, "Ошибка при выполнении программы");
}
}
}
}
8) WorkAreaForm.cs
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
using flowchart.blocks;
namespace flowchart
{
public partial class WorkAreaForm : Form
{
private Bitmap _picture;
private Graphics g;
private TextBox codeTextBox;
public Chart Chart;
private BlockProreptiesEditor blockProreptiesEditorForm;
public bool Insertion = false;
public int BlockType = 0;
public WorkAreaForm(TextBox textBox)
{
codeTextBox = textBox;
InitializeComponent();
panel1.Width = ClientSize.Width;
panel1.Height = ClientSize.Height;
panel1.Top = panel1.Left = 0;
_picture = new Bitmap(ClientSize.Width, ClientSize.Height);
workAreaFormPictureBox.Image = _picture;
workAreaFormPictureBox.Width = ClientSize.Width;
workAreaFormPictureBox.Height = ClientSize.Height;
workAreaFormPictureBox.Top = workAreaFormPictureBox.Left = 0;
g = Graphics.FromImage(workAreaFormPictureBox.Image);
g.SmoothingMode = SmoothingMode.AntiAlias;
}
private void WorkAreaForm_Load(object sender, System.EventArgs e)
{
Location = new Point(95, 0);
}
private void workAreaFormPictureBox_MouseClick(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
Insertion = false;
UpdateChart();
BlockType = 0;
Cursor = Cursors.Arrow;
return;
}
if (Insertion)
{
Chart.ProcessMouseClickInsertion(e.X, e.Y, BlockType);
UpdateChart();
Insertion = false;
BlockType = 0;
codeTextBox.Text = Chart.GetCode();
Cursor = Cursors.Arrow;
}
else
{
Chart.ProcessMouseClickBlockSelection(e.X, e.Y);
UpdateChart();
}
}
public void UpdateChart(bool insertion = false)
{
if (Chart.width > ClientSize.Width)
{
workAreaFormPictureBox.Width = Chart.width;
_picture = new Bitmap(Chart.width, ClientSize.Height);
workAreaFormPictureBox.Image = _picture;
g = Graphics.FromImage(workAreaFormPictureBox.Image);
g.SmoothingMode = SmoothingMode.AntiAlias;
}
else if (Chart.height > ClientSize.Height)
{
workAreaFormPictureBox.Height = Chart.height;
_picture = new Bitmap(ClientSize.Width, Chart.height);
workAreaFormPictureBox.Image = _picture;
g = Graphics.FromImage(workAreaFormPictureBox.Image);
g.SmoothingMode = SmoothingMode.AntiAlias;
}
Clear();
DrawChart(insertion);
}
public void UpdateCode()
{
codeTextBox.Text = Chart.GetCode();
}
public void DrawChart(bool insertion = false)
{
Chart.Draw(g, insertion);
workAreaFormPictureBox.Refresh();
}
public void Clear()
{
g.Clear(Color.White);
}
private void WorkAreaForm_Resize(object sender, System.EventArgs e)
{
panel1.Width = ClientSize.Width;
panel1.Height = ClientSize.Height;
if (workAreaFormPictureBox.Width < panel1.Width || workAreaFormPictureBox.Height < panel1.Height)
{
workAreaFormPictureBox.Width = panel1.Width;
workAreaFormPictureBox.Height = panel1.Height;
_picture = new Bitmap(panel1.Width, panel1.Height);
workAreaFormPictureBox.Image = _picture;
g = Graphics.FromImage(workAreaFormPictureBox.Image);
g.SmoothingMode = SmoothingMode.AntiAlias;
UpdateChart();
}
}
private void workAreaFormPictureBox_MouseMove(object sender, MouseEventArgs e)
{
if (!Insertion)
return;
bool movementResult = Chart.ProcessMouseMove(e.X, e.Y);
Cursor = movementResult ? Cursors.Hand : Cursors.Arrow;
UpdateChart(true);
}
private void workAreaFormPictureBox_MouseDoubleClick(object sender, MouseEventArgs e)
{
Block block = Chart.ProcessMouseDoubleClick(e.X, e.Y);
if (block == null)
return;
if (block is RegularBLock)
{
blockProreptiesEditorForm = new BlockProreptiesEditor("regular", block, this);
}
else if (block is ConditionBlock)
{
blockProreptiesEditorForm = new BlockProreptiesEditor("condition", block, this);
}
else if (block is LoopBlock)
{
blockProreptiesEditorForm = new BlockProreptiesEditor("loop_for", block, this);
}
blockProreptiesEditorForm.MdiParent = this.MdiParent;
blockProreptiesEditorForm.Show();
}
public void DeleteBLock()
{
if (Chart.DeleteSelectedBlock())
{
UpdateChart();
UpdateCode();
}
}
public void ClearChart()
{
Chart.ClearChart();
UpdateChart();
UpdateCode();
}
}
}
9) BlockProreptiesEditor.cs
using System;
using System.Drawing;
using System.Windows.Forms;
namespace flowchart
{
public partial class BlockProreptiesEditor : Form
{
private Block blockToEdit;
private WorkAreaForm workAreaForm;
private string loopType;
public BlockProreptiesEditor(string type, Block block, WorkAreaForm workAreaForm)
{
loopType = type;
InitializeComponent();
this.blockToEdit = block;
this.workAreaForm = workAreaForm;
blockContentTextBox.Text = block.Text;
switch (type)
{
case "regular":
blockContentLabel.Text = "Текст";
Text = "Обычный блок";
AdjustFormFormForConditionOrRegular();
break;
case "condition":
blockContentLabel.Text = "Условие";
Text = "Условие";
AdjustFormFormForConditionOrRegular();
break;
case "loop_for":
blockContentLabel.Text = " Цикл";
Text = "Цикл";
loopTypeComboBox.SelectedIndex = 0;
break;
case "loop_while":
blockContentLabel.Text = "Предусловие";
Text = "Цикл";
loopTypeComboBox.SelectedIndex = 1;
break;
case "loop_do_while":
blockContentLabel.Text = "Постусловие";
Text = "Цикл";
loopTypeComboBox.SelectedIndex = 2;
break;
}
}
private void AdjustFormFormForConditionOrRegular()
{
loopTypeLabel.Visible = false;
loopTypeComboBox.Visible = false;
Width = 300;
Height = 170;
blockContentLabel.Top = 15;
blockContentLabel.Left = 1;
blockContentTextBox.Top = 12;
blockContentTextBox.Left = 55;
blockContentTextBox.Height = 80;
}
private void loopTypeComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
switch(loopTypeComboBox.SelectedIndex)
{
case 0:
blockContentLabel.Text = " Цикл";
loopType = "loop_for";
break;
case 1:
blockContentLabel.Text = "Предусловие";
loopType = "loop_while";
break;
case 2:
blockContentLabel.Text = "Постусловие";
loopType = "loop_do_while";
break;
}
}
private void cancelButton_Click(object sender, EventArgs e)
{
Close();
}
private void okButton_Click(object sender, EventArgs e)
{
if (loopType == "loop_do_while")
{
blockToEdit.Text = "do";
blockToEdit.TextAtTheEnd = blockContentTextBox.Text;
}
else
{
blockToEdit.Text = blockContentTextBox.Text;
blockToEdit.TextAtTheEnd = "";
}
foreach (Block block in workAreaForm.Chart.blocks)
{
block.isSelected = false;
}
workAreaForm.UpdateChart();
workAreaForm.UpdateCode();
Close();
}
private void BlockProreptiesEditor_Load(object sender, EventArgs e)
{
Location = new Point(400, 150);
}
}
}
10) Chart.cs
using System;
using System.Collections.Generic;
using System.Drawing;
using flowchart.blocks;
using System.Xml.Serialization;
namespace flowchart
{
[Serializable]
public class Chart
{
public ChartMainBlock root;
private Block selectedBlock;
[XmlIgnore]
public CodeGenerator codeGen;
[XmlIgnore]
public List<Block> blocks = new List<Block>();
[XmlIgnore]
public List<InsertionPoint> insertionPoints = new List<InsertionPoint>();
[XmlIgnore]
public int height;
[XmlIgnore]
public int width;
public Chart()
{
root = new ChartMainBlock("main block");
Branch rootMainBranch = new Branch("main branch");
root.Items.Add(rootMainBranch);
blocks.Add(root);
blocks.Add(rootMainBranch);
RealignBlocks();
RegenerateInsertionPoints();
codeGen = new CodeGenerator(root);
}
public void RealignBlocks()
{
root.AdjustSize();
root.AdjustPosition(0, 20);
width = root.width;
height = root.height+100;
}
public void RegenerateInsertionPoints()
{
insertionPoints.Clear();
GenerateInsertionPoints(root);
}
public void GenerateInsertionPoints(Block block)
{
if (block is Branch)
{
int x = block.X + block.width / 2;
for (int i = 0; i < block.Items.Count; i++)
{
int y = block.Items[i].Y;
InsertionPoint point = new InsertionPoint();
point.branch = block;
point.x = x;
point.y = y;
point.index = i;
insertionPoints.Add(point);
GenerateInsertionPoints(block.Items[i]);
}
InsertionPoint p = new InsertionPoint();
p.branch = block;
if (block.Items.Count == 0)
{
p.x = x;
p.y = block.Y + block.height / 2;
}
else
{
p.x = x;
p.y = block.Y + block.height;
}
p.index = block.Items.Count;
insertionPoints.Add(p);
}
else
{
foreach (Block item in block.Items)
{
GenerateInsertionPoints(item);
}
}
}
public void InsertIntoBranch(Block branch, Block newBlock, int index)
{
newBlock.Branch = branch;
branch.Items.Insert(index, newBlock);
RealignBlocks();
RegenerateInsertionPoints();
}
private Block CreateNewBlock(int type)
{
switch (type)
{
case (1):
Block regularBLock = new RegularBLock("action");
blocks.Add(regularBLock);
return regularBLock;
case (2):
Block conditionBlock = new ConditionBlock("condition");
Block left = new Branch("condition left branch");
Block right = new Branch("condition right branch");
//left.Branch = right.Branch = conditionBlock;
conditionBlock.Items.Add(left);
conditionBlock.Items.Add(right);
blocks.Add(conditionBlock);
blocks.Add(left);
blocks.Add(right);
return conditionBlock;
case (3):
LoopBlock loopBlock = new LoopBlock("loop");
loopBlock.TextAtTheEnd = "loop end";
Block loopBranch = new Branch("loop branch");
//loopBranch.Branch = loopBlock;
loopBlock.Items.Add(loopBranch);
blocks.Add(loopBlock);
blocks.Add(loopBranch);
return loopBlock;
default:
return null;
}
}
/// <summary>
/// Проверить является ли расстояние между двумя точками меньше заданного
/// </summary>
public bool CheckTwoPoints(int x1, int y1, int x2, int y2, int r)
{
int dx = Math.Abs(x1 - x2);
int dy = Math.Abs(y1 - y2);
return dx * dx + dy * dy <= r * r;
}
public InsertionPoint GetPointAt(int x, int y)
{
foreach (InsertionPoint ip in insertionPoints)
{
if (CheckTwoPoints(ip.x, ip.y, x, y, ip.R))
{
return ip;
}
}
return null;
}
/// <summary>
/// Удаляет выбранный блок схемы
/// </summary>
/// <returns>true - если был удален блок (было что удалять) </returns>
public bool DeleteSelectedBlock()
{
if (selectedBlock == null)
return false;
selectedBlock.Branch.Items.Remove(selectedBlock);
UpdateAllBlocksList();
RealignBlocks();
RegenerateInsertionPoints();
return true;
}
public void UpdateAllBlocksList()
{
blocks.Clear();
WalkChart(root);
}
private void WalkChart(Block block)
{
blocks.Add(block);
foreach (var item in block.Items)
{
WalkChart(item);
}
}
public void ClearChart()
{
root.Items[0].Items.Clear();
blocks.Clear();
RealignBlocks();
RegenerateInsertionPoints();
}
#region mouse events handling
public void ProcessMouseClickInsertion(int mouseX, int mouseY, int blockType)
{
InsertionPoint insertionPointClicked = GetPointAt(mouseX, mouseY);
if (insertionPointClicked == null)
return;
Block newBLock = CreateNewBlock(blockType);
InsertIntoBranch(insertionPointClicked.branch, newBLock, insertionPointClicked.index);
}
public void ProcessMouseClickBlockSelection(int mouseX, int mouseY)
{
selectedBlock = null;
foreach (Block block in blocks)
{
block.isSelected = false;
}
foreach (Block block in blocks)
{
if (block is Branch || block is ChartMainBlock)
continue;
if (block.PointInsideBlock(mouseX, mouseY))
{
selectedBlock = block;
selectBlock(block);
return;
}
}
}
public bool ProcessMouseMove(int mouseX, int mouseY)
{
bool result = false;
foreach (InsertionPoint ip in insertionPoints)
{
if (CheckTwoPoints(ip.x, ip.y, mouseX, mouseY, ip.R))
{
ip.underCursor = true;
result = true;
}
else
{
ip.underCursor = false;
}
}
return result;
}
public Block ProcessMouseDoubleClick(int mouseX, int mouseY)
{
foreach (Block block in blocks)
{
if (block is Branch || block is ChartMainBlock)
continue;
if (block.PointInsideBlock(mouseX, mouseY))
{
return block;
}
}
return null;
}
#endregion
private void selectBlock(Block block)
{
block.isSelected = true;
if (block is RegularBLock)
return;
foreach (Block item in block.Items)
{
selectBlock(item);
}
}
//отрисовка схемы
public void Draw(Graphics g, bool insertion = false)
{
root.Draw(g);
drawBlockItems(root, g);
if (!insertion) return;
foreach (InsertionPoint insertionPoint in insertionPoints)
{
insertionPoint.draw(g);
}
}
private void drawBlockItems(Block block, Graphics g)
{
foreach (Block item in block.Items)
{
item.Draw(g);
drawBlockItems(item, g);
}
}
public string GetCode()
{
return codeGen.GetGeneratedCode();
}
}
}
11) CodeGenerator.cs
using System;
using flowchart.blocks;
namespace flowchart
{
public class CodeGenerator
{
private Block root;
private string code;
//новая строка
private string br = Environment.NewLine;
private int tab = 2;
public CodeGenerator(Block root)
{
this.root = root;
}
public string GetGeneratedCode()
{
code = "";
GenerateCode(root, 0);
return code;
}
private void GenerateCode(Block block, int indent)
{
if (block is ChartMainBlock)
{
GenerateCode(block.Items[0], indent);
}
else if (block is Branch)
{
foreach (var item in block.Items)
{
GenerateCode(item, indent);
}
}
else if (block is RegularBLock)
{
code += GetIndent(indent);
code += block.Text + ";" + br;
}
else if (block is ConditionBlock)
{
code += GetIndent(indent) + String.Format("if ({0})", block.Text) + br;
code += GetIndent(indent) + "{" + br;
GenerateCode(block.Items[0], indent + tab);
code += GetIndent(indent) + "}" + br;
code += GetIndent(indent) + "else" + br;
code += GetIndent(indent) + "{" + br;
GenerateCode(block.Items[1], indent + tab);
code += GetIndent(indent) + "}" + br;
}
else if (block is LoopBlock)
{
code += GetIndent(indent) + block.Text + br;
code += GetIndent(indent) + "{" + br;
GenerateCode(block.Items[0], indent + tab);
code += GetIndent(indent) + "} ";
if (block.TextAtTheEnd != "")
{
code += block.TextAtTheEnd + ";";
}
code += br;
}
}
private string GetIndent(int indent)
{
string res = "";
for (int i = 0; i < indent; i++)
{
res += " ";
}
return res;
}
}
}
12) InsertionPoint.cs
using System.Drawing;
namespace flowchart
{
public class InsertionPoint
{
public Block branch;
public int index;
public int x;
public int y;
public bool underCursor = false;
public int R = 10;
private int paintingR = 4;
public void draw(Graphics g)
{
g.FillEllipse(Brushes.Firebrick, x - paintingR, y - paintingR, 2 * paintingR, 2 * paintingR);
if (underCursor)
{
g.FillEllipse(Brushes.CornflowerBlue, x - R, y - R, 2 * R, 2 * R);
}
}
}
}
13) JsCodeInterpreter.cs
using System;
using System.Windows.Forms;
using Jint;
namespace flowchart
{
public class JsCodeInterpreter
{
private TextBox textBox;
private JintEngine jsEngine;
public JsCodeInterpreter(TextBox textBox)
{
this.textBox = textBox;
jsEngine = new JintEngine();
PrintCodeExecutionResultDelegate print = delegate(object text) { textBox.Text += text + Environment.NewLine; };
jsEngine.SetFunction("print", print);
}
public delegate void PrintCodeExecutionResultDelegate(object text);
public void RunScript(string script)
{
textBox.Text = "";
jsEngine.Run(script);
}
}
Приложение Б.
(справочное)
XML файл генерируемый программой
<?xml version="1.0"?>
<ChartMainBlock xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" Text="main block">
<Items>
<Block xsi:type="Branch" Text="main branch">
<Items>
<Block xsi:type="RegularBLock" Text="a = 1" TextAtTheEnd="">
<Items />
</Block>
<Block xsi:type="RegularBLock" Text="b = 2" TextAtTheEnd="">
<Items />
</Block>
<Block xsi:type="RegularBLock" Text="c = -3" TextAtTheEnd="">
<Items />
</Block>
<Block xsi:type="RegularBLock" Text="d = b*b - 4*a*c" TextAtTheEnd="">
<Items />
</Block>
<Block xsi:type="ConditionBlock" Text="d >= 0" TextAtTheEnd="">
<Items>
<Block xsi:type="Branch" Text="condition left branch">
<Items>
<Block xsi:type="RegularBLock" Text="x1 = (-b - Math.sqrt(d))/2*a" TextAtTheEnd="">
<Items />
</Block>
<Block xsi:type="RegularBLock" Text="x1 = (-b + Math.sqrt(d))/2*a" TextAtTheEnd="">
<Items />
</Block>
<Block xsi:type="RegularBLock" Text="print('x1=' + x1)" TextAtTheEnd="">
<Items />
</Block>
<Block xsi:type="RegularBLock" Text="print('x2=' + x2)" TextAtTheEnd="">
<Items />
</Block>
</Items>
</Block>
<Block xsi:type="Branch" Text="condition right branch">
<Items>
<Block xsi:type="RegularBLock" Text="print('корней нет')" TextAtTheEnd="">
<Items />
</Block>
</Items>
</Block>
</Items>
</Block>
</Items>
</Block>
</Items>
</ChartMainBlock>
Список литературы
1. Джон Пол Мюллер, Дебби Валковски, Microsoft Office Visio 2007 для "чайников"- М.: 2008.- 304с
2. Бонни Бьяфоре, Visio 2007 Bible- М.:2009.-800с
3. Джим Арлоу, Айла Нейдштадт, UML и Унифицированный процесс- М.:2007.-617с
4. http://khpi-iip.mipk.kharkiv.edu/library/case/leon/
5. Дж. Рамбо, UML 2.0. Объектно-ориентированное моделирование и разработка- М.:2007.-544с
Размещено на Allbest.ru
Подобные документы
Реализация системы визуального программирования. Выбор технических средств для нее. Варианты использования языка JavaScript. Создание приложения программы-редактора блок-схем и сайта удалённого обучения на основе интерактивной системы обучения Moodle.
дипломная работа [2,2 M], добавлен 07.07.2012Побудова блок-схем алгоритмів програм. Створення блок схем алгоритмів за допомогою FCEditor. Експорт блок-схеми в графічний файл. Огляд програмних та апаратних засобів. Мови програмування високого рівня. Цикли та умовний оператор IF з лічильником.
дипломная работа [1,4 M], добавлен 15.12.2013Microsoft Office — пакет приложений, созданных корпорацией Microsoft для операционных систем Microsoft Windows и Apple Mac OS X. Автоматизация процедуры выплаты заработной платы. Создание презентации в Power Point. Автоматическое создание блок-схем.
практическая работа [2,1 M], добавлен 14.07.2012Изучение особенностей растровых и векторных графических редакторов. Создание графического редактора: выбор языка программирования, разработка структуры программы и алгоритма работы. Описание интерфейса программы. Руководство программиста и пользователя.
курсовая работа [1,3 M], добавлен 28.07.2013Описание работы элементов программы в виде блок-схем. Анализ структурной схемы модели домофона. Блок-схема работы открытия двери ключом. Моделирование в Proteus: принцип динамического опроса и индикации, внешний вид жидкокристаллического дисплея.
курсовая работа [1,4 M], добавлен 12.04.2019Приобретение навыков структурных блок-схем и листингов программ на языке "Ассемблер" для простых микропроцессорных систем управления процессами. Типовые структуры блок-схем алгоритмов обработки данных. Программная реализация типовых функций управления.
методичка [1007,8 K], добавлен 01.10.2010Управление дистанционной настройкой и установкой ПО. История развития VMware ThinApp. Создание пакета автоматической установки Microsoft Office Visio Professional 2007. Анализ программного обеспечения для него. Тестирование полученного msi-пакета.
курсовая работа [1,5 M], добавлен 14.03.2013Программы для делопроизводства, обмена информацией, деловой графики и презентаций. Работа с текстовыми и табличными процессорами, с системами управления базами данных на примере программы Microsoft Office Word. Описание основных функций программ.
курсовая работа [1,0 M], добавлен 12.01.2015Анализ существующих разработок для работы со схемами устройств релейной защиты и автоматики железнодорожного транспорта. Разработка программных модулей. Структура данных программного комплекса. Алгоритмы редактора схем. Отладка и модульное тестирование.
дипломная работа [2,6 M], добавлен 19.01.2017Разработка программы-интерпретатора, способной получать на входе текстовый файл (в формате ASCII или ANSI) с текстом программы и на выходе выводить на экран результаты вычислений, определяемых программистом. Выбор лексем, интерфейс и листинг программы.
курсовая работа [132,0 K], добавлен 12.03.2013