From a83c683e724a5085dfaa54b6b2f8ec1d90644290 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9C=D0=BE=D1=80=D0=BE=D0=B7=D0=BE=D0=B2=20=D0=90=D0=BD?= =?UTF-8?q?=D0=B4=D1=80=D0=B5=D0=B9?= Date: Wed, 10 Nov 2021 11:24:31 +0000 Subject: [PATCH] =?UTF-8?q?=D0=97=D0=B0=D0=B3=D1=80=D1=83=D0=B7=D0=B8?= =?UTF-8?q?=D0=BB(=D0=B0)=20=D1=84=D0=B0=D0=B9=D0=BB=D1=8B=20=D0=B2=20'flu?= =?UTF-8?q?tter/lib'?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- flutter/lib/curve_painter.dart | 288 ++++++-------- flutter/lib/drawing_page.dart | 507 ++++++++++++++++++++++++ flutter/lib/graph.dart | 679 +++++++++++++++++++++++++++++++++ 3 files changed, 1295 insertions(+), 179 deletions(-) create mode 100644 flutter/lib/drawing_page.dart create mode 100644 flutter/lib/graph.dart diff --git a/flutter/lib/curve_painter.dart b/flutter/lib/curve_painter.dart index 0a334e5..4363d0b 100644 --- a/flutter/lib/curve_painter.dart +++ b/flutter/lib/curve_painter.dart @@ -8,71 +8,85 @@ class CurvePainter extends CustomPainter { Key? key, required this.graphData, required this.bfsPath, - required this.dfsStart, + required this.start, + required this.end, required this.dfsAccessTable, }); List? bfsPath; List? dfsAccessTable; - int? dfsStart; + int? start; + int? end; Graphs graphData; - final double dotRad = 6; - final double lineWidth = 2; - final Color lineColor = Colors.black; - final double aboveHeight = 5; - double circleRad = 100; - final TextStyle textStyle = TextStyle( - color: Colors.green.shade900, + final double _dotRad = 6; + final double _lineWidth = 1.5; + final Color _lineColor = Colors.black; + final double _aboveHeight = 5; + double _circleRad = 100; + final TextStyle _textStyle = TextStyle( + color: Colors.red.shade900, + decorationColor: Colors.green.shade900, + decorationThickness: 10, + decorationStyle: TextDecorationStyle.dashed, fontSize: 20, ); - - void drawLine(Canvas canvas, Offset p1, Offset p2) { + Map _off = {}; + void _drawLine(Canvas canvas, Offset p1, Offset p2) { Paint p = Paint(); - p.color = lineColor; - p.strokeWidth = lineWidth; + p.color = _lineColor; + p.strokeWidth = _lineWidth; canvas.drawLine(p1, p2, p); } - void drawDot(Canvas canvas, Offset p1) { + void _drawDot(Canvas canvas, Offset p1, [double plusRad = 0, Color? col]) { + col ??= Colors.yellow.shade900; var p = Paint(); - p.color = Colors.yellow.shade900; - p.strokeWidth = lineWidth + 2; - canvas.drawCircle(p1, dotRad, p); + p.color = col; + p.strokeWidth = _lineWidth + 2; + canvas.drawCircle(p1, _dotRad + plusRad, p); } - void drawSelfConnect(Canvas canvas, Offset p1) { + void _drawSelfConnect(Canvas canvas, Offset p1) { var p = Paint(); - p.color = lineColor; - p.strokeWidth = lineWidth; + p.color = _lineColor; + p.strokeWidth = _lineWidth; p.style = PaintingStyle.stroke; - canvas.drawCircle(Offset(p1.dx + dotRad + 20, p1.dy), dotRad + 20, p); + canvas.drawCircle(Offset(p1.dx + _dotRad + 20, p1.dy), _dotRad + 20, p); } - TextSpan _getTextSpan(String s) => TextSpan(text: s, style: textStyle); + TextSpan _getTextSpan(String s) => TextSpan(text: s, style: _textStyle); TextPainter _getTextPainter(String s) => TextPainter( text: _getTextSpan(s), textDirection: TextDirection.ltr, textAlign: TextAlign.center); - void drawDotNames(Canvas canvas, Offset place, String s) { + void _drawDotNames(Canvas canvas, Offset place, String s) { var textPainter = _getTextPainter(s); textPainter.layout(); textPainter.paint( canvas, Offset((place.dx - textPainter.width), - (place.dy - textPainter.height) - aboveHeight)); + (place.dy - textPainter.height) - _aboveHeight)); } - void drawAboveText(Canvas canvas, Offset size, String s) { - var textPainter = _getTextPainter(s); + void _drawDotNum(Canvas canvas, Offset size, String s) { + var textPainter = TextPainter( + text: TextSpan( + text: s, + style: const TextStyle( + color: Colors.black, + fontSize: 17, + )), + textDirection: TextDirection.ltr, + textAlign: TextAlign.center); textPainter.layout(); textPainter.paint( canvas, - Offset((size.dx - textPainter.width), - (size.dy - textPainter.height) - aboveHeight)); + Offset((size.dx - textPainter.width) + 25, + (size.dy - textPainter.height) + _aboveHeight + 30)); } - int getHighInputConnections() { + int _getHighInputConnections() { if (graphData.getDots().length != 1 && graphData.getDots().length <= 3) { return -1; } @@ -83,17 +97,18 @@ class CurvePainter extends CustomPainter { return higest; } - Map getDotPos(int dotsAm, Size size, [int? exclude]) { + Map _getDotPos(int dotsAm, Size size) { Map off = {}; var width = size.width / 2; var height = size.height / 2; int add = 0; - int h = getHighInputConnections(); + int h = _getHighInputConnections(); for (int i = 0; i < dotsAm; i++) { if ((i + 1) != h) { - double x = cos(2 * pi * (i - add) / (dotsAm - add)) * circleRad + width; + double x = + cos(2 * pi * (i - add) / (dotsAm - add)) * _circleRad + width; double y = - sin(2 * pi * (i - add) / (dotsAm - add)) * circleRad + height; + sin(2 * pi * (i - add) / (dotsAm - add)) * _circleRad + height; off[i + 1] = Offset(x, y); } else if ((i + 1) == h) { @@ -110,7 +125,7 @@ class CurvePainter extends CustomPainter { return off; } - void drawHArrow(Canvas canvas, Size size, Offset from, Offset to, + void _drawHArrow(Canvas canvas, Size size, Offset from, Offset to, [bool doubleSided = false]) { Path path; @@ -120,7 +135,7 @@ class CurvePainter extends CustomPainter { ..style = PaintingStyle.stroke ..strokeCap = StrokeCap.round ..strokeJoin = StrokeJoin.round - ..strokeWidth = lineWidth; + ..strokeWidth = _lineWidth; var length = sqrt((to.dx - from.dx) * (to.dx - from.dx) + (to.dy - from.dy) * (to.dy - from.dy)); @@ -131,8 +146,8 @@ class CurvePainter extends CustomPainter { path.relativeCubicTo( 0, 0, - -(from.dx + to.dx) / (length * 2) - 40, - -(from.dy + to.dy) / (length * 2) - 40, + -(from.dx + to.dx + length) / (length) - 40, + -(from.dy + to.dy + length) / (length) - 40, to.dx - from.dx, to.dy - from.dy); path = @@ -140,7 +155,7 @@ class CurvePainter extends CustomPainter { canvas.drawPath(path, paint); } - void drawHighArrow(Canvas canvas, Size size, Offset from, Offset to, + void _drawHighArrow(Canvas canvas, Size size, Offset from, Offset to, [bool doubleSided = false]) { Path path; @@ -150,7 +165,7 @@ class CurvePainter extends CustomPainter { ..style = PaintingStyle.stroke ..strokeCap = StrokeCap.round ..strokeJoin = StrokeJoin.round - ..strokeWidth = lineWidth; + ..strokeWidth = _lineWidth; var length = sqrt((to.dx - from.dx) * (to.dx - from.dx) + (to.dy - from.dy) * (to.dy - from.dy)); @@ -161,7 +176,7 @@ class CurvePainter extends CustomPainter { path.relativeCubicTo( 0, 0, - (from.dx + to.dx) / (length * 3) + 40, + (from.dx + to.dx) / (length * 2) + 40, (from.dy + to.dy) / (length * 2) + 40, to.dx - from.dx, to.dy - from.dy); @@ -173,29 +188,29 @@ class CurvePainter extends CustomPainter { canvas.drawPath(path, paint); } - void drawConnections( + void _drawConnections( Canvas canvas, Size size, List dots, Map off) { for (var i in dots) { var list = i.getL(); var beg = off[i.num]; for (var d in list.keys) { if (d == i.num) { - drawSelfConnect(canvas, off[d]!); + _drawSelfConnect(canvas, off[d]!); } else { if (graphData.getDoubleSidedBool()) { if (d > i.num) { - drawHArrow(canvas, size, beg!, off[d]!, false); + _drawHArrow(canvas, size, beg!, off[d]!, false); if (graphData.getUseLengthBool()) { - drawDotNames( + _drawDotNames( canvas, Offset((off[d]!.dx + beg.dx) / 2 - 18, (off[d]!.dy + beg.dy) / 2 - 18), i.getL()[d].toString()); } } else { - drawHighArrow(canvas, size, beg!, off[d]!, false); + _drawHighArrow(canvas, size, beg!, off[d]!, false); if (graphData.getUseLengthBool()) { - drawDotNames( + _drawDotNames( canvas, Offset((off[d]!.dx + beg.dx) / 2 + 30, (off[d]!.dy + beg.dy) / 2 + 30), @@ -203,9 +218,9 @@ class CurvePainter extends CustomPainter { } } } else { - drawLine(canvas, beg!, off[d]!); + _drawLine(canvas, beg!, off[d]!); if (graphData.getUseLengthBool()) { - drawDotNames( + _drawDotNames( canvas, Offset((off[d]!.dx + beg.dx) / 2, (off[d]!.dy + beg.dy) / 2), i.getL()[d].toString()); @@ -216,52 +231,71 @@ class CurvePainter extends CustomPainter { } } + void _drawBFS(Canvas canvas) { + if (bfsPath != null) { + for (int i = 0; i < bfsPath!.length; i++) { + _drawDot(canvas, _off[bfsPath![i]]!, 8, Colors.yellow); + } + _drawDot(canvas, _off[start]!, 9, Colors.green); + _drawDot(canvas, _off[end]!, 7, Colors.red.shade200); + for (int i = 0; i < bfsPath!.length; i++) { + _drawDotNum(canvas, _off[bfsPath![i]]!, "bfs: №${i + 1}"); + } + } + } + + void _drawDFS(Canvas canvas) { + if (dfsAccessTable != null) { + for (int i = 0; i < dfsAccessTable!.length; i++) { + if (dfsAccessTable![i]) { + _drawDot(canvas, _off[i + 1]!, 8, Colors.green.shade500); + _drawDotNum(canvas, _off[i + 1]!, "dfs: visible"); + } else { + _drawDot(canvas, _off[i + 1]!, 7, Colors.red.shade500); + _drawDotNum(canvas, _off[i + 1]!, "dfs: not visible"); + } + } + _drawDot(canvas, _off[start]!, 9, Colors.green.shade900); + } + } + @override void paint(Canvas canvas, Size size) { if (size.width > size.height) { - circleRad = size.height / 3; + _circleRad = size.height / 3; } else { - circleRad = size.width / 3; + _circleRad = size.width / 3; } - //var paint = Paint(); - //drawLine(canvas, Offset(0, size.height / 2), - //Offset(size.width, size.height / 2)); - //gr = getGraph(); - //int higest = getHighConnections(); - //if (higest > -1) { - var off = getDotPos(graphData.getDotAmount(), size); //, higest); - //off[higest] = Offset(size.width / 2, size.height / 2); - for (int i in off.keys) { - drawDot(canvas, off[i]!); - drawDotNames( - canvas, off[i]!, "${graphData.getDots()[i - 1].getName()}:[$i]"); + _off = _getDotPos(graphData.getDotAmount(), size); //, higest); + for (int i in _off.keys) { + _drawDot(canvas, _off[i]!); + //drawDotNames(canvas, off[i]!, "${graphData.getDots()[i - 1].getName()}:[$i]"); } - //var g = gr.getNoRepeatDots(); - //print(g); + var g = graphData.getDots(); - drawConnections(canvas, size, g, off); + _drawBFS(canvas); + _drawDFS(canvas); + _drawConnections(canvas, size, g, _off); //pringArr(canvas, size); //drawArrow(canvas, Offset(size.width / 2, size.height / 2), // Offset(size.width / 2 + 50, size.height / 2 + 200)); //} + + for (int i in _off.keys) { + //drawDot(canvas, off[i]!); + _drawDotNames( + canvas, _off[i]!, "${graphData.getDots()[i - 1].getName()}:[$i]"); + } } @override bool shouldRepaint(CustomPainter oldDelegate) { return true; } - - /*void _drawTextAt(String txt, Offset position, Canvas canvas) { - final textPainter = getTextPainter(txt); - textPainter.layout(minWidth: 0, maxWidth: 0); - Offset drawPosition = - Offset(position.dx, position.dy - (textPainter.height / 2)); - textPainter.paint(canvas, drawPosition); - }*/ } -void pringArr(Canvas canvas, Size size) { +/*void _pringArr(Canvas canvas, Size size) { TextSpan textSpan; TextPainter textPainter; Path path; @@ -292,108 +326,4 @@ void pringArr(Canvas canvas, Size size) { ); textPainter.layout(minWidth: size.width); textPainter.paint(canvas, Offset(0, size.height * 0.06)); -/* - /// Draw a double sided arrow. - path = Path(); - path.moveTo(size.width * 0.25, size.height * 0.2); - path.relativeCubicTo(0, 0, size.width * 0.25, 50, size.width * 0.5, 0); - path = ArrowPath.make(path: path, isDoubleSided: true); - canvas.drawPath(path, paint..color = Colors.cyan); - - textSpan = const TextSpan( - text: 'Double sided arrow', - style: TextStyle(color: Colors.cyan), - ); - textPainter = TextPainter( - text: textSpan, - textAlign: TextAlign.center, - textDirection: TextDirection.ltr, - ); - textPainter.layout(minWidth: size.width); - textPainter.paint(canvas, Offset(0, size.height * 0.16)); - - /// Use complex path. - path = Path(); - path.moveTo(size.width * 0.25, size.height * 0.3); - path.relativeCubicTo(0, 0, size.width * 0.25, 0, size.width * 0.5, 50); - path.relativeCubicTo(0, 0, -size.width * 0.25, 50, -size.width * 0.5, 50); - //path.relativeCubicTo(0, 0, size.width * 0.125, 10, size.width * 0.25, -10); - path = ArrowPath.make(path: path, isDoubleSided: true); - canvas.drawPath(path, paint..color = Colors.blue); - - textSpan = const TextSpan( - text: 'Complex path', - style: TextStyle(color: Colors.blue), - ); - textPainter = TextPainter( - text: textSpan, - textAlign: TextAlign.center, - textDirection: TextDirection.ltr, - ); - textPainter.layout(minWidth: size.width); - textPainter.paint(canvas, Offset(0, size.height * 0.28)); - - /// Draw several arrows on the same path. - path = Path(); - path.moveTo(size.width * 0.25, size.height * 0.53); - path.relativeCubicTo(0, 0, size.width * 0.25, 50, size.width * 0.5, 50); - path = ArrowPath.make(path: path); - path.relativeCubicTo(0, 0, -size.width * 0.25, 0, -size.width * 0.5, 50); - path = ArrowPath.make(path: path); - Path subPath = Path(); - subPath.moveTo(size.width * 0.375, size.height * 0.53 + 100); - subPath.relativeCubicTo(0, 0, size.width * 0.125, 10, size.width * 0.25, -10); - subPath = ArrowPath.make(path: subPath, isDoubleSided: true); - path.addPath(subPath, Offset.zero); - canvas.drawPath(path, paint..color = Colors.cyan); - - textSpan = const TextSpan( - text: 'Several arrows on the same path', - style: TextStyle(color: Colors.cyan), - ); - textPainter = TextPainter( - text: textSpan, - textAlign: TextAlign.center, - textDirection: TextDirection.ltr, - ); - textPainter.layout(minWidth: size.width); - textPainter.paint(canvas, Offset(0, size.height * 0.49)); - - /// Adjusted - path = Path(); - path.moveTo(size.width * 0.1, size.height * 0.8); - path.relativeCubicTo(0, 0, size.width * 0.3, 50, size.width * 0.25, 75); - path = ArrowPath.make(path: path, isAdjusted: true); - canvas.drawPath(path, paint..color = Colors.blue); - - textSpan = const TextSpan( - text: 'Adjusted', - style: TextStyle(color: Colors.blue), - ); - textPainter = TextPainter( - text: textSpan, - textAlign: TextAlign.left, - textDirection: TextDirection.ltr, - ); - textPainter.layout(); - textPainter.paint(canvas, Offset(size.width * 0.2, size.height * 0.77)); - - /// Non adjusted. - path = Path(); - path.moveTo(size.width * 0.6, size.height * 0.8); - path.relativeCubicTo(0, 0, size.width * 0.3, 50, size.width * 0.25, 75); - path = ArrowPath.make(path: path, isAdjusted: false); - canvas.drawPath(path, paint..color = Colors.blue); - - textSpan = const TextSpan( - text: 'Non adjusted', - style: TextStyle(color: Colors.blue), - ); - textPainter = TextPainter( - text: textSpan, - textAlign: TextAlign.left, - textDirection: TextDirection.ltr, - ); - textPainter.layout(); - textPainter.paint(canvas, Offset(size.width * 0.65, size.height * 0.77));*/ -} +}*/ diff --git a/flutter/lib/drawing_page.dart b/flutter/lib/drawing_page.dart new file mode 100644 index 0000000..426256d --- /dev/null +++ b/flutter/lib/drawing_page.dart @@ -0,0 +1,507 @@ +import 'package:graphs/src/graph.dart'; +import 'package:graphs/curve_painter.dart'; + +import 'package:file_picker/file_picker.dart'; +import 'package:flutter/material.dart'; + +Graphs getGraph() { + List d = []; + d.add(Dot.fromTwoLists("1", [2, 3], [5, 1])); + d.add(Dot.fromTwoLists("2", [1, 3], [1, 1])); + d.add(Dot.fromTwoLists("3", [1, 2], [1, 2])); + //d.add(Dot.fromTwoLists("Name1", [], [])); + //d.add(Dot.fromTwoLists("Name2", [], [])); + return Graphs.fromList("Имя", d, true, true); +} + +class DrawingPage extends StatefulWidget { + const DrawingPage({Key? key}) : super(key: key); + + @override + State createState() => _DrawingPageState(); +} + +class _DrawingPageState extends State { + double screenSize = 0; + Graphs graphData = getGraph(); + List? bfsPath; + List? dfsAccessTable; + int? startDot; + int? endDot; + String? dropdownValue1; + String? dropdownValue2; + + final _textNameController = TextEditingController(); + final _textNumbController = TextEditingController(); + final _textDestController = TextEditingController(); + final _textLnthController = TextEditingController(); + final _textGrNmController = TextEditingController(); + + void clearInputData() { + setState(() { + _textDestController.clear(); + _textNumbController.clear(); + _textLnthController.clear(); + _textNameController.clear(); + dropdownValue1 = null; + dropdownValue2 = null; + /*startDot = null; + bfsPath = null; + dfsAccessTable = null; + endDot = null;*/ + }); + } + + @override + Widget build(BuildContext context) { + screenSize = MediaQuery.of(context).size.width; + _textGrNmController.text = graphData.getName(); + return MaterialApp( + home: Scaffold( + appBar: AppBar( + title: const Align( + alignment: Alignment.topLeft, + child: Text("Graph name:\n", + style: TextStyle( + fontSize: 18, + color: Colors.white, + ))), + toolbarHeight: 110, + flexibleSpace: Container( + color: Colors.green.shade900, + child: Column(children: [ + const SizedBox(height: 5), + Row(children: [ + addSpaceW(screenSize / 8 + 19), + createButton("\nAdd dot\n", addDotPushed), + createInputBox("Dot name", screenSize / 4 - 25, Icons.label, + _textNameController), + addSpaceW(8), + createButton("\nAdd path\n", addPathPushed), + createInputBox("Input length", screenSize / 4 - 25, + Icons.arrow_right_alt_outlined, _textLnthController), + ]), + addSpaceH(3), + Row(children: [ + addSpaceW(6), + createInputBox( + "Name", screenSize / 8 - 25, null, _textGrNmController), + //addSpaceW(screenSize / 8 - 4), + createButton("\nDel dot \n", delDotPushed), + //createInputBox("Dot number", screenSize / 4 - 25, Icons.fiber_manual_record, _textNumbController), + addSpaceW(54), + dropList1(screenSize / 4 - 80), + addSpaceW(54), + createButton("\nDel path\n", delPathPushed), + addSpaceW(54), + dropList2(screenSize / 4 - 80), + //createInputBox("Destination number", screenSize / 4 - 25, Icons.fiber_manual_record, _textDestController), + ]), + ]), + ), + actions: [ + IconButton( + onPressed: () => graphData.flushData(), + icon: const Icon(Icons.delete_sweep), + iconSize: 60, + ), + ]), + body: CustomPaint( + painter: CurvePainter( + graphData: graphData, + bfsPath: bfsPath, + dfsAccessTable: dfsAccessTable, + start: startDot, + end: endDot), + child: Align( + alignment: Alignment.topRight, + child: ButtonBar( + mainAxisSize: MainAxisSize.min, + children: [ + createButton("Bfs", bfsPushed), + createButton("Dfs", dfsPushed), + createButton("Clear dfs or bfs", () { + setState(() { + bfsPath = null; + dfsAccessTable = null; + startDot = null; + endDot = null; + }); + }), + createButton(graphData.getUseLengthStr(), changeLength), + createButton(graphData.getDoubleSidedStr(), changeOriented), + /*Text(_textGrNmController.text, + style: + TextStyle(fontSize: 15, color: Colors.blueGrey.shade900)),*/ + createButton("Save to file", fileSaver), + createButton("Load from file", fileOpener), + createButton("Help", () { + String out = + " В поле \"Graph name\" можно сменить имя графу.\n"; + out += + " Для добавления точки необходимо ввести имя в \"Dot name\" и нажать на \"Add dot\".\n"; + out += + " Для удаления точки необходимо ввести номер в \"Dot number\" и нажать на \"Del dot\".\n"; + out += + " Для добавления пути необходимо ввести: номер выходной вершины в \"Dot number\", номер входной вершины в \"Destination number\" "; + out += + "и, если граф взвешенный, то ввести длину пути в \"Input length\". Затем нажать \"Add path\".\n"; + out += + " Для удаления пути необходимо ввести номер выходной вершины в \"Dot number\" и номер входной вершины в \"Destination number\". Затем нажать \"Del path\".\n\n"; + out += + " Кнопки \"Bfs\" и \"Dfs\" нумеруют точки в зависимости от послежовательности, в которой они будут пройдены.\n"; + out += + " Кнопки \"Взвешенный\" и \"Ориентированный\" позволяют сменить эти значения перед построением графа (т.е. для их работы граф должен быть пустым).\n"; + out += + " Кнопки \"Save to file\" и \"Load from file\" позволяют вывести информацию в файл и загрузить информацию из файла соответственно.\n"; + out += + " Кнопка \"Help\" описывает работу с интерфейсом программы."; + showPopUp("Help:", out); + }) + ], + ), + ), + ), + )); + } + + // ignore: avoid_types_as_parameter_names, non_constant_identifier_names, use_function_type_syntax_for_parameters + ElevatedButton createButton(String txt, void onPressing()) { + return ElevatedButton( + onPressed: onPressing, + style: ButtonStyle( + backgroundColor: MaterialStateProperty.resolveWith( + (states) => Colors.green.shade700)), + child: Text(txt, + style: const TextStyle( + fontSize: 15, + color: Colors.white70, + height: 1, + )), + ); + } + + Container createInputBox(String text, double wid, IconData? icon, + TextEditingController? controller) { + if (icon == null) { + return Container( + width: wid, + height: 40, + margin: const EdgeInsets.symmetric(horizontal: 20, vertical: 5), + child: TextField( + controller: controller, + textAlign: TextAlign.center, + onChanged: (name) => graphData.setName(name), + decoration: InputDecoration( + contentPadding: + const EdgeInsets.symmetric(vertical: 10, horizontal: 10), + filled: true, + fillColor: Colors.white, + //prefixIcon: Icon(icon, color: Colors.black), + border: const OutlineInputBorder( + borderRadius: BorderRadius.all(Radius.circular(40))), + hintStyle: const TextStyle(color: Colors.black38), + hintText: text), + )); + } + return Container( + width: wid, + height: 40, + margin: const EdgeInsets.symmetric(horizontal: 20, vertical: 5), + child: TextField( + controller: controller, + textAlign: TextAlign.center, + decoration: InputDecoration( + contentPadding: + const EdgeInsets.symmetric(vertical: 10, horizontal: 10), + filled: true, + fillColor: Colors.white, + prefixIcon: Icon(icon, color: Colors.black), + border: const OutlineInputBorder( + borderRadius: BorderRadius.all(Radius.circular(40))), + hintStyle: const TextStyle(color: Colors.black38), + hintText: text), + )); + } + + SizedBox addSpaceH(double h) { + return SizedBox(height: h); + } + + SizedBox addSpaceW(double w) { + return SizedBox(width: w); + } + + void showPopUp(String alertTitle, String err) => showDialog( + context: context, + builder: (BuildContext context) => AlertDialog( + title: Text(alertTitle), + content: Text(err), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context, 'OK'), + child: const Text('OK'), + ), + ], + ), + ); + +//*********ButtonsFunctions********* + void addDotPushed() { + //showPopUp("Test", "Test message"); + //var inp = int.tryParse(_textNameController.text); + setState(() { + if (_textNameController.text == "") { + showPopUp("Error", "No name in \"Dot name\" box"); + } else { + String? res = graphData.addIsolated(_textNameController.text); + if (res != null) { + showPopUp("Error", res); + } + } + clearInputData(); + }); + } + + void addPathPushed() { + setState(() { + if (dropdownValue1 == null) { + showPopUp("Error", "Select output dot"); + } else if (dropdownValue2 == null) { + showPopUp("Error", "select input dot"); + } else if (_textLnthController.text == "" && + graphData.getUseLengthBool()) { + showPopUp("Error", "No length in \"Input length\" box"); + } else { + int? from = int.parse(dropdownValue1!); + int? to = int.parse(dropdownValue2!); + int? len = int.tryParse(_textLnthController.text); + if (len == null && graphData.getUseLengthBool()) { + showPopUp("Error", + "Can't parse input.\nInts only allowed in \"Dot number\", \"Destination number\" and \"Input length\""); + } else { + len ??= 0; + String? res = graphData.addPath(from, to, len); + if (res != null) { + showPopUp("Error", res); + } + } + } + clearInputData(); + }); + } + + void changeOriented() { + setState(() { + String? res = graphData.flipUseOrientation(); + if (res != null) showPopUp("Error", res); + }); + } + + void changeLength() { + setState(() { + String? res = graphData.flipUseLength(); + if (res != null) showPopUp("Error", res); + }); + } + + void delPathPushed() { + setState(() { + if (_textNumbController.text == "") { + showPopUp("Error", "No number in \"Dot number\" box"); + } else if (_textDestController.text == "") { + showPopUp("Error", "No name in \"Dot name\" box"); + } else { + int? from = int.tryParse(_textNumbController.text); + int? to = int.tryParse(_textDestController.text); + if (from == null || to == null) { + showPopUp("Error", + "Can't parse input.\nInts only allowed in \"Dot number\" and \"Destination number\""); + } else { + String? res = graphData.delPath(from, to); + if (res != null) { + showPopUp("Error", res); + } + } + } + clearInputData(); + }); + } + + void delDotPushed() { + setState(() { + /*if (_textNumbController.text == "") { + showPopUp("Error", "No number in \"Dot number\" box"); + } else { + int? dot = int.tryParse(_textNumbController.text); + if (dot == null) { + showPopUp("Error", "Can't parse input.\nInts only allowed"); + } else { + String? res = graphData.delDot(dot); + if (res != null) { + showPopUp("Error", res); + } + } + }*/ + if (dropdownValue1 != null) { + graphData.delDot(int.parse(dropdownValue1!)); + } else { + showPopUp("Error", "Nothing in input"); + } + clearInputData(); + }); + } + + void fileOpener() async { + FilePickerResult? result = + await FilePicker.platform.pickFiles(allowedExtensions: ["txt"]); + setState(() { + if (result != null) { + if (!result.files.single.path!.endsWith(".txt")) { + showPopUp("Error", "Can open only \".txt\" files"); + } else { + //print(result.files.single.path!); + String? res = + graphData.replaceDataFromFile(result.files.single.path!); + if (res != null) showPopUp("Error", res); + } + } else { + showPopUp("Error", "No file selected"); + // User canceled the picker + } + }); + } + + void fileSaver() async { + String? outputFile = await FilePicker.platform.saveFile( + dialogTitle: 'Please select an output file:', + fileName: 'output-file.txt', + allowedExtensions: ["txt"]); + if (outputFile == null) { + showPopUp("Error", "Save cancelled"); + // User canceled the picker + } else { + if (!outputFile.endsWith(".txt")) { + outputFile += ".txt"; + } + graphData.printToFile(outputFile); + } + } + + void bfsPushed() { + setState(() { + bfsPath = null; + dfsAccessTable = null; + startDot = null; + endDot = null; + if (dropdownValue1 == null) { + showPopUp("Error", "No number in \"Dot number\" box"); + } else if (dropdownValue2 == null) { + showPopUp("Error", "No number in \"Destination number\" box"); + } else { + startDot = int.parse(dropdownValue1!); + endDot = int.parse(dropdownValue2!); + + bfsPath = graphData.bfsPath(startDot!, endDot!); + if (bfsPath == null) { + showPopUp("Info", "There is no path"); + } + print(bfsPath); + } + }); + clearInputData(); + } + + void dfsPushed() { + setState(() { + bfsPath = null; + dfsAccessTable = null; + startDot = null; + endDot = null; + if (dropdownValue1 == null) { + showPopUp("Error", "No number in \"Dot number\" box"); + } else { + startDot = int.parse(dropdownValue1!); + dfsAccessTable = graphData.dfsIterative(startDot!); + if (dfsAccessTable == null) { + showPopUp("Err", "report this error."); + } + print(dfsAccessTable); + } + clearInputData(); + }); + } + //*********ButtonsFunctions********* + + SizedBox dropList1(double width) { + var button = DropdownButton( + hint: const Text( + 'Select Dot', + style: TextStyle(color: Colors.white, fontSize: 13), + ), // Not necessary for Option 1 + alignment: AlignmentDirectional.centerEnd, + value: dropdownValue1, + + isDense: true, + borderRadius: const BorderRadius.all(Radius.circular(20)), + dropdownColor: Colors.green.shade800, + style: const TextStyle( + //background: Paint()..color = Colors.white, + color: Colors.white, + fontSize: 18, + ), + onChanged: (String? newValue) { + setState(() { + dropdownValue1 = newValue; + }); + }, + items: graphData.getDots().map((location) { + return DropdownMenuItem( + child: Text(location.getName()), + value: location.num.toString(), + ); + }).toList(), + ); + + return SizedBox( + child: button, + width: width, + ); + } + + SizedBox dropList2(double width) { + var button = DropdownButton( + hint: const Text( + 'Select Dot', + style: TextStyle(color: Colors.white, fontSize: 13), + ), // Not necessary for Option 1 + alignment: AlignmentDirectional.centerEnd, + value: dropdownValue2, + + isDense: true, + borderRadius: const BorderRadius.all(Radius.circular(20)), + dropdownColor: Colors.green.shade800, + style: const TextStyle( + //background: Paint()..color = Colors.white, + color: Colors.white, + fontSize: 18, + ), + onChanged: (String? newValue) { + setState(() { + dropdownValue2 = newValue; + }); + }, + items: graphData.getDots().map((location) { + return DropdownMenuItem( + child: Text(location.getName()), + value: location.num.toString(), + ); + }).toList(), + ); + + return SizedBox( + child: button, + width: width, + ); + } +} diff --git a/flutter/lib/graph.dart b/flutter/lib/graph.dart new file mode 100644 index 0000000..cd8707b --- /dev/null +++ b/flutter/lib/graph.dart @@ -0,0 +1,679 @@ +import 'dart:io'; + +class Separators { + static const String dotToConnections = ": "; + static const String dotToLength = "|"; + static const String space = " "; + static const String hasLength = "Взвешенный"; + static const String hasNoLength = "НеВзвешенный"; + static const String isOriented = "Ориентированный"; + static const String isNotOriented = "НеОриентированный"; + static const String nL = "\n"; + static const String end = "END"; + + Separators(); +} + +class Dot { + //Data + // ignore: prefer_final_fields + String _name = ""; + int num = -1; + Map _ln = {}; + + //****Get**** + String getName() => _name; + bool hasConnection(int n) => _ln.containsKey(n); + Map getL() => _ln; + + int getLength(int x) { + if (hasConnection(x)) { + return _ln[x]!; + } + return -1; + } + //****Get**** + + //Set + void setName(String n) => _name = n; + + //Add + void addPath(int inp, int length) => _ln[inp] = length; + + //Del + void delPath(int n) => _ln.removeWhere((key, value) => + key == n); // удалить обратный путь если не ориентированный + + //Print + void printD() { + stdout.write("$_name: №$num => "); + for (var i in _ln.keys) { + stdout.write("$i|${_ln[i]} "); + } + stdout.write("\n"); + } + + //******Constructor****** + Dot([String name = "Undefined", int n = -1]) { + _name = name; + num = n; + _ln = {}; + } + Dot.fromTwoLists(String name, List num0, List length, + [int n = -1]) { + _name = name; + num = n; + Map nw = {}; + if (num0.length != length.length) { + print("Error in lists"); + } else { + for (var i = 0; i < num0.length; i++) { + nw[num0[i]] = length[i]; + _ln = nw; + } + } + } + Dot.fromMap(String name, Map l, [int n = -1]) { + _name = name; + num = n; + _ln = l; + } + //******Constructor****** + + //Copy + Dot.clone(Dot a) { + _name = a.getName(); + num = a.num; + _ln = a.getL(); + } +} + +class Graphs { + //Data + String _name = "Undefined"; //Имя + int _amount = 0; //Количество вершин + List _dots = []; //Список смежности вершин + Map _nameTable = {}; //Список вершин по именам + bool _useLength = false; //Взвешенность + bool _oriented = false; //Ориентированность + + //*********************Add************************ + String? addDot(Dot a) { + if (getNumByName(a.getName()) != null) { + return ("Dot name \"${a.getName()}\" already in use. Change name or use addPath"); + } + _amount++; + a.num = _amount; + _dots.add(a); + _syncNameTable(); + checkDots(false); + if (!_oriented) _fullFix(); + return null; + } + + bool addDotFromToLists(String name, List num0, List length, + [int n = -1]) { + var a = Dot.fromTwoLists(name, num0, length, n); + if (getNumByName(a.getName()) != null) { + print( + "Dot name ${a.getName()} already in use. Change name or use addPath"); + return false; + } + _amount++; + a.num = _amount; + _dots.add(a); + _syncNameTable(); + checkDots(false); + if (!_oriented) _fixPathAfterInsert(a); + return true; + } + + String? addIsolated(String name) { + var res = addDot(Dot.fromTwoLists(name, [], [])); + _syncNameTable(); + return res; + } + + String? addPath(int from, int to, [int len = 0]) { + if (from <= 0 || from > _amount || to <= 0 && to > _amount) { + return "Index out of range. Have dots 1..$_amount"; + } + _dots[from - 1].addPath(to, len); + if (!_oriented) { + _dots[to - 1].addPath(from, len); + } + return null; + } + //*********************Add************************ + + //*********Delete********* + String? delPath(int from, int to) { + if (from <= 0 || from > _amount || to <= 0 && to > _amount) { + return "Can't find specified path"; + } + _dots[from - 1].delPath(to); + if (!_oriented) { + _dots[to - 1].delPath(from); + } + return null; + } + + String? delDot(int inn) { + if (inn > _amount || inn < 1) { + return "Index out of range. Allowed 1..$_amount"; + } + List toDel = []; + for (int i in _dots[inn - 1].getL().keys) { + toDel.add(i); + } + for (int i in toDel) { + delPath(i, inn); + } + _dots.removeAt(inn - 1); + _syncNum(); + _syncNameTable(); + _fixAfterDel(inn); + return null; + } + + void flushData() { + _dots = []; + _amount = 0; + _nameTable = {}; + } + //*********Delete********* + + //******Helper******* + bool checkDots([bool verbose = false]) { + for (var a in _dots) { + for (var i in a.getL().keys) { + try { + if (!_dots[i - 1].getL().containsKey(a.num)) { + if (verbose) print("Can't find ${a.num}"); + return false; + } + } catch (e) { + if (verbose) { + print("Can't find Dot $i for path ${a.num}->$i. Exception $e"); + } + _dots[a.num - 1].getL().remove(i); + return false; + } + } + } + return true; + } + + void _fixAfterDel(int inn) { + for (int i = 0; i < _dots.length; i++) { + Map l = {}; + for (int j in _dots[i].getL().keys) { + if (j >= inn) { + l[j - 1] = _dots[i].getL()[j]!; + } else { + l[j] = _dots[i].getL()[j]!; + } + } + _dots[i] = Dot.fromMap(_dots[i].getName(), l, _dots[i].num); + } + } + + void _fixPathAfterInsert(Dot a) { + //Для неориентированного + for (var i in a.getL().keys) { + if (!_dots[i - 1].getL().containsKey(a.num)) { + addPath(i, a.num, a.getL()[i]!); + } + } + } + + void _fullFix() { + for (var i in _dots) { + _fixPathAfterInsert(i); + } + } + + void _syncNameTable() { + _nameTable = {}; + for (var i in _dots) { + _nameTable[i.num] = i.getName(); + } + } + + void _syncNum() { + _amount = 0; + for (var i in _dots) { + i.num = ++_amount; + } + _syncNameTable(); + } + //******Helper******* + + //*****Setters******* + void setName(String name) => _name = name; + String? flipUseOrientation() { + if (_amount != 0) { + return "Can change use of orientation only in empty graph"; + } + _oriented = !_oriented; + return null; + } + + String? flipUseLength() { + if (_amount != 0) { + return "Can change use of length only in empty graph"; + } + _useLength = !_useLength; + return null; + } + + String? replaceDataFromFile(String path) { + File file = File(path); + List lines = file.readAsLinesSync(); + if (lines.length < 3) { + return "Not enough lines in file"; + } + String name = lines.removeAt(0); + bool oriented; + switch (lines.removeAt(0)) { + case Separators.isOriented: + oriented = true; + break; + case Separators.isNotOriented: + oriented = false; + break; + default: + return "Error on parsing \"IsOriented\""; + } + bool useLength; + switch (lines.removeAt(0).trim()) { + case Separators.hasLength: + useLength = true; + break; + case Separators.hasNoLength: + useLength = false; + break; + default: + return "Error on parsing \"HasLength\""; + } + List dots = []; + for (var l in lines) { + l = l.trimRight(); + if (l != Separators.end) { + var spl = l.split(Separators.space); + List dot = []; + List len = []; + String name = spl.removeAt(0); + name = name.substring(0, name.length - 1); + for (var splitted in spl) { + if (splitted != "") { + var dt = splitted.split(Separators.dotToLength); + if (dt.length == 2) { + int? parsed = int.tryParse(dt[0]); + if (parsed == null) { + return "Error while parsing file\nin parsing int in \"${dt[0]}\""; + } + dot.add(parsed); + if (useLength) { + parsed = int.tryParse(dt[1]); + if (parsed == null) { + return "Error while parsing file\nin parsing int in \"${dt[1]}\""; + } + len.add(parsed); + } else { + len.add(0); + } + } else if (dt.length == 1) { + int? parsed = int.tryParse(splitted); + if (parsed == null) { + return "Error while parsing file\nin parsing int in \"$splitted\""; + } + dot.add(parsed); + len.add(0); + } + } + } + dots.add(Dot.fromTwoLists(name, dot, len)); + } + } + _name = name; + _oriented = oriented; + _useLength = useLength; + _dots = dots; + _syncNum(); + _syncNameTable(); + if (!_oriented) _fullFix(); + return null; + } + //*****Setters******* + + //*****Getters******* + bool getDoubleSidedBool() => _oriented; + String getDoubleSidedStr() { + if (_oriented) return Separators.isOriented; + return Separators.isNotOriented; + } + + bool getUseLengthBool() => _useLength; + String getUseLengthStr() { + if (_useLength) return Separators.hasLength; + return Separators.hasNoLength; + } + + List getDots() => _dots; + String getName() => _name; + String? getNameByNum(int n) => _nameTable[n]; + Map getNameTable() => _nameTable; + int getDotAmount() => _dots.length; + int? getNumByName(String n) { + for (var i in _nameTable.keys) { + if (_nameTable[i] == n) return i; + } + return null; + } + + List>? getLenTable() { + List>? out = >[]; + for (int i = 0; i < _amount; i++) { + List xx = []; + for (int j = 1; j <= _amount; j++) { + xx.add(_dots[i].getLength(j)); + } + out.add(xx); + } + return out; + } + + List>? getPathTable() { + List>? out = >[]; + for (int i = 0; i < _amount; i++) { + List xx = []; + for (int j = 1; j <= _amount; j++) { + if (_dots[i].getLength(j) != -1) { + xx.add(i); + } else { + xx.add(-1); + } + } + out.add(xx); + } + return out; + } + + /*List getNoRepeatDots() { + List ret = []; + for (int i = 0; i < _amount; i++) { + ret.add(Dot(_dots[i].getName(), _dots[i].num)); + } + for (int i = 0; i < _amount; i++) { + for (int j in _dots[i].getL().keys) { + if (!ret[j - 1].hasConnection(i + 1) && !ret[i].hasConnection(j) || + i == j) { + var len = _dots[i].getLength(j); + ret[i].addPath(j, len); + } + } + } + return ret; + }*/ + //*****Getters******* + + //******Print****** + void printG() { + stdout.write("$_name: "); + if (_oriented) { + stdout.write("Ориентированный, "); + } else { + stdout.write("Не ориентированный, "); + } + if (_useLength) { + print("Взвешенный"); + } else { + print("Не взвешенный"); + } + for (var i in _dots) { + i.printD(); + } + } + + void printToFile(String name) { + var file = File(name); + file.writeAsStringSync("$_name\n"); + if (_oriented) { + file.writeAsStringSync("${Separators.isOriented}\n", + mode: FileMode.append); + } else { + file.writeAsStringSync("${Separators.isNotOriented}\n", + mode: FileMode.append); + } + if (_useLength) { + file.writeAsStringSync("${Separators.hasLength}\n", + mode: FileMode.append); + } else { + file.writeAsStringSync("${Separators.hasNoLength}\n", + mode: FileMode.append); + } + for (int i = 0; i < _amount; i++) { + file.writeAsStringSync((i + 1).toString() + Separators.dotToConnections, + mode: FileMode.append); + var d = _dots[i].getL(); + for (var j in d.keys) { + file.writeAsStringSync( + j.toString() + Separators.dotToLength + d[j].toString() + " ", + mode: FileMode.append); + } + file.writeAsStringSync(Separators.nL, mode: FileMode.append); + } + file.writeAsStringSync(Separators.end, mode: FileMode.append); + } + //******Print****** + + //*******Constructor******** + Graphs( + [String name = "Undefined", + bool hasLen = false, + bool isOriented = false]) { + _name = name; + _dots = []; + _useLength = hasLen; + _oriented = isOriented; + _amount = 0; + _nameTable = {}; + } + Graphs.fromList(String name, List dots, bool hasLen, bool oriented) { + _name = name; + _dots = dots; + _useLength = hasLen; + _amount = _dots.length; + _oriented = oriented; + _syncNum(); + if (!_oriented) _fullFix(); + } + Graphs.fromFile(String path) { + replaceDataFromFile(path); + /*File file = File(path); + List lines = file.readAsLinesSync(); + _name = lines.removeAt(0); + _oriented = lines.removeAt(0) == Separators.isOriented.trim(); + _useLength = lines.removeAt(0) == Separators.hasLength.trim(); + _dots = []; + for (var l in lines) { + if (l != Separators.end) { + var spl = l.split(Separators.space); + List dot = []; + List len = []; + String name = spl.removeAt(0); + name = name.substring(0, name.length - 1); + for (var splitted in spl) { + var dt = splitted.split(Separators.dotToLength); + if (dt.length == 2) { + dot.add(int.parse(dt[0])); + if (_useLength) { + len.add(int.parse(dt[1])); + } else { + len.add(0); + } + } else if (dt.length == 1) { + dot.add(int.parse(splitted)); + len.add(0); + } + } + _dots.add(Dot.fromTwoLists(name, dot, len)); + } + } + _syncNum(); + _syncNameTable(); + if (!_oriented) _fullFix();*/ + } + //*******Constructor******** + + //Copy + Graphs.clone(Graphs a) { + _name = a.getName(); + _dots = a.getDots(); + _oriented = a.getDoubleSidedBool(); + _useLength = a.getUseLengthBool(); + _amount = _dots.length; + _syncNameTable(); + } + + //************Алгоритмы************ + /* bool bfsHasPath(int startDot, int goalDot) { + // обход в ширину + startDot--; + goalDot--; + List visited = []; + List queue = []; + for (int i = 0; i < _amount; i++) { + visited.add(false); + } // изначально список посещённых узлов пуст + queue.add(startDot); // начиная с узла-источника + visited[startDot] = true; + while (queue.isNotEmpty) { + // пока очередь не пуста + int node = queue.removeAt(0); // извлечь первый элемент в очереди + if (node == goalDot) { + return true; // проверить, не является ли текущий узел целевым + } + for (int child in _dots[node].getL().keys) { + // все преемники текущего узла, ... + if (!visited[child - 1]) { + // ... которые ещё не были посещены ... + queue.add(child - 1); // ... добавить в конец очереди... + visited[child - 1] = true; // ... и пометить как посещённые + } + } + } + return false; // Целевой узел недостижим + }*/ + + List? bfsPath(int startDot, int goalDot) { + if (startDot == goalDot) return [startDot]; + //if (!bfsHasPath(startDot, goalDot)) return null; + startDot--; + goalDot--; + List>? graph = getLenTable(); + List used = []; + List dst = []; + List pr = []; + + for (int i = 0; i < _amount; i++) { + dst.add(-1); + used.add(false); + pr.add(0); + } + + List q = []; + q.add(startDot); + used[startDot] = true; + dst[startDot] = 0; + pr[startDot] = + -1; //Пометка, означающая, что у вершины startDot нет предыдущей. + + while (q.isNotEmpty) { + int cur = q.removeAt(0); + int x = 0; + for (int neighbor in graph![cur]) { + if (neighbor != -1) { + if (!used[x]) { + q.add(x); + used[x] = true; + dst[x] = dst[cur] + 1; + pr[x] = cur; //сохранение предыдущей вершины + } + } + x++; + } + } + + //Восстановим кратчайший путь + //Для восстановления пути пройдём его в обратном порядке, и развернём. + List path = []; + + int cur = goalDot; //текущая вершина пути + path.add(cur + 1); + + while (pr[cur] != -1) { + //пока существует предыдущая вершина + cur = pr[cur]; //переходим в неё + path.add(cur + 1); //и дописываем к пути + } + + path = path.reversed.toList(); + + //print("Shortest path between vertices ${startDot+1} and ${goalDot+1} is: $path"); + if (path[0] == (startDot + 1) && + path[1] == (goalDot + 1) && + !_dots[startDot].hasConnection(goalDot + 1)) return null; + return path; + } + + List? dfsIterative(int v) { + v--; + //List? pos = []; + List label = []; + for (int i = 0; i < _amount; i++) { + label.add(false); + } + List stack = []; + stack.add(v); + //pos.add(v); + while (stack.isNotEmpty) { + v = stack.removeLast(); + if (!label[v]) { + label[v] = true; + for (int i in _dots[v].getL().keys) { + stack.add(i - 1); + //pos.add(i); + } + } + } + //print(pos); + return label; + } + + void dijkstra(int source) { + /* + create vertex set Q; + + for each vertex v in Graph{ + dist[v] ← INFINITY ; + prev[v] ← UNDEFINED ; + add v to Q;} + dist[source] ← 0; + + while Q is not empty{ + u ← vertex in Q with min dist[u] + + remove u from Q + + for each neighbor v of u still in Q{ + alt ← dist[u] + length(u, v); + if alt < dist[v]: { + dist[v] ← alt; + prev[v] ← u;} + }} + return dist[], prev[]*/ + } + //************Алгоритмы************ +}