import { AfterViewChecked, OnInit, Component, ChangeDetectionStrategy, ChangeDetectorRef, ElementRef, Inject, Input, OnDestroy, PLATFORM_ID, ViewChild } from '@angular/core'; import { isPlatformBrowser } from '@angular/common'; import { FormsModule } from '@angular/forms'; import { NgTemplateOutlet } from '@angular/common'; import { BatchItem, MAX_BATCH_BYTES, MAX_BATCH_FILES, batchAccepts, runBatch, walkEntries } from './batch'; import { BACKGROUND, Built, FOREGROUND, Matrix, Shape, mul, transform } from './dxf-geometry'; import { DrawingError, Opened } from './drawing-file'; import { DrawingJob, openOffPage } from './open-client'; import { dwgThumbnail } from './dwg'; import { PaintOptions, Segment, backgroundCss, cssColor, paintSegments, prepare } from './render'; import { Sheet, pickViewport } from './scene'; import { exportBox, sheetSvg } from './export-svg'; import { wheelZooms } from './wheel'; import { Picked, ROUGH_AREA, areaText, evenOddArea, isClosed, outlineArea, shapeAreaOf, pickClosed, pickNearest, ringLength, shapeLength } from './measure'; import { MAX_PIXELS, MAX_SIDE, PictureSize, planPicture } from './picture'; import { MAX_HITS, TextHit, findText, hitOutline } from './find'; import { PAPER_SIZES, PLOT_SCALES, PdfOptions, PdfPage, makePdf, planPage } from './pdf'; import { mmPerUnit as unitMm } from './drawing-file'; import { pickerAccept } from '../shared/touch'; import { r12Dxf } from './r12'; interface LayerRow { name: string; /** RGB, or FOREGROUND for ACI 7. */ rgb: number; /** Items on this layer in the tab being shown. */ count: number; visible: boolean; } /** A point clicked while measuring, in sheet units; on a layout, also the viewport it fell in and the model point there. */ interface Pick { x: number; y: number; vp: number; mx: number; my: number; } const UNITS: Record = { 1: 'inches', 2: 'feet', 3: 'miles', 4: 'millimetres', 5: 'centimetres', 6: 'metres', 7: 'kilometres', 8: 'microinches', 9: 'mils', 10: 'yards', 11: 'ångströms', 12: 'nanometres', 13: 'microns', 14: 'decimetres', }; const UNIT_SHORT: Record = { 1: 'in', 2: 'ft', 4: 'mm', 5: 'cm', 6: 'm', 7: 'km', 10: 'yd', 14: 'dm' }; /** * The viewer itself: drop zone, tabs, drawing, layers and saving. /dwg-viewer, * /dwg-to-pdf and /dwg-to-dxf each put it on their page with their own copy; * `start` says which saving to put first once a drawing is open. */ @Component({ selector: 'app-dwg-view', imports: [FormsModule, NgTemplateOutlet], templateUrl: './dwg-view.component.html', changeDetection: ChangeDetectionStrategy.Eager, styleUrl: './dwg-view.component.scss' }) export class DwgViewComponent implements OnInit, AfterViewChecked, OnDestroy { /** The file picker's accept list; none on iOS, whose picker greys out kinds it does not know (shared/touch.ts). */ readonly pickerAccept = pickerAccept; /** What the page is for: viewing, or converting to PDF or to DXF, which opens that saving first. */ @Input() start: 'view' | 'pdf' | 'dxf' = 'view'; @ViewChild('canvas') canvasRef?: ElementRef; loadError = ''; dragOver = false; busy = ''; private openRun = 0; fileName = ''; /** The file was a DWG, converted on opening; it can be saved back out as the DXF it became. */ fromDwg = false; private dxfBytes: Uint8Array | null = null; version = ''; units = 0; /** The open drawing: the model and its layouts. */ opened: Opened | null = null; /** The tab being shown: 0 is the model. */ sheetIndex = 0; layers: LayerRow[] = []; layerFilter = ''; dark = true; /** Lines drawn at their lineweights, as AutoCAD's Show Lineweight; starts as the drawing was saved ($LWDISPLAY). */ showLw = false; tool: 'pan' | 'measure' | 'area' | 'info' = 'pan'; /** Area: click corners, or click a closed shape to take its outline. */ areaMode: 'points' | 'pick' = 'points'; areaPoints: Pick[] = []; areaShape: Picked | null = null; /** Info: the shape last clicked. */ infoPick: Picked | null = null; measure: { a: Pick; b: Pick | null } | null = null; private view = { cx: 0, cy: 0, scale: 1 }; /** Prepared paths, per tab's own shapes and the model's (viewports share them). */ private prepared = new Map(); private pointers = new Map(); private drag: { x: number; y: number; cx: number; cy: number; moved: boolean } | null = null; private pinch: { dist: number; scale: number } | null = null; private frame = 0; /** Until the reader pans or zooms, a resize re-fits the drawing rather than keeping the view. */ private autoFit = true; private resizeObserver: ResizeObserver | null = null; private observed: HTMLCanvasElement | null = null; constructor(private cdr: ChangeDetectorRef, @Inject(PLATFORM_ID) private platformId: object) {} /** * The canvas exists only while a drawing is open, and is a new element each * time one is. Once it is on the page, a resize observer is attached to it; * the observer's first callback, which arrives with the laid-out size, fits * the drawing to it. */ ngAfterViewChecked(): void { const canvas = this.canvasRef?.nativeElement; if (!canvas || canvas === this.observed) return; this.resizeObserver?.disconnect(); this.observed = canvas; this.resizeObserver = new ResizeObserver(() => (this.autoFit ? this.fit() : this.redraw())); this.resizeObserver.observe(canvas); } ngOnDestroy(): void { // Prerendering destroys the component under Node, where there are no animation frames. if (!isPlatformBrowser(this.platformId)) return; this.resizeObserver?.disconnect(); cancelAnimationFrame(this.frame); clearTimeout(this.zoomHintTimer); clearInterval(this.busyTimer); this.job?.cancel(); this.setThumbnail(null); } /* ── Input ─────────────────────────────────────────────────────────────── */ onDragOver(e: DragEvent): void { e.preventDefault(); this.dragOver = true; } onDragLeave(): void { this.dragOver = false; } async onDrop(e: DragEvent): Promise { e.preventDefault(); this.dragOver = false; const file = e.dataTransfer?.files?.[0]; // Several files, or a folder, are converted together below; one is opened. if (await this.onBatchDrop(e)) return; if (file) this.open(file); } onFileInput(e: Event): void { const el = e.target as HTMLInputElement; const file = el.files?.[0]; el.value = ''; if (file) this.open(file); } /** The DWG's own preview picture, shown while it converts. */ thumbnail = ''; /** Seconds since the file was dropped, while it is being opened. */ busySeconds = 0; private job: DrawingJob | null = null; private busyTimer: ReturnType | undefined; /** * Opens a file in a worker, so the page stays usable and Cancel works; * the stages it reports are shown with the time so far. */ private async open(file: File): Promise { // A file opened while another is still reading wins; the older one is dropped. const run = ++this.openRun; this.job?.cancel(); this.loadError = ''; this.setThumbnail(null); this.busy = `Reading ${file.name}…`; this.startBusyClock(); this.cdr.detectChanges(); try { const bytes = new Uint8Array(await file.arrayBuffer()); if (run !== this.openRun) return; const thumb = dwgThumbnail(bytes); if (thumb) this.setThumbnail(new Blob([thumb.data as BlobPart], { type: thumb.type })); const job = openOffPage(bytes, file.name, (stage) => { if (run !== this.openRun) return; this.busy = stage === 'convert' ? `Converting ${file.name} from DWG - the first time, the converter downloads as well (about 10 MB)…` : stage === 'read' ? `Reading the drawing in ${file.name}…` : `Building the model and layouts of ${file.name}…`; this.cdr.detectChanges(); }); this.job = job; const opened = await job.result; if (run !== this.openRun) return; this.show(opened, file.name); } catch (err: any) { if (run !== this.openRun) return; this.loadError = err instanceof DrawingError ? err.message : `${file.name} could not be opened: ${err?.message ?? String(err)}.`; } finally { if (run === this.openRun) this.endBusy(); } } /** Stops opening the file: the worker is ended and the page goes back to how it was. */ cancelOpen(): void { this.openRun++; this.job?.cancel(); this.endBusy(); } private startBusyClock(): void { clearInterval(this.busyTimer); const t0 = Date.now(); this.busySeconds = 0; this.busyTimer = setInterval(() => { this.busySeconds = Math.floor((Date.now() - t0) / 1000); this.cdr.detectChanges(); }, 1000); } private endBusy(): void { clearInterval(this.busyTimer); this.job = null; this.busy = ''; this.setThumbnail(null); this.cdr.detectChanges(); } private setThumbnail(blob: Blob | null): void { if (this.thumbnail) URL.revokeObjectURL(this.thumbnail); this.thumbnail = blob ? URL.createObjectURL(blob) : ''; } private show(opened: Opened, name: string): void { this.opened = opened; this.fromDwg = !!opened.dxf; this.dxfBytes = opened.dxf; this.fileName = name; this.version = opened.version; this.units = opened.units; this.showLw = opened.lwDisplay; this.pdfUnits = opened.units; this.measure = null; this.prepared = new Map(); this.findQuery = ''; this.findHits = []; this.findShown = null; this.layers = [...opened.layers.entries()] .map(([n, l]) => ({ name: n, count: 0, rgb: l.rgb, visible: l.visible })) .sort((a, b) => a.name.localeCompare(b.name, undefined, { numeric: true })); this.setSheet(opened.scene.initial); // On /dwg-to-pdf and /dwg-to-dxf the page's own saving comes first. if (this.start === 'pdf') this.pdfOpen = true; if (this.start === 'dxf') this.dxfOpen = true; } /* ── Tabs ──────────────────────────────────────────────────────────────── */ get sheets(): Sheet[] { return this.opened?.scene.sheets ?? []; } get sheet(): Sheet | null { return this.sheets[this.sheetIndex] ?? null; } /** The model's shapes: what the Model tab shows and every viewport looks at. */ get model(): Built | null { return this.sheets[0]?.space ?? null; } /** Shows a tab: its layers counted, the measurement cleared, the view fitted. */ setSheet(i: number): void { if (!this.sheets[i]) return; this.sheetIndex = i; this.measure = null; this.areaPoints = []; this.areaShape = null; this.infoPick = null; this.refreshPicks(); const s = this.sheets[i]; const counts = new Map(s.space.layerCounts); if (s.viewports.length) for (const [n, c] of this.model!.layerCounts) counts.set(n, (counts.get(n) ?? 0) + c); for (const l of this.layers) l.count = counts.get(l.name) ?? 0; this.autoFit = true; this.cdr.detectChanges(); this.fit(); } /** Arrow keys, Home and End move between tabs, as tabs do. */ onTabKey(e: KeyboardEvent): void { const n = this.sheets.length; let i = this.sheetIndex; if (e.key === 'ArrowRight') i = (i + 1) % n; else if (e.key === 'ArrowLeft') i = (i - 1 + n) % n; else if (e.key === 'Home') i = 0; else if (e.key === 'End') i = n - 1; else return; e.preventDefault(); this.setSheet(i); (e.currentTarget as HTMLElement).querySelectorAll('[role=tab]')[i]?.focus(); } /* ── Batch ─────────────────────────────────────────────────────────────── */ readonly maxBatch = MAX_BATCH_FILES; readonly maxBatchMb = MAX_BATCH_BYTES / 1024 / 1024; batchTarget: 'pdf' | 'dxf' = 'pdf'; batchContent: 'tab' | 'all' = 'tab'; /** The units taken for a drawing that does not say (millimetres). */ batchUnits = 4; batch: BatchItem[] = []; batchRunning = false; batchStopped = false; batchZip: Blob | null = null; batchZipName = ''; batchOthers = 0; batchCapped = false; batchError = ''; private batchRun = 0; private batchJob: DrawingJob | null = null; ngOnInit(): void { if (this.start === 'dxf') this.batchTarget = 'dxf'; } /** Files or a folder chosen for converting together. */ onBatchInput(event: Event): void { const el = event.target as HTMLInputElement; const files = Array.from(el.files ?? []); const fromFolder = el.hasAttribute('webkitdirectory'); el.value = ''; // A chosen folder's files carry their path from it ("Plans/Level 1/house.dwg"), the chosen folder's own name first. const all = files.map((file) => ({ file, folder: fromFolder ? (file.webkitRelativePath || '').split('/').slice(0, -1).join('/') : '' })); const keep = all.filter((f) => batchAccepts(f.file.name)); void this.startBatch(keep.slice(0, MAX_BATCH_FILES), all.length - keep.length, keep.length > MAX_BATCH_FILES); } /** Several files, or a folder, dropped on the drawing box go to the batch. */ async onBatchDrop(e: DragEvent): Promise { const items = Array.from(e.dataTransfer?.items ?? []); const entries = items.map((i) => (i.kind === 'file' ? i.webkitGetAsEntry?.() : null)).filter((x): x is FileSystemEntry => !!x); const files = Array.from(e.dataTransfer?.files ?? []); if (files.length <= 1 && !entries.some((x) => x.isDirectory)) return false; // One batch at a time: a second drop while one runs would mix their lists and settings. if (this.batchRunning) { this.batchError = 'Drawings are still being converted. Wait for them, or press Stop, before adding more.'; this.cdr.detectChanges(); return true; } try { if (!entries.length) { const keep = files.filter((f) => batchAccepts(f.name)); void this.startBatch(keep.slice(0, MAX_BATCH_FILES).map((file) => ({ file, folder: '' })), files.length - keep.length, keep.length > MAX_BATCH_FILES); } else { const { found, others, capped } = await walkEntries(entries); void this.startBatch(found, others, capped); } } catch { this.batchError = 'The dropped folder could not be read. Try Choose a folder instead.'; } this.cdr.detectChanges(); return true; } private async startBatch(items: { file: File; folder: string }[], others: number, capped: boolean): Promise { const run = ++this.batchRun; this.batch = items.map((x) => ({ ...x, status: 'waiting' })); this.batchOthers = others; this.batchCapped = capped; this.batchZip = null; this.batchError = ''; this.batchStopped = false; if (!items.length) { this.batchError = others ? 'None of those are .dwg or .dxf files.' : ''; this.cdr.detectChanges(); return; } this.batchRunning = true; this.cdr.detectChanges(); try { const zip = await runBatch(this.batch, { target: this.batchTarget, pdf: { ...this.pdfOptions(), unitMm: unitMm(Number(this.batchUnits)) }, content: this.batchContent, stopped: () => run !== this.batchRun || this.batchStopped, onJob: (job) => (this.batchJob = job), update: () => this.cdr.detectChanges(), }); if (run !== this.batchRun) return; this.batchZip = zip; const top = items[0].folder.split('/')[0]; this.batchZipName = `${top && items.every((x) => x.folder.split('/')[0] === top) ? top : 'Drawings'} (${this.batchTarget}).zip`; } catch (err) { if (run === this.batchRun) this.batchError = 'The files could not be converted: ' + ((err as Error)?.message || 'unknown error') + '.'; } finally { if (run === this.batchRun) { this.batchRunning = false; this.cdr.detectChanges(); } } } get batchDone(): number { return this.batch.filter((x) => x.status === 'done').length; } get batchSkipped(): BatchItem[] { return this.batch.filter((x) => x.status === 'skipped'); } get batchAt(): number { return this.batch.filter((x) => x.status !== 'waiting').length; } /** Stops after ending the file being worked on; what is done so far can still be saved. */ stopBatch(): void { this.batchStopped = true; this.batchJob?.cancel(); } saveBatch(): void { if (this.batchZip) save(this.batchZip, this.batchZipName); } clearBatch(): void { this.batchRun++; this.batch = []; this.batchZip = null; this.batchError = ''; } /* ── Find text ─────────────────────────────────────────────────────────── */ readonly maxHits = MAX_HITS; findQuery = ''; findHits: TextHit[] = []; findMore = false; /** The match being shown, highlighted on the drawing. */ findShown: TextHit | null = null; onFind(): void { const r = this.opened ? findText(this.opened.scene, this.findQuery) : { hits: [], more: false }; this.findHits = r.hits; this.findMore = r.more; if (this.findShown && !r.hits.includes(this.findShown)) { this.findShown = null; this.redraw(); } } /** Enter in the box shows the first match. */ onFindEnter(e: Event): void { e.preventDefault(); if (this.findHits.length) this.showHit(this.findHits[0]); } /** Goes to a match's tab and zooms to it, with the text outlined. */ showHit(hit: TextHit): void { if (hit.sheet !== this.sheetIndex) this.setSheet(hit.sheet); const canvas = this.canvasRef?.nativeElement; const ring = hitOutline(hit); let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity; for (let i = 0; i < ring.length; i += 2) { minX = Math.min(minX, ring[i]); maxX = Math.max(maxX, ring[i]); minY = Math.min(minY, ring[i + 1]); maxY = Math.max(maxY, ring[i + 1]); } this.findShown = hit; if (canvas) { const w = canvas.clientWidth || 800, h = canvas.clientHeight || 600; // The text a quarter of the view across, so what is round it shows too. const scale = Math.min((w * 0.25) / Math.max(maxX - minX, 1e-9), (h * 0.25) / Math.max(maxY - minY, 1e-9)); this.autoFit = false; this.view = { cx: (minX + maxX) / 2, cy: (minY + maxY) / 2, scale }; } this.redraw(); } /* ── Layers ────────────────────────────────────────────────────────────── */ /** Layers with something on them in this tab, filtered by the box above the list. */ get visibleLayers(): LayerRow[] { const f = this.layerFilter.trim().toLowerCase(); const rows = this.layers.filter((l) => l.count > 0); return f ? rows.filter((l) => l.name.toLowerCase().includes(f)) : rows; } get tabLayerCount(): number { return this.layers.filter((l) => l.count > 0).length; } toggleLayer(l: LayerRow): void { l.visible = !l.visible; this.redraw(); } setAllLayers(visible: boolean): void { this.layers.forEach((l) => (l.visible = visible)); this.redraw(); } /** Layers switched off in the list. */ private hiddenLayers(): Set { return new Set(this.layers.filter((l) => !l.visible).map((l) => l.name)); } toggleLw(): void { this.showLw = !this.showLw; this.redraw(); } toggleDark(): void { this.dark = !this.dark; this.redraw(); } /* ── Drawing ───────────────────────────────────────────────────────────── */ fit(): void { const b = this.sheet; const canvas = this.canvasRef?.nativeElement; if (!b || !canvas) return; const w = canvas.clientWidth || 800; const h = canvas.clientHeight || 600; const dx = Math.max(b.maxX - b.minX, 1e-9); const dy = Math.max(b.maxY - b.minY, 1e-9); this.view = { cx: (b.minX + b.maxX) / 2, cy: (b.minY + b.maxY) / 2, scale: Math.min(w / dx, h / dy) * 0.94 }; this.redraw(); } zoomBy(f: number, sx?: number, sy?: number): void { const canvas = this.canvasRef?.nativeElement; if (!canvas) return; const w = canvas.clientWidth; const h = canvas.clientHeight; const px = sx ?? w / 2; const py = sy ?? h / 2; // Keep the world point under the cursor where it is. const [wx, wy] = this.toWorld(px, py); this.autoFit = false; this.view.scale *= f; this.view.cx = wx - (px - w / 2) / this.view.scale; this.view.cy = wy + (py - h / 2) / this.view.scale; this.redraw(); } private toWorld(sx: number, sy: number): [number, number] { const canvas = this.canvasRef!.nativeElement; return [this.view.cx + (sx - canvas.clientWidth / 2) / this.view.scale, this.view.cy - (sy - canvas.clientHeight / 2) / this.view.scale]; } private toScreen(x: number, y: number): [number, number] { const canvas = this.canvasRef!.nativeElement; return [(x - this.view.cx) * this.view.scale + canvas.clientWidth / 2, canvas.clientHeight / 2 - (y - this.view.cy) * this.view.scale]; } redraw(): void { cancelAnimationFrame(this.frame); this.frame = requestAnimationFrame(() => this.draw()); } private draw(): void { const canvas = this.canvasRef?.nativeElement; if (!canvas || !this.sheet) return; const dpr = window.devicePixelRatio || 1; const w = canvas.clientWidth; const h = canvas.clientHeight; if (canvas.width !== Math.round(w * dpr) || canvas.height !== Math.round(h * dpr)) { canvas.width = Math.round(w * dpr); canvas.height = Math.round(h * dpr); } const ctx = canvas.getContext('2d')!; this.paint(ctx, w, h, dpr, this.view, this.dark); this.paintFound(ctx, dpr); this.paintMeasure(ctx, dpr); this.paintPicks(ctx, dpr); } private segmentsOf(b: Built): Segment[] { let s = this.prepared.get(b); if (!s) { s = prepare(b.shapes); this.prepared.set(b, s); } return s; } /** Paints the tab into any 2D context: the screen, or a canvas for a picture. */ private paint(ctx: CanvasRenderingContext2D, w: number, h: number, dpr: number, view: { cx: number; cy: number; scale: number }, dark: boolean): void { const sheet = this.sheet!; const s = view.scale; ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.fillStyle = backgroundCss(dark); ctx.fillRect(0, 0, w * dpr, h * dpr); const m: Matrix = [s, 0, 0, -s, w / 2 - view.cx * s, h / 2 + view.cy * s]; // On the model a lineweight is a width in pixels whatever the zoom, as in // AutoCAD's model space: 0.25 mm and thinner one pixel, thicker in // proportion. On a layout it is its real width on the sheet. const mmPerUnit = sheet.paper?.mmPerUnit ?? 1; const lwPx = sheet.kind === 'model' ? (mm: number) => (this.showLw ? Math.max(1, mm / 0.25) : 1) : (mm: number) => (this.showLw ? Math.max(1, (mm / mmPerUnit) * s) : 1); if (sheet.paper) this.paintPaper(ctx, dpr, m, sheet, dark); this.paintSheet(ctx, sheet, { m, dpr, dark, mode: 'color', w, h, lwPx }); } /** A tab's own shapes, then the model through each of its viewports, clipped and with their frozen layers hidden. */ private paintSheet(ctx: CanvasRenderingContext2D, sheet: Sheet, o: Omit): void { const hidden = this.hiddenLayers(); paintSegments(ctx, this.segmentsOf(sheet.space), { ...o, hidden }); for (const v of sheet.viewports) { paintSegments(ctx, this.segmentsOf(this.model!), { ...o, m: mul(o.m, v.m), hidden: v.frozen.length ? new Set([...hidden, ...v.frozen]) : hidden, clip: v.clip.map((r) => transform(o.m, r)), }); } } /** The page of a layout: a sheet a shade off the background, with a thin edge. */ private paintPaper(ctx: CanvasRenderingContext2D, dpr: number, m: Matrix, sheet: Sheet, dark: boolean): void { const p = sheet.paper!; const [x0, y0, x1, y1] = transform(m, [p.originX, p.originY, p.originX + p.widthMm / p.mmPerUnit, p.originY + p.heightMm / p.mmPerUnit]); ctx.setTransform(dpr, 0, 0, dpr, 0, 0); ctx.fillStyle = dark ? '#262934' : '#f3f4f8'; ctx.fillRect(x0, y1, x1 - x0, y0 - y1); ctx.strokeStyle = dark ? '#4a4f60' : '#b8bdcc'; ctx.lineWidth = 1; ctx.strokeRect(x0, y1, x1 - x0, y0 - y1); } /** The match found with Find text, outlined. */ private paintFound(ctx: CanvasRenderingContext2D, dpr: number): void { const hit = this.findShown; if (!hit || hit.sheet !== this.sheetIndex) return; const r = hitOutline(hit); ctx.setTransform(dpr, 0, 0, dpr, 0, 0); ctx.beginPath(); for (let i = 0; i < r.length; i += 2) { const [x, y] = this.toScreen(r[i], r[i + 1]); if (i) ctx.lineTo(x, y); else ctx.moveTo(x, y); } ctx.closePath(); ctx.lineWidth = 2; ctx.strokeStyle = '#ff9800'; ctx.stroke(); } private paintMeasure(ctx: CanvasRenderingContext2D, dpr: number): void { const m = this.measure; if (!m) return; ctx.setTransform(dpr, 0, 0, dpr, 0, 0); const [ax, ay] = this.toScreen(m.a.x, m.a.y); ctx.strokeStyle = '#ff5ca8'; ctx.fillStyle = '#ff5ca8'; ctx.lineWidth = 1.5; ctx.beginPath(); ctx.arc(ax, ay, 4, 0, Math.PI * 2); ctx.fill(); if (m.b) { const [bx, by] = this.toScreen(m.b.x, m.b.y); ctx.beginPath(); ctx.moveTo(ax, ay); ctx.lineTo(bx, by); ctx.stroke(); ctx.beginPath(); ctx.arc(bx, by, 4, 0, Math.PI * 2); ctx.fill(); } } /* ── Pointer ───────────────────────────────────────────────────────────── */ /** Shown over the drawing for a moment when the wheel scrolls past it without Ctrl. */ zoomHint = false; /** "Ctrl", or "Cmd" on a Mac; read when first needed, as prerendering has no navigator. */ zoomKey = 'Ctrl'; private zoomHintTimer: ReturnType | undefined; /** * Ctrl (or Cmd) and the wheel zooms; the wheel alone scrolls the page, which * it could not do past a drawing most of a screen tall. A trackpad pinch * arrives as a wheel event with ctrlKey set, so it still zooms. */ onWheel(e: WheelEvent): void { if (!wheelZooms(e)) { this.zoomKey = /Mac|iPhone|iPad/.test(navigator.platform || navigator.userAgent) ? 'Cmd' : 'Ctrl'; this.zoomHint = true; clearTimeout(this.zoomHintTimer); this.zoomHintTimer = setTimeout(() => { this.zoomHint = false; this.cdr.detectChanges(); }, 1500); return; } e.preventDefault(); const rect = (e.target as HTMLElement).getBoundingClientRect(); this.zoomBy(e.deltaY < 0 ? 1.2 : 1 / 1.2, e.clientX - rect.left, e.clientY - rect.top); } onPointerDown(e: PointerEvent): void { (e.target as HTMLElement).setPointerCapture(e.pointerId); this.pointers.set(e.pointerId, { x: e.clientX, y: e.clientY }); if (this.pointers.size === 2) { const [a, b] = [...this.pointers.values()]; this.pinch = { dist: Math.hypot(a.x - b.x, a.y - b.y), scale: this.view.scale }; this.drag = null; return; } this.drag = { x: e.clientX, y: e.clientY, cx: this.view.cx, cy: this.view.cy, moved: false }; } onPointerMove(e: PointerEvent): void { if (!this.pointers.has(e.pointerId)) return; this.pointers.set(e.pointerId, { x: e.clientX, y: e.clientY }); if (this.pinch && this.pointers.size === 2) { const [a, b] = [...this.pointers.values()]; const rect = (e.target as HTMLElement).getBoundingClientRect(); const f = (this.pinch.scale * Math.hypot(a.x - b.x, a.y - b.y)) / this.pinch.dist / this.view.scale; this.zoomBy(f, (a.x + b.x) / 2 - rect.left, (a.y + b.y) / 2 - rect.top); return; } const d = this.drag; if (!d) return; const dx = e.clientX - d.x; const dy = e.clientY - d.y; if (Math.abs(dx) + Math.abs(dy) > 3) d.moved = true; if (d.moved) { this.autoFit = false; this.view.cx = d.cx - dx / this.view.scale; this.view.cy = d.cy + dy / this.view.scale; this.redraw(); } } onPointerUp(e: PointerEvent): void { this.pointers.delete(e.pointerId); if (this.pointers.size < 2) this.pinch = null; const d = this.drag; this.drag = null; if (d && !d.moved && this.tool !== 'pan') { const rect = (e.target as HTMLElement).getBoundingClientRect(); const sx = e.clientX - rect.left, sy = e.clientY - rect.top; if (this.tool === 'measure') this.measureClick(sx, sy); else if (this.tool === 'area') this.areaClick(sx, sy); else this.infoClick(sx, sy); } } /** Two clicks, each snapped to the nearest drawn vertex within ten pixels. */ private measureClick(sx: number, sy: number): void { const [x, y] = this.snap(sx, sy); const at = this.sheet!.kind === 'layout' ? pickViewport(this.sheet!, x, y) : { index: -1, mx: x, my: y }; const p: Pick = { x, y, vp: at.index, mx: at.mx, my: at.my }; if (!this.measure || this.measure.b) this.measure = { a: p, b: null }; else this.measure.b = p; this.redraw(); } /** Every drawn vertex of the tab, in sheet units: its own shapes, and the model's through each viewport. */ private *vertices(): Generator<[number, number]> { const sheet = this.sheet; if (!sheet) return; const hidden = this.hiddenLayers(); for (const s of sheet.space.shapes) { if (hidden.has(s.layer) || !s.rings) continue; for (const r of s.rings) for (let i = 0; i < r.length; i += 2) yield [r[i], r[i + 1]]; } for (const v of sheet.viewports) { const m = v.m; for (const s of this.model!.shapes) { if (hidden.has(s.layer) || v.frozen.includes(s.layer) || !s.rings) continue; for (const r of s.rings) for (let i = 0; i < r.length; i += 2) yield [m[0] * r[i] + m[2] * r[i + 1] + m[4], m[1] * r[i] + m[3] * r[i + 1] + m[5]]; } } } private snap(sx: number, sy: number): [number, number] { const [wx, wy] = this.toWorld(sx, sy); const limit = 10 / this.view.scale; let best = limit * limit; let out: [number, number] = [wx, wy]; for (const [x, y] of this.vertices()) { const d = (x - wx) ** 2 + (y - wy) ** 2; if (d < best) { best = d; out = [x, y]; } } return out; } setTool(t: 'pan' | 'measure' | 'area' | 'info'): void { this.tool = t; this.measure = null; this.areaPoints = []; this.areaShape = null; this.infoPick = null; this.refreshPicks(); this.redraw(); } /* ── Area and Info ─────────────────────────────────────────────────────── */ private pickAt(sx: number, sy: number): Pick { const [x, y] = this.snap(sx, sy); const at = this.sheet!.kind === 'layout' ? pickViewport(this.sheet!, x, y) : { index: -1, mx: x, my: y }; return { x, y, vp: at.index, mx: at.mx, my: at.my }; } setAreaMode(m: 'points' | 'pick'): void { this.areaMode = m; this.areaPoints = []; this.areaShape = null; this.refreshPicks(); this.redraw(); } private areaClick(sx: number, sy: number): void { if (this.areaMode === 'pick') { const [x, y] = this.toWorld(sx, sy); this.areaShape = pickClosed(this.sheet!, this.model!.shapes, this.hiddenLayers(), x, y, 8 / this.view.scale); } else { this.areaPoints = [...this.areaPoints, this.pickAt(sx, sy)]; } this.refreshPicks(); this.redraw(); } undoAreaPoint(): void { this.areaPoints = this.areaPoints.slice(0, -1); this.refreshPicks(); this.redraw(); } clearArea(): void { this.areaPoints = []; this.areaShape = null; this.refreshPicks(); this.redraw(); } /** The units a picked shape or a set of points is in: the model's, or the sheet's paper units. */ private unitText(inModel: boolean): number { if (inModel) return this.units; return this.sheet?.paper?.mmPerUnit === 25.4 ? 1 : 4; } private lengthText(l: number, inModel: boolean): string { const u = UNIT_SHORT[this.unitText(inModel)]; return `${(+l.toPrecision(7)).toLocaleString('en', { maximumFractionDigits: 6 })}${u ? ' ' + u : ' units'}`; } /** Area and perimeter of the points clicked or the shape picked. */ /** Area and perimeter of what is picked, worked out once when it changes (a big hatch's area is not cheap). */ areaResult: { area: string; perimeter: string; what: string } | null = null; /** What Info shows, likewise worked out once per click. */ infoRows: { k: string; v: string }[] = []; private refreshPicks(): void { this.areaResult = this.tool === 'area' ? this.computeArea() : null; this.infoRows = this.tool === 'info' ? this.computeInfo() : []; this.highlight = this.tool === 'info' ? this.highlightOf(this.infoPick) : this.tool === 'area' ? this.highlightOf(this.areaShape) : null; } /** What outlines the picked shape, worked out once per pick. */ private highlight: { p: Picked; rings: number[][]; segs: boolean; closed: boolean; fill: boolean } | null = null; /** * The picked shape's highlight. Up to 20,000 points it is the shape * itself; past that, stroking and filling all of it every frame would make * panning crawl, so a closed shape is outlined by its largest loop, * unfilled, and a dense hatch pattern by its hatch's boundary instead. */ private highlightOf(p: Picked | null): { p: Picked; rings: number[][]; segs: boolean; closed: boolean; fill: boolean } | null { if (!p) return null; const s = p.shape; const rings = s.rings ?? []; const closed = isClosed(s); if (rings.reduce((n, r) => n + r.length / 2, 0) <= 20000) return { p, rings, segs: !!s.segs, closed, fill: true }; const largest = (rs: number[][]) => { let best = rs[0], bestA = -1; for (const r of rs) { const a = outlineArea([r]); if (a > bestA) { best = r; bestA = a; } } return best ? [best] : []; }; if (closed) return { p, rings: largest(rings), segs: false, closed: true, fill: false }; if (s.segs && s.info) { // The pattern's lines share their info with the hatch's unpainted outline. const space = p.vp >= 0 ? this.model! : this.sheet!.space; const ghost = space.shapes.find((g) => g.ghost && g.info === s.info); if (ghost?.rings) return { p, rings: largest(ghost.rings), segs: false, closed: true, fill: false }; } // A long open line is cheap enough to stroke whole. return { p, rings: s.segs ? [] : rings, segs: false, closed: false, fill: false }; } private computeArea(): { area: string; perimeter: string; what: string } | null { const sheet = this.sheet; if (!sheet) return null; if (this.areaShape) { const s = this.areaShape.shape; const inModel = sheet.kind === 'model' || this.areaShape.vp >= 0; const a = shapeAreaOf(s); return { area: `${a.exact ? '' : 'about '}${areaText(a.area, this.unitText(inModel))}${a.exact ? '' : ` (${ROUGH_AREA})`}`, perimeter: this.lengthText(shapeLength(s), inModel), what: `${this.describe(s)}${sheet.kind === 'layout' ? (inModel ? ', in the model' : ', on the sheet') : ''}` }; } const p = this.areaPoints; if (p.length < 3) return null; const inModel = sheet.kind === 'model' || (p[0].vp >= 0 && p.every((q) => q.vp === p[0].vp)); const ring = p.flatMap((q) => (inModel ? [q.mx, q.my] : [q.x, q.y])); return { area: areaText(evenOddArea([ring]), this.unitText(inModel)), perimeter: this.lengthText(ringLength(ring, true), inModel), what: `${p.length} points${sheet.kind === 'layout' ? (inModel ? ', in the model' : ', on the sheet') : ''}` }; } private infoClick(sx: number, sy: number): void { const [x, y] = this.toWorld(sx, sy); this.infoPick = pickNearest(this.sheet!, this.model!.shapes, this.hiddenLayers(), x, y, 8 / this.view.scale); this.refreshPicks(); this.redraw(); } private describe(s: Shape): string { const t = s.info?.type ?? (s.kind === 'text' ? 'TEXT' : 'shape'); return t === 'LWPOLYLINE' || t === 'POLYLINE' ? (isClosed(s) ? 'closed polyline' : 'polyline') : t.toLowerCase(); } /** What the Info tool shows about the shape clicked. */ private computeInfo(): { k: string; v: string }[] { const p = this.infoPick; const sheet = this.sheet; if (!p || !sheet) return []; const s = p.shape; const inModel = sheet.kind === 'model' || p.vp >= 0; const rows: { k: string; v: string }[] = [{ k: 'Type', v: s.info?.type ?? s.kind }]; rows.push({ k: 'Layer', v: s.layer }); rows.push({ k: 'Colour', v: s.color === FOREGROUND ? 'white or black (ACI 7, follows the background)' : s.color === BACKGROUND ? 'the background' : `#${s.color.toString(16).padStart(6, '0')}` }); if (s.info?.owner) rows.push({ k: 'Block', v: `${s.info.owner.block} (${s.info.owner.type === 'INSERT' ? 'block reference' : s.info.owner.type === 'ACAD_TABLE' ? 'table' : s.info.owner.type.toLowerCase()})` }); if (s.kind === 'text' && s.text) rows.push({ k: 'Text', v: s.text.lines.join(' ') }); if (s.info?.radius) rows.push({ k: 'Radius', v: this.lengthText(s.info.radius, inModel) }); if (s.info?.axes) rows.push({ k: 'Semi-axes', v: `${this.lengthText(s.info.axes[0], inModel)} and ${this.lengthText(s.info.axes[1], inModel)} (a circle in a block stretched unevenly, so an ellipse)` }); if (s.kind !== 'text' && s.kind !== 'point') { rows.push({ k: isClosed(s) ? 'Perimeter' : 'Length', v: this.lengthText(shapeLength(s), inModel) }); if (isClosed(s)) { const a = shapeAreaOf(s); rows.push({ k: 'Area', v: `${a.exact ? '' : 'about '}${areaText(a.area, this.unitText(inModel))}${a.exact ? '' : ` (${ROUGH_AREA})`}` }); } } if (s.kind === 'line') rows.push({ k: 'Lineweight', v: `${(s.lw ?? 0).toFixed(2)} mm` }); if (s.info?.handle) rows.push({ k: 'Handle', v: s.info.handle }); if (sheet.kind === 'layout') { let where = 'on the sheet itself'; if (p.vp >= 0) { const v = sheet.viewports[p.vp]; const n = unitMm(this.units) / (v.scale * (sheet.paper?.mmPerUnit ?? 1)); where = `through viewport ${p.vp + 1}${n > 0 ? `, at 1:${+n.toPrecision(4)}` : ''}`; } rows.push({ k: 'Seen', v: where }); } return rows; } /** Outlines the picked shape, or the area being clicked out. */ private paintPicks(ctx: CanvasRenderingContext2D, dpr: number): void { ctx.setTransform(dpr, 0, 0, dpr, 0, 0); ctx.lineWidth = 2; ctx.lineJoin = 'round'; const outline = (pick: Picked | null, color: string, fill: boolean) => { const hl = this.highlight; if (!pick || !hl || hl.p !== pick) return; const p = pick; ctx.beginPath(); // One matrix from the shape's units to the screen, worked out once: a // picked hatch can have a million vertices, painted every frame. const canvas = this.canvasRef!.nativeElement; const sc = this.view.scale; const m = mul([sc, 0, 0, -sc, canvas.clientWidth / 2 - this.view.cx * sc, canvas.clientHeight / 2 + this.view.cy * sc], p.m); const closed = hl.closed; if (!hl.fill) fill = false; for (const r of hl.rings) { if (hl.segs) { for (let i = 0; i + 3 < r.length; i += 4) { ctx.moveTo(m[0] * r[i] + m[2] * r[i + 1] + m[4], m[1] * r[i] + m[3] * r[i + 1] + m[5]); ctx.lineTo(m[0] * r[i + 2] + m[2] * r[i + 3] + m[4], m[1] * r[i + 2] + m[3] * r[i + 3] + m[5]); } continue; } for (let i = 0; i < r.length; i += 2) { const x = m[0] * r[i] + m[2] * r[i + 1] + m[4], y = m[1] * r[i] + m[3] * r[i + 1] + m[5]; if (i === 0) ctx.moveTo(x, y); else ctx.lineTo(x, y); } if (closed) ctx.closePath(); } if (p.shape.kind === 'text' && p.shape.text) { const [x, y] = this.toScreen(...(transform(p.m, [p.shape.text.x, p.shape.text.y]) as [number, number])); ctx.moveTo(x + 6, y); ctx.arc(x, y, 6, 0, Math.PI * 2); } if (fill) { ctx.fillStyle = 'rgba(255, 152, 0, 0.25)'; ctx.fill('evenodd'); } ctx.strokeStyle = color; ctx.stroke(); }; if (this.tool === 'info') outline(this.infoPick, '#ff9800', false); if (this.tool === 'area') { outline(this.areaShape, '#ff9800', true); const p = this.areaPoints; if (p.length) { ctx.beginPath(); p.forEach((q, i) => { const [x, y] = this.toScreen(q.x, q.y); if (i) ctx.lineTo(x, y); else ctx.moveTo(x, y); }); if (p.length >= 3) { ctx.closePath(); ctx.fillStyle = 'rgba(255, 92, 168, 0.2)'; ctx.fill(); } ctx.strokeStyle = '#ff5ca8'; ctx.stroke(); ctx.fillStyle = '#ff5ca8'; for (const q of p) { const [x, y] = this.toScreen(q.x, q.y); ctx.beginPath(); ctx.arc(x, y, 3.5, 0, Math.PI * 2); ctx.fill(); } } } } /** * The distance between the two points: in drawing units when both are in * the model (on the Model tab, or inside the same viewport of a layout), * otherwise in the layout's paper units. */ get measurement(): { d: string; dx: string; dy: string; angle: string; where: string } | null { const m = this.measure; if (!m || !m.b) return null; const sheet = this.sheet!; const inModel = sheet.kind === 'model' || (m.a.vp >= 0 && m.a.vp === m.b.vp); const dx = inModel ? m.b.mx - m.a.mx : m.b.x - m.a.x; const dy = inModel ? m.b.my - m.a.my : m.b.y - m.a.y; const unit = inModel ? UNIT_SHORT[this.units] : sheet.paper?.mmPerUnit === 25.4 ? 'in' : 'mm'; const u = unit ? ` ${unit}` : ''; const f = (v: number) => `${+v.toPrecision(7)}${u}`; const where = sheet.kind === 'model' ? '' : inModel ? ' (in the model, through the viewport)' : ' (on the sheet)'; return { d: f(Math.hypot(dx, dy)), dx: f(Math.abs(dx)), dy: f(Math.abs(dy)), angle: `${+((Math.atan2(dy, dx) * 180) / Math.PI).toFixed(2)}°`, where }; } /* ── Output ────────────────────────────────────────────────────────────── */ swatch(l: LayerRow): string { return cssColor(l.rgb, this.dark); } get unitsLabel(): string { return UNITS[this.units] ?? ''; } get itemCount(): number { const n = (b: Built) => b.shapes.length - b.shapes.filter((s) => s.ghost).length; return this.sheet ? n(this.sheet.space) + (this.sheet.viewports.length ? n(this.model!) : 0) : 0; } get skippedLabel(): string { const s = this.model?.skipped; if (!s?.size) return ''; return [...s.entries()].map(([t, n]) => `${n} ${t}`).join(', '); } /** Hatches whose patterns were too dense to draw line by line, shown as a tint instead. */ get hatchesAsTint(): number { return this.sheets.reduce((n, s) => n + s.space.hatchesAsTint, 0); } get truncated(): boolean { return !!this.opened?.scene.truncated; } get tooDeep(): boolean { return !!this.opened?.scene.tooDeep; } get baseName(): string { return this.fileName.replace(/\.(dxf|dwg)$/i, '') || 'drawing'; } /** The name a saved file of the tab takes: the file's, and the layout's when it is not the model. */ private get outName(): string { const s = this.sheet; return s && s.kind === 'layout' ? `${this.baseName} - ${s.name.replace(/[\\/:*?"<>|]/g, '_')}` : this.baseName; } /** The Save as DXF panel, open first on /dwg-to-dxf. */ dxfOpen = false; /** "AutoCAD 2018": the version a converted DXF is written as, the DWG's own. */ get dxfVersion(): string { return this.version.replace(/ DXF$/, ''); } saveDxf(): void { if (this.dxfBytes) save(new Blob([this.dxfBytes as BlobPart], { type: 'application/dxf' }), `${this.baseName}.dxf`); } /** Said after the R12 copy is saved: what it left out or assumed. */ r12Note = ''; /** * The model's lines as an AutoCAD R12 DXF in millimetres (r12.ts), for * older laser, vinyl and CNC software: LibreDWG writes only the DWG's own * version, so this copy is made from the drawing as shown: outlines, and text as R12 TEXT. */ saveR12(): void { const model = this.opened?.scene.sheets[0]?.space; // As shown: without the layers switched off or frozen in the drawing, or hidden in the list here. const r = model ? r12Dxf(model, this.opened!.units, this.hiddenLayers()) : null; if (!r) { this.r12Note = 'The model has no lines or text to put in an R12 DXF.'; return; } save(new Blob([r.text], { type: 'application/dxf' }), `${this.baseName} (R12).dxf`); const notes: string[] = []; if (r.unitless) notes.push('The drawing does not say its units, so they were taken as millimetres.'); if (r.textCount) notes.push(`${r.textCount === 1 ? 'Its text is' : `Its ${r.textCount.toLocaleString()} text items are`} in it as R12 text, a line at a time, shown in the font of the program that opens it; bold, italic and colours inside multi-line text are not kept.`); if (r.textCut) notes.push(`${r.textCut === 1 ? 'One line of text is' : `${r.textCut.toLocaleString()} lines of text are`} longer than an R12 text holds (about 250 letters), so ${r.textCut === 1 ? 'it is' : 'they are'} cut short there.`); if (this.hiddenLayers().size) notes.push('Layers that are off, frozen or hidden in the list were left out.'); if (this.truncated) notes.push('The drawing is very large and only part of it was read, so only that part is in the file.'); this.r12Note = notes.join(' '); } /** The view as it is on screen, at the screen's resolution. */ savePng(): void { this.canvasRef?.nativeElement.toBlob((blob) => blob && save(blob, `${this.outName} (view).png`), 'image/png'); } /* ── Picture of the whole tab ─────────────────────────────────────────── */ readonly maxSide = MAX_SIDE; readonly maxMp = MAX_PIXELS / 1e6; picOpen = false; picBusy = false; picFormat: 'png' | 'jpg' = 'png'; /** "px:4000" for a long side in pixels, "dpi:300" for dots per inch on the PDF options' page. */ picSize = 'px:4000'; picColor: PaintOptions['mode'] = 'color'; picError = ''; togglePic(): void { this.picOpen = !this.picOpen; } private pictureSize(sheet: Sheet): PictureSize | { error: string } { const [mode, n] = this.picSize.split(':'); if (mode === 'px') return { mode: 'px', long: Number(n) }; const page = planPage(sheet, this.pdfOptions()); if ('error' in page) return { error: `The page set in the PDF options cannot be used: ${page.error}` }; return { mode: 'dpi', dpi: Number(n), page }; } /** The picture as it will come out, or why it cannot. */ get picPlan(): string { const sheet = this.sheet; if (!sheet) return ''; const size = this.pictureSize(sheet); if ('error' in size) return size.error; const p = planPicture(sheet, size); if ('error' in p) return p.error; return `${p.w.toLocaleString('en')} × ${p.h.toLocaleString('en')} pixels${size.mode === 'dpi' ? ` (${size.page.label}, ${size.dpi} dpi)` : ''}`; } get picBlocked(): boolean { const sheet = this.sheet; if (!sheet) return true; const size = this.pictureSize(sheet); return 'error' in size || 'error' in planPicture(sheet, size); } /** * The whole tab, not just the view, drawn afresh on a canvas of its own on * white paper: the layers that are on, lineweights as on screen. */ async savePicture(): Promise { const sheet = this.sheet; if (!sheet || this.picBusy) return; const size = this.pictureSize(sheet); const plan = 'error' in size ? size : planPicture(sheet, size); if ('error' in plan) return; this.picBusy = true; this.picError = ''; this.cdr.detectChanges(); const c = document.createElement('canvas'); try { await new Promise((r) => setTimeout(r, 20)); c.width = plan.w; c.height = plan.h; const ctx = c.getContext('2d'); if (!ctx) throw new Error('no canvas'); ctx.fillStyle = '#ffffff'; ctx.fillRect(0, 0, plan.w, plan.h); const lw = this.showLw; this.paintSheet(ctx, sheet, { m: plan.m, dpr: 1, dark: false, mode: this.picColor, w: plan.w, h: plan.h, lwPx: (mm) => Math.max(1, (lw ? Math.max(mm, 0.05) : 0.25) * plan.pxPerMm), }); const type = this.picFormat === 'jpg' ? 'image/jpeg' : 'image/png'; const blob = await new Promise((r) => c.toBlob(r, type, 0.92)); if (!blob) throw new Error('no picture'); save(blob, `${this.outName}.${this.picFormat}`); } catch { this.picError = 'Your browser could not make a picture this large. Choose a smaller size and try again.'; } finally { c.width = c.height = 0; this.picBusy = false; this.cdr.detectChanges(); } } /** The tab as SVG, dark-on-light, whatever the screen is showing. */ saveSvg(): void { const sheet = this.sheet; if (!sheet) return; const box = exportBox(sheet); // Lineweights are millimetres on paper; a layout's SVG is its sheet, the model's is sized as if its long side were printed 420 mm (A3). const mmPerUnit = sheet.paper ? sheet.paper.mmPerUnit : 420 / Math.max(box.maxX - box.minX, box.maxY - box.minY); const svg = sheetSvg(sheet, this.model!, { mmPerUnit, lineweights: this.showLw, mode: 'color', hidden: this.hiddenLayers(), box }); save(new Blob([svg], { type: 'image/svg+xml' }), `${this.outName}.svg`); } /* ── PDF ───────────────────────────────────────────────────────────────── */ readonly papers = PAPER_SIZES; readonly scaleGroups = ['Metric', 'Architectural (inches to feet)', 'Engineering (inches to feet)'].map((g) => ({ g, scales: PLOT_SCALES.filter((s) => s.group === g) })); /** Units a drawing can be said to be in, for a plot scale when the file does not say. */ readonly unitChoices: { u: number; label: string }[] = [ { u: 4, label: 'millimetre' }, { u: 5, label: 'centimetre' }, { u: 6, label: 'metre' }, { u: 7, label: 'kilometre' }, { u: 1, label: 'inch' }, { u: 2, label: 'foot' }, { u: 10, label: 'yard' }, { u: 3, label: 'mile' }, ]; /** The choices, with the file's own units added when they are an unusual one. */ get unitOptions(): { u: number; label: string }[] { const known = this.unitChoices.some((c) => c.u === this.units); return known || !UNITS[this.units] ? this.unitChoices : [...this.unitChoices, { u: this.units, label: UNITS[this.units] }]; } pdfOpen = false; pdfBusy = false; pdfPaper = 'a4'; pdfOrient: PdfOptions['orientation'] = 'auto'; pdfMargin = 10; /** 'fit', or N of 1:N as text (a select's value). */ pdfScale = 'fit'; /** $INSUNITS the scale is worked from: the file's, or the reader's choice. */ pdfUnits = 0; pdfColor: PdfOptions['color'] = 'color'; pdfLw = true; pdfContent: 'tab' | 'all' = 'tab'; togglePdf(): void { this.pdfOpen = !this.pdfOpen; } private pdfOptions(): PdfOptions { return { paper: this.pdfPaper, orientation: this.pdfOrient, marginMm: Number(this.pdfMargin) || 0, scale: this.pdfScale === 'fit' ? 'fit' : Number(this.pdfScale), unitMm: unitMm(Number(this.pdfUnits)), color: this.pdfColor, lineweights: this.pdfLw, }; } /** The tabs the PDF will hold. */ private get pdfSheets(): Sheet[] { return this.pdfContent === 'all' ? this.sheets : this.sheet ? [this.sheet] : []; } /** Each page as it will come out, or why it cannot: shown under the options as they change. */ get pdfPlans(): { name: string; label: string; error: string }[] { const o = this.pdfOptions(); return this.pdfSheets.map((sh) => { const p = planPage(sh, o); return { name: sh.name, label: 'error' in p ? '' : p.label, error: 'error' in p ? p.error : '' }; }); } get pdfBlocked(): boolean { return this.pdfPlans.some((p) => p.error); } /** Whether a tab being printed has its own page setup, which the paper and scale here do not change. */ get pdfHasOwnPaper(): boolean { return this.pdfSheets.some((s) => !!s.paper); } /** * The tab, or every tab, as a PDF: the layers that are on, as vectors, so * lines stay sharp at any zoom or print size. */ async savePdf(): Promise { if (!this.sheet || this.pdfBusy || this.pdfBlocked) return; this.pdfBusy = true; this.loadError = ''; this.cdr.detectChanges(); try { const o = this.pdfOptions(); const pages: PdfPage[] = this.pdfSheets.map((sheet) => ({ sheet, plan: planPage(sheet, o) as PdfPage['plan'] })); const name = this.pdfContent === 'all' ? this.baseName : this.outName; save(await makePdf(pages, this.model!, o, this.hiddenLayers(), name), `${name}.pdf`); } catch { this.loadError = 'The PDF could not be made from this drawing. The SVG and PNG downloads still work.'; } finally { this.pdfBusy = false; this.cdr.detectChanges(); } } reset(): void { this.r12Note = ''; this.opened = null; this.layers = []; this.fileName = ''; this.measure = null; this.tool = 'pan'; this.prepared = new Map(); this.resizeObserver?.disconnect(); this.resizeObserver = null; this.observed = null; this.loadError = ''; } } /* ── Helpers ───────────────────────────────────────────────────────────── */ function save(blob: Blob, name: string): void { const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = name; a.click(); setTimeout(() => URL.revokeObjectURL(url), 1000); }