Материал: Разработка модуля визуализации компьютерных структур с WEB-интерфейсом

Внимание! Если размещение файла нарушает Ваши авторские права, то обязательно сообщите нам

4.                  Используемые технические средства.

Среда разработки Qt Creator, классы и методы Qt, веб-сервер Apache, операционная система Linux.

.                    Вызов и загрузка.

Вызов приложения происходит через файл Beta. Открытие главной веб-страницы происходит через файл indexOh.html.

.                    Входные данные.

Ссылка на граф.

.                    Выходные данные.

Изображение графа в окне виджета. Сохраненное изображение в память компьютера. Веб-страница с изображением графа.

ПРИЛОЖЕНИЕ Б

Пояснительная записка.

Введение.

Программный модуль Beta получает ссылку на граф и выводит его изображение на экран. Изображение сохраняется в память компьютера. Программный модуль может выполняться на стороне сервера при вызове с веб-страницы, и помещать результат на веб-страницу.

.                    Назначение и область применения.

Программа визуализирует граф, представленный совокупностью дескрипторов. Это поможет более наглядно изучить результат работы над графом, создание и изменения которого производятся в подключаемом модуле. Помимо этого для данной программы разработан веб-интерфейс, с помощью которого выполнение программы можно вызывать на стороне сервера с веб-страницы. Программа сохраняет изображение графа в память компьютера и загружает его на веб-страницу для дальнейшего изучения результата.

Программа является одним из модулей библиотеки транслятора языка моделирования, предназначенного для проведения исследований в области информационных процессов и систем в рамках проекта «Разработка и реализация информационно-аналитической среды, предназначенной для исследования и проектирования информационно-коммуникационных систем» Программы развития КубГУ.

.        Технические характеристики.

Программа написана на языке С++ в среде разработки Qt Creator под операционную систему Linux.

В файле graph.h описаны методы реализации графа, представленного совокупностью дескрипторов. Для представления графа в виде связанных дескрипторов понадобилось 8 структур: 5 для дескрипторов и 3 вспомогательных. Структура DescG представляет собой дескриптор графа. DescV - дескриптор вершины. DescIn и DescOut - дескрипторы входа и выхода. DescAr - дескриптор дуги. SupportInOutArc, SupportArcOut, SupportArcIn - это вспомогательные структуры для оптимизации связи вершин и дуг.

В классе “MainWindow” описан весь алгоритм работы программного модуля.

В методе PaintEvent описан алгоритм обработки и рисования графа. Граф отрисовывается методами drawLine, drawRect и drawText. Сначала рисуются дуги графа. Зеленым цветом обозначен выход дуги, красным вход. Полностью красная дуга означает, что она двунаправленная. Далее рисуются прямоугольники, означающие вершины. В прямоугольниках записаны имена вершин.

В методе StartDraw() происходит создание графа, который будет рисовать программный модуль.

Метод Grab() получает скриншот изображения окна виждета с нарисованным графом и сохраняет его в память компьютера под именем screen.jpg.

В методе keyPressEvent() описываются клавиши клавиатуры, при нажатии на которые вызываются соответствующие методы.

При нажатии на клавишу W вызывается метод zoomIn(2), который увеличивает значения координат вершин в два раза, тем самым увеличивая в два раза изображение, которое мы в итоге получаем.

При нажатии на клавишу S вызывается метод zoomOut(2), который описанным выше методом уменьшает координаты и изображение в два раза.

При нажатии на клавишу Up вызывается метод moveUp(10), в котором координаты по оси y увеличиваются на 10, тем самым передвигая изображение вверх.

При нажатии Down изображение методом moveDown(10) аналогичным образом смещается вниз.

При нажатии Right и Left вызываются соответственно методы moveRight(10) и moveLeft(10), которые увеличивают и уменьшают координаты по оси х на 10, тем самым сдвигая изображения вправо и влево.

При нажатии на клавишу Escape программа закрывается вызовом метода Close().

В файле “main.cpp” создается экземпляр w класса MainWindow. Затем вызывается метод этого класса StartDraw() и создается граф. Далее методом show() создается виджет и происходит реализация алгоритма рисования. После вызывается метод Grab() и изображение графа сохраняется в память компьютера. Также была реализована версия модуля, специально для использования под Веб-интерфейс, которая автоматически закрывает приложение методом Close().

Файл “indexOh.html” является главной веб-страницей. В нем описаны переходы по двум ссылкам. Первая это ссылка на страницу “Oh.php”, где реализуется алгоритм вызова выполнения программного модуля на стороне сервера. Вторая ссылка на страницу “index.html”, куда будет загружаться изображение с результатом работы программы.

Данная программа поможет более наглядно анализировать граф. Также с помощью нее можно работать со структурой компьютера, проводить нужные изменения, и их можно будет анализировать по полученному изображению.

ПРИЛОЖЕНИЕ В

Код программы.

Файл “graph.h”.

#ifndef GRAPH_H

#define GRAPH_H

#include <iostream>

#include<stdio.h>

#include<stdlib.h>

#include<string.h>

#include<math.h>

#include<string.h>

#define N 10

#pragma onceVertCoor

{VertCoor* next;sign;* type;X;Y;

};SupportGraph // ??????????????? ??????? ?????????? ??????

{SupportGraph* next;descV* vert;descAr* arch;

};

list

{* name;list* next;

};id

{* name;ntype;val;

};id* ident[20];descG {sign;descG* next;descG* prev;uid;* name;* pname;type;arn;VertNum;descV* LVert;ArchNum;descAr* LArch;GInNum;descV* GIn;GOutNum;descV* GOut;

};descV {sign;descV* next;descV* prev;uid;* name;* pname;type;descG* graph;InNum;descIn* LIn;OutNum;descOut* LOut;ConnectPr;

};descIn {sign;descIn* next;descIn* prev;uid;* name;* pname;type;ArchNum;SupportInOutArc* LArc;ConnectPr;descV* vert;

};descOut {sign;descOut* next;descOut* prev;uid;* name;* pname;type;ArchNum;SupportInOutArc* LArc;ConnectPr;descV* vert;

};descAr {sign;descAr* next;descAr* prev;uid;* name;* pname;type;arn;InNum;SupportArcIn* LIn;OutNum;SupportArcOut* LOut;

};

// supporting elementsSupportInOutArc

{ struct SupportInOutArc* next;descAr* arch;

};SupportArcOut

{ struct SupportArcOut* next;descOut* Out;

};SupportArcIn

{ struct SupportArcIn* next;descIn* In;

};Soed (struct descV* p1, struct descV* p2,struct descAr* dd);descG* Graph (struct descG* g,struct list* listing, int m1, int m2, int f);list* sp;i,j,u;descG *G;descV *a,*b,*pt,*p,*q,*l;descIn *Vx, *Vxq, *Vxl;descOut *Vi, *Viq, *Vil;descAr *d, *dq, *dl;SupportInOutArc *WD, *WDq, *WDl, WDlp;SupportArcIn *WVx, *WVxq, *WVxl;SupportArcOut *WVi, *WViq, *Wvil;ab[10];*a1;*a2;n;* stringcopy(char* str,int pos1,int pos2)

{* s;i=pos1;j=0;=(char*) malloc(1000*sizeof(char));(i!=pos2)

{[j]=str[i];=i+1 ; j=j+1;

}[j]='\0';s;

}Soed (struct descV* p1, struct descV* p2,struct descAr* dd)

{* c;=stringcopy(p1->name,0,strlen(p1->name));(i=0;i<strlen(p1->name);i++)[i+strlen(p1->name)]=p2->name[i];[strlen(p1->name)+strlen(p2->name)]='\0';=(struct descAr*)malloc(sizeof(struct descAr));>next=NULL;>prev=NULL;>arn=2;>OutNum=1;>InNum=1;>name=stringcopy(c,0,strlen(c));=(struct SupportArcIn*)malloc(sizeof(struct SupportArcIn));=(struct SupportArcOut*)malloc(sizeof(struct SupportArcOut));>next=NULL;>In=p2->LIn;>next=NULL;>Out=p1->LOut;>LIn=WVxq;>LOut=WViq;>next=dq;>prev=dd;=dq;=(struct SupportInOutArc*)malloc(sizeof(struct SupportInOutArc));>next=NULL;>arch=dd;(p1->LOut->LArc!=NULL) {WDl=(struct SupportInOutArc*)malloc(sizeof(struct SupportInOutArc));WDl=p1->LOut->LArc;}(p1->LOut->LArc==NULL)

{->LOut->LArc=WDq;=(struct SupportInOutArc*)malloc(sizeof(struct SupportInOutArc));=p1->LOut->LArc;

}

{(p1->LOut->LArc->next!=NULL) {p1->LOut->LArc=p1->LOut->LArc->next;}->LOut->LArc->next=WDq;->LOut->LArc=WDl;

}=(struct SupportInOutArc*)malloc(sizeof(struct SupportInOutArc));>next=NULL;>arch=dd;(p2->LIn->LArc!=NULL) {WDl=(struct SupportInOutArc*)malloc(sizeof(struct SupportInOutArc));WDl=p2->LIn->LArc;}(p2->LIn->LArc==NULL)

{->LIn->LArc=WDq;=(struct SupportInOutArc*)malloc(sizeof(struct SupportInOutArc));=p2->LIn->LArc;

}

{(p2->LIn->LArc->next!=NULL) {p2->LIn->LArc=p2->LIn->LArc->next;}->LIn->LArc->next=WDq;->LIn->LArc=WDl;

}(p1->graph->type!=4) p1->graph->type=4;(p1->graph->LArch==NULL) p1->graph->LArch=dd;

}list* InNames1()

{list* im;list* l1;list* l2;=(struct list*) malloc(sizeof(struct list));->name="a";=(struct list*) malloc(sizeof(struct list));>next=l1;>name="Svyazi";=(struct list*) malloc(sizeof(struct list));->next=l2;->name="b";=l2;=(struct list*) malloc(sizeof(struct list));->next=l2;->name="c";=l2;=(struct list*) malloc(sizeof(struct list));->next=l2;->name="d";=l2;=(struct list*) malloc(sizeof(struct list));->next=l2;->name="e";=l2;=(struct list*) malloc(sizeof(struct list));->next=l2;->name="f";->next=NULL;im;

}list* InNames2()

{list* im;list* l1;list* l2;=(struct list*) malloc(sizeof(struct list));->name="a1";=(struct list*) malloc(sizeof(struct list));>next=l1;>name="Pustota";=(struct list*) malloc(sizeof(struct list));->next=l2;->name="a2";=l2;=(struct list*) malloc(sizeof(struct list));->next=l2;->name="a3";=l2;=(struct list*) malloc(sizeof(struct list));->next=l2;->name="a4";=l2;=(struct list*) malloc(sizeof(struct list));->next=l2;->name="a5";=l2;=(struct list*) malloc(sizeof(struct list));->next=l2;->name="a6";=l2;=(struct list*) malloc(sizeof(struct list));->next=l2;->name="b1";=l2;=(struct list*) malloc(sizeof(struct list));->next=l2;->name="b2";=l2;=(struct list*) malloc(sizeof(struct list));->next=l2;->name="b3";=l2;=(struct list*) malloc(sizeof(struct list));->next=l2;->name="b4";->next=NULL;im;

}                   Odin(struct descG* g,struct descAr* d)

{i;descV* p;descV* pv;=g->LVert;=p;(i=1;i<=5;i++)

{=pv->next;(p,pv,d);=d->next;=p->next;

}=p->prev->prev;(pv,p,d);=d->next;=g->LVert->next;(pv,p,d);

}Dva(struct descG* g,struct descAr* d)

{i;descV* p;descV* pv;=g->LVert;=p;(i=1;i<=5;i++)

{=pv->next;(p,pv,d);=d->next;

}=pv->next;=p->next;(i=1;i<=3;i++)

{(p,pv,d);=d->next;=p->next;=pv->next;

}=p->prev->prev->prev;(p,pv,d);

}descG* Graph (struct descG* G,struct list* listing, int m1, int m2, int f )

{=listing;>sign=4;>type=0;=m1+m2;>name=stringcopy(sp->name,0,strlen(sp->name));=sp->next;(" Struct name : %s \n",G->name);(" Look at the struct : \n");>arn=1;>VertNum=n;>LVert=NULL;(i=1; i<=n; i++)

{(sp==NULL) break;(i==1)

{=(struct descV*)malloc(sizeof(struct descV));>prev=NULL;>next=NULL;>InNum=1;>OutNum=1;>graph=G;>name=stringcopy(sp->name,0,strlen(sp->name));=sp->next;=(struct descOut*)malloc(sizeof(struct descOut));>next=NULL;>prev=NULL;>name=stringcopy(p->name,0,strlen(p->name));>vert=p;>LArc=NULL;=Vi;=(struct descIn*)malloc(sizeof(struct descIn));>next=NULL;>prev=NULL;>name=stringcopy(p->name,0,strlen(p->name));>vert=p;>LArc=NULL;=Vx;>LIn=Vx;>LOut=Vi;=p;>LVert=p;

}

{=(struct descV*) malloc(sizeof(struct descV));>name=stringcopy(sp->name,0,strlen(sp->name));=sp->next;>next=NULL;>prev=NULL;>InNum=1;>OutNum=1;>graph=G;=(struct descIn*)malloc(sizeof(struct descIn));=(struct descOut*)malloc(sizeof(struct descOut));>name=stringcopy(q->name,0,strlen(q->name));>name=stringcopy(q->name,0,strlen(q->name));>vert=q;>next=NULL;>prev=NULL;>next=NULL;>prev=NULL;>vert=q;>LArc=NULL;>LArc=NULL;>next=Vxq;>prev=Vx;=Vxq;>next=Viq;>prev=Vi;=Viq;>LIn=Vx;>LOut=Vi;>next=q;>prev=p;=q;>next=NULL;

}

}=(struct descAr*) malloc(sizeof(struct descAr));>next=NULL;>prev=NULL;=d;>LArch=NULL;(" Struct name : %s \n",G->name);(f==1) Odin(G,d);Dva(G,d);(" \n \n First look : \n");G;

}

#endif //GRAPH_H

Файл “main.cpp”.

#include <QtGui/QApplication>

#include "mainwindow.h"main(int argc, char *argv[])

{a(argc, argv);w;.StartDraw();.show();.Grab();

// w.Close();a.exec();

}

Файл “MainWindow.h”.

#ifndef MAINWINDOW_H

#define MAINWINDOW_H

#include <QMainWindow>Ui {MainWindow;

}MainWindow : public QMainWindow

{_OBJECT:MainWindow(QWidget *parent = 0);

~MainWindow();Grab();keyPressEvent(QKeyEvent *e);StartDraw();Close();:::MainWindow *ui;:paintEvent(QPaintEvent *);moveLeft(int k);moveRight(int k);moveUp(int k);moveDown(int k);zoomIn(int k);zoomOut(int k);VertCoor *VCoor;VertCoor* VCoorL;descG* g1;descG* g2;f;

};

#endif // MAINWINDOW_H

Файл “MainWindow.cpp”.

#include "mainwindow.h"

#include "ui_mainwindow.h"

#include <QPainter>

#include <QtCore>

#include <QtGui>

#include "graph.h"

#include <QTextCodec>

#include <QString>

#include <fstream>

#include <cstdlib>

#include <cmath>

#include <ctime>

#include <iostream>

#include <time.h>

#include <QDebug>

#include <QObject>::MainWindow(QWidget *parent) :(parent),(new Ui::MainWindow)

{>setupUi(this);

}::~MainWindow()

{ui;

}MainWindow::paintEvent(QPaintEvent *)

{(Qt::StrongFocus);>setFocus();(800,600);(0,0);("Vizualisation of Graph");p(this);.setRenderHint(QPainter::Antialiasing, true);.setRenderHint(QPainter::TextAntialiasing, true);penB(Qt::white);.setWidth(1);penR(Qt::black);.setWidth(1);.setPen(penR);.setBrush(QBrush(Qt::darkCyan,Qt::SolidPattern));.fillRect(0,0,width(),height(),Qt::white);lg = QLinearGradient(QPointF(0,0),QPointF(0,1));.setCoordinateMode(QGradient::ObjectBoundingMode );.setSpread(QGradient::PadSpread);.setColorAt(0.0,Qt::green);.setColorAt(1.0,Qt::red);brush = QBrush(lg);painter(this);.setBrush(brush);p2;.setBrush(brush);.setWidth(2);n=0;descV* NumV=g1->LVert;(NumV->next!=NULL)

{ n++;=NumV->next;

}descV* VList;=g1->LVert;(int i=0;i!=n;i++)

{>sign=i;=VList->next;

}(VList->prev!=NULL)

{=VList->prev;

}->LVert=VList;(f)

{aK=0;x=this->width()/2;y=this->height()/2;pi=3.14;VertCoor* VCoor3;=(struct VertCoor*)malloc(sizeof(struct VertCoor));>X=(int)(x+120*cos(aK*pi/180));>Y=(int)(y-120*sin(aK*pi/180));>sign=VList->sign;>type=VList->name;=VCoor;=aK+360/(n+1);=VList->next;(int i=0;i!=n;i++)

{=(struct VertCoor*)malloc(sizeof(struct VertCoor));->sign=VList->sign;->type=VList->name;->X=(int)(x+120*cos(aK*pi/180));->Y=(int)(y-120*sin(aK*pi/180));>next=VCoor3;=VCoor3;=VList->next;=aK+360/(n+1);

}>next=NULL;

}=VCoorL;descV* vert;=g1->LVert;x1,y1,x2,y2,n1,n2;sign1;.setPen(p2);descV* vert2;=g1->LVert;(vert2!=NULL)

{SupportInOutArc* ALIST2 = vert2->LOut->LArc;(ALIST2!=NULL)

{=ALIST2->arch->LOut->Out->vert->sign;=VCoorL;(VCoor!=NULL)

{(VCoor->sign == sign1 )

{=VCoor->X;=VCoor->Y;=sign1;

}=VCoor->next;

}=ALIST2->arch->LIn->In->vert->sign;=VCoorL;(VCoor!=NULL)

{(VCoor->sign==sign1 )

{=VCoor->X;=VCoor->Y;=sign1;

}=VCoor->next;

}.drawLine(x1,y1,x2,y2);= ALIST2->next;

}= vert2->next;

}p3(this);brush1 = QBrush(Qt::darkCyan,Qt::SolidPattern);.setBrush(brush1);=VCoorL;(VCoor!=NULL)

{.drawRect(VCoor->X-15,VCoor->Y-15,30,30);=VCoor->next;

}p4(this);penB2(Qt::white);.setPen(penB2);.setFont(QFont("Times", 14));=VCoorL;(VCoor!=NULL)

{text=(QString)VCoor->type;.drawText(VCoor->X-8,VCoor->Y+8,text);=VCoor->next;

}

}MainWindow::StartDraw()

{=true;list* names1;list* names2;=(struct descG*)malloc(sizeof(struct descG));->next=NULL;->prev=NULL;->sign=0;=(struct descG*)malloc(sizeof(struct descG));->next=NULL;->prev=NULL;->sign=0;=InNames1();=InNames2();=Graph(g1,names1,4,2,1);=Graph(g2,names2,6,4,2);->next=NULL;->next=NULL;

}MainWindow::Grab()

{okno = QPixmap::grabWidget(this,0,0,800,600);.save("/var/www/screen.jpg","JPG",100);

}MainWindow::keyPressEvent(QKeyEvent *e)

{(e->key())

{Qt::Key_W: zoomIn(2); break;Qt::Key_S: zoomOut(2); break;Qt::Key_Up: moveUp(10);break;Qt::Key_Down: moveDown(10);break;Qt::Key_Right: moveRight(10); break;Qt::Key_Left: moveLeft(10); break;Qt::Key_Escape: Close(); break;

}

}MainWindow::moveLeft(int k)

{=false;=VCoorL;(VCoor!=NULL)

{>X-=k;=VCoor->next;

}>repaint();

}MainWindow::moveRight(int k)

{f=false;=VCoorL;(VCoor!=NULL)

{>X+=k;=VCoor->next;

}>repaint();

}MainWindow::moveUp(int k)

{f=false;=VCoorL;(VCoor!=NULL)

{>Y-=k;=VCoor->next;

}>repaint();

}MainWindow::moveDown(int k)

{f=false;=VCoorL;(VCoor!=NULL)

{>Y+=k;=VCoor->next;

}>repaint();

}MainWindow::zoomIn(int k)

{f=false;=VCoorL;(VCoor!=NULL)

{>X*=k;>Y*=k;=VCoor->next;

}>repaint();

Источник: https://www.bibliofond.ru/view.aspx?id=868565