#if !PLATFORM_WINDOWS #include #endif #include //- string builder on arena typedef struct StrBuf StrBuf; struct StrBuf { char *data; u64 size; u64 cap; }; internal void strbuf_init(Arena *arena, StrBuf *b, u64 cap) { b->data = PushArray(arena, char, cap); b->size = 0; b->cap = cap; } internal void strbuf_fmt(StrBuf *b, const char *fmt, ...) { if(b->size + 1 >= b->cap) return; va_list args; va_start(args, fmt); int n = vsnprintf(b->data + b->size, b->cap - b->size, fmt, args); va_end(args); if(n > 0) b->size += Min((u64)n, b->cap - 1 - b->size); } //- binary format (.dit) // NOTE: v2 adds docs (the text heap), source links, repo settings, more bends and message y. // v1 files still load: their structs are kept below and converted field by field. #define DIT_MAGIC 0x54494444u // "DDIT" #define DIT_VERSION 2u typedef struct DitHeaderV1 DitHeaderV1; struct DitHeaderV1 { u32 magic; u32 version; u32 node_count; u32 edge_count; u32 section_count; u32 member_count; u32 next_id; u32 default_routing; char title[96]; }; typedef struct DitHeader DitHeader; struct DitHeader { DitHeaderV1 v1; u32 text_size; u32 doc_off; u32 doc_len; u32 node_size; // sizeof(DiagramNode) when written, a mismatch means another build wrote it u32 edge_size; u32 reserved[3]; char repo[256]; char repo_ref[64]; char repo_root[512]; }; typedef struct DiagramNodeV1 DiagramNodeV1; struct DiagramNodeV1 { b32 alive; u32 id, kind, border_style; s32 parent; b32 collapsed, pinned, selected; f32 x, y, w, h; b32 manual_size; f32 min_w, min_h; u32 color; s32 first_section, last_section; u32 section_count; char key[48], name[80], stereotype[48], tag[32], note[128]; f32 header_h; }; typedef struct DiagramEdgeV1 DiagramEdgeV1; struct DiagramEdgeV1 { b32 alive; u32 id; s32 src, dst; u32 kind, routing, src_port, dst_port; s32 src_member, dst_member; b32 selected; u32 color; u32 waypoint_count; Vec2f waypoints[4]; char label[64], src_mult[16], dst_mult[16], tag[32]; }; internal b32 diagram_save_binary(Diagram *d, const char *path) { FILE *f = fopen(path, "wb"); if(!f) return false; diagram_compact_text(d); DitHeader hdr = {}; hdr.v1.magic = DIT_MAGIC; hdr.v1.version = DIT_VERSION; hdr.v1.node_count = d->node_count; hdr.v1.edge_count = d->edge_count; hdr.v1.section_count = d->section_count; hdr.v1.member_count = d->member_count; hdr.v1.next_id = d->next_id; hdr.v1.default_routing = d->default_routing; hdr.text_size = d->text_size; hdr.doc_off = d->doc_off; hdr.doc_len = d->doc_len; hdr.node_size = sizeof(DiagramNode); hdr.edge_size = sizeof(DiagramEdge); MemCpy(hdr.v1.title, d->title, sizeof(hdr.v1.title)); MemCpy(hdr.repo, d->repo, sizeof(hdr.repo)); MemCpy(hdr.repo_ref, d->repo_ref, sizeof(hdr.repo_ref)); MemCpy(hdr.repo_root, d->repo_root, sizeof(hdr.repo_root)); fwrite(&hdr, sizeof(hdr), 1, f); if(d->node_count) fwrite(d->nodes, sizeof(DiagramNode), d->node_count, f); if(d->edge_count) fwrite(d->edges, sizeof(DiagramEdge), d->edge_count, f); if(d->section_count) fwrite(d->sections, sizeof(NodeSection), d->section_count, f); if(d->member_count) fwrite(d->members, sizeof(NodeMember), d->member_count, f); if(d->text_size) fwrite(d->text, 1, d->text_size, f); fclose(f); snprintf(d->file_path, sizeof(d->file_path), "%s", path); d->dirty = false; return true; } internal b32 diagram_load_binary(Diagram *d, const char *path) { FILE *f = fopen(path, "rb"); if(!f) return false; DitHeader hdr = {}; if(fread(&hdr.v1, sizeof(hdr.v1), 1, f) != 1 || hdr.v1.magic != DIT_MAGIC || (hdr.v1.version != 1 && hdr.v1.version != DIT_VERSION)) { fclose(f); return false; } b32 v1 = (hdr.v1.version == 1); if(!v1) { if(fread((u8 *)&hdr + sizeof(hdr.v1), sizeof(hdr) - sizeof(hdr.v1), 1, f) != 1 || hdr.node_size != sizeof(DiagramNode) || hdr.edge_size != sizeof(DiagramEdge) || hdr.text_size > d->text_cap) { fclose(f); return false; } } if(hdr.v1.node_count > d->node_cap || hdr.v1.edge_count > d->edge_cap || hdr.v1.section_count > d->section_cap || hdr.v1.member_count > d->member_cap) { fclose(f); return false; } diagram_clear(d); d->node_count = hdr.v1.node_count; d->edge_count = hdr.v1.edge_count; d->section_count = hdr.v1.section_count; d->member_count = hdr.v1.member_count; d->next_id = Max(hdr.v1.next_id, 1u); d->default_routing = hdr.v1.default_routing < ROUTE_COUNT ? hdr.v1.default_routing : ROUTE_ORTHOGONAL; MemCpy(d->title, hdr.v1.title, sizeof(d->title)); d->title[sizeof(d->title) - 1] = 0; b32 ok = true; if(v1) { ScratchArena scratch = ScratchGet(); DiagramNodeV1 *nodes = PushArrayZero(scratch.arena, DiagramNodeV1, d->node_count + 1); DiagramEdgeV1 *edges = PushArrayZero(scratch.arena, DiagramEdgeV1, d->edge_count + 1); if(d->node_count && fread(nodes, sizeof(DiagramNodeV1), d->node_count, f) != d->node_count) ok = false; if(d->edge_count && fread(edges, sizeof(DiagramEdgeV1), d->edge_count, f) != d->edge_count) ok = false; for(u32 i = 0; ok && i < d->node_count; ++i) { DiagramNodeV1 *o = &nodes[i]; DiagramNode *n = &d->nodes[i]; MemSetZero(n, sizeof(*n)); n->alive = o->alive; n->id = o->id; n->kind = o->kind < NODE_KIND_COUNT ? o->kind : NODE_STRUCT; n->border_style = o->border_style; n->parent = o->parent; n->collapsed = o->collapsed; n->pinned = o->pinned; n->x = o->x; n->y = o->y; n->w = o->w; n->h = o->h; n->manual_size = o->manual_size; n->color = o->color; n->first_section = o->first_section; n->last_section = o->last_section; n->section_count = o->section_count; MemCpy(n->key, o->key, sizeof(n->key)); MemCpy(n->name, o->name, sizeof(n->name)); MemCpy(n->stereotype, o->stereotype, sizeof(n->stereotype)); MemCpy(n->tag, o->tag, sizeof(n->tag)); MemCpy(n->note, o->note, sizeof(n->note)); } for(u32 i = 0; ok && i < d->edge_count; ++i) { DiagramEdgeV1 *o = &edges[i]; DiagramEdge *e = &d->edges[i]; MemSetZero(e, sizeof(*e)); e->alive = o->alive; e->id = o->id; e->src = o->src; e->dst = o->dst; e->kind = o->kind < EDGE_KIND_COUNT ? o->kind : EDGE_ASSOCIATION; e->routing = o->routing; e->src_port = o->src_port; e->dst_port = o->dst_port; e->src_member = o->src_member; e->dst_member = o->dst_member; e->color = o->color; e->waypoint_count = Min(o->waypoint_count, 4u); for(u32 w = 0; w < e->waypoint_count; ++w) e->waypoints[w] = o->waypoints[w]; MemCpy(e->label, o->label, sizeof(e->label)); MemCpy(e->src_mult, o->src_mult, sizeof(e->src_mult)); MemCpy(e->dst_mult, o->dst_mult, sizeof(e->dst_mult)); MemCpy(e->tag, o->tag, sizeof(e->tag)); } scratch_end(&scratch); } else { if(d->node_count && fread(d->nodes, sizeof(DiagramNode), d->node_count, f) != d->node_count) ok = false; if(d->edge_count && fread(d->edges, sizeof(DiagramEdge), d->edge_count, f) != d->edge_count) ok = false; } if(ok && d->section_count && fread(d->sections, sizeof(NodeSection), d->section_count, f) != d->section_count) ok = false; if(ok && d->member_count && fread(d->members, sizeof(NodeMember), d->member_count, f) != d->member_count) ok = false; if(ok && !v1) { d->text_size = hdr.text_size; d->doc_off = hdr.doc_off; d->doc_len = hdr.doc_len; if(d->text_size && fread(d->text, 1, d->text_size, f) != d->text_size) ok = false; MemCpy(d->repo, hdr.repo, sizeof(d->repo)); MemCpy(d->repo_ref, hdr.repo_ref, sizeof(d->repo_ref)); MemCpy(d->repo_root, hdr.repo_root, sizeof(d->repo_root)); d->repo[sizeof(d->repo) - 1] = d->repo_ref[sizeof(d->repo_ref) - 1] = d->repo_root[sizeof(d->repo_root) - 1] = 0; } fclose(f); if(!ok) { diagram_clear(d); return false; } for(u32 i = 0; i < d->node_count; ++i) { d->nodes[i].selected = false; if(d->nodes[i].kind >= NODE_KIND_COUNT) d->nodes[i].kind = NODE_STRUCT; } for(u32 i = 0; i < d->edge_count; ++i) { d->edges[i].selected = false; if(d->edges[i].waypoint_count > DIAGRAM_MAX_WAYPOINTS) d->edges[i].waypoint_count = 0; if(d->edges[i].kind >= EDGE_KIND_COUNT) d->edges[i].kind = EDGE_ASSOCIATION; } d->live_nodes = 0; d->live_edges = 0; for(u32 i = 0; i < d->node_count; ++i) d->live_nodes += (d->nodes[i].alive != 0); for(u32 i = 0; i < d->edge_count; ++i) d->live_edges += (d->edges[i].alive != 0); diagram_measure_all(d); diagram_fit_lifelines(d); diagram_rebuild_tags(d); snprintf(d->file_path, sizeof(d->file_path), "%s", path); d->dirty = false; ++d->version; return true; } //- human-readable DSL (.dit.txt) // NOTE: quoted strings escape \" and \\ only, any other backslash is literal (windows paths) internal void dsl_emit_quoted(StrBuf *b, const char *s) { strbuf_fmt(b, "\""); for(; *s; ++s) { if(*s == '"' || *s == '\\') strbuf_fmt(b, "\\%c", *s); else if(*s == '\n') strbuf_fmt(b, "\\n"); else strbuf_fmt(b, "%c", *s); } strbuf_fmt(b, "\""); } internal void dsl_indent(StrBuf *b, u32 indent) { for(u32 i = 0; i < indent; ++i) strbuf_fmt(b, " "); } // NOTE: doc """ block: one text line per line, indented one level deeper than the keyword. a line // holding """ gets it escaped so the block can't end early internal void dsl_emit_doc(StrBuf *b, String8 doc, u32 indent) { if(doc.size == 0) return; dsl_indent(b, indent); strbuf_fmt(b, "doc \"\"\"\n"); u64 start = 0; for(u64 i = 0; i <= doc.size; ++i) { if(i < doc.size && doc.data[i] != '\n') continue; String8 line = ToString8Size(doc.data + start, i - start); if(line.size && line.data[line.size - 1] == '\r') --line.size; if(line.size) dsl_indent(b, indent + 1); for(u64 c = 0; c < line.size; ++c) { if(c + 2 < line.size && line.data[c] == '"' && line.data[c + 1] == '"' && line.data[c + 2] == '"') { strbuf_fmt(b, "\\\"\"\""); c += 2; } else { strbuf_fmt(b, "%c", line.data[c]); } } strbuf_fmt(b, "\n"); start = i + 1; } dsl_indent(b, indent); strbuf_fmt(b, "\"\"\"\n"); } // NOTE: include == NULL emits every node, otherwise only flagged ones (a copy of the selection) internal void dsl_emit_node(StrBuf *b, Diagram *d, s32 idx, u32 indent, const b8 *include) { DiagramNode *n = &d->nodes[idx]; dsl_indent(b, indent); strbuf_fmt(b, "%s ", node_kind_name(n->kind)); dsl_emit_quoted(b, n->name); strbuf_fmt(b, " id=%s", n->key); if(n->stereotype[0]) { strbuf_fmt(b, " stereo="); dsl_emit_quoted(b, n->stereotype); } if(n->tag[0]) strbuf_fmt(b, " tag=%s", n->tag); if(n->color) strbuf_fmt(b, " color=#%08X", n->color); if(n->link[0]) { strbuf_fmt(b, " link="); dsl_emit_quoted(b, n->link); } strbuf_fmt(b, " x=%.0f y=%.0f", n->x, n->y); if(n->manual_size || n->kind == NODE_MODULE) strbuf_fmt(b, " w=%.0f h=%.0f", n->w, n->h); if(n->collapsed) strbuf_fmt(b, " collapsed=1"); if(n->pinned) strbuf_fmt(b, " pinned=1"); b32 has_children = false; for(u32 j = 0; j < d->node_count; ++j) { if(d->nodes[j].alive && d->nodes[j].parent == idx && (!include || include[j])) { has_children = true; break; } } if(n->first_section < 0 && !n->note[0] && !n->doc_len && !has_children) { strbuf_fmt(b, "\n"); return; } strbuf_fmt(b, " {\n"); if(n->note[0]) { dsl_indent(b, indent + 1); strbuf_fmt(b, "note "); dsl_emit_quoted(b, n->note); strbuf_fmt(b, "\n"); } dsl_emit_doc(b, diagram_doc(d, n->doc_off, n->doc_len), indent + 1); for(s32 s = n->first_section; s >= 0; s = d->sections[s].next) { NodeSection *sec = &d->sections[s]; dsl_indent(b, indent + 1); strbuf_fmt(b, "section "); dsl_emit_quoted(b, sec->title); strbuf_fmt(b, "%s {\n", sec->collapsed ? " collapsed=1" : ""); for(s32 m = sec->first_member; m >= 0; m = d->members[m].next) { NodeMember *mem = &d->members[m]; dsl_indent(b, indent + 2); if(mem->visibility) strbuf_fmt(b, "%c ", mem->visibility); strbuf_fmt(b, "%s", mem->name); if(mem->type[0]) strbuf_fmt(b, " : %s", mem->type); if(mem->badge[0]) strbuf_fmt(b, " [%s]", mem->badge); strbuf_fmt(b, "\n"); } dsl_indent(b, indent + 1); strbuf_fmt(b, "}\n"); } if(has_children) { for(u32 j = 0; j < d->node_count; ++j) { if(d->nodes[j].alive && d->nodes[j].parent == idx && (!include || include[j])) dsl_emit_node(b, d, (s32)j, indent + 1, include); } } dsl_indent(b, indent); strbuf_fmt(b, "}\n"); } internal void dsl_emit_edge(StrBuf *b, Diagram *d, s32 index) { DiagramEdge *e = &d->edges[index]; strbuf_fmt(b, "%s %s %s", d->nodes[e->src].key, edge_kind_symbol(e->kind), d->nodes[e->dst].key); if(e->label[0]) { strbuf_fmt(b, " : "); dsl_emit_quoted(b, e->label); } if(e->src_mult[0] || e->dst_mult[0]) strbuf_fmt(b, " [%s -> %s]", e->src_mult, e->dst_mult); if(e->routing != ROUTE_AUTO) strbuf_fmt(b, " route=%s", edge_routing_name(e->routing)); if(e->src_port != PORT_AUTO) strbuf_fmt(b, " from=%s", port_side_name(e->src_port)); if(e->dst_port != PORT_AUTO) strbuf_fmt(b, " to=%s", port_side_name(e->dst_port)); if(e->tag[0]) strbuf_fmt(b, " tag=%s", e->tag); if(e->color) strbuf_fmt(b, " color=#%08X", e->color); if(diagram_edge_is_message(d, index)) strbuf_fmt(b, " y=%.0f", e->msg_y); if(e->waypoint_count) { strbuf_fmt(b, " via="); for(u32 w = 0; w < e->waypoint_count; ++w) strbuf_fmt(b, "%s%.0f,%.0f", w ? ";" : "", e->waypoints[w].x, e->waypoints[w].y); } String8 doc = diagram_doc(d, e->doc_off, e->doc_len); if(doc.size) { strbuf_fmt(b, " {\n"); dsl_emit_doc(b, doc, 1); strbuf_fmt(b, "}\n"); } else { strbuf_fmt(b, "\n"); } } internal String8 dsl_emit(Arena *arena, Diagram *d, const b8 *include, b32 header) { StrBuf b; strbuf_init(arena, &b, MiB(1) + (u64)d->text_size * 2); if(header) { strbuf_fmt(&b, "diagram "); dsl_emit_quoted(&b, d->title); strbuf_fmt(&b, " routing=%s", edge_routing_name(d->default_routing)); if(d->repo[0]) { strbuf_fmt(&b, " repo="); dsl_emit_quoted(&b, d->repo); } if(d->repo_ref[0]) { strbuf_fmt(&b, " ref="); dsl_emit_quoted(&b, d->repo_ref); } if(d->repo_root[0]) { strbuf_fmt(&b, " root="); dsl_emit_quoted(&b, d->repo_root); } strbuf_fmt(&b, "\n"); dsl_emit_doc(&b, diagram_doc(d, d->doc_off, d->doc_len), 0); strbuf_fmt(&b, "\n"); } for(u32 i = 0; i < d->node_count; ++i) { DiagramNode *n = &d->nodes[i]; if(!n->alive || (include && !include[i])) continue; b32 top = (n->parent < 0) || (include && !include[n->parent]); if(top) dsl_emit_node(&b, d, (s32)i, 0, include); } b32 first_edge = true; for(u32 i = 0; i < d->edge_count; ++i) { DiagramEdge *e = &d->edges[i]; if(!e->alive || (include && (!include[e->src] || !include[e->dst]))) continue; if(first_edge) { strbuf_fmt(&b, "\n"); first_edge = false; } dsl_emit_edge(&b, d, (s32)i); } return ToString8Size((u8 *)b.data, b.size); } internal String8 diagram_to_dsl(Arena *arena, Diagram *d) { return dsl_emit(arena, d, NULL, true); } // NOTE: the selected nodes, everything inside selected modules, and the edges among them. what the // clipboard holds, so pasting into a text editor shows plain DSL internal String8 diagram_selection_to_dsl(Arena *arena, Diagram *d, s32 also_node, u32 *out_nodes) { b8 *include = PushArrayZero(arena, b8, d->node_count + 1); u32 count = 0; for(u32 i = 0; i < d->node_count; ++i) { if(d->nodes[i].alive && (d->nodes[i].selected || (s32)i == also_node)) include[i] = 1; } // children of included modules come along (a few passes cover nesting) for(u32 pass = 0; pass < 8; ++pass) { b32 changed = false; for(u32 i = 0; i < d->node_count; ++i) { DiagramNode *n = &d->nodes[i]; if(n->alive && !include[i] && n->parent >= 0 && include[n->parent]) { include[i] = 1; changed = true; } } if(!changed) break; } for(u32 i = 0; i < d->node_count; ++i) count += include[i]; if(out_nodes) *out_nodes = count; if(!count) return str8_zero(); String8 body = dsl_emit(arena, d, include, false); // NOTE: the marker line tells paste this is ours, a text editor just sees a comment String8 marker = str8((char *)"# design-it selection\n"); u8 *out = PushArray(arena, u8, marker.size + body.size + 1); MemCpy(out, marker.data, marker.size); MemCpy(out + marker.size, body.data, body.size); out[marker.size + body.size] = 0; return ToString8Size(out, marker.size + body.size); } internal const char *dsl_skip_ws(const char *p) { while(*p == ' ' || *p == '\t' || *p == '\r') ++p; return p; } internal const char *dsl_read_quoted(const char *p, char *out, u32 cap) { p = dsl_skip_ws(p); u32 n = 0; if(*p == '"') { ++p; while(*p && *p != '"' && *p != '\n') { char c = *p; if(c == '\\' && (p[1] == '"' || p[1] == '\\')) { c = p[1]; ++p; } else if(c == '\\' && p[1] == 'n') { c = '\n'; ++p; } if(n + 1 < cap) out[n++] = c; ++p; } if(*p == '"') ++p; } else { while(*p && *p != ' ' && *p != '\t' && *p != '\n' && *p != '\r' && *p != '{' && *p != '}') { if(n + 1 < cap) out[n++] = *p; ++p; } } out[n] = 0; return p; } internal s32 dsl_match_node_kind(const char *word) { for(u32 i = 0; i < NODE_KIND_COUNT; ++i) if(!strcasecmp(word, diagram_node_kind_names[i])) return (s32)i; if(!strcasecmp(word, "participant")) return NODE_LIFELINE; return -1; } internal s32 dsl_match_edge_sym(const char *sym) { for(u32 i = 0; i < EDGE_KIND_COUNT; ++i) if(!strcmp(sym, diagram_edge_kind_symbols[i])) return (s32)i; return -1; } internal u32 dsl_parse_color(const char *tok) { const char *hx = (tok[0] == '#') ? tok + 1 : tok; u32 c = (u32)strtoul(hx, NULL, 16); if(strlen(hx) == 6) c = (c << 8) | 0xFF; return c; } internal u32 dsl_parse_port(const char *tok) { for(u32 i = 0; i < PORT_COUNT; ++i) if(!strcasecmp(tok, diagram_port_side_names[i])) return i; if(!strcasecmp(tok, "n") || !strcasecmp(tok, "top")) return PORT_NORTH; if(!strcasecmp(tok, "s") || !strcasecmp(tok, "bottom")) return PORT_SOUTH; if(!strcasecmp(tok, "e") || !strcasecmp(tok, "right")) return PORT_EAST; if(!strcasecmp(tok, "w") || !strcasecmp(tok, "left")) return PORT_WEST; return PORT_AUTO; } // NOTE: next key=value pair on a line: false at the end or at a '{'. values may be quoted internal b32 dsl_next_attr(const char **at, char *key, u32 key_cap, char *value, u32 value_cap, b32 *brace) { const char *q = *at; for(;;) { q = dsl_skip_ws(q); if(!*q || *q == '\n') { *at = q; return false; } if(*q == '{') { if(brace) *brace = true; *at = q + 1; return false; } const char *eq = q; while(*eq && *eq != '=' && *eq != ' ' && *eq != '\t' && *eq != '{') ++eq; if(*eq == '=' && eq > q && (u32)(eq - q) < key_cap) { MemCpy(key, q, (u64)(eq - q)); key[eq - q] = 0; *at = dsl_read_quoted(eq + 1, value, value_cap); return true; } // not an attribute: skip the word (or the quoted string) if(*q == '"') { char skip[8]; q = dsl_read_quoted(q, skip, sizeof(skip)); } else { while(*q && *q != ' ' && *q != '\t' && *q != '{') ++q; } } } typedef struct DslKeyMap DslKeyMap; struct DslKeyMap { char key[48]; s32 node; }; typedef enum DslDocTarget { DSL_DOC_NONE, DSL_DOC_DIAGRAM, DSL_DOC_NODE, DSL_DOC_EDGE, } DslDocTarget; // NOTE: append = paste: nothing is cleared, the title / repo / diagram doc are left alone, keys in the // text map to the nodes this text creates (never to existing nodes with the same key), and new nodes // whose key is taken get a fresh one internal b32 dsl_parse(Diagram *d, String8 text, b32 append, b32 *out_has_positions) { ScratchArena scratch = ScratchGet(); if(!append) diagram_clear(d); s32 node_stack[16]; u32 node_depth = 0; s32 cur_section = -1; s32 cur_edge = -1; b32 has_positions = false; u32 created = 0; DslKeyMap *map = PushArray(scratch.arena, DslKeyMap, DIAGRAM_MAX_NODES); u32 map_count = 0; u32 doc_target = DSL_DOC_NONE; s32 doc_index = -1; u64 doc_cap = Min(text.size + 16, (u64)DIAGRAM_TEXT_CAP); char *doc_raw = PushArray(scratch.arena, char, doc_cap); u64 doc_size = 0; const char *at = (const char *)text.data; const char *end = at + text.size; while(at < end) { const char *line_start = at; while(at < end && *at != '\n') ++at; u64 len = (u64)(at - line_start); if(at < end && *at == '\n') ++at; //- inside a doc """ block: raw lines until the closing """ if(doc_target != DSL_DOC_NONE) { const char *t = line_start; while(t < line_start + len && (*t == ' ' || *t == '\t')) ++t; if(line_start + len - t >= 3 && t[0] == '"' && t[1] == '"' && t[2] == '"') { // strip the closing line's indent (plus one level) from every line, unescape \""" u64 indent = (u64)(t - line_start) + 2; char *clean = PushArray(scratch.arena, char, doc_size + 1); u64 size = 0; u64 ls = 0; for(u64 i = 0; i <= doc_size; ++i) { if(i < doc_size && doc_raw[i] != '\n') continue; u64 s = ls, strip = 0; while(s < i && strip < indent && (doc_raw[s] == ' ' || doc_raw[s] == '\t')) { ++s; ++strip; } for(u64 c = s; c < i; ++c) { if(c + 3 < i && doc_raw[c] == '\\' && doc_raw[c + 1] == '"' && doc_raw[c + 2] == '"' && doc_raw[c + 3] == '"') continue; clean[size++] = doc_raw[c]; } if(i < doc_size) clean[size++] = '\n'; ls = i + 1; } // NOTE: leading blank lines are dropped, trailing ones by diagram_set_doc u64 skip = 0; while(skip < size && clean[skip] == '\n') ++skip; if(doc_target == DSL_DOC_DIAGRAM && !append) diagram_set_doc(d, &d->doc_off, &d->doc_len, clean + skip, size - skip); if(doc_target == DSL_DOC_NODE && doc_index >= 0) diagram_set_doc(d, &d->nodes[doc_index].doc_off, &d->nodes[doc_index].doc_len, clean + skip, size - skip); if(doc_target == DSL_DOC_EDGE && doc_index >= 0) diagram_set_doc(d, &d->edges[doc_index].doc_off, &d->edges[doc_index].doc_len, clean + skip, size - skip); doc_target = DSL_DOC_NONE; doc_size = 0; } else if(doc_size + len + 1 < doc_cap) { MemCpy(doc_raw + doc_size, line_start, len); doc_size += len; doc_raw[doc_size++] = '\n'; } continue; } char line[1024]; u64 copy = Min(len, (u64)sizeof(line) - 1); MemCpy(line, line_start, copy); line[copy] = 0; const char *p = dsl_skip_ws(line); if(!*p || *p == '#' || (p[0] == '/' && p[1] == '/')) continue; if(*p == '}') { if(cur_section >= 0) cur_section = -1; else if(cur_edge != -1) cur_edge = -1; else if(node_depth > 0) --node_depth; continue; } // inside a section: parse member line "[vis] name [: type] [[badge]]" if(cur_section >= 0) { char vis = 0; if((*p == '+' || *p == '-' || *p == '#' || *p == '~' || *p == '@' || *p == '*') && (p[1] == ' ' || p[1] == '\t')) { vis = *p; p = dsl_skip_ws(p + 1); } char name[64] = {}, type[80] = {}, badge[24] = {}; char work[384]; snprintf(work, sizeof(work), "%s", p); // strip trailing [badge] char *lb = strrchr(work, '['); char *rb = lb ? strchr(lb, ']') : NULL; if(lb && rb) { *lb = 0; *rb = 0; snprintf(badge, sizeof(badge), "%s", lb + 1); } char *colon = strchr(work, ':'); if(colon) { *colon = 0; const char *ts = dsl_skip_ws(colon + 1); snprintf(type, sizeof(type), "%s", ts); u32 tl = (u32)strlen(type); while(tl > 0 && (type[tl - 1] == ' ' || type[tl - 1] == '\t')) type[--tl] = 0; } snprintf(name, sizeof(name), "%s", work); u32 nl = (u32)strlen(name); while(nl > 0 && (name[nl - 1] == ' ' || name[nl - 1] == '\t')) name[--nl] = 0; if(name[0]) diagram_add_member(d, cur_section, vis, name, type, badge); continue; } char first[64] = {}; const char *after = dsl_read_quoted(p, first, sizeof(first)); //- doc: a """ block, or one quoted line (\n for breaks) if(!strcmp(first, "doc")) { const char *q = dsl_skip_ws(after); u32 target = DSL_DOC_DIAGRAM; s32 index = -1; if(cur_edge != -1) { target = DSL_DOC_EDGE; index = cur_edge; } // -2: the edge was dropped else if(node_depth > 0) { target = DSL_DOC_NODE; index = node_stack[node_depth - 1]; } if(q[0] == '"' && q[1] == '"' && q[2] == '"') { doc_target = target; doc_index = index; doc_size = 0; } else if(*q == '"') { char one[1024]; dsl_read_quoted(q, one, sizeof(one)); if(target == DSL_DOC_DIAGRAM && !append) diagram_set_doc(d, &d->doc_off, &d->doc_len, one, strlen(one)); if(target == DSL_DOC_NODE && index >= 0) diagram_set_doc(d, &d->nodes[index].doc_off, &d->nodes[index].doc_len, one, strlen(one)); if(target == DSL_DOC_EDGE && index >= 0) diagram_set_doc(d, &d->edges[index].doc_off, &d->edges[index].doc_len, one, strlen(one)); } continue; } if(!strcmp(first, "diagram") && node_depth == 0) { char title[96] = {}; const char *q = dsl_read_quoted(after, title, sizeof(title)); if(append) continue; snprintf(d->title, sizeof(d->title), "%s", title); char key[32], value[512]; while(dsl_next_attr(&q, key, sizeof(key), value, sizeof(value), NULL)) { if(!strcmp(key, "routing")) { for(u32 i = 0; i < ROUTE_COUNT; ++i) if(!strcasecmp(value, diagram_edge_routing_names[i])) d->default_routing = i; } else if(!strcmp(key, "repo")) snprintf(d->repo, sizeof(d->repo), "%s", value); else if(!strcmp(key, "ref")) snprintf(d->repo_ref, sizeof(d->repo_ref), "%s", value); else if(!strcmp(key, "root")) snprintf(d->repo_root, sizeof(d->repo_root), "%s", value); } continue; } if(!strcmp(first, "section") && node_depth > 0) { char stitle[40] = {}; const char *q = dsl_read_quoted(after, stitle, sizeof(stitle)); cur_section = diagram_add_section(d, node_stack[node_depth - 1], stitle); char key[32], value[64]; while(cur_section >= 0 && dsl_next_attr(&q, key, sizeof(key), value, sizeof(value), NULL)) { if(!strcmp(key, "collapsed")) d->sections[cur_section].collapsed = atoi(value) != 0; } continue; } if(!strcmp(first, "note") && node_depth > 0 && *dsl_skip_ws(after) == '"') { DiagramNode *cur = &d->nodes[node_stack[node_depth - 1]]; dsl_read_quoted(after, cur->note, sizeof(cur->note)); continue; } s32 nkind = dsl_match_node_kind(first); if(nkind >= 0) { char name[80] = {}; after = dsl_read_quoted(after, name, sizeof(name)); s32 idx = diagram_add_node(d, (NodeKind)nkind, name, 40.0f + (f32)created * 32.0f, 40.0f); if(idx < 0) continue; ++created; DiagramNode *nd = &d->nodes[idx]; if(node_depth > 0) nd->parent = node_stack[node_depth - 1]; b32 open_brace = false; const char *q = after; char key[32], tok[512]; while(dsl_next_attr(&q, key, sizeof(key), tok, sizeof(tok), &open_brace)) { if(!strcmp(key, "id")) { if(append) { if(map_count < DIAGRAM_MAX_NODES) { snprintf(map[map_count].key, sizeof(map[map_count].key), "%s", tok); map[map_count++].node = idx; } s32 other = diagram_find_node_by_key(d, tok); if(other < 0 || other == idx) snprintf(nd->key, sizeof(nd->key), "%s", tok); else { nd->key[0] = 0; diagram_make_key(d, nd->key, sizeof(nd->key), tok, nd->id); } } else { snprintf(nd->key, sizeof(nd->key), "%s", tok); } } else if(!strcmp(key, "stereo")) snprintf(nd->stereotype, sizeof(nd->stereotype), "%s", tok); else if(!strcmp(key, "tag")) snprintf(nd->tag, sizeof(nd->tag), "%s", tok); else if(!strcmp(key, "link")) snprintf(nd->link, sizeof(nd->link), "%s", tok); else if(!strcmp(key, "x")) { nd->x = (f32)atof(tok); has_positions = true; } else if(!strcmp(key, "y")) { nd->y = (f32)atof(tok); has_positions = true; } else if(!strcmp(key, "w")) { nd->w = (f32)atof(tok); nd->manual_size = true; } else if(!strcmp(key, "h")) { nd->h = (f32)atof(tok); nd->manual_size = true; } else if(!strcmp(key, "collapsed")) nd->collapsed = atoi(tok) != 0; else if(!strcmp(key, "pinned")) nd->pinned = atoi(tok) != 0; else if(!strcmp(key, "color")) nd->color = dsl_parse_color(tok); } // NOTE: a lifeline's height is derived from its messages, w / h only pin the width if(node_kind_is_lifeline(nd->kind)) nd->manual_size = false; if(open_brace && node_depth < ArrayCount(node_stack)) { node_stack[node_depth++] = idx; } continue; } // otherwise try edge: src_key dst_key [: "label"] [m1 -> m2] [key=value ...] [{ doc }] char sym[16] = {}, dst_key[64] = {}; const char *p2 = dsl_read_quoted(after, sym, sizeof(sym)); s32 ekind = dsl_match_edge_sym(sym); if(ekind >= 0) { const char *p3 = dsl_read_quoted(p2, dst_key, sizeof(dst_key)); s32 src = -1, dst = -1; if(append) { for(u32 i = 0; i < map_count; ++i) { if(src < 0 && !strcmp(map[i].key, first)) src = map[i].node; if(dst < 0 && !strcmp(map[i].key, dst_key)) dst = map[i].node; } } else { src = diagram_find_node_by_key(d, first); dst = diagram_find_node_by_key(d, dst_key); } if(src >= 0 && dst >= 0) { s32 ei = diagram_add_edge(d, src, dst, (EdgeKind)ekind, ""); if(ei >= 0) { DiagramEdge *ed = &d->edges[ei]; const char *q = dsl_skip_ws(p3); if(*q == ':') q = dsl_read_quoted(q + 1, ed->label, sizeof(ed->label)); q = dsl_skip_ws(q); if(*q == '[') { const char *rb = strchr(q, ']'); if(rb) { char mbuf[64] = {}; u64 ml = Min((u64)(rb - q - 1), (u64)sizeof(mbuf) - 1); MemCpy(mbuf, q + 1, ml); char *arr = strstr(mbuf, "->"); if(arr) { *arr = 0; snprintf(ed->src_mult, sizeof(ed->src_mult), "%s", dsl_skip_ws(mbuf)); snprintf(ed->dst_mult, sizeof(ed->dst_mult), "%s", dsl_skip_ws(arr + 2)); u32 sl = (u32)strlen(ed->src_mult); while(sl > 0 && ed->src_mult[sl - 1] == ' ') ed->src_mult[--sl] = 0; } q = rb + 1; } } b32 open_brace = false; char key[32], tok[512]; while(dsl_next_attr(&q, key, sizeof(key), tok, sizeof(tok), &open_brace)) { if(!strcmp(key, "route")) { for(u32 i = 0; i < ROUTE_COUNT; ++i) if(!strcasecmp(tok, diagram_edge_routing_names[i])) ed->routing = i; } else if(!strcmp(key, "tag")) snprintf(ed->tag, sizeof(ed->tag), "%s", tok); else if(!strcmp(key, "color")) ed->color = dsl_parse_color(tok); else if(!strcmp(key, "from")) ed->src_port = dsl_parse_port(tok); else if(!strcmp(key, "to")) ed->dst_port = dsl_parse_port(tok); else if(!strcmp(key, "y")) ed->msg_y = (f32)atof(tok); else if(!strcmp(key, "via")) { ed->waypoint_count = 0; const char *v = tok; while(*v && ed->waypoint_count < DIAGRAM_MAX_WAYPOINTS) { char *next = NULL; f32 x = strtof(v, &next); if(!next || next == v || *next != ',') break; v = next + 1; f32 y = strtof(v, &next); if(!next || next == v) break; ed->waypoints[ed->waypoint_count++] = Vec2f{x, y}; v = next; while(*v == ';' || *v == ' ') ++v; } } } if(open_brace) cur_edge = ei; } } else { // NOTE: an edge to a missing node still may own a { doc } body, skip it const char *q = p3; b32 open_brace = false; char key[32], tok[64]; while(dsl_next_attr(&q, key, sizeof(key), tok, sizeof(tok), &open_brace)) {} if(open_brace) cur_edge = -2; } } } // NOTE: an unterminated """ block keeps what it had if(doc_target != DSL_DOC_NONE && doc_size) { if(doc_target == DSL_DOC_NODE && doc_index >= 0) diagram_set_doc(d, &d->nodes[doc_index].doc_off, &d->nodes[doc_index].doc_len, doc_raw, doc_size); if(doc_target == DSL_DOC_EDGE && doc_index >= 0) diagram_set_doc(d, &d->edges[doc_index].doc_off, &d->edges[doc_index].doc_len, doc_raw, doc_size); if(doc_target == DSL_DOC_DIAGRAM && !append) diagram_set_doc(d, &d->doc_off, &d->doc_len, doc_raw, doc_size); } // NOTE: messages without y= already got one in file order from diagram_add_edge diagram_measure_all(d); if(out_has_positions) *out_has_positions = has_positions; scratch_end(&scratch); return created > 0; } internal b32 diagram_from_dsl(Diagram *d, String8 text) { b32 has_positions = false; dsl_parse(d, text, false, &has_positions); if(!has_positions && d->live_nodes > 0) diagram_layout_layered(d, false); else diagram_fit_containers(d); diagram_fit_lifelines(d); diagram_rebuild_tags(d); d->dirty = false; return d->live_nodes > 0; } // NOTE: paste. new nodes keep the positions in the text, the caller moves them where they belong internal b32 diagram_append_dsl(Diagram *d, String8 text) { b32 ok = dsl_parse(d, text, true, NULL); diagram_fit_containers(d); diagram_fit_lifelines(d); diagram_rebuild_tags(d); d->dirty = true; ++d->version; return ok; } internal b32 diagram_save_file(Diagram *d, const char *path) { u64 len = strlen(path); if(len >= 4 && !strcmp(path + len - 4, ".dit")) { return diagram_save_binary(d, path); } ScratchArena scratch = ScratchGet(); String8 text = diagram_to_dsl(scratch.arena, d); FILE *f = fopen(path, "wb"); if(!f) { scratch_end(&scratch); return false; } fwrite(text.data, 1, text.size, f); fclose(f); snprintf(d->file_path, sizeof(d->file_path), "%s", path); d->dirty = false; scratch_end(&scratch); return true; } internal b32 diagram_load_file(Diagram *d, const char *path) { u64 len = strlen(path); if(len >= 4 && !strcmp(path + len - 4, ".dit")) { return diagram_load_binary(d, path); } ScratchArena scratch = ScratchGet(); String8 text = FileLoad(scratch.arena, str8((char *)path)); if(text.size == 0) { scratch_end(&scratch); return false; } // NOTE: .dit.txt, mermaid (.mmd) or plantuml (.puml), by extension and then by content b32 ok = diagram_import_text(d, text, path); if(ok) snprintf(d->file_path, sizeof(d->file_path), "%s", path); scratch_end(&scratch); return ok; } //- native vector SVG export internal void svg_color(char *out, u32 cap, u32 rgba) { snprintf(out, cap, "#%06X", (rgba >> 8) & 0xFFFFFFu); } internal void svg_escape(StrBuf *b, const char *s) { for(; *s; ++s) { if(*s == '&') strbuf_fmt(b, "&"); else if(*s == '<') strbuf_fmt(b, "<"); else if(*s == '>') strbuf_fmt(b, ">"); else if(*s == '"') strbuf_fmt(b, """); else strbuf_fmt(b, "%c", *s); } } internal void svg_escape_n(StrBuf *b, String8 s) { for(u64 i = 0; i < s.size; ++i) { char c = (char)s.data[i]; if(c == '&') strbuf_fmt(b, "&"); else if(c == '<') strbuf_fmt(b, "<"); else if(c == '>') strbuf_fmt(b, ">"); else if(c == '"') strbuf_fmt(b, """); else strbuf_fmt(b, "%c", c); } } internal b32 diagram_export_svg(Diagram *d, const char *path, const u32 *colors) { ScratchArena scratch = ScratchGet(); StrBuf b; strbuf_init(scratch.arena, &b, MiB(4)); Rect bounds = diagram_bounds(d); f32 pad = 48.0f; f32 vx = bounds.x0 - pad, vy = bounds.y0 - pad; f32 vw = Max(rect_w(bounds) + pad * 2.0f, 320.0f); f32 vh = Max(rect_h(bounds) + pad * 2.0f, 200.0f); char c_bg[16], c_panel[16], c_edge[16], c_hdr[16], c_txt[16], c_dim[16], c_acc[16]; svg_color(c_bg, sizeof(c_bg), colors[0]); // BG svg_color(c_panel, sizeof(c_panel), colors[1]); // PANEL svg_color(c_edge, sizeof(c_edge), colors[3]); // FOCUS_EDGE svg_color(c_hdr, sizeof(c_hdr), colors[5]); // TAB_ACTIVE svg_color(c_txt, sizeof(c_txt), colors[10]); // TEXT svg_color(c_dim, sizeof(c_dim), colors[11]); // TEXT_DIM svg_color(c_acc, sizeof(c_acc), colors[13]); // ACCENT strbuf_fmt(&b, "\n", vx, vy, vw, vh, vw, vh); strbuf_fmt(&b, "\n", vx, vy, vw, vh, c_bg); strbuf_fmt(&b, "\n"); // 1. Containers behind for(u32 i = 0; i < d->node_count; ++i) { DiagramNode *n = &d->nodes[i]; if(!n->alive || n->kind != NODE_MODULE || diagram_node_hidden(d, (s32)i)) continue; char stroke[16]; svg_color(stroke, sizeof(stroke), n->color ? n->color : colors[3]); strbuf_fmt(&b, "\n", n->x, n->y, n->w, n->h, c_panel, stroke); strbuf_fmt(&b, "", n->x + 10.0f, n->y + 19.0f, c_txt); svg_escape(&b, n->name); strbuf_fmt(&b, "\n"); } // 2. Edges EdgePath ep; for(u32 i = 0; i < d->edge_count; ++i) { DiagramEdge *e = &d->edges[i]; if(!e->alive || diagram_edge_hidden(d, (s32)i) || !diagram_edge_route(d, (s32)i, &ep)) continue; char ec[16]; svg_color(ec, sizeof(ec), e->color ? e->color : ((e->kind == EDGE_DATAFLOW) ? colors[13] : colors[11])); b32 dashed = (e->kind == EDGE_DEPENDENCY || e->kind == EDGE_IMPLEMENTS || e->kind == EDGE_ASYNC || e->kind == EDGE_REPLY); f32 sw = (e->kind == EDGE_DATAFLOW) ? 2.2f : 1.4f; if(ep.routing == ROUTE_BEZIER) { strbuf_fmt(&b, "\n", ep.points[0].x, ep.points[0].y, ep.c0.x, ep.c0.y, ep.c1.x, ep.c1.y, ep.points[1].x, ep.points[1].y, ec, sw, dashed ? " stroke-dasharray=\"6 4\"" : ""); } else { strbuf_fmt(&b, "\n", ec, sw, dashed ? " stroke-dasharray=\"6 4\"" : ""); } // Target arrowhead if(e->kind != EDGE_LINK) { Vec2f tip = ep.points[ep.point_count - 1]; Vec2f dir = ep.dst_dir; Vec2f side = {-dir.y, dir.x}; f32 len = 11.0f, hw = 5.5f; Vec2f b1 = {tip.x - dir.x * len + side.x * hw, tip.y - dir.y * len + side.y * hw}; Vec2f b2 = {tip.x - dir.x * len - side.x * hw, tip.y - dir.y * len - side.y * hw}; b32 hollow = (e->kind == EDGE_INHERITANCE || e->kind == EDGE_IMPLEMENTS); b32 open = (e->kind == EDGE_REPLY || e->kind == EDGE_ASSOCIATION || e->kind == EDGE_DEPENDENCY || e->kind == EDGE_BIDIR); if(open) { strbuf_fmt(&b, "\n", b1.x, b1.y, tip.x, tip.y, b2.x, b2.y, ec); } else { strbuf_fmt(&b, "\n", tip.x, tip.y, b1.x, b1.y, b2.x, b2.y, hollow ? c_bg : ec, ec); } } if(e->label[0]) { b32 message = diagram_edge_is_message(d, (s32)i); strbuf_fmt(&b, "", ep.label_pos.x, ep.label_pos.y - (message ? 0.0f : 6.0f), c_dim, (message && e->src == e->dst) ? "start" : "middle"); svg_escape(&b, e->label); String8 doc = diagram_doc(d, e->doc_off, e->doc_len); if(doc.size) { strbuf_fmt(&b, ""); svg_escape_n(&b, doc); strbuf_fmt(&b, ""); } strbuf_fmt(&b, "\n"); } } // 3. Regular nodes (a link wraps the node in , the doc becomes its hover ) for(u32 i = 0; i < d->node_count; ++i) { DiagramNode *n = &d->nodes[i]; if(!n->alive || n->kind == NODE_MODULE || diagram_node_hidden(d, (s32)i)) continue; char stroke[16]; svg_color(stroke, sizeof(stroke), n->color ? n->color : colors[3]); char url[1024] = {}; if(n->link[0]) diagram_link_url(d, n->link, url, sizeof(url)); if(url[0]) { strbuf_fmt(&b, "\n"); } strbuf_fmt(&b, ""); String8 doc = diagram_doc(d, n->doc_off, n->doc_len); if(doc.size || n->link[0]) { strbuf_fmt(&b, ""); svg_escape(&b, n->name); if(n->link[0]) { strbuf_fmt(&b, " ("); svg_escape(&b, n->link); strbuf_fmt(&b, ")"); } if(doc.size) { strbuf_fmt(&b, "\n\n"); svg_escape_n(&b, doc); } strbuf_fmt(&b, "\n"); } if(node_kind_is_lifeline(n->kind)) { f32 cx = n->x + n->w * 0.5f; strbuf_fmt(&b, "\n", cx, n->y + n->header_h, cx, n->y + n->h, c_dim); if(n->kind == NODE_ACTOR) { f32 hy = n->y + 10.0f; strbuf_fmt(&b, "\n", cx, hy, stroke); strbuf_fmt(&b, "\n", cx, hy + 7.0f, cx, hy + 24.0f, cx - 11.0f, hy + 13.0f, cx + 11.0f, hy + 13.0f, cx - 9.0f, hy + 36.0f, cx, hy + 24.0f, cx + 9.0f, hy + 36.0f, stroke); strbuf_fmt(&b, "", cx, n->y + 58.0f, c_txt); svg_escape(&b, n->name); strbuf_fmt(&b, "\n"); } else { strbuf_fmt(&b, "\n", n->x, n->y, n->w, n->header_h, c_hdr, stroke); strbuf_fmt(&b, "", cx, n->y + 20.0f, c_txt); svg_escape(&b, n->name); strbuf_fmt(&b, "\n"); } if(n->stereotype[0]) { strbuf_fmt(&b, "", cx, n->y + n->header_h - 8.0f, c_dim); svg_escape(&b, n->stereotype); strbuf_fmt(&b, "\n"); } strbuf_fmt(&b, "%s\n", url[0] ? "" : ""); continue; } f32 rx = (n->kind == NODE_STATE) ? 14.0f : 0.0f; strbuf_fmt(&b, "\n", n->x, n->y, n->w, n->h, rx, c_panel, stroke, n->border_style == BORDER_DASHED ? " stroke-dasharray=\"5 3\"" : ""); strbuf_fmt(&b, "\n", n->x + 1, n->y + 1, n->w - 2, n->header_h - 1, rx, c_hdr); strbuf_fmt(&b, "", n->x + 10.0f, n->y + 20.0f, c_txt); svg_escape(&b, n->name); strbuf_fmt(&b, "\n"); strbuf_fmt(&b, "%s\n", n->x + n->w - 8.0f, n->y + 19.0f, c_acc, node_kind_badge(n->kind)); if(!n->collapsed) { f32 y = n->y + n->header_h; if(n->note[0]) { strbuf_fmt(&b, "", n->x + 10.0f, y + 16.0f, c_dim); svg_escape(&b, n->note); strbuf_fmt(&b, "\n"); y += 24.0f; } for(s32 s = n->first_section; s >= 0; s = d->sections[s].next) { NodeSection *sec = &d->sections[s]; strbuf_fmt(&b, "\n", n->x, y, n->x + n->w, y, stroke); strbuf_fmt(&b, "", n->x + 8.0f, y + 14.0f, c_dim); svg_escape(&b, sec->title); strbuf_fmt(&b, "\n"); y += 20.0f; if(!sec->collapsed) { for(s32 m = sec->first_member; m >= 0; m = d->members[m].next) { NodeMember *mem = &d->members[m]; strbuf_fmt(&b, "", n->x + 10.0f, y + 14.0f, c_txt); if(mem->visibility) strbuf_fmt(&b, "%c ", mem->visibility); svg_escape(&b, mem->name); if(mem->type[0]) { strbuf_fmt(&b, " : "); svg_escape(&b, mem->type); } strbuf_fmt(&b, "\n"); y += 20.0f; } y += 4.0f; } } } strbuf_fmt(&b, "%s\n", url[0] ? "" : ""); } strbuf_fmt(&b, "\n"); FILE *f = fopen(path, "wb"); if(!f) { scratch_end(&scratch); return false; } fwrite(b.data, 1, b.size, f); fclose(f); scratch_end(&scratch); return true; } //- C/C++ codebase structure scanner (:scan ) internal b32 is_ident_char(char c) { return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_'; } internal void scan_cpp_file(Diagram *d, Arena *arena, const char *path, s32 parent_module) { String8 text = FileLoad(arena, str8((char *)path)); if(text.size == 0) return; const char *at = (const char *)text.data; const char *end = at + text.size; const char *line_at = at; // newlines counted up to here u32 line = 1; while(at < end) { // skip comments if(at + 1 < end && at[0] == '/' && at[1] == '/') { while(at < end && *at != '\n') ++at; continue; } if(at + 1 < end && at[0] == '/' && at[1] == '*') { at += 2; while(at + 1 < end && !(at[0] == '*' && at[1] == '/')) ++at; at += 2; continue; } // match struct/class/enum declaration NodeKind kind = NODE_KIND_COUNT; u32 kw_len = 0; if(at + 7 < end && !strncmp(at, "struct ", 7) && (at == (const char *)text.data || !is_ident_char(at[-1]))) { kind = NODE_STRUCT; kw_len = 7; } else if(at + 6 < end && !strncmp(at, "class ", 6) && (at == (const char *)text.data || !is_ident_char(at[-1]))) { kind = NODE_CLASS; kw_len = 6; } else if(at + 5 < end && !strncmp(at, "enum ", 5) && (at == (const char *)text.data || !is_ident_char(at[-1]))) { kind = NODE_ENUM; kw_len = 5; } if(kind == NODE_KIND_COUNT) { ++at; continue; } for(; line_at < at; ++line_at) if(*line_at == '\n') ++line; u32 decl_line = line; at += kw_len; while(at < end && (*at == ' ' || *at == '\t')) ++at; if(kind == NODE_ENUM && at + 6 < end && !strncmp(at, "class ", 6)) { at += 6; while(at < end && *at == ' ') ++at; } char name[64] = {}; u32 nlen = 0; while(at < end && is_ident_char(*at) && nlen + 1 < sizeof(name)) name[nlen++] = *at++; if(nlen == 0) continue; // find '{' before ';' const char *scan = at; char base_name[64] = {}; while(scan < end && *scan != '{' && *scan != ';') { if(*scan == ':' && !base_name[0]) { ++scan; while(scan < end && (*scan == ' ' || *scan == '\t')) ++scan; if(scan + 7 < end && !strncmp(scan, "public ", 7)) scan += 7; else if(scan + 10 < end && !strncmp(scan, "protected ", 10)) scan += 10; while(scan < end && (*scan == ' ' || *scan == '\t')) ++scan; u32 bl = 0; while(scan < end && is_ident_char(*scan) && bl + 1 < sizeof(base_name)) base_name[bl++] = *scan++; continue; } ++scan; } if(scan >= end || *scan != '{') continue; at = scan + 1; // create node (skip duplicates) if(d->live_nodes >= DIAGRAM_MAX_NODES - 4) return; s32 node = diagram_add_node(d, kind, name, 0, 0); if(node < 0) continue; if(parent_module >= 0) d->nodes[node].parent = parent_module; if(base_name[0]) snprintf(d->nodes[node].stereotype, sizeof(d->nodes[node].stereotype), ": %s", base_name); const char *slash = strrchr(path, '/'); snprintf(d->nodes[node].tag, sizeof(d->nodes[node].tag), "%s", slash ? slash + 1 : path); // NOTE: the absolute path for now, diagram_scan_cpp makes it relative to the repo snprintf(d->nodes[node].link, sizeof(d->nodes[node].link), "%s:%u", path, decl_line); s32 sec = diagram_add_section(d, node, kind == NODE_ENUM ? "values" : "fields"); u32 brace_depth = 1; u32 member_cap = 0; while(at < end && brace_depth > 0) { if(at + 1 < end && at[0] == '/' && at[1] == '/') { while(at < end && *at != '\n') ++at; continue; } if(at + 1 < end && at[0] == '/' && at[1] == '*') { at += 2; while(at + 1 < end && !(at[0] == '*' && at[1] == '/')) ++at; at += 2; continue; } if(*at == '{') { ++brace_depth; ++at; continue; } if(*at == '}') { --brace_depth; ++at; continue; } if(brace_depth == 1 && (*at != ' ' && *at != '\t' && *at != '\n' && *at != '\r' && *at != '#')) { const char *ls = at; while(at < end && *at != ';' && *at != '\n' && *at != ',' && *at != '{' && *at != '}') ++at; if(member_cap < 14) { char stmt[160] = {}; u64 sl = Min((u64)(at - ls), (u64)sizeof(stmt) - 1); MemCpy(stmt, ls, sl); // trim comments / trailing ws char *cmm = strstr(stmt, "//"); if(cmm) *cmm = 0; u32 len2 = (u32)strlen(stmt); while(len2 > 0 && (stmt[len2 - 1] == ' ' || stmt[len2 - 1] == '\t' || stmt[len2 - 1] == '\r')) stmt[--len2] = 0; if(len2 > 0 && strcmp(stmt, "public:") != 0 && strcmp(stmt, "private:") != 0 && strcmp(stmt, "protected:") != 0) { if(kind == NODE_ENUM) { char *eq = strchr(stmt, '='); if(eq) *eq = 0; diagram_add_member(d, sec, 0, stmt, "", ""); ++member_cap; } else { // split last identifier as field name, rest as type char *last_sp = strrchr(stmt, ' '); if(last_sp && last_sp[1]) { *last_sp = 0; const char *fname = last_sp + 1; b32 is_ptr = false; while(*fname == '*') { is_ptr = true; ++fname; } char ftype[80]; snprintf(ftype, sizeof(ftype), "%s%s", stmt, is_ptr ? "*" : ""); diagram_add_member(d, sec, '+', fname, ftype, ""); ++member_cap; } } } } } if(at < end && *at != '{' && *at != '}') ++at; } } } internal b32 app_path_is_dir(const char *path) { #if PLATFORM_WINDOWS WCHAR wide[MAX_PATH * 2]; win32_utf8_to_wide(path, -1, wide, ArrayCount(wide)); DWORD attributes = GetFileAttributesW(wide); return attributes != INVALID_FILE_ATTRIBUTES && (attributes & FILE_ATTRIBUTE_DIRECTORY); #else struct stat st; return stat(path, &st) == 0 && S_ISDIR(st.st_mode); #endif } internal b32 scan_is_header(const char *name) { u64 len = strlen(name); return (len > 2 && !strcmp(name + len - 2, ".h")) || (len > 4 && !strcmp(name + len - 4, ".hpp")); } internal b32 scan_skip_dir(const char *name) { return name[0] == '.' || !strcmp(name, "build") || !strcmp(name, "protocols") || !strcmp(name, "node_modules"); } #if PLATFORM_WINDOWS internal void scan_cpp_dir(Diagram *d, Arena *arena, const char *path, u32 depth) { if(depth > 4) return; WCHAR wide[MAX_PATH * 2]; win32_utf8_to_wide(path, -1, wide, ArrayCount(wide)); DWORD attributes = GetFileAttributesW(wide); if(attributes == INVALID_FILE_ATTRIBUTES) return; if(!(attributes & FILE_ATTRIBUTE_DIRECTORY)) { if(scan_is_header(path)) scan_cpp_file(d, arena, path, -1); return; } const char *base = strrchr(path, '/'); const char *back = strrchr(path, '\\'); if(back && (!base || back > base)) base = back; s32 mod = -1; if(depth > 0 && base && base[1]) { mod = diagram_add_node(d, NODE_MODULE, base + 1, 0, 0); } WCHAR pattern[MAX_PATH * 2]; int length = win32_utf8_to_wide(path, -1, pattern, ArrayCount(pattern) - 3); pattern[length++] = L'\\'; pattern[length++] = L'*'; pattern[length] = 0; WIN32_FIND_DATAW data; HANDLE find = FindFirstFileW(pattern, &data); if(find == INVALID_HANDLE_VALUE) return; do { char name[MAX_PATH * 4]; win32_wide_to_utf8(data.cFileName, -1, name, sizeof(name)); if(scan_skip_dir(name)) continue; char child[640]; snprintf(child, sizeof(child), "%s/%s", path, name); if(data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { if(!(data.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)) scan_cpp_dir(d, arena, child, depth + 1); } else if(scan_is_header(name)) { scan_cpp_file(d, arena, child, mod); } } while(FindNextFileW(find, &data)); FindClose(find); } #else internal void scan_cpp_dir(Diagram *d, Arena *arena, const char *path, u32 depth) { if(depth > 4) return; struct stat st; if(stat(path, &st) != 0) return; if(S_ISREG(st.st_mode)) { if(scan_is_header(path)) scan_cpp_file(d, arena, path, -1); return; } if(!S_ISDIR(st.st_mode)) return; DIR *dir = opendir(path); if(!dir) return; const char *base = strrchr(path, '/'); s32 mod = -1; if(depth > 0 && base && base[1]) { mod = diagram_add_node(d, NODE_MODULE, base + 1, 0, 0); } struct dirent *ent; while((ent = readdir(dir)) != NULL) { if(scan_skip_dir(ent->d_name)) continue; char child[640]; snprintf(child, sizeof(child), "%s/%s", path, ent->d_name); struct stat cst; if(stat(child, &cst) != 0) continue; if(S_ISDIR(cst.st_mode)) { scan_cpp_dir(d, arena, child, depth + 1); } else if(scan_is_header(ent->d_name)) { scan_cpp_file(d, arena, child, mod); } } closedir(dir); } #endif internal u32 diagram_scan_cpp(Diagram *d, const char *path) { ScratchArena scratch = ScratchGet(); diagram_clear(d); snprintf(d->title, sizeof(d->title), "Codebase: %s", path); char abs[1024]; path_make_absolute(path, abs, sizeof(abs)); scan_cpp_dir(d, scratch.arena, abs, 0); // NOTE: links relative to the git checkout around the scanned folder (or the folder itself), // with the origin remote as the repo url so gx opens the right line online char root[1024], dir[1024]; if(app_path_is_dir(abs)) snprintf(dir, sizeof(dir), "%s", abs); else path_dirname(abs, dir, sizeof(dir)); if(!diagram_detect_repo(d, dir, root, sizeof(root))) snprintf(root, sizeof(root), "%s", dir); snprintf(d->repo_root, sizeof(d->repo_root), "%s", root); for(u32 i = 0; i < d->node_count; ++i) { DiagramNode *n = &d->nodes[i]; if(!n->alive || !n->link[0]) continue; char rel[DIAGRAM_LINK_SIZE]; path_relative_to(n->link, root, rel, sizeof(rel)); snprintf(n->link, sizeof(n->link), "%s", rel); } // infer relationships from member types and inheritance stereotypes! for(u32 i = 0; i < d->node_count; ++i) { DiagramNode *n = &d->nodes[i]; if(!n->alive || n->kind == NODE_MODULE) continue; // inheritance from ": Base" if(n->stereotype[0] == ':' && n->stereotype[1] == ' ') { const char *base = n->stereotype + 2; for(u32 j = 0; j < d->node_count; ++j) { if(i != j && d->nodes[j].alive && !strcmp(d->nodes[j].name, base)) { diagram_add_edge(d, (s32)i, (s32)j, EDGE_INHERITANCE, "extends"); break; } } } // composition / association from member types for(s32 s = n->first_section; s >= 0; s = d->sections[s].next) { for(s32 m = d->sections[s].first_member; m >= 0; m = d->members[m].next) { NodeMember *mem = &d->members[m]; if(!mem->type[0]) continue; b32 is_ptr = (strchr(mem->type, '*') != NULL); for(u32 j = 0; j < d->node_count; ++j) { if(i == j || !d->nodes[j].alive || d->nodes[j].kind == NODE_MODULE) continue; if(strlen(d->nodes[j].name) < 3) continue; const char *hit = strstr(mem->type, d->nodes[j].name); if(hit) { b32 left_ok = (hit == mem->type || !is_ident_char(hit[-1])); u64 tlen = strlen(d->nodes[j].name); b32 right_ok = !is_ident_char(hit[tlen]); if(left_ok && right_ok) { // avoid duplicate edge between same pair b32 exists = false; for(u32 e = 0; e < d->edge_count; ++e) { if(d->edges[e].alive && d->edges[e].src == (s32)i && d->edges[e].dst == (s32)j) { exists = true; break; } } if(!exists) { s32 ei = diagram_add_edge(d, (s32)i, (s32)j, is_ptr ? EDGE_ASSOCIATION : EDGE_COMPOSITION, mem->name); if(ei >= 0) d->edges[ei].src_member = m; } break; } } } } } } // prune empty module containers for(u32 i = 0; i < d->node_count; ++i) { if(d->nodes[i].alive && d->nodes[i].kind == NODE_MODULE) { b32 any = false; for(u32 j = 0; j < d->node_count; ++j) if(d->nodes[j].alive && d->nodes[j].parent == (s32)i) { any = true; break; } if(!any) diagram_delete_node(d, (s32)i); } } diagram_layout_layered(d, false); diagram_rebuild_tags(d); scratch_end(&scratch); return d->live_nodes; } //- built-in showcase templates global_variable const DiagramTemplate diagram_templates[] = { {"arch", "Design-It Vulkan + Wayland Engine Architecture (default)"}, {"ecs", "Data-Oriented ECS Game Engine"}, {"microservices", "Event-Driven Distributed Backend"}, {"compiler", "Optimizing Compiler Frontend -> SSA IR -> Codegen"}, {"uml", "Classic UML Domain & Design Patterns"}, {"sequence", "Sequence Diagram: login with a token cache"}, {"stress", "1,000 Nodes / 2,000 Edges Performance Benchmark"}, }; internal u32 diagram_template_count(void) { return ArrayCount(diagram_templates); } internal const DiagramTemplate *diagram_template_info(u32 index) { return index < ArrayCount(diagram_templates) ? &diagram_templates[index] : &diagram_templates[0]; } internal void template_load_arch(Diagram *d) { diagram_clear(d); snprintf(d->title, sizeof(d->title), "Design-It Software Architecture"); d->default_routing = ROUTE_ORTHOGONAL; // Containers s32 m_plat = diagram_add_node(d, NODE_MODULE, "Platform & Host", 0, 0); snprintf(d->nodes[m_plat].tag, sizeof(d->nodes[m_plat].tag), "platform"); s32 m_ren = diagram_add_node(d, NODE_MODULE, "Vulkan 1.3 SDF Renderer", 0, 0); snprintf(d->nodes[m_ren].tag, sizeof(d->nodes[m_ren].tag), "render"); s32 m_diag = diagram_add_node(d, NODE_MODULE, "Diagram Graph Engine", 0, 0); snprintf(d->nodes[m_diag].tag, sizeof(d->nodes[m_diag].tag), "diagram"); s32 m_ui = diagram_add_node(d, NODE_MODULE, "RAD-Style Dockable UI (.so)", 0, 0); snprintf(d->nodes[m_ui].tag, sizeof(d->nodes[m_ui].tag), "ui"); // Platform nodes s32 n_app = diagram_add_node(d, NODE_SYSTEM, "AppHost", 60, 80); d->nodes[n_app].parent = m_plat; snprintf(d->nodes[n_app].stereotype, sizeof(d->nodes[n_app].stereotype), "event-driven main loop"); snprintf(d->nodes[n_app].tag, sizeof(d->nodes[n_app].tag), "platform"); s32 s = diagram_add_section(d, n_app, "state"); s32 m_app_win = diagram_add_member(d, s, '+', "window", "PlatformWindow*", "wayland"); s32 m_app_ren = diagram_add_member(d, s, '+', "renderer", "VulkanRenderer", "vk1.3"); s32 m_app_dia = diagram_add_member(d, s, '+', "diagram", "Diagram*", "hot-safe"); diagram_add_member(d, s, '+', "ui_code", "UiCode (.so)", "inotify"); s = diagram_add_section(d, n_app, "loop"); diagram_add_member(d, s, '+', "poll_idle()", "0% cpu idle", "O(1)"); diagram_add_member(d, s, '+', "hot_reload()", "dlopen .so", "live"); s32 n_wl = diagram_add_node(d, NODE_INTERFACE, "PlatformWindow", 60, 380); d->nodes[n_wl].parent = m_plat; snprintf(d->nodes[n_wl].stereotype, sizeof(d->nodes[n_wl].stereotype), "xdg-shell + layer-shell"); snprintf(d->nodes[n_wl].tag, sizeof(d->nodes[n_wl].tag), "platform"); s = diagram_add_section(d, n_wl, "events"); diagram_add_member(d, s, '@', "keyboard", "xkbcommon utf8", ""); diagram_add_member(d, s, '@', "pointer", "pos + scroll_x/y", ""); diagram_add_member(d, s, '@', "frame_cb", "compositor paced", "vsync"); // Render nodes s32 n_vk = diagram_add_node(d, NODE_SYSTEM, "VulkanRenderer", 460, 80); d->nodes[n_vk].parent = m_ren; snprintf(d->nodes[n_vk].stereotype, sizeof(d->nodes[n_vk].stereotype), "dynamic rendering + sync2"); snprintf(d->nodes[n_vk].tag, sizeof(d->nodes[n_vk].tag), "render"); s = diagram_add_section(d, n_vk, "pipeline"); diagram_add_member(d, s, '+', "frames[2]", "VulkanFrame", "in-flight"); diagram_add_member(d, s, '+', "pipeline", "1 instanced SDF", "hot"); s32 m_vk_atlas = diagram_add_member(d, s, '+', "atlas", "R8 2048x2048", "4 MB"); s = diagram_add_section(d, n_vk, "methods"); diagram_add_member(d, s, '+', "vk_frame_begin()", "DrawInstance*", "mapped"); diagram_add_member(d, s, '+', "vk_render()", "1 draw / clip", "<0.4ms"); s32 n_inst = diagram_add_node(d, NODE_STRUCT, "DrawInstance", 460, 380); d->nodes[n_inst].parent = m_ren; snprintf(d->nodes[n_inst].stereotype, sizeof(d->nodes[n_inst].stereotype), "32 bytes (2 per cacheline)"); snprintf(d->nodes[n_inst].tag, sizeof(d->nodes[n_inst].tag), "hot"); s = diagram_add_section(d, n_inst, "memory layout"); diagram_add_member(d, s, '+', "rect[4]", "f32 (x0,y0,x1,y1)", "0x00"); diagram_add_member(d, s, '+', "data[2]", "u32 packed SDF/UV", "0x10"); diagram_add_member(d, s, '+', "colors[2]", "u32 top/bottom", "0x18"); s = diagram_add_section(d, n_inst, "SDF kinds"); diagram_add_member(d, s, '*', "RECT / CIRCLE / DIAMOND", "exact SDF", ""); diagram_add_member(d, s, '*', "LINE / ARROW / GLYPH", "dashed+orient", "gpu"); s32 n_font = diagram_add_node(d, NODE_STORAGE, "FontSystem", 840, 80); d->nodes[n_font].parent = m_ren; snprintf(d->nodes[n_font].stereotype, sizeof(d->nodes[n_font].stereotype), "FreeType + HarfBuzz"); snprintf(d->nodes[n_font].tag, sizeof(d->nodes[n_font].tag), "render"); s = diagram_add_section(d, n_font, "caches"); diagram_add_member(d, s, '+', "glyphs[16384]", "open-addr table", "O(1)"); diagram_add_member(d, s, '+', "runs[8192]", "shaped runs", "cached"); diagram_add_member(d, s, '+', "recent[1024]", "ptr fastpath", "ns"); // Diagram engine nodes s32 n_diag = diagram_add_node(d, NODE_STRUCT, "Diagram", 460, 710); d->nodes[n_diag].parent = m_diag; snprintf(d->nodes[n_diag].stereotype, sizeof(d->nodes[n_diag].stereotype), "flat arena pools"); snprintf(d->nodes[n_diag].tag, sizeof(d->nodes[n_diag].tag), "diagram"); s = diagram_add_section(d, n_diag, "pools"); diagram_add_member(d, s, '+', "nodes[4096]", "DiagramNode*", "index-id"); diagram_add_member(d, s, '+', "edges[8192]", "DiagramEdge*", "routed"); diagram_add_member(d, s, '+', "sections[8192]", "NodeSection*", "custom"); diagram_add_member(d, s, '+', "members[32768]", "NodeMember*", "pin-able"); s = diagram_add_section(d, n_diag, "history"); diagram_add_member(d, s, '+', "undo_ring[32]", "Arena snapshots", "O(N)"); s32 n_lay = diagram_add_node(d, NODE_SYSTEM, "AutoLayout & Router", 840, 710); d->nodes[n_lay].parent = m_diag; snprintf(d->nodes[n_lay].stereotype, sizeof(d->nodes[n_lay].stereotype), "zero-heap scratch arena"); snprintf(d->nodes[n_lay].tag, sizeof(d->nodes[n_lay].tag), "diagram"); s = diagram_add_section(d, n_lay, "algorithms"); diagram_add_member(d, s, '+', "layout_layered()", "Sugiyama ranks", "DAG"); diagram_add_member(d, s, '+', "layout_force()", "Fruchterman-R", "spring"); diagram_add_member(d, s, '+', "edge_route()", "ortho / bezier", "ports"); s32 n_io = diagram_add_node(d, NODE_SYSTEM, "Codec & C++ Scanner", 840, 930); d->nodes[n_io].parent = m_diag; snprintf(d->nodes[n_io].stereotype, sizeof(d->nodes[n_io].stereotype), ".dit / .dit.txt / .svg"); snprintf(d->nodes[n_io].tag, sizeof(d->nodes[n_io].tag), "diagram"); s = diagram_add_section(d, n_io, "pipelines"); diagram_add_member(d, s, '+', "dsl_parse/emit()", "git-friendly", "2-way"); diagram_add_member(d, s, '+', "export_svg()", "themed vector", "exact"); diagram_add_member(d, s, '+', "scan_cpp()", "header -> UML", "auto"); // UI nodes s32 n_ui = diagram_add_node(d, NODE_CLASS, "DockableLayout", 60, 710); d->nodes[n_ui].parent = m_ui; snprintf(d->nodes[n_ui].stereotype, sizeof(d->nodes[n_ui].stereotype), "binary split tree"); snprintf(d->nodes[n_ui].tag, sizeof(d->nodes[n_ui].tag), "ui"); s = diagram_add_section(d, n_ui, "views"); diagram_add_member(d, s, '+', "Canvas", "infinite pan/zoom", "LOD"); diagram_add_member(d, s, '+', "Outline / Edges", "watch tables", "vim"); diagram_add_member(d, s, '+', "Inspector / Source", "inline + DSL", "live"); diagram_add_member(d, s, '+', "Settings / Profiler", "18 colors+heap", "2Hz"); // Note s32 n_note = diagram_add_node(d, NODE_NOTE, "Quick Reference", 840, 380); snprintf(d->nodes[n_note].tag, sizeof(d->nodes[n_note].tag), "ui"); snprintf(d->nodes[n_note].note, sizeof(d->nodes[n_note].note), "Drag nodes, scroll to zoom, : for commands"); s = diagram_add_section(d, n_note, "keys"); diagram_add_member(d, s, '*', "a / e / dd / u", "add / edge / del / undo", ""); diagram_add_member(d, s, '*', "f / 0 / G / F", "fit / 100% / grid / focus", ""); diagram_add_member(d, s, '*', ":scan / :tpl / :export", "C++ / templates / svg", ""); diagram_add_member(d, s, '*', "^w v / ^w s / :view", "split / open views", ""); // Edges (showcasing member pinning, UML kinds, multiplicities, animated dataflow) s32 e; e = diagram_add_edge(d, n_app, n_wl, EDGE_COMPOSITION, "owns surface"); d->edges[e].src_member = m_app_win; snprintf(d->edges[e].src_mult, sizeof(d->edges[e].src_mult), "1"); snprintf(d->edges[e].dst_mult, sizeof(d->edges[e].dst_mult), "1"); e = diagram_add_edge(d, n_app, n_vk, EDGE_COMPOSITION, "presents"); d->edges[e].src_member = m_app_ren; e = diagram_add_edge(d, n_app, n_diag, EDGE_ASSOCIATION, "persists"); d->edges[e].src_member = m_app_dia; e = diagram_add_edge(d, n_vk, n_inst, EDGE_DATAFLOW, "131k mapped GPU"); snprintf(d->edges[e].dst_mult, sizeof(d->edges[e].dst_mult), "0..131k"); snprintf(d->edges[e].tag, sizeof(d->edges[e].tag), "hot"); e = diagram_add_edge(d, n_vk, n_font, EDGE_DEPENDENCY, "uploads dirty rows"); d->edges[e].src_member = m_vk_atlas; e = diagram_add_edge(d, n_ui, n_diag, EDGE_BIDIR, "reads & mutates"); e = diagram_add_edge(d, n_ui, n_inst, EDGE_DATAFLOW, "emits quads"); snprintf(d->edges[e].tag, sizeof(d->edges[e].tag), "hot"); e = diagram_add_edge(d, n_diag, n_lay, EDGE_DEPENDENCY, "ranks & routes"); e = diagram_add_edge(d, n_io, n_diag, EDGE_ASSOCIATION, "parse / serialize"); diagram_measure_all(d); diagram_fit_containers(d); diagram_rebuild_tags(d); d->dirty = false; } internal void template_load_ecs(Diagram *d) { diagram_clear(d); snprintf(d->title, sizeof(d->title), "Data-Oriented ECS Game Engine"); d->default_routing = ROUTE_ORTHOGONAL; s32 m_mem = diagram_add_node(d, NODE_MODULE, "Archetype Storage", 0, 0); s32 m_sys = diagram_add_node(d, NODE_MODULE, "Parallel Scheduler", 0, 0); s32 world = diagram_add_node(d, NODE_STRUCT, "World", 0, 0); s32 s = diagram_add_section(d, world, "tables"); diagram_add_member(d, s, '+', "entities", "SparseSet", "O(1)"); diagram_add_member(d, s, '+', "archetypes", "HashMap", ""); s32 arch = diagram_add_node(d, NODE_STRUCT, "Archetype", 0, 0); d->nodes[arch].parent = m_mem; s = diagram_add_section(d, arch, "layout"); diagram_add_member(d, s, '+', "signature", "u64[4] bitset", "256c"); diagram_add_member(d, s, '+', "chunks", "Chunk* list", "SoA"); s32 chunk = diagram_add_node(d, NODE_STORAGE, "Chunk (16 KB)", 0, 0); d->nodes[chunk].parent = m_mem; snprintf(d->nodes[chunk].stereotype, sizeof(d->nodes[chunk].stereotype), "L1 cache aligned"); s = diagram_add_section(d, chunk, "columns"); diagram_add_member(d, s, '+', "pos_x / pos_y", "f32[N]", "SIMD"); diagram_add_member(d, s, '+', "vel_x / vel_y", "f32[N]", "AVX2"); s32 sched = diagram_add_node(d, NODE_SYSTEM, "JobScheduler", 0, 0); d->nodes[sched].parent = m_sys; s = diagram_add_section(d, sched, "workers"); diagram_add_member(d, s, '+', "queues[N]", "WorkStealingDeque", "lock-free"); diagram_add_member(d, s, '+', "dispatch()", "DAG barrier", ""); s32 isys = diagram_add_node(d, NODE_INTERFACE, "ISystem", 0, 0); d->nodes[isys].parent = m_sys; s = diagram_add_section(d, isys, "contract"); diagram_add_member(d, s, '+', "query()", "ReadMask / WriteMask", "pure"); diagram_add_member(d, s, '+', "tick(Chunk*)", "void", "hot"); s32 phys = diagram_add_node(d, NODE_CLASS, "PhysicsSystem", 0, 0); d->nodes[phys].parent = m_sys; s32 rend = diagram_add_node(d, NODE_CLASS, "RenderExtract", 0, 0); d->nodes[rend].parent = m_sys; diagram_add_edge(d, world, arch, EDGE_COMPOSITION, "owns"); diagram_add_edge(d, arch, chunk, EDGE_COMPOSITION, "16KB slabs"); diagram_add_edge(d, sched, isys, EDGE_AGGREGATION, "schedules"); diagram_add_edge(d, phys, isys, EDGE_IMPLEMENTS, "implements"); diagram_add_edge(d, rend, isys, EDGE_IMPLEMENTS, "implements"); diagram_add_edge(d, phys, chunk, EDGE_DATAFLOW, "SIMD write"); diagram_add_edge(d, rend, chunk, EDGE_DATAFLOW, "RO gather"); diagram_layout_layered(d, false); diagram_rebuild_tags(d); d->dirty = false; } internal void template_load_microservices(Diagram *d) { diagram_clear(d); snprintf(d->title, sizeof(d->title), "Event-Driven Distributed Architecture"); d->default_routing = ROUTE_BEZIER; s32 gw = diagram_add_node(d, NODE_SYSTEM, "Edge Gateway", 0, 0); snprintf(d->nodes[gw].tag, sizeof(d->nodes[gw].tag), "edge"); s32 s = diagram_add_section(d, gw, "routes"); diagram_add_member(d, s, '@', "/v1/orders", "gRPC proxy", "TLS"); diagram_add_member(d, s, '@', "/v1/auth", "JWT verify", "5ms"); s32 auth = diagram_add_node(d, NODE_SYSTEM, "Auth Service", 0, 0); snprintf(d->nodes[auth].tag, sizeof(d->nodes[auth].tag), "core"); s32 ord = diagram_add_node(d, NODE_SYSTEM, "Order Service", 0, 0); snprintf(d->nodes[ord].tag, sizeof(d->nodes[ord].tag), "core"); s32 inv = diagram_add_node(d, NODE_SYSTEM, "Inventory Worker", 0, 0); snprintf(d->nodes[inv].tag, sizeof(d->nodes[inv].tag), "async"); s32 bill = diagram_add_node(d, NODE_SYSTEM, "Billing Worker", 0, 0); snprintf(d->nodes[bill].tag, sizeof(d->nodes[bill].tag), "async"); s32 bus = diagram_add_node(d, NODE_STORAGE, "Event Bus (Kafka)", 0, 0); snprintf(d->nodes[bus].tag, sizeof(d->nodes[bus].tag), "infra"); s = diagram_add_section(d, bus, "topics"); diagram_add_member(d, s, '@', "orders.created", "partition=16", "log"); diagram_add_member(d, s, '@', "payments.settled", "partition=8", "log"); s32 pg = diagram_add_node(d, NODE_STORAGE, "PostgreSQL Primary", 0, 0); snprintf(d->nodes[pg].tag, sizeof(d->nodes[pg].tag), "infra"); s32 rds = diagram_add_node(d, NODE_STORAGE, "Redis Cluster", 0, 0); snprintf(d->nodes[rds].tag, sizeof(d->nodes[rds].tag), "infra"); diagram_add_edge(d, gw, auth, EDGE_ASSOCIATION, "verify token"); diagram_add_edge(d, gw, ord, EDGE_DATAFLOW, "CreateOrder"); diagram_add_edge(d, auth, rds, EDGE_DEPENDENCY, "session cache"); diagram_add_edge(d, ord, pg, EDGE_DATAFLOW, "ACID write"); diagram_add_edge(d, ord, bus, EDGE_ASYNC, "publish event"); diagram_add_edge(d, bus, inv, EDGE_ASYNC, "reserve stock"); diagram_add_edge(d, bus, bill, EDGE_ASYNC, "charge card"); diagram_add_edge(d, inv, pg, EDGE_DEPENDENCY, "update qty"); diagram_layout_layered(d, true); diagram_rebuild_tags(d); d->dirty = false; } internal void template_load_compiler(Diagram *d) { diagram_clear(d); snprintf(d->title, sizeof(d->title), "Compiler Pipeline (Frontend -> SSA -> x64)"); d->default_routing = ROUTE_ORTHOGONAL; s32 src = diagram_add_node(d, NODE_STORAGE, "Source Buffer", 0, 0); s32 lex = diagram_add_node(d, NODE_SYSTEM, "Lexer", 0, 0); s32 parse = diagram_add_node(d, NODE_SYSTEM, "Recursive Parser", 0, 0); s32 ast = diagram_add_node(d, NODE_ENUM, "AST Node", 0, 0); s32 s = diagram_add_section(d, ast, "variants"); diagram_add_member(d, s, '+', "Expr / Stmt", "tagged union", "arena"); diagram_add_member(d, s, '+', "Decl / Type", "index-linked", "flat"); s32 sema = diagram_add_node(d, NODE_SYSTEM, "Type Checker", 0, 0); s32 ssa = diagram_add_node(d, NODE_STRUCT, "SSA IR Module", 0, 0); s = diagram_add_section(d, ssa, "blocks"); diagram_add_member(d, s, '+', "BasicBlock[]", "dominator tree", ""); diagram_add_member(d, s, '+', "Inst[]", "3-address SSA", "phi"); s32 opt = diagram_add_node(d, NODE_STATE, "Opt Passes (GVN/DCE/Inline)", 0, 0); s32 reg = diagram_add_node(d, NODE_SYSTEM, "Linear Scan RegAlloc", 0, 0); s32 emit = diagram_add_node(d, NODE_SYSTEM, "x64 / ARM64 Emitter", 0, 0); diagram_add_edge(d, src, lex, EDGE_DATAFLOW, "UTF-8 bytes"); diagram_add_edge(d, lex, parse, EDGE_DATAFLOW, "Token[]"); diagram_add_edge(d, parse, ast, EDGE_COMPOSITION, "builds"); diagram_add_edge(d, ast, sema, EDGE_DATAFLOW, "resolve"); diagram_add_edge(d, sema, ssa, EDGE_DATAFLOW, "lower"); diagram_add_edge(d, ssa, opt, EDGE_BIDIR, "fixed-point"); diagram_add_edge(d, ssa, reg, EDGE_DATAFLOW, "live intervals"); diagram_add_edge(d, reg, emit, EDGE_DATAFLOW, "machine ops"); diagram_layout_layered(d, true); diagram_rebuild_tags(d); d->dirty = false; } internal void template_load_uml(Diagram *d) { diagram_clear(d); snprintf(d->title, sizeof(d->title), "UML Class & Design Patterns"); d->default_routing = ROUTE_ORTHOGONAL; s32 isub = diagram_add_node(d, NODE_INTERFACE, "Observer", 0, 0); snprintf(d->nodes[isub].stereotype, sizeof(d->nodes[isub].stereotype), "<>"); s32 s = diagram_add_section(d, isub, "methods"); diagram_add_member(d, s, '+', "on_event(Event&)", "void", "abstract"); s32 node = diagram_add_node(d, NODE_CLASS, "SceneNode", 0, 0); s = diagram_add_section(d, node, "attributes"); diagram_add_member(d, s, '-', "id", "u64", ""); diagram_add_member(d, s, '#', "transform", "Mat4", ""); s = diagram_add_section(d, node, "operations"); diagram_add_member(d, s, '+', "update(dt)", "void", "virtual"); s32 group = diagram_add_node(d, NODE_CLASS, "GroupNode", 0, 0); s = diagram_add_section(d, group, "operations"); diagram_add_member(d, s, '+', "add_child(SceneNode*)", "void", ""); s32 mesh = diagram_add_node(d, NODE_CLASS, "MeshNode", 0, 0); s32 bus = diagram_add_node(d, NODE_CLASS, "EventDispatcher", 0, 0); s32 strat = diagram_add_node(d, NODE_INTERFACE, "CullStrategy", 0, 0); snprintf(d->nodes[strat].stereotype, sizeof(d->nodes[strat].stereotype), "<>"); s32 bvh = diagram_add_node(d, NODE_CLASS, "BVHCuller", 0, 0); s32 e; e = diagram_add_edge(d, group, node, EDGE_INHERITANCE, "extends"); e = diagram_add_edge(d, mesh, node, EDGE_INHERITANCE, "extends"); e = diagram_add_edge(d, group, node, EDGE_COMPOSITION, "children"); snprintf(d->edges[e].src_mult, sizeof(d->edges[e].src_mult), "1"); snprintf(d->edges[e].dst_mult, sizeof(d->edges[e].dst_mult), "0..*"); e = diagram_add_edge(d, bus, isub, EDGE_AGGREGATION, "listeners"); snprintf(d->edges[e].src_mult, sizeof(d->edges[e].src_mult), "1"); snprintf(d->edges[e].dst_mult, sizeof(d->edges[e].dst_mult), "0..*"); e = diagram_add_edge(d, node, isub, EDGE_IMPLEMENTS, "realizes"); e = diagram_add_edge(d, bvh, strat, EDGE_IMPLEMENTS, "realizes"); e = diagram_add_edge(d, group, strat, EDGE_DEPENDENCY, "uses"); diagram_layout_layered(d, false); diagram_rebuild_tags(d); d->dirty = false; } internal void template_load_stress(Diagram *d) { diagram_clear(d); snprintf(d->title, sizeof(d->title), "Performance Benchmark (1,000 Nodes / 1,900 Edges)"); d->default_routing = ROUTE_STRAIGHT; u32 cols = 40, rows = 25; s32 ids[1000]; for(u32 r = 0; r < rows; ++r) { for(u32 c = 0; c < cols; ++c) { u32 idx = r * cols + c; char name[32]; snprintf(name, sizeof(name), "Node_%03u", idx); NodeKind k = (NodeKind)(idx % 8); if(k == NODE_MODULE) k = NODE_STRUCT; s32 n = diagram_add_node(d, k, name, (f32)c * 260.0f, (f32)r * 130.0f); ids[idx] = n; snprintf(d->nodes[n].tag, sizeof(d->nodes[n].tag), "layer_%u", r / 5); s32 sec = diagram_add_section(d, n, "fields"); diagram_add_member(d, sec, '+', "value", "u64", ""); diagram_add_member(d, sec, '+', "next", "Node*", ""); } } for(u32 r = 0; r < rows; ++r) { for(u32 c = 0; c < cols; ++c) { u32 idx = r * cols + c; if(c + 1 < cols) diagram_add_edge(d, ids[idx], ids[idx + 1], (idx % 5 == 0) ? EDGE_DATAFLOW : EDGE_ASSOCIATION, ""); if(r + 1 < rows) diagram_add_edge(d, ids[idx], ids[idx + cols], (idx % 3 == 0) ? EDGE_DEPENDENCY : EDGE_COMPOSITION, ""); } } diagram_measure_all(d); diagram_rebuild_tags(d); d->dirty = false; } internal void template_load_sequence(Diagram *d) { const char *text = "diagram \"Login Sequence\" routing=orthogonal\n" "doc \"\"\"\n" " How a login request travels. Drag along a lifeline to add a message,\n" " drag a message up or down to reorder it, :seq re-spaces everything.\n" "\"\"\"\n" "actor \"User\" id=user\n" "lifeline \"Web App\" id=web stereo=\"frontend\"\n" "lifeline \"Auth Service\" id=auth\n" "lifeline \"Token Cache\" id=cache stereo=\"redis\"\n" "lifeline \"User DB\" id=db stereo=\"postgres\"\n" "user ->> web : \"submit credentials\"\n" "web ->> auth : \"POST /login\" {\n" " doc \"\"\"\n" " Rate limited per IP: 10 attempts per minute.\n" " \"\"\"\n" "}\n" "auth ->> cache : \"GET session:\"\n" "cache -->> auth : \"miss\"\n" "auth ->> db : \"SELECT hash WHERE email\"\n" "db -->> auth : \"row\"\n" "auth ->> auth : \"verify argon2\"\n" "auth ~> cache : \"SET session (ttl 1h)\"\n" "auth -->> web : \"200 + token\"\n" "web -->> user : \"dashboard\"\n"; diagram_from_dsl(d, str8((char *)text)); } internal b32 diagram_load_template(Diagram *d, const char *name) { if(!strcasecmp(name, "arch")) { template_load_arch(d); return true; } if(!strcasecmp(name, "ecs")) { template_load_ecs(d); return true; } if(!strcasecmp(name, "microservices")) { template_load_microservices(d); return true; } if(!strcasecmp(name, "compiler")) { template_load_compiler(d); return true; } if(!strcasecmp(name, "uml")) { template_load_uml(d); return true; } if(!strcasecmp(name, "sequence") || !strcasecmp(name, "seq")) { template_load_sequence(d); return true; } if(!strcasecmp(name, "stress")) { template_load_stress(d); return true; } return false; }