1
0
mirror of https://github.com/ManyakRus/crud_generator.git synced 2024-12-22 00:36:41 +02:00

новый

This commit is contained in:
Nikitin Aleksandr 2023-09-28 18:08:00 +03:00
parent b4489c07a3
commit dae94b634c
10 changed files with 454 additions and 1289 deletions

View File

@ -0,0 +1,273 @@
package object_model
import (
"context"
"errors"
"fmt"
"gitlab.aescorp.ru/dsp_dev/claim/nikitin/micro"
"gitlab.aescorp.ru/dsp_dev/claim/nikitin/postgres_gorm"
"gorm.io/gorm"
"time"
)
type crud_MessageType struct {
}
// Read - находит запись в БД по ID
func (crud crud_MessageType) read(m *MessageType) error {
var err error
//log.Trace("start Read() ", TableName, " id: ", id)
ctxMain := context.Background()
ctx, ctxCancelFunc := context.WithTimeout(ctxMain, time.Second*time.Duration(TIMEOUT_DB_SECONDS))
defer ctxCancelFunc()
err = crud.read_ctx(ctx, m)
return err
}
// Read_ctx - находит запись в БД по ID
func (crud crud_MessageType) read_ctx(ctx context.Context, m *MessageType) error {
var err error
db := postgres_gorm.GetConnection()
db.WithContext(ctx)
tx := db.First(m, m.ID)
err = tx.Error
return err
}
// Save - записывает новый или существующий объект в базу данных
func (crud crud_MessageType) save(m *MessageType) error {
err := crud.create_update(m, false)
return err
}
// Save_ctx - записывает новый или существующий объект в базу данных
func (crud crud_MessageType) save_ctx(ctx context.Context, m *MessageType) error {
is_create := !micro.BoolFromInt64(m.ID)
err := crud.create_update_ctx(ctx, m, is_create)
return err
}
// Update - записывает существующий объект в базу данных
func (crud crud_MessageType) update(m *MessageType) error {
err := crud.create_update(m, false)
return err
}
// Update_ctx - записывает существующий объект в базу данных
func (crud crud_MessageType) update_ctx(ctx context.Context, m *MessageType) error {
err := crud.create_update_ctx(ctx, m, false)
return err
}
// Create - записывает новый объект в базу данных
func (crud crud_MessageType) create(m *MessageType) error {
err := crud.create_update(m, true)
return err
}
// Create_ctx - записывает новый объект в базу данных
func (crud crud_MessageType) create_ctx(ctx context.Context, m *MessageType) error {
err := crud.create_update_ctx(ctx, m, true)
return err
}
// create_update - записывает объект в базу данных
func (crud crud_MessageType) create_update(m *MessageType, is_create bool) error {
var err error
//log.Trace("start Save() ", TableName, " id: ", m.ID)
ctxMain := context.Background()
ctx, ctxCancelFunc := context.WithTimeout(ctxMain, time.Second*time.Duration(TIMEOUT_DB_SECONDS))
defer ctxCancelFunc()
err = crud.create_update_ctx(ctx, m, is_create)
return err
}
// create_update_ctx - записывает объект в базу данных
func (crud crud_MessageType) create_update_ctx(ctx context.Context, m *MessageType, is_create bool) error {
var err error
//log.Trace("start Save() ", TableName, " id: ", m.ID)
// проверка ID
if is_create == true {
if m.ID != 0 {
TextError := fmt.Sprint("db.Save() ", m.TableName(), " error: id !=0")
//log.Panic(sError)
err = errors.New(TextError)
return err
}
} else if m.ID == 0 {
TextError := fmt.Sprint("db.Save() ", m.TableName(), " error: id =0")
err = errors.New(TextError)
//log.Panic(sError)
return err
}
//
db := postgres_gorm.GetConnection()
db.WithContext(ctx)
//заполним даты
Now := time.Now()
m.ModifiedAt = Now
if m.IsDeleted == true && m.DeletedAt.IsZero() == true {
m.DeletedAt = Now
} else if m.IsDeleted == false && m.DeletedAt.IsZero() == false {
m.DeletedAt = time.Time{}
}
//колонки с null
tx := db
MassOmit := make([]string, 0)
var ColumnName string
ColumnName = "DeletedAt"
if m.DeletedAt.IsZero() == true {
MassOmit = append(MassOmit, ColumnName)
}
ColumnName = "ExtID"
if m.ExtID == 0 {
MassOmit = append(MassOmit, ColumnName)
}
//игнор пустых колонок
tx = tx.Omit(MassOmit...)
//запись
if is_create == true {
tx = tx.Create(m)
} else {
tx = tx.Save(m)
}
err = tx.Error
if err != nil {
return err
}
//запишем NULL в пустые колонки
for f := 0; f < len(MassOmit); f++ {
ColumnName := MassOmit[f]
tx = db.First(m).Update(ColumnName, gorm.Expr("NULL"))
err = tx.Error
if err != nil {
TextError := fmt.Sprint("db.Update() ", m.TableName(), " id: ", m.ID, " error: ", err)
err = errors.New(TextError)
return err
//log.Panic(sError)
}
}
return err
}
// Delete - записывает is_deleted = true
func (crud crud_MessageType) delete(m *MessageType) error {
var err error
ctxMain := context.Background()
ctx, ctxCancelFunc := context.WithTimeout(ctxMain, time.Second*time.Duration(TIMEOUT_DB_SECONDS))
defer ctxCancelFunc()
err = crud.delete_ctx(ctx, m)
return err
}
// Delete_ctx - записывает is_deleted = true
func (crud crud_MessageType) delete_ctx(ctx context.Context, m *MessageType) error {
var err error
var m2 *MessageType
m2.ID = m.ID
err = crud.read_ctx(ctx, m2)
if err != nil {
return err
}
m.IsDeleted = true
m2.IsDeleted = true
err = crud.save_ctx(ctx, m2)
return err
}
// Restore - записывает is_deleted = true
func (crud crud_MessageType) restore(m *MessageType) error {
var err error
ctxMain := context.Background()
ctx, ctxCancelFunc := context.WithTimeout(ctxMain, time.Second*time.Duration(TIMEOUT_DB_SECONDS))
defer ctxCancelFunc()
err = crud.restore_ctx(ctx, m)
return err
}
// Restore_ctx - записывает is_deleted = true
func (crud crud_MessageType) restore_ctx(ctx context.Context, m *MessageType) error {
var err error
var m2 *MessageType
m2.ID = m.ID
err = crud.read_ctx(ctx, m2)
if err != nil {
return err
}
m.IsDeleted = false
m2.IsDeleted = false
err = crud.save_ctx(ctx, m2)
return err
}
//// Find_ByExtID - находит запись в БД по ext_id и connection_id
//func Find_ByExtID(ext_id int64, connection_id int64) (MessageType, error) {
// var Otvet MessageType
// var err error
//
// if ext_id <= 0 {
// err = errors.New("Error: ext_id <=0")
// return Otvet, err
// }
//
// //
// ctxMain := context.Background()
// ctx, ctxCancelFunc := context.WithTimeout(ctxMain, time.Second*time.Duration(TIMEOUT_DB_SECONDS))
// defer ctxCancelFunc()
//
// Otvet, err = Find_ByExtID_ctx(ctx, ext_id, connection_id)
//
// return Otvet, err
//}
//// Find_ByExtID_ctx - находит запись в БД по ext_id и connection_id
//func Find_ByExtID_ctx(ctx context.Context, ext_id int64, connection_id int64) (MessageType, error) {
// var Otvet MessageType
// var err error
// //log.Trace("start Find_ByExtID() ", TableName, " ext_id: ", ext_id)
//
// if ext_id <= 0 {
// err = errors.New("Error: ext_id <=0")
// return Otvet, err
// }
//
// db := postgres_gorm.GetConnection()
// db.WithContext(ctx)
//
// tx := db.Where("ext_id = ?", ext_id).Where("connection_id = ?", connection_id).First(&Otvet)
// err = tx.Error
//
// return Otvet, err
//}

View File

@ -0,0 +1,131 @@
package object_model
import (
"encoding/json"
"github.com/vmihailenco/msgpack/v5"
"reflect"
)
// versionMessageType - версия структуры модели, с учётом имен и типов полей
var versionMessageType uint32
// MessageType - Типы сообщений
type MessageType struct {
CommonStruct
NameStruct
Code int `json:"code" gorm:"column:code;default:0"`
}
// TableName - возвращает имя таблицы в БД, нужен для gorm
func (m MessageType) TableName() string {
return "message_types"
}
// GetID - возвращает ID объекта
func (m MessageType) GetID() int64 {
return m.ID
}
// NewMessageType - возвращает новый объект
func NewMessageType() MessageType {
return MessageType{}
}
// AsMessageType - создаёт объект из упакованного объекта в массиве байтов
func AsMessageType(b []byte) (MessageType, error) {
c := NewMessageType()
err := msgpack.Unmarshal(b, &c)
if err != nil {
return NewMessageType(), err
}
return c, nil
}
// MessageTypeAsBytes - упаковывает объект в массив байтов
func MessageTypeAsBytes(m *MessageType) ([]byte, error) {
b, err := msgpack.Marshal(m)
if err != nil {
return nil, err
}
return b, nil
}
// GetStructVersion - возвращает версию модели
func (m MessageType) GetStructVersion() uint32 {
if versionMessageType == 0 {
versionMessageType = CalcStructVersion(reflect.TypeOf(m))
}
return versionMessageType
}
// GetModelFromJSON - создаёт модель из строки json
func (m *MessageType) GetModelFromJSON(sModel string) error {
var err error
var bytes []byte
bytes = []byte(sModel)
err = json.Unmarshal(bytes, m)
return err
}
// GetJSON - возвращает строку json из модели
func (m MessageType) GetJSON() (string, error) {
var ReturnVar string
var err error
bytes, err := json.Marshal(m)
if err != nil {
return ReturnVar, err
}
ReturnVar = string(bytes)
return ReturnVar, err
}
//---------------------------- CRUD операции ------------------------------------------------------------
// Read - находит запись в БД по ID, и заполняет в объект
func (m *MessageType) Read() error {
err := m.read()
return err
}
// Save - записывает объект в БД по ID
func (m *MessageType) Save() error {
err := m.save()
return err
}
// Update - обновляет объект в БД по ID
func (m *MessageType) Update() error {
err := m.update()
return err
}
// Create - создаёт объект в БД с новым ID
func (m *MessageType) Create() error {
err := m.create()
return err
}
// Delete - устанавливает признак пометки удаления в БД
func (m *MessageType) Delete() error {
err := m.delete()
return err
}
// Restore - снимает признак пометки удаления в БД
func (m *MessageType) Restore() error {
err := m.restore()
return err
}
//---------------------------- конец CRUD операции ------------------------------------------------------------

View File

@ -4,28 +4,28 @@ import (
"os"
)
const FILENAME_GRAPHML = "connections.graphml"
// Settings хранит все нужные переменные окружения
var Settings SettingsINI
// SettingsINI - структура для хранения всех нужных переменных окружения
type SettingsINI struct {
FILENAME_GRAPHML string
INCLUDE_TABLES string
EXCLUDE_TABLES string
INCLUDE_TABLES string
EXCLUDE_TABLES string
TEMPLATE_FILENAME_MODEL string
TEMPLATE_FILENAME_DB string
TEMPLATE_FILENAME_GRPC string
TEMPLATE_FILENAME_NRPC string
}
// FillSettings загружает переменные окружения в структуру из переменных окружения
func FillSettings() {
Settings = SettingsINI{}
Settings.FILENAME_GRAPHML = os.Getenv("FILENAME_GRAPHML")
Settings.INCLUDE_TABLES = os.Getenv("INCLUDE_TABLES")
Settings.EXCLUDE_TABLES = os.Getenv("EXCLUDE_TABLES")
if Settings.FILENAME_GRAPHML == "" {
Settings.FILENAME_GRAPHML = FILENAME_GRAPHML
}
Settings.TEMPLATE_FILENAME_MODEL = os.Getenv("TEMPLATE_FILENAME_MODEL")
Settings.TEMPLATE_FILENAME_DB = os.Getenv("TEMPLATE_FILENAME_DB")
Settings.TEMPLATE_FILENAME_GRPC = os.Getenv("TEMPLATE_FILENAME_GRPC")
Settings.TEMPLATE_FILENAME_NRPC = os.Getenv("TEMPLATE_FILENAME_NRPC")
//
}
@ -47,7 +47,4 @@ func FillFlags() {
return
}
if len(Args) > 0 {
Settings.FILENAME_GRAPHML = Args[0]
}
}

View File

@ -1,6 +1,9 @@
package constants
const TEXT_HELP = `
Run the image_connections file with parameters:
image_connections <your repository directory> <filename.graphml>
Need create .env file with settings
`
const FolderTemplates string = "templates"
const FolderReady string = "ready"

View File

@ -1,16 +1,16 @@
package logic
import (
"github.com/ManyakRus/crud_generator/internal/constants"
"github.com/ManyakRus/crud_generator/internal/postgres"
"github.com/ManyakRus/crud_generator/internal/types"
"github.com/ManyakRus/crud_generator/pkg/graphml"
"github.com/ManyakRus/starter/log"
"sort"
"github.com/ManyakRus/starter/micro"
)
//var MassTable []types.Table
func StartFillAll(FileName string) bool {
func StartFillAll() bool {
Otvet := false
//заполним MapAll
@ -29,99 +29,45 @@ func StartFillAll(FileName string) bool {
return Otvet
}
//создадим документ
DocXML, ElementInfoGraph := graphml.CreateDocument()
//заполним прямоугольники в документ
err = FillEntities(ElementInfoGraph, &MapAll)
if err != nil {
log.Error("FillEntities() error: ", err)
return Otvet
}
//заполним стрелки в документ
err = FillEdges(ElementInfoGraph, &MapAll)
if err != nil {
log.Error("FillEdges() error: ", err)
return Otvet
}
log.Info("Start save file")
DocXML.Indent(2)
err = DocXML.WriteToFile(FileName)
if err != nil {
log.Error("WriteToFile() FileName: ", FileName, " error: ", err)
}
err = CreateModelFiles(MapAll)
return Otvet
}
// FillEntities - заполняет прямоугольники Entities в файл .xml
func FillEntities(ElementInfoGraph types.ElementInfoStruct, MapAll *map[string]*types.Table) error {
//// MassFromMapColumns - возвращает Slice из Map
//func MassFromMapColumns(MapColumns map[string]types.Column) []types.Column {
// Otvet := make([]types.Column, 0)
//
// for _, v := range MapColumns {
// Otvet = append(Otvet, v)
// }
//
// sort.Slice(Otvet[:], func(i, j int) bool {
// return Otvet[i].OrderNumber < Otvet[j].OrderNumber
// })
//
// return Otvet
//}
func CreateModelFiles(MapAll map[string]*types.Table) error {
var err error
for _, table1 := range *MapAll {
TextAttributes := ""
MassColumns := MassFromMapColumns(table1.MapColumns)
for _, column1 := range MassColumns {
if TextAttributes != "" {
TextAttributes = TextAttributes + "\n"
}
TextAttributes = TextAttributes + column1.Name + " " + column1.Type
}
ElementInfo1 := graphml.CreateElement_Entity(ElementInfoGraph, table1.Name, TextAttributes)
table1.ElementInfo = ElementInfo1
}
return err
}
// MassFromMapColumns - возвращает Slice из Map
func MassFromMapColumns(MapColumns map[string]types.Column) []types.Column {
Otvet := make([]types.Column, 0)
for _, v := range MapColumns {
Otvet = append(Otvet, v)
}
sort.Slice(Otvet[:], func(i, j int) bool {
return Otvet[i].OrderNumber < Otvet[j].OrderNumber
})
return Otvet
}
// FillEdges - заполняет стрелки в файл .xml
func FillEdges(ElementInfoGraph types.ElementInfoStruct, MapAll *map[string]*types.Table) error {
var err error
MapAll0 := *MapAll
for _, table1 := range *MapAll {
for _, column1 := range table1.MapColumns {
if column1.TableKey == "" || column1.ColumnKey == "" {
continue
}
//только если есть внешний ключ
//тыблица из ключа
TableKey, ok := MapAll0[column1.TableKey]
if ok == false {
log.Warn("Error. Not found table name: ", column1.TableKey)
continue
}
//колонка из ключа
ColumnKey, ok := TableKey.MapColumns[column1.ColumnKey]
if ok == false {
log.Warn("Error. Not found column name: ", column1.ColumnKey)
continue
}
//
decription := column1.Name + " - " + ColumnKey.Name
graphml.CreateElement_Edge(ElementInfoGraph, table1.ElementInfo, TableKey.ElementInfo, "", decription, column1.OrderNumber+1, ColumnKey.OrderNumber+1)
for _, table1 := range MapAll {
err = CreateModelFiles1(table1)
if err != nil {
return err
}
}
return err
}
func CreateModelFiles1(table1 *types.Table) error {
var err error
DirBin := micro.ProgramDir_bin()
DirTemplates := DirBin + constants.FolderTemplates + micro.SeparatorFile()
DirReady := DirBin + constants.FolderReady + micro.SeparatorFile()
return err
}

View File

@ -24,10 +24,8 @@ func StartApp() {
graphml.StartReadFile()
FileName := config.Settings.FILENAME_GRAPHML
log.Info("file graphml: ", FileName)
log.Info("postgres host: ", postgres_gorm.Settings.DB_HOST)
ok := logic.StartFillAll(FileName)
ok := logic.StartFillAll()
if ok == false {
println(constants.TEXT_HELP)
}

View File

@ -1,944 +0,0 @@
package graphml
import (
"fmt"
"github.com/ManyakRus/crud_generator/internal/types"
"github.com/beevik/etree"
_ "github.com/beevik/etree"
"math"
"strconv"
"strings"
)
// FONT_SIZE_ENTITY - размер шрифта Entity
var FONT_SIZE_ENTITY = 16
// FONT_SIZE_BENDS - размер шрифта стрелки куриная лапка
var FONT_SIZE_BENDS = 8
// FONT_SIZE_SHAPE - размер шрифта прямоугольника
var FONT_SIZE_SHAPE = 16
// FONT_SIZE_SHAPE - размер шрифта групп
var FONT_SIZE_GROUP = 10
// FONT_SIZE_EDGE - размер шрифта стрелок
var FONT_SIZE_EDGE = 8
// CreateElement_Entity - создаёт элемент - Entity
func CreateElement_Entity(ElementInfoMain types.ElementInfoStruct, ElementName, ElementAttribute string) types.ElementInfoStruct {
Width := findWidth_Entity(ElementName + "\n" + ElementAttribute)
Height := findHeight_Entity(ElementName + ElementAttribute)
sWidth := fmt.Sprintf("%.1f", float64(Width))
sHeight := fmt.Sprintf("%.1f", float64(Height))
sFontSize := strconv.Itoa(FONT_SIZE_ENTITY)
//ищем graph
var ElementGraph *etree.Element
ElementGraph2 := ElementInfoMain.Element.SelectElement("graph")
if ElementGraph2 != nil {
ElementGraph = ElementGraph2
} else {
ElementGraph = ElementInfoMain.Element
}
//node
ElementNode := ElementGraph.CreateElement("node")
var ElementInfoNode types.ElementInfoStruct
ElementInfoNode.Element = ElementNode
ElementInfoNode.Name = ElementName
ElementInfoNode.Parent = &ElementInfoMain
ElementInfoNode.Attribute = ElementAttribute
ElementInfoNode.Width = Width
ElementInfoNode.Height = Height
sId := FindId(ElementInfoMain, ElementInfoNode)
ElementNode.CreateAttr("id", sId)
//ElementNode.CreateAttr("id", "n"+strconv.Itoa(ElementNode.Index()))
//data
ElementData := ElementNode.CreateElement("data")
ElementData.CreateAttr("key", "d4")
//data
ElementData2 := ElementNode.CreateElement("data")
ElementData2.CreateAttr("key", "d5")
//y:GenericNode
ElementYGenericNode := ElementData2.CreateElement("y:GenericNode")
ElementYGenericNode.CreateAttr("configuration", "com.yworks.entityRelationship.big_entity")
sx := "-270"
sy := "-65"
NodeStructOld, ok := types.MapNodeStructOld[ElementName]
if ok == true {
sx = fmt.Sprintf("%f", NodeStructOld.X)
sy = fmt.Sprintf("%f", NodeStructOld.Y)
}
//YGeometry
ElementYGeometry := ElementYGenericNode.CreateElement("y:Geometry")
ElementYGeometry.CreateAttr("height", sHeight)
ElementYGeometry.CreateAttr("width", sWidth)
ElementYGeometry.CreateAttr("x", sx)
ElementYGeometry.CreateAttr("y", sy)
//YFill
ElementYFill := ElementYGenericNode.CreateElement("y:Fill")
ElementYFill.CreateAttr("color", "#E8EEF7")
ElementYFill.CreateAttr("color2", "#B7C9E3")
ElementYFill.CreateAttr("transparent", "false")
//BorderStyle
ElementBorderStyle := ElementYGenericNode.CreateElement("y:BorderStyle")
ElementBorderStyle.CreateAttr("color", "#000000")
ElementBorderStyle.CreateAttr("type", "line")
ElementBorderStyle.CreateAttr("width", "1.0")
//NodeLabel
ElementNodeLabel := ElementYGenericNode.CreateElement("y:NodeLabel")
ElementNodeLabel.CreateAttr("alignment", "center")
ElementNodeLabel.CreateAttr("autoSizePolicy", "content")
ElementNodeLabel.CreateAttr("backgroundColor", "#B7C9E3")
ElementNodeLabel.CreateAttr("configuration", "com.yworks.entityRelationship.label.name")
ElementNodeLabel.CreateAttr("fontFamily", "Dialog")
ElementNodeLabel.CreateAttr("fontSize", sFontSize)
ElementNodeLabel.CreateAttr("fontStyle", "plain")
ElementNodeLabel.CreateAttr("hasLineColor", "false")
ElementNodeLabel.CreateAttr("height", sHeight)
ElementNodeLabel.CreateAttr("horizontalTextPosition", "center")
ElementNodeLabel.CreateAttr("iconTextGap", "4")
ElementNodeLabel.CreateAttr("modelName", "internal")
ElementNodeLabel.CreateAttr("modelPosition", "t")
ElementNodeLabel.CreateAttr("textColor", "#000000")
ElementNodeLabel.CreateAttr("verticalTextPosition", "bottom")
ElementNodeLabel.CreateAttr("visible", "true")
ElementNodeLabel.CreateAttr("width", sWidth)
ElementNodeLabel.CreateAttr("x", "16.0")
ElementNodeLabel.CreateAttr("xml:space", "preserve")
ElementNodeLabel.CreateAttr("y", "4.0")
ElementNodeLabel.CreateText(ElementName)
//NodeLabel
ElementNodeLabel2 := ElementYGenericNode.CreateElement("y:NodeLabel")
ElementNodeLabel2.CreateAttr("alignment", "left")
ElementNodeLabel2.CreateAttr("autoSizePolicy", "content")
ElementNodeLabel2.CreateAttr("configuration", "com.yworks.entityRelationship.label.attributes")
ElementNodeLabel2.CreateAttr("fontFamily", "Dialog")
ElementNodeLabel2.CreateAttr("fontSize", sFontSize)
ElementNodeLabel2.CreateAttr("fontStyle", "plain")
ElementNodeLabel2.CreateAttr("hasBackgroundColor", "false")
ElementNodeLabel2.CreateAttr("hasLineColor", "false")
ElementNodeLabel2.CreateAttr("height", sHeight)
ElementNodeLabel2.CreateAttr("horizontalTextPosition", "center")
ElementNodeLabel2.CreateAttr("iconTextGap", "4")
ElementNodeLabel2.CreateAttr("modelName", "free")
ElementNodeLabel2.CreateAttr("modelPosition", "anywhere")
ElementNodeLabel2.CreateAttr("textColor", "#000000")
ElementNodeLabel2.CreateAttr("verticalTextPosition", "top")
ElementNodeLabel2.CreateAttr("visible", "true")
ElementNodeLabel2.CreateAttr("width", sWidth)
ElementNodeLabel2.CreateAttr("x", "2.0")
ElementNodeLabel2.CreateAttr("xml:space", "preserve")
ElementNodeLabel2.CreateAttr("y", "30.0")
ElementNodeLabel2.CreateText(ElementAttribute)
//y:LabelModel
ElementYLabelModel := ElementNodeLabel2.CreateElement("y:LabelModel")
//y:ErdAttributesNodeLabelModel
ElementYLabelModel.CreateElement("y:ErdAttributesNodeLabelModel")
//y:ModelParameter
ElementYModelParameter := ElementNodeLabel2.CreateElement("y:ModelParameter")
//y:ErdAttributesNodeLabelModelParameter
ElementYModelParameter.CreateElement("y:ErdAttributesNodeLabelModelParameter")
//y:StyleProperties
ElementYStyleProperties := ElementYGenericNode.CreateElement("y:StyleProperties")
//y:Property
ElementYProperty := ElementYStyleProperties.CreateElement("y:Property")
ElementYProperty.CreateAttr("class", "java.lang.Boolean")
ElementYProperty.CreateAttr("name", "y.view.ShadowNodePainter.SHADOW_PAINTING")
ElementYProperty.CreateAttr("value", "true")
return ElementInfoNode
}
// CreateElement_Edge - создаёт элемент graphml - стрелка
func CreateElement_Edge(ElementInfoGraph, ElementInfoFrom, ElementInfoTo types.ElementInfoStruct, label, Description string, NumberAttributeFrom, NumberAttributeTo int) types.ElementInfoStruct {
NameFrom := ElementInfoFrom.Name
NodeStructFrom, ok_from := types.MapNodeStructOld[NameFrom]
NameTo := ElementInfoTo.Name
NodeStructTo, ok_to := types.MapNodeStructOld[NameTo]
var sx_koef float32 = 1
var tx_koef float32 = 1
if ok_to == true && ok_from == true {
if NodeStructFrom.X < NodeStructTo.X {
sx_koef = -1
} else {
tx_koef = -1
}
}
//
sx := float32(-ElementInfoFrom.Width/2) * sx_koef
sy := float32(-ElementInfoFrom.Height/2) + 40 + float32(FONT_SIZE_ENTITY)*1.1659*float32(NumberAttributeFrom-1)
tx := float32(-ElementInfoTo.Width/2) * tx_koef
ty := float32(-ElementInfoTo.Height/2) + 40 + float32(FONT_SIZE_ENTITY)*1.1659*float32(NumberAttributeTo-1)
TextSx := fmt.Sprintf("%.2f", sx)
TextSy := fmt.Sprintf("%.2f", sy)
TextTx := fmt.Sprintf("%.2f", tx)
TextTy := fmt.Sprintf("%.2f", ty)
//node
ElementEdge := ElementInfoGraph.Element.CreateElement("edge")
var ElementInfoEdge types.ElementInfoStruct
ElementInfoEdge.Element = ElementEdge
ElementInfoEdge.Parent = &ElementInfoGraph
ElementInfoEdge.Name = label
ElementInfoEdge.Description = Description
//EdgeId := FindId(ElementInfoGraph, ElementEdge)
//EdgeID := EdgeId
EdgeID := "e" + strconv.Itoa(ElementEdge.Index())
ElementEdge.CreateAttr("id", EdgeID)
//Source := "n" + strconv.Itoa(IndexElementFrom) + "::" + "n" + strconv.Itoa(IndexElementTo)
IdFrom := FindId(ElementInfoGraph, ElementInfoFrom)
IdTo := FindId(ElementInfoGraph, ElementInfoTo)
ElementEdge.CreateAttr("source", IdFrom)
ElementEdge.CreateAttr("target", IdTo)
//data
ElementData := ElementEdge.CreateElement("data")
ElementData.CreateAttr("key", "d8")
ElementData.CreateAttr("xml:space", "preserve")
//ElementInfoStruct.CreateText("<![CDATA[descr]]>")
//ElementInfoStruct.CreateElement("![CDATA[descr]]")
ElementData.CreateCData(Description)
//data2
ElementData2 := ElementEdge.CreateElement("data")
ElementData2.CreateAttr("key", "d9")
//y:PolyLineEdge
ElementYPolyLineEdge := ElementData2.CreateElement("y:PolyLineEdge")
//y:Path
ElementYPath := ElementYPolyLineEdge.CreateElement("y:Path")
ElementYPath.CreateAttr("sx", TextSx)
ElementYPath.CreateAttr("sy", TextSy)
ElementYPath.CreateAttr("tx", TextTx)
ElementYPath.CreateAttr("ty", TextTy)
//y:LineStyle
ElementYLineStyle := ElementYPolyLineEdge.CreateElement("y:LineStyle")
ElementYLineStyle.CreateAttr("color", "#000000")
ElementYLineStyle.CreateAttr("type", "line")
ElementYLineStyle.CreateAttr("width", "1.0")
//y:Arrows
ElementYArrows := ElementYPolyLineEdge.CreateElement("y:Arrows")
ElementYArrows.CreateAttr("source", "crows_foot_many")
ElementYArrows.CreateAttr("target", "none")
//y:EdgeLabel
ElementYEdgeLabel := ElementYPolyLineEdge.CreateElement("y:EdgeLabel")
ElementYEdgeLabel.CreateAttr("alignment", "center")
ElementYEdgeLabel.CreateAttr("configuration", "AutoFlippingLabel")
ElementYEdgeLabel.CreateAttr("distance", "0.0")
ElementYEdgeLabel.CreateAttr("fontFamily", "Dialog")
ElementYEdgeLabel.CreateAttr("fontSize", strconv.Itoa(FONT_SIZE_EDGE))
ElementYEdgeLabel.CreateAttr("fontStyle", "plain")
ElementYEdgeLabel.CreateAttr("hasBackgroundColor", "false")
ElementYEdgeLabel.CreateAttr("hasLineColor", "false")
ElementYEdgeLabel.CreateAttr("height", "17.96875")
ElementYEdgeLabel.CreateAttr("horizontalTextPosition", "center")
ElementYEdgeLabel.CreateAttr("iconTextGap", "4")
ElementYEdgeLabel.CreateAttr("modelName", "centered")
ElementYEdgeLabel.CreateAttr("modelPosition", "head")
ElementYEdgeLabel.CreateAttr("preferredPlacement", "anywhere")
//ElementYEdgeLabel.CreateAttr("modelName", "two_pos")
//ElementYEdgeLabel.CreateAttr("modelPosition", "head")
//ElementYEdgeLabel.CreateAttr("preferredPlacement", "on_edge")
ElementYEdgeLabel.CreateAttr("ratio", "0.5")
ElementYEdgeLabel.CreateAttr("textColor", "#000000")
ElementYEdgeLabel.CreateAttr("verticalTextPosition", "bottom")
ElementYEdgeLabel.CreateAttr("visible", "true")
ElementYEdgeLabel.CreateAttr("width", "41.8")
ElementYEdgeLabel.CreateAttr("x", "71.5")
ElementYEdgeLabel.CreateAttr("xml:space", "preserve")
ElementYEdgeLabel.CreateAttr("y", "0.5")
ElementYEdgeLabel.CreateAttr("bottomInset", "0")
ElementYEdgeLabel.CreateAttr("leftInset", "0")
ElementYEdgeLabel.CreateAttr("rightInset", "0")
ElementYEdgeLabel.CreateAttr("topInset", "0")
ElementYEdgeLabel.CreateText(label)
//y:PreferredPlacementDescriptor
ElementYPreferredPlacementDescriptor := ElementYEdgeLabel.CreateElement("y:PreferredPlacementDescriptor")
ElementYPreferredPlacementDescriptor.CreateAttr("angle", "0.0")
ElementYPreferredPlacementDescriptor.CreateAttr("angleOffsetOnRightSide", "0")
ElementYPreferredPlacementDescriptor.CreateAttr("angleReference", "absolute")
ElementYPreferredPlacementDescriptor.CreateAttr("angleRotationOnRightSide", "co")
ElementYPreferredPlacementDescriptor.CreateAttr("distance", "-1.0")
//ElementYPreferredPlacementDescriptor.CreateAttr("frozen", "true")
ElementYPreferredPlacementDescriptor.CreateAttr("placement", "anywhere")
ElementYPreferredPlacementDescriptor.CreateAttr("side", "on_edge")
ElementYPreferredPlacementDescriptor.CreateAttr("sideReference", "relative_to_edge_flow")
//y:BendStyle
ElementYBendStyle := ElementYPolyLineEdge.CreateElement("y:BendStyle")
ElementYBendStyle.CreateAttr("smoothed", "false")
return ElementInfoEdge
}
// CreateElement_Group - создаёт элемент xgml - группа
func CreateElement_Group(ElementInfoGraph types.ElementInfoStruct, GroupCaption string, Width, Height float64) types.ElementInfoStruct {
//Width := FindWidth_Group(GroupCaption)
//Height := FindHeight_Group(GroupCaption)
sWidth := fmt.Sprintf("%.1f", float32(Width))
sHeight := fmt.Sprintf("%.1f", float32(Height))
sWidth = "0.0"
sHeight = "0.0" //авторазмер
//ищем graph
var ElementGraph *etree.Element
ElementGraph2 := ElementInfoGraph.Element.SelectElement("graph")
if ElementGraph2 != nil {
ElementGraph = ElementGraph2
} else {
ElementGraph = ElementInfoGraph.Element
}
//node
ElementNode := ElementGraph.CreateElement("node")
var ElementInfoGroup types.ElementInfoStruct
ElementInfoGroup.Element = ElementNode
ElementInfoGroup.Parent = &ElementInfoGraph
ElementInfoGroup.Name = GroupCaption
ElementInfoGroup.Description = ""
//NodeId := "n" + strconv.Itoa(ElementNode.Index())
NodeId := FindId(ElementInfoGraph, ElementInfoGroup)
ElementNode.CreateAttr("id", NodeId)
ElementNode.CreateAttr("yfiles.foldertype", "group")
//data
ElementData := ElementNode.CreateElement("data")
ElementData.CreateAttr("key", "d5")
//YProxyAutoBoundsNode
ElementYProxyAutoBoundsNode := ElementData.CreateElement("y:ProxyAutoBoundsNode")
//YRealizers
ElementYRealizers := ElementYProxyAutoBoundsNode.CreateElement("y:Realizers")
ElementYRealizers.CreateAttr("active", "0")
//----------------------- visible ---------------------------------------------
//YGroupNode
ElementYGroupNode := ElementYRealizers.CreateElement("y:GroupNode")
//YGeometry
ElementYGeometry := ElementYGroupNode.CreateElement("y:Geometry")
ElementYGeometry.CreateAttr("height", sHeight)
ElementYGeometry.CreateAttr("width", sWidth)
ElementYGeometry.CreateAttr("x", "0.0")
ElementYGeometry.CreateAttr("y", "0.0")
//YFill
ElementYFill := ElementYGroupNode.CreateElement("y:Fill")
ElementYFill.CreateAttr("color", "#E8EEF7")
ElementYFill.CreateAttr("color2", "#B7C9E3")
ElementYFill.CreateAttr("transparent", "false")
//YBorderStyle
ElementYBorderStyle := ElementYGroupNode.CreateElement("y:BorderStyle")
ElementYBorderStyle.CreateAttr("color", "#F5F5F5")
ElementYBorderStyle.CreateAttr("type", "dashed")
ElementYBorderStyle.CreateAttr("width", "1.0")
//YNodeLabel
ElementYNodeLabel := ElementYGroupNode.CreateElement("y:NodeLabel")
ElementYNodeLabel.CreateAttr("alignment", "right")
ElementYNodeLabel.CreateAttr("autoSizePolicy", "content")
//ElementYNodeLabel.CreateAttr("backgroundColor", "#EBEBEB")
ElementYNodeLabel.CreateAttr("borderDistance", "0.0")
ElementYNodeLabel.CreateAttr("fontFamily", "Dialog")
ElementYNodeLabel.CreateAttr("fontSize", strconv.Itoa(FONT_SIZE_GROUP))
ElementYNodeLabel.CreateAttr("fontStyle", "bold")
ElementYNodeLabel.CreateAttr("hasBackgroundColor", "false")
ElementYNodeLabel.CreateAttr("hasLineColor", "false")
ElementYNodeLabel.CreateAttr("height", sHeight)
ElementYNodeLabel.CreateAttr("horizontalTextPosition", "center")
ElementYNodeLabel.CreateAttr("iconTextGap", "4")
ElementYNodeLabel.CreateAttr("modelName", "internal")
ElementYNodeLabel.CreateAttr("modelPosition", "t")
ElementYNodeLabel.CreateAttr("textColor", "#000000")
ElementYNodeLabel.CreateAttr("verticalTextPosition", "bottom")
ElementYNodeLabel.CreateAttr("width", sWidth)
ElementYNodeLabel.CreateAttr("x", "0")
ElementYNodeLabel.CreateAttr("xml:space", "preserve")
ElementYNodeLabel.CreateAttr("y", "0")
ElementYNodeLabel.CreateText(GroupCaption)
//YShape
ElementYShape := ElementYGroupNode.CreateElement("y:Shape")
ElementYShape.CreateAttr("type", "rectangle")
//YState
ElementYState := ElementYGroupNode.CreateElement("y:State")
ElementYState.CreateAttr("closed", "false")
ElementYState.CreateAttr("closedHeight", "80.0")
ElementYState.CreateAttr("closedWidth", "100.0")
ElementYState.CreateAttr("innerGraphDisplayEnabled", "false")
//YInsets
ElementYInsets := ElementYGroupNode.CreateElement("y:Insets")
ElementYInsets.CreateAttr("bottom", "0")
ElementYInsets.CreateAttr("bottomF", "0.0")
ElementYInsets.CreateAttr("left", "0")
ElementYInsets.CreateAttr("leftF", "0.0")
ElementYInsets.CreateAttr("right", "0")
ElementYInsets.CreateAttr("rightF", "0.0")
ElementYInsets.CreateAttr("top", "0")
ElementYInsets.CreateAttr("topF", "0.0")
//YBorderInsets
ElementYBorderInsets := ElementYGroupNode.CreateElement("y:BorderInsets")
ElementYBorderInsets.CreateAttr("bottom", "54")
ElementYBorderInsets.CreateAttr("bottomF", "54.0")
ElementYBorderInsets.CreateAttr("left", "0")
ElementYBorderInsets.CreateAttr("leftF", "0.0")
ElementYBorderInsets.CreateAttr("right", "23")
ElementYBorderInsets.CreateAttr("rightF", "23.35")
ElementYBorderInsets.CreateAttr("top", "0")
ElementYBorderInsets.CreateAttr("topF", "0.0")
//----------------------- not visible ---------------------------------------------
//YGroupNode
ElementYGroupNode2 := ElementYRealizers.CreateElement("y:GroupNode")
//YGeometry
ElementYGeometry2 := ElementYGroupNode2.CreateElement("y:Geometry")
ElementYGeometry2.CreateAttr("height", "40.0")
ElementYGeometry2.CreateAttr("width", sWidth)
ElementYGeometry2.CreateAttr("x", "0.0")
ElementYGeometry2.CreateAttr("y", "0.0")
//YFill
ElementYFill2 := ElementYGroupNode2.CreateElement("y:Fill")
ElementYFill2.CreateAttr("color", "#E8EEF7")
ElementYFill2.CreateAttr("color2", "#B7C9E3")
ElementYFill2.CreateAttr("transparent", "false")
//YBorderStyle
ElementYBorderStyle2 := ElementYGroupNode2.CreateElement("y:BorderStyle")
ElementYBorderStyle2.CreateAttr("color", "#000000")
ElementYBorderStyle2.CreateAttr("type", "dashed")
ElementYBorderStyle2.CreateAttr("width", "1.0")
//YNodeLabel
ElementYNodeLabel2 := ElementYGroupNode2.CreateElement("y:NodeLabel")
ElementYNodeLabel2.CreateAttr("alignment", "right")
ElementYNodeLabel2.CreateAttr("autoSizePolicy", "content")
//ElementYNodeLabel2.CreateAttr("backgroundColor", "#EBEBEB")
ElementYNodeLabel2.CreateAttr("borderDistance", "0.0")
ElementYNodeLabel2.CreateAttr("fontFamily", "Dialog")
ElementYNodeLabel2.CreateAttr("fontSize", strconv.Itoa(FONT_SIZE_GROUP))
ElementYNodeLabel2.CreateAttr("fontStyle", "bold")
ElementYNodeLabel.CreateAttr("hasBackgroundColor", "false")
ElementYNodeLabel2.CreateAttr("hasLineColor", "false")
ElementYNodeLabel2.CreateAttr("hasText", "true") //только у 2
ElementYNodeLabel2.CreateAttr("height", sHeight)
ElementYNodeLabel2.CreateAttr("horizontalTextPosition", "center")
ElementYNodeLabel2.CreateAttr("iconTextGap", "4")
ElementYNodeLabel2.CreateAttr("modelName", "internal")
ElementYNodeLabel2.CreateAttr("modelPosition", "t")
ElementYNodeLabel2.CreateAttr("textColor", "#000000")
ElementYNodeLabel2.CreateAttr("verticalTextPosition", "bottom")
ElementYNodeLabel2.CreateAttr("width", sWidth)
ElementYNodeLabel2.CreateAttr("x", "0")
ElementYNodeLabel2.CreateAttr("xml:space", "preserve") //только у 2
ElementYNodeLabel2.CreateAttr("y", "0")
ElementYNodeLabel2.CreateText(GroupCaption) //только у 2
//YShape
ElementYShape2 := ElementYGroupNode2.CreateElement("y:Shape")
ElementYShape2.CreateAttr("type", "roundrectangle")
//YState
ElementYState2 := ElementYGroupNode2.CreateElement("y:State")
ElementYState2.CreateAttr("closed", "true")
ElementYState2.CreateAttr("closedHeight", "80.0")
ElementYState2.CreateAttr("closedWidth", "100.0")
ElementYState2.CreateAttr("innerGraphDisplayEnabled", "false")
//YInsets
ElementYInsets2 := ElementYGroupNode2.CreateElement("y:Insets")
ElementYInsets2.CreateAttr("bottom", "15")
ElementYInsets2.CreateAttr("bottomF", "15.0")
ElementYInsets2.CreateAttr("left", "15")
ElementYInsets2.CreateAttr("leftF", "15.0")
ElementYInsets2.CreateAttr("right", "15")
ElementYInsets2.CreateAttr("rightF", "15.0")
ElementYInsets2.CreateAttr("top", "15")
ElementYInsets2.CreateAttr("topF", "15.0")
//YBorderInsets
ElementYBorderInsets2 := ElementYGroupNode2.CreateElement("y:BorderInsets")
ElementYBorderInsets2.CreateAttr("bottom", "54")
ElementYBorderInsets2.CreateAttr("bottomF", "54.0")
ElementYBorderInsets2.CreateAttr("left", "0")
ElementYBorderInsets2.CreateAttr("leftF", "0.0")
ElementYBorderInsets2.CreateAttr("right", "23")
ElementYBorderInsets2.CreateAttr("rightF", "23.35")
ElementYBorderInsets2.CreateAttr("top", "0")
ElementYBorderInsets2.CreateAttr("topF", "0.0")
//----------------------- продолжение ---------------------------------------------
//YBorderInsets
ElementGraphGraph := ElementNode.CreateElement("graph")
ElementGraphGraph.CreateAttr("edgedefault", "directed")
ElementGraphGraph.CreateAttr("id", NodeId+":")
return ElementInfoGroup
}
// CreateElement_SmallEntity - создаёт элемент - Entity
func CreateElement_SmallEntity(ElementInfoMain types.ElementInfoStruct, ElementName string, Width float64, AttributeIndex int) types.ElementInfoStruct {
//Width := findWidth_SmallEntity(ElementName)
Height := findHeight_SmallEntity(ElementName)
sWidth := fmt.Sprintf("%.1f", float64(Width))
sHeight := fmt.Sprintf("%.1f", float64(Height))
sY := fmt.Sprintf("%.1f", float64(AttributeIndex)*Height)
sFontSize := strconv.Itoa(FONT_SIZE_ENTITY)
//ищем graph
var ElementGraph *etree.Element
ElementGraph2 := ElementInfoMain.Element.SelectElement("graph")
if ElementGraph2 != nil {
ElementGraph = ElementGraph2
} else {
ElementGraph = ElementInfoMain.Element
}
//node
ElementNode := ElementGraph.CreateElement("node")
var ElementInfoNode types.ElementInfoStruct
ElementInfoNode.Element = ElementNode
ElementInfoNode.Name = ElementName
ElementInfoNode.Parent = &ElementInfoMain
ElementInfoNode.Attribute = ""
ElementInfoNode.Width = Width
ElementInfoNode.Height = Height
sId := FindId(ElementInfoMain, ElementInfoNode)
ElementNode.CreateAttr("id", sId)
//ElementNode.CreateAttr("id", "n"+strconv.Itoa(ElementNode.Index()))
//data
ElementData := ElementNode.CreateElement("data")
ElementData.CreateAttr("key", "d4")
//data
ElementData2 := ElementNode.CreateElement("data")
ElementData2.CreateAttr("key", "d5")
//y:GenericNode
ElementYGenericNode := ElementData2.CreateElement("y:GenericNode")
ElementYGenericNode.CreateAttr("configuration", "com.yworks.entityRelationship.small_entity")
//YGeometry
ElementYGeometry := ElementYGenericNode.CreateElement("y:Geometry")
ElementYGeometry.CreateAttr("height", sHeight)
ElementYGeometry.CreateAttr("width", sWidth)
ElementYGeometry.CreateAttr("x", "0")
ElementYGeometry.CreateAttr("y", sY)
//YFill
ElementYFill := ElementYGenericNode.CreateElement("y:Fill")
ElementYFill.CreateAttr("color", "#E8EEF7")
ElementYFill.CreateAttr("color2", "#B7C9E3")
ElementYFill.CreateAttr("transparent", "false")
//BorderStyle
ElementBorderStyle := ElementYGenericNode.CreateElement("y:BorderStyle")
ElementBorderStyle.CreateAttr("hasColor", "false")
//ElementBorderStyle.CreateAttr("color", "#000000")
ElementBorderStyle.CreateAttr("type", "line")
ElementBorderStyle.CreateAttr("width", "1.0")
//NodeLabel
ElementNodeLabel := ElementYGenericNode.CreateElement("y:NodeLabel")
ElementNodeLabel.CreateAttr("alignment", "left")
ElementNodeLabel.CreateAttr("autoSizePolicy", "content")
ElementNodeLabel.CreateAttr("backgroundColor", "#B7C9E3")
ElementNodeLabel.CreateAttr("borderDistance", "0.0")
ElementNodeLabel.CreateAttr("configuration", "com.yworks.entityRelationship.label.name")
ElementNodeLabel.CreateAttr("fontFamily", "Dialog")
ElementNodeLabel.CreateAttr("fontSize", sFontSize)
ElementNodeLabel.CreateAttr("fontStyle", "plain")
ElementNodeLabel.CreateAttr("hasLineColor", "false")
ElementNodeLabel.CreateAttr("height", sHeight)
ElementNodeLabel.CreateAttr("horizontalTextPosition", "center")
ElementNodeLabel.CreateAttr("iconTextGap", "4")
ElementNodeLabel.CreateAttr("modelName", "internal")
ElementNodeLabel.CreateAttr("modelPosition", "tl")
ElementNodeLabel.CreateAttr("textColor", "#000000")
ElementNodeLabel.CreateAttr("verticalTextPosition", "bottom")
ElementNodeLabel.CreateAttr("visible", "true")
ElementNodeLabel.CreateAttr("width", sWidth)
ElementNodeLabel.CreateAttr("x", "16.0")
ElementNodeLabel.CreateAttr("xml:space", "preserve")
ElementNodeLabel.CreateAttr("y", "4.0")
ElementNodeLabel.CreateText(ElementName)
//y:LabelModel
ElementYLabelModel := ElementNodeLabel.CreateElement("y:LabelModel")
//y:SmartNodeLabelModel
ElementYSmartNodeLabelModel := ElementYLabelModel.CreateElement("y:SmartNodeLabelModel")
ElementYSmartNodeLabelModel.CreateAttr("distance", "0.0")
////y:ErdAttributesNodeLabelModel
//ElementYLabelModel.CreateElement("y:ErdAttributesNodeLabelModel")
////y:ModelParameter
ElementYModelParameter := ElementNodeLabel.CreateElement("y:ModelParameter")
//y:SmartNodeLabelModelParameter
ElementYSmartNodeLabelModelParameter := ElementYModelParameter.CreateElement("y:SmartNodeLabelModelParameter")
ElementYSmartNodeLabelModelParameter.CreateAttr("labelRatioX", "0.0")
ElementYSmartNodeLabelModelParameter.CreateAttr("labelRatioY", "0.0")
ElementYSmartNodeLabelModelParameter.CreateAttr("nodeRatioX", "0.0")
ElementYSmartNodeLabelModelParameter.CreateAttr("nodeRatioY", "0.0")
ElementYSmartNodeLabelModelParameter.CreateAttr("offsetX", "0.0")
ElementYSmartNodeLabelModelParameter.CreateAttr("offsetY", "0.0")
ElementYSmartNodeLabelModelParameter.CreateAttr("upX", "0.0")
ElementYSmartNodeLabelModelParameter.CreateAttr("upY", "-1.0")
//y:StyleProperties
ElementYStyleProperties := ElementYGenericNode.CreateElement("y:StyleProperties")
//y:Property
ElementYProperty := ElementYStyleProperties.CreateElement("y:Property")
ElementYProperty.CreateAttr("class", "java.lang.Boolean")
ElementYProperty.CreateAttr("name", "y.view.ShadowNodePainter.SHADOW_PAINTING")
ElementYProperty.CreateAttr("value", "true")
return ElementInfoNode
}
// findWidth_Entity - возвращает число - ширину элемента
func findWidth_Entity(ElementName string) float64 {
var Otvet float64 = float64(FONT_SIZE_ENTITY) * 2
LenMax := findMaxLenRow(ElementName)
//var OtvetF float64
Otvet = float64(Otvet) + float64(LenMax)*float64(FONT_SIZE_SHAPE)*float64(0.48)
//Otvet = int(math.Round(OtvetF))
return Otvet
}
// findHeight_Entity - возвращает число - высоту элемента
func findHeight_Entity(ElementName string) float64 {
var Otvet float64
Otvet = float64(12 + FONT_SIZE_ENTITY*3)
RowsTotal := countLines(ElementName)
Otvet = float64(Otvet) + (float64(RowsTotal-1) * math.Round(float64(FONT_SIZE_ENTITY)*float64(1.16)))
return Otvet
}
// findWidth_Bends - возвращает число - ширину элемента
func findWidth_Bends(ElementName string) int {
Otvet := FONT_SIZE_BENDS * 2
LenMax := findMaxLenRow(ElementName)
var OtvetF float64
OtvetF = float64(Otvet) + float64(LenMax)*float64(FONT_SIZE_SHAPE/2)
Otvet = int(math.Round(OtvetF))
return Otvet
}
// findHeight_Bends - возвращает число - высоту элемента
func findHeight_Bends(ElementName string) int {
Otvet := 10 + FONT_SIZE_BENDS*3
RowsTotal := countLines(ElementName)
Otvet = Otvet + (RowsTotal-1)*FONT_SIZE_SHAPE*2
return Otvet
}
// findWidth_Shape - возвращает число - ширину элемента
func findWidth_Shape(ElementName string) int {
Otvet := FONT_SIZE_SHAPE * 2
LenMax := findMaxLenRow(ElementName)
var OtvetF float64
OtvetF = float64(Otvet) + float64(LenMax)*float64(FONT_SIZE_SHAPE/2)
Otvet = int(math.Round(OtvetF))
return Otvet
}
// findHeight_Shape - возвращает число - высоту элемента
func findHeight_Shape(ElementName string) int {
Otvet := 10 + FONT_SIZE_SHAPE*3
RowsTotal := countLines(ElementName)
Otvet = Otvet + (RowsTotal-1)*FONT_SIZE_SHAPE*2
return Otvet
}
// findWidth_Group - возвращает число - ширину элемента
func findWidth_Group(ElementName string) int {
Otvet := 10
LenMax := findMaxLenRow(ElementName)
var OtvetF float64
OtvetF = float64(Otvet) + float64(LenMax)*10
Otvet = int(math.Round(OtvetF))
return Otvet
}
// findHeight_Group - возвращает число - высоту элемента
func findHeight_Group(ElementName string) int {
Otvet := 30
RowsTotal := countLines(ElementName)
Otvet = Otvet + (RowsTotal-1)*18
return Otvet
}
// findWidth_Edge - возвращает число - ширину элемента
func findWidth_Edge(Label string) int {
Otvet := 10
LenMax := findMaxLenRow(Label)
var OtvetF float64
OtvetF = float64(Otvet) + float64(LenMax)*10
Otvet = int(math.Round(OtvetF))
return Otvet
}
// findHeight_Edge - возвращает число - высоту элемента
func findHeight_Edge(Label string) int {
Otvet := 30
RowsTotal := countLines(Label)
Otvet = Otvet + (RowsTotal-1)*18
return Otvet
}
// findWidth_SmallEntity - возвращает число - ширину элемента
func findWidth_SmallEntity(ElementName string) int {
Otvet := FONT_SIZE_ENTITY * 2
LenMax := findMaxLenRow(ElementName)
var OtvetF float64
OtvetF = float64(Otvet) + float64(LenMax)*float64(FONT_SIZE_SHAPE)*float64(0.48)
Otvet = int(math.Round(OtvetF))
return Otvet
}
// findHeight_SmallEntity - возвращает число - высоту элемента
func findHeight_SmallEntity(ElementName string) float64 {
var Otvet float64
Otvet = float64(6 + FONT_SIZE_ENTITY)
RowsTotal := countLines(ElementName)
Otvet = float64(Otvet) + (float64(RowsTotal-1) * float64(FONT_SIZE_ENTITY))
return Otvet
}
// countLines - возвращает количество переводов строки
func countLines(s string) int {
Otvet := 1
Otvet2 := strings.Count(s, "\n")
Otvet = Otvet + Otvet2
return Otvet
}
// findMaxLenRow - возвращает количество символов в строке максимум
func findMaxLenRow(ElementName string) int {
Otvet := 0
Mass := strings.Split(ElementName, "\n")
for _, Mass1 := range Mass {
MassRune := []rune(Mass1)
len1 := len(MassRune)
if len1 > Otvet {
Otvet = len1
}
}
return Otvet
}
// CreateDocument - создаёт новый документ .xgml
func CreateDocument() (*etree.Document, types.ElementInfoStruct) {
DocXML := etree.NewDocument()
DocXML.CreateProcInst("xml", `version="1.0" encoding="UTF-8" standalone="no"`)
ElementGraphMl := DocXML.CreateElement("graphml")
var ElementInfoGraphML types.ElementInfoStruct
ElementInfoGraphML.Element = ElementGraphMl
ElementInfoGraphML.Parent = nil
ElementGraphMl.CreateAttr("xmlns", "http://graphml.graphdrawing.org/xmlns")
ElementGraphMl.CreateAttr("xmlns:java", "http://www.yworks.com/xml/yfiles-common/1.0/java")
ElementGraphMl.CreateAttr("xmlns:sys", "http://www.yworks.com/xml/yfiles-common/markup/primitives/2.0")
ElementGraphMl.CreateAttr("xmlns:x", "http://www.yworks.com/xml/yfiles-common/markup/2.0")
ElementGraphMl.CreateAttr("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance")
ElementGraphMl.CreateAttr("xmlns:y", "http://www.yworks.com/xml/graphml")
ElementGraphMl.CreateAttr("xmlns:y", "http://www.yworks.com/xml/graphml")
ElementGraphMl.CreateAttr("xmlns:yed", "http://www.yworks.com/xml/yed/3")
ElementGraphMl.CreateAttr("xsi:schemaLocation", "http://graphml.graphdrawing.org/xmlns http://www.yworks.com/xml/schema/graphml/1.1/ygraphml.xsd")
ElementD0 := ElementGraphMl.CreateElement("key")
ElementD0.CreateAttr("for", "port")
ElementD0.CreateAttr("id", "d0")
ElementD0.CreateAttr("yfiles.type", "portgraphics")
ElementD1 := ElementGraphMl.CreateElement("key")
ElementD1.CreateAttr("for", "port")
ElementD1.CreateAttr("id", "d1")
ElementD1.CreateAttr("yfiles.type", "portgeometry")
ElementD2 := ElementGraphMl.CreateElement("key")
ElementD2.CreateAttr("for", "port")
ElementD2.CreateAttr("id", "d2")
ElementD2.CreateAttr("yfiles.type", "portuserdata")
ElementD3 := ElementGraphMl.CreateElement("key")
ElementD3.CreateAttr("attr.name", "url")
ElementD3.CreateAttr("attr.type", "string")
ElementD3.CreateAttr("for", "node")
ElementD3.CreateAttr("id", "d3")
ElementD4 := ElementGraphMl.CreateElement("key")
ElementD4.CreateAttr("attr.name", "description")
ElementD4.CreateAttr("attr.type", "string")
ElementD4.CreateAttr("for", "node")
ElementD4.CreateAttr("id", "d4")
ElementD5 := ElementGraphMl.CreateElement("key")
ElementD5.CreateAttr("for", "node")
ElementD5.CreateAttr("id", "d5")
ElementD5.CreateAttr("yfiles.type", "nodegraphics")
ElementD6 := ElementGraphMl.CreateElement("key")
ElementD6.CreateAttr("for", "graphml")
ElementD6.CreateAttr("id", "d6")
ElementD6.CreateAttr("yfiles.type", "resources")
ElementD7 := ElementGraphMl.CreateElement("key")
ElementD7.CreateAttr("attr.name", "url")
ElementD7.CreateAttr("attr.type", "string")
ElementD7.CreateAttr("for", "edge")
ElementD7.CreateAttr("id", "d7")
ElementD8 := ElementGraphMl.CreateElement("key")
ElementD8.CreateAttr("attr.name", "description")
ElementD8.CreateAttr("attr.type", "string")
ElementD8.CreateAttr("for", "edge")
ElementD8.CreateAttr("id", "d8")
ElementD9 := ElementGraphMl.CreateElement("key")
ElementD9.CreateAttr("for", "edge")
ElementD9.CreateAttr("id", "d9")
ElementD9.CreateAttr("yfiles.type", "edgegraphics")
ElementGraph := ElementGraphMl.CreateElement("graph")
ElementGraph.CreateAttr("edgedefault", "directed")
ElementGraph.CreateAttr("id", "G")
return DocXML, ElementInfoGraphML
}
// FindId - находит ИД в формате "n1::n1::n1"
func FindId(ElementInfoMain, ElementInfo types.ElementInfoStruct) string {
Otvet := ""
//if Element == nil {
// return Otvet
//}
//if Element == ElementGraph0 {
// return Otvet
//}
if ElementInfo.Element.Tag == "node" {
Otvet = "n" + strconv.Itoa(ElementInfo.Element.Index())
//return Otvet
}
ParentSID := ""
if ElementInfo.Parent != nil {
ParentSID = FindId(ElementInfoMain, *ElementInfo.Parent)
}
if ParentSID != "" {
if Otvet == "" {
Otvet = ParentSID
} else {
Otvet = ParentSID + "::" + Otvet
}
}
return Otvet
}

View File

@ -1,140 +0,0 @@
package graphml
import (
"github.com/ManyakRus/crud_generator/internal/config"
"github.com/ManyakRus/crud_generator/internal/types"
"github.com/ManyakRus/starter/log"
"github.com/ManyakRus/starter/micro"
"github.com/beevik/etree"
"strconv"
)
func ReadFile(Filename string) (*etree.Document, error) {
var err error
doc := etree.NewDocument()
err = doc.ReadFromFile(Filename)
if err != nil {
log.Panic(err)
}
return doc, err
}
func FindMassElement(doc *etree.Document) []*etree.Element {
MassElement := make([]*etree.Element, 0)
ElementGraphMl := doc.SelectElement("graphml")
ElementGraph := ElementGraphMl.SelectElement("graph")
MassElement = ElementGraph.SelectElements("node")
return MassElement
}
func FindMapNodeStruct(MassElement []*etree.Element) map[string]types.NodeStruct {
MapNodeStruct := make(map[string]types.NodeStruct, 0)
var err error
for _, ElementNode1 := range MassElement {
sx := ""
sy := ""
Name := ""
MassData := ElementNode1.SelectElements("data")
if len(MassData) == 0 {
continue
}
var ElementData1 *etree.Element
ElementData1 = MassData[len(MassData)-1]
//for _, ElementData1 = range MassData {
//key := ElementData1.SelectAttrValue("key", "")
//if key != "d5" {
// continue
//}
ElementGenericNode := ElementData1.SelectElement("y:GenericNode")
if ElementGenericNode == nil {
continue
}
ElementGeometry := ElementGenericNode.SelectElement("y:Geometry")
if ElementGeometry == nil {
continue
}
sx = ElementGeometry.SelectAttrValue("x", "0")
sy = ElementGeometry.SelectAttrValue("y", "0")
ElementNodeLabel := ElementGenericNode.SelectElement("y:NodeLabel")
if ElementNodeLabel == nil {
continue
}
Name = ElementNodeLabel.Text()
if Name == "" {
log.Warn("Name = ''")
continue
}
var x float64
if sx != "" {
x, err = strconv.ParseFloat(sx, 32)
if err != nil {
log.Warn("Name: ", Name+" ParseFloat(", sx, ") error: ", err)
}
}
var y float64
if sy != "" {
y, err = strconv.ParseFloat(sy, 32)
if err != nil {
log.Warn("Name: ", Name+" ParseFloat(", sy, ") error: ", err)
}
}
NodeStruct1 := types.NodeStruct{}
NodeStruct1.Element = ElementNode1
NodeStruct1.Name = Name
NodeStruct1.X = x
NodeStruct1.Y = y
MapNodeStruct[Name] = NodeStruct1
//}
}
return MapNodeStruct
}
// StartReadFile - читает старый файл в
func StartReadFile() {
//dir := micro.ProgramDir()
//Filename := dir + "test" + micro.SeparatorFile() + "test.graphml"
Filename := config.Settings.FILENAME_GRAPHML
ok, err := micro.FileExists(Filename)
if ok == false {
return
}
doc, err := ReadFile(Filename)
if err != nil {
log.Error("ReadFile() error: ", err)
return
}
if doc == nil {
log.Error("ReadFile() error: doc =nil")
return
}
MassElement := FindMassElement(doc)
if len(MassElement) == 0 {
log.Warn("FindMassElement() error: len =0")
return
}
types.MapNodeStructOld = FindMapNodeStruct(MassElement)
if len(types.MapNodeStructOld) == 0 {
log.Warn("FindMapNodeStruct() error: len =0")
return
}
}

View File

@ -1,67 +0,0 @@
package graphml
import (
"github.com/ManyakRus/crud_generator/internal/config"
ConfigMain "github.com/ManyakRus/starter/config"
"github.com/ManyakRus/starter/micro"
"testing"
)
func TestReadFile(t *testing.T) {
dir := micro.ProgramDir()
Filename := dir + "test" + micro.SeparatorFile() + "test.graphml"
doc, err := ReadFile(Filename)
if err != nil {
t.Error("TestReadFile() error: ", err)
}
if doc == nil {
t.Error("TestReadFile() error: doc =nil")
}
}
func TestFindMassEntity(t *testing.T) {
dir := micro.ProgramDir()
Filename := dir + "test" + micro.SeparatorFile() + "test.graphml"
doc, err := ReadFile(Filename)
if err != nil {
t.Error("TestFindMassEntity() error: ", err)
}
if doc == nil {
t.Error("TestFindMassEntity() error: doc =nil")
}
Otvet := FindMassElement(doc)
if len(Otvet) == 0 {
t.Error("TestFindMassEntity() error: len =0")
}
}
func TestFindMapNodeStruct(t *testing.T) {
dir := micro.ProgramDir()
Filename := dir + "test" + micro.SeparatorFile() + "test.graphml"
doc, err := ReadFile(Filename)
if err != nil {
t.Error("TestFindMapNodeStruct() error: ", err)
}
if doc == nil {
t.Error("TestFindMapNodeStruct() error: doc =nil")
}
MassElement := FindMassElement(doc)
if len(MassElement) == 0 {
t.Error("TestFindMapNodeStruct() error: len =0")
}
Otvet := FindMapNodeStruct(MassElement)
if len(Otvet) == 0 {
t.Error("TestFindMapNodeStruct() error: ", err)
}
}
func TestStartReadFile(t *testing.T) {
ConfigMain.LoadEnv()
config.FillSettings()
StartReadFile()
}

View File

@ -1,32 +0,0 @@
package graphml
import (
"github.com/ManyakRus/starter/micro"
"testing"
)
func TestCreateNewGraphml(t *testing.T) {
dir := micro.ProgramDir()
DocXML, ElementGraph := CreateDocument()
Entity1 := CreateElement_Entity(ElementGraph, "Entity1", "Field1\nField2\nField3\n1234567890")
Entity2 := CreateElement_Entity(ElementGraph, "Entity2", "Field1\nField2\nField3\n1234567890")
CreateElement_Edge(ElementGraph, Entity1, Entity2, "edge1", "descr", 4, 1)
//Shape2 := CreateElement_Shape(ElementGraph, "Shape2")
//Group1 := CreateElement_Group(ElementGraph, "Group1")
//Shape1 := CreateElement_Shape(Group1, "Shape1")
//CreateElement_Edge(ElementGraph, Shape1, Shape2, "edge1", "descr")
//CreateElement_Edge_blue(ElementGraph, Shape2, Shape1, "edge2", "descr2")
//
//if Shape1 == nil || Shape2 == nil {
//
//}
FileName := dir + "test" + micro.SeparatorFile() + "test.graphml"
//DocXML.IndentTabs()
DocXML.Indent(2)
err := DocXML.WriteToFile(FileName)
if err != nil {
t.Error("TestCreateNewXGML() error: ", err)
}
}