Files
likang 7e01147566
CI / typecheck + test + build (push) Has been cancelled
Initial commit: import VibeMake PCB Studio
2026-11-03 11:20:08 +08:00

1012 lines
33 KiB
TypeScript

// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (C) 2026 ZiroEDA and contributors.
// Portions derived from KiCad, copyright The KiCad Developers. See NOTICE.md.
/**
* `pcbnew/pcb_textbox.h` / `pcb_textbox.cpp`: `PCB_TEXTBOX`, a `PCB_SHAPE`
* rectangle (or, once rotated off a cardinal angle, a polygon) that carries an
* `EDA_TEXT` wrapped inside it.
*
* `EDA_TEXT` is the second base, mixed in with `applyMixins`.
*
* Not here: `Serialize`/`Deserialize` (the kiapi protobuf surface) and
* `PCB_TEXTBOX_DESC`, the `PROPERTY_MANAGER` registration.
*/
import { CALLBACK_GAL } from '@ziroeda/common/callback_gal.js';
import { ResolveTextVars, type TextVarResolverFn } from '@ziroeda/common/common.js';
import { PCB_EDIT_FRAME_NAME } from '@ziroeda/common/eda_draw_frame.js';
import type { EDA_DRAW_FRAME_LIKE } from '@ziroeda/common/eda_item.js';
import type { EDA_SEARCH_DATA } from '@ziroeda/common/eda_search_data.js';
import { EDA_SHAPE, SHAPE_T } from '@ziroeda/common/eda_shape.js';
import { EDA_TEXT } from '@ziroeda/common/eda_text.js';
import { LINE_STYLE } from '@ziroeda/common/stroke_params.js';
import {
ENUM_MAP,
type INSPECTABLE_ITEM,
NO_SETTER,
PG_CHOICES,
PROPERTY,
PROPERTY_DISPLAY,
PROPERTY_ENUM,
TYPE_BOOL,
TYPE_CAST,
TYPE_COLOR4D,
TYPE_DOUBLE,
TYPE_INT,
TYPE_OPT_INT,
TYPE_STRING,
} from '@ziroeda/common/properties/property.js';
import { PROPERTY_MANAGER, REGISTER_TYPE } from '@ziroeda/common/properties/property_mgr.js';
import { COORD_TYPES_T } from '@ziroeda/common/origin_transforms.js';
import { pcbIUScale } from '@ziroeda/common/eda_units.js';
import type { OutStr } from '@ziroeda/common/font/font.js';
import type { METRICS } from '@ziroeda/common/font/font_metrics.js';
import { GR_TEXT_H_ALIGN_T, GR_TEXT_V_ALIGN_T } from '@ziroeda/common/font/text_attributes.js';
import { FLASHING, GAL_LAYER_ID, IsBackLayer, PCB_LAYER_ID } from '@ziroeda/common/layer_id.js';
import { unescapeString } from '@ziroeda/common/string_utils.js';
import type { UNITS_PROVIDER } from '@ziroeda/common/units_provider.js';
import { MSG_PANEL_ITEM } from '@ziroeda/common/widgets/msgpanel.js';
import {
KIUI_EllipsizeMenuText,
KIUI_EllipsizeStatusText,
} from '@ziroeda/common/widgets/ui_common.js';
import { applyMixins } from '@ziroeda/core/mixins.js';
import { FLIP_DIRECTION } from '@ziroeda/core/mirror.js';
import { KICAD_T } from '@ziroeda/core/typeinfo.js';
import { ERROR_LOC } from '@ziroeda/kimath/src/convert_basic_shapes_to_polygon.js';
import {
ANGLE_90,
ANGLE_180,
ANGLE_270,
type EDA_ANGLE,
} from '@ziroeda/kimath/src/geometry/eda_angle.js';
import type { SHAPE } from '@ziroeda/kimath/src/geometry/shape.js';
import type { SHAPE_LINE_CHAIN } from '@ziroeda/kimath/src/geometry/shape_line_chain.js';
import {
CornerStrategy,
SHAPE_POLY_SET,
TransformOvalToPolygon,
} from '@ziroeda/kimath/src/geometry/shape_poly_set.js';
import type { BOX2I } from '@ziroeda/kimath/src/math/box2.js';
import { KiROUND } from '@ziroeda/kimath/src/math/util.js';
import {
EuclideanNormI,
type VECTOR2I,
add,
divideI,
sub,
} from '@ziroeda/kimath/src/math/vector2.js';
import { RotatePoint } from '@ziroeda/kimath/src/trigo.js';
import type { BOARD_DESIGN_SETTINGS } from './board_design_settings.js';
import { BOARD_ITEM } from './board_item.js';
import { PCB_SHAPE, type PCB_VIEW_FOR_LOD } from './pcb_shape.js';
import { PCB_TEXT } from './pcb_text.js';
// `Replace`, `Similarity` and `Compare` are overloaded across the bases in C++; the class
// carries its own forms, so the merged interface leaves the EDA_TEXT ones out.
// biome-ignore lint/suspicious/noEmptyInterface: declaration merging carries the EDA_TEXT mixin's members
export interface PCB_TEXTBOX extends Omit<EDA_TEXT, 'Replace' | 'Similarity' | 'Compare'> {}
// biome-ignore lint/suspicious/noUnsafeDeclarationMerging: KiCad's multiple inheritance, see libs/core/mixins.ts
export class PCB_TEXTBOX extends PCB_SHAPE {
protected m_borderEnabled: boolean; ///< Controls drawing the border (as defined by the stroke members)
private m_marginLeft: number;
private m_marginTop: number;
private m_marginRight: number;
private m_marginBottom: number;
constructor(aParent: BOARD_ITEM | null, aType: KICAD_T = KICAD_T.PCB_TEXTBOX_T) {
super(aParent, aType, SHAPE_T.RECTANGLE);
this.initEdaText(pcbIUScale);
this.m_borderEnabled = true;
this.SetHorizJustify(GR_TEXT_H_ALIGN_T.GR_TEXT_H_ALIGN_LEFT);
this.SetVertJustify(GR_TEXT_V_ALIGN_T.GR_TEXT_V_ALIGN_CENTER);
this.SetMultilineAllowed(true);
const defaultMargin = this.GetLegacyTextMargin();
this.m_marginLeft = defaultMargin;
this.m_marginTop = defaultMargin;
this.m_marginRight = defaultMargin;
this.m_marginBottom = defaultMargin;
}
// Do not create a copy constructor & operator=.
// The ones generated by the compiler are adequate.
/** `PCB_TEXTBOX( const PCB_TEXTBOX& )`: the compiler-generated copy, as a static. */
static override copyOf(aOther: PCB_TEXTBOX): PCB_TEXTBOX {
const copy = new PCB_TEXTBOX(null, aOther.Type());
copy.assignPcbTextbox(aOther);
(copy as { m_Uuid: string }).m_Uuid = aOther.m_Uuid;
return copy;
}
/** `operator=`: the compiler-generated one over every base and member. */
assignPcbTextbox(aOther: PCB_TEXTBOX): this {
this.assignPcbShape(aOther);
this.assignEdaText(aOther as unknown as EDA_TEXT);
this.m_borderEnabled = aOther.m_borderEnabled;
this.m_marginLeft = aOther.m_marginLeft;
this.m_marginTop = aOther.m_marginTop;
this.m_marginRight = aOther.m_marginRight;
this.m_marginBottom = aOther.m_marginBottom;
return this;
}
override CopyFrom(aOther: BOARD_ITEM | null): void {
if (!(aOther && aOther.Type() === KICAD_T.PCB_TEXTBOX_T)) return; // wxCHECK
this.assignPcbTextbox(aOther as PCB_TEXTBOX);
}
static override ClassOf(aItem: { Type(): KICAD_T } | null): boolean {
return aItem !== null && KICAD_T.PCB_TEXTBOX_T === aItem.Type();
}
override IsType(aScanTypes: readonly KICAD_T[]): boolean {
if (BOARD_ITEM.prototype.IsType.call(this, aScanTypes)) return true;
for (const scanType of aScanTypes) {
if (scanType === KICAD_T.PCB_LOCATE_TEXT_T) return true;
}
return false;
}
override GetFriendlyName(): string {
return 'Text Box';
}
override StyleFromSettings(settings: BOARD_DESIGN_SETTINGS, aCheckSide: boolean): void {
PCB_SHAPE.prototype.StyleFromSettings.call(this, settings, aCheckSide);
this.SetTextSize(settings.GetTextSize(this.GetLayer()));
this.SetTextThickness(settings.GetTextThickness(this.GetLayer()));
this.SetItalic(settings.GetTextItalic(this.GetLayer()));
if (this.GetParentFootprint()) this.SetKeepUpright(settings.GetTextUpright(this.GetLayer()));
if (aCheckSide) {
const board = this.GetBoard();
if (board) this.SetMirrored(board.IsBackLayer(this.GetLayer()));
else this.SetMirrored(IsBackLayer(this.GetLayer()));
}
}
GetLegacyTextMargin(): number {
return KiROUND(this.GetStroke().GetWidth() / 2.0) + KiROUND(this.GetTextSize().y * 0.75);
}
/**
* Return the minimum height needed to contain the textbox's wrapped text content
* plus margins. Width is unconstrained (returns 0) so text freely rewraps.
* The constrained axis depends on rotation: y-axis for 0/180, x-axis for 90/270.
*/
GetMinSize(): VECTOR2I {
if (this.GetText().length === 0) return { x: 0, y: 0 };
const textBox = this.GetTextBox(null);
let textHeight = Math.abs(textBox.GetHeight());
if (this.GetTextAngle().IsHorizontal())
textHeight += this.GetMarginTop() + this.GetMarginBottom();
else textHeight += this.GetMarginLeft() + this.GetMarginRight();
// Only enforce minimum height. Width returns 0 so the user can freely shrink width
// (text rewraps) while height is constrained to fit the wrapped text content.
// GetTextBox returns dimensions in text-local coordinates. For 90/270 degree rotations,
// the text's natural height maps to screen x-axis.
const rotation = this.GetDrawRotation();
if (rotation.equals(ANGLE_90) || rotation.equals(ANGLE_270)) return { x: textHeight, y: 0 };
return { x: 0, y: textHeight };
}
override GetTopLeft(): VECTOR2I {
const rotation = this.GetDrawRotation();
if (rotation.equals(ANGLE_90)) return { x: this.GetStartX(), y: this.GetEndY() };
else if (rotation.equals(ANGLE_180)) return this.GetEnd();
else if (rotation.equals(ANGLE_270)) return { x: this.GetEndX(), y: this.GetStartY() };
else return this.GetStart();
}
override GetBotRight(): VECTOR2I {
const rotation = this.GetDrawRotation();
if (rotation.equals(ANGLE_90)) return { x: this.GetEndX(), y: this.GetStartY() };
else if (rotation.equals(ANGLE_180)) return this.GetStart();
else if (rotation.equals(ANGLE_270)) return { x: this.GetStartX(), y: this.GetEndY() };
else return this.GetEnd();
}
override SetTop(aVal: number): void {
const rotation = this.GetDrawRotation();
if (rotation.equals(ANGLE_90) || rotation.equals(ANGLE_180)) this.SetEndY(aVal);
else this.SetStartY(aVal);
}
override SetBottom(aVal: number): void {
const rotation = this.GetDrawRotation();
if (rotation.equals(ANGLE_90) || rotation.equals(ANGLE_180)) this.SetStartY(aVal);
else this.SetEndY(aVal);
}
override SetLeft(aVal: number): void {
const rotation = this.GetDrawRotation();
if (rotation.equals(ANGLE_180) || rotation.equals(ANGLE_270)) this.SetEndX(aVal);
else this.SetStartX(aVal);
}
override SetRight(aVal: number): void {
const rotation = this.GetDrawRotation();
if (rotation.equals(ANGLE_180) || rotation.equals(ANGLE_270)) this.SetStartX(aVal);
else this.SetEndX(aVal);
}
SetMarginLeft(aLeft: number): void {
this.m_marginLeft = aLeft;
}
SetMarginTop(aTop: number): void {
this.m_marginTop = aTop;
}
SetMarginRight(aRight: number): void {
this.m_marginRight = aRight;
}
SetMarginBottom(aBottom: number): void {
this.m_marginBottom = aBottom;
}
GetMarginLeft(): number {
return this.m_marginLeft;
}
GetMarginTop(): number {
return this.m_marginTop;
}
GetMarginRight(): number {
return this.m_marginRight;
}
GetMarginBottom(): number {
return this.m_marginBottom;
}
SetTextAngle(aAngle: EDA_ANGLE): void {
const delta = aAngle.Normalized().sub(this.GetTextAngle());
this.Rotate(this.GetPosition(), delta);
}
GetDrawPos(aIsFlipped = false): VECTOR2I {
const drawAngle = this.GetDrawRotation();
const corners = this.GetCornersInSequence(drawAngle);
let horizontalAlignment = this.GetHorizJustify();
const verticalAlignment = this.GetVertJustify();
let textAnchor: VECTOR2I = { x: 0, y: 0 };
const offset: VECTOR2I = { x: 0, y: 0 };
// Calculate midpoints
const midTop = divideI(add(corners[0]!, corners[1]!), 2);
const midBottom = divideI(add(corners[3]!, corners[2]!), 2);
const midLeft = divideI(add(corners[0]!, corners[3]!), 2);
const midRight = divideI(add(corners[1]!, corners[2]!), 2);
const center = divideI(add(add(add(corners[0]!, corners[1]!), corners[2]!), corners[3]!), 4);
if (this.IsMirrored() !== aIsFlipped) {
switch (this.GetHorizJustify()) {
case GR_TEXT_H_ALIGN_T.GR_TEXT_H_ALIGN_LEFT:
horizontalAlignment = GR_TEXT_H_ALIGN_T.GR_TEXT_H_ALIGN_RIGHT;
break;
case GR_TEXT_H_ALIGN_T.GR_TEXT_H_ALIGN_CENTER:
horizontalAlignment = GR_TEXT_H_ALIGN_T.GR_TEXT_H_ALIGN_CENTER;
break;
case GR_TEXT_H_ALIGN_T.GR_TEXT_H_ALIGN_RIGHT:
horizontalAlignment = GR_TEXT_H_ALIGN_T.GR_TEXT_H_ALIGN_LEFT;
break;
case GR_TEXT_H_ALIGN_T.GR_TEXT_H_ALIGN_INDETERMINATE:
horizontalAlignment = GR_TEXT_H_ALIGN_T.GR_TEXT_H_ALIGN_INDETERMINATE;
break;
}
}
console.assert(
horizontalAlignment !== GR_TEXT_H_ALIGN_T.GR_TEXT_H_ALIGN_INDETERMINATE &&
verticalAlignment !== GR_TEXT_V_ALIGN_T.GR_TEXT_V_ALIGN_INDETERMINATE,
'Indeterminate state legal only in dialogs. Horizontal and vertical alignment ' +
'must be set before calling PCB_TEXTBOX::GetDrawPos.',
);
if (
horizontalAlignment === GR_TEXT_H_ALIGN_T.GR_TEXT_H_ALIGN_INDETERMINATE ||
verticalAlignment === GR_TEXT_V_ALIGN_T.GR_TEXT_V_ALIGN_INDETERMINATE
) {
return center;
}
const H = GR_TEXT_H_ALIGN_T;
const V = GR_TEXT_V_ALIGN_T;
if (
horizontalAlignment === H.GR_TEXT_H_ALIGN_LEFT &&
verticalAlignment === V.GR_TEXT_V_ALIGN_TOP
) {
textAnchor = corners[0]!;
} else if (
horizontalAlignment === H.GR_TEXT_H_ALIGN_CENTER &&
verticalAlignment === V.GR_TEXT_V_ALIGN_TOP
) {
textAnchor = midTop;
} else if (
horizontalAlignment === H.GR_TEXT_H_ALIGN_RIGHT &&
verticalAlignment === V.GR_TEXT_V_ALIGN_TOP
) {
textAnchor = corners[1]!;
} else if (
horizontalAlignment === H.GR_TEXT_H_ALIGN_LEFT &&
verticalAlignment === V.GR_TEXT_V_ALIGN_CENTER
) {
textAnchor = midLeft;
} else if (
horizontalAlignment === H.GR_TEXT_H_ALIGN_CENTER &&
verticalAlignment === V.GR_TEXT_V_ALIGN_CENTER
) {
textAnchor = center;
} else if (
horizontalAlignment === H.GR_TEXT_H_ALIGN_RIGHT &&
verticalAlignment === V.GR_TEXT_V_ALIGN_CENTER
) {
textAnchor = midRight;
} else if (
horizontalAlignment === H.GR_TEXT_H_ALIGN_LEFT &&
verticalAlignment === V.GR_TEXT_V_ALIGN_BOTTOM
) {
textAnchor = corners[3]!;
} else if (
horizontalAlignment === H.GR_TEXT_H_ALIGN_CENTER &&
verticalAlignment === V.GR_TEXT_V_ALIGN_BOTTOM
) {
textAnchor = midBottom;
} else if (
horizontalAlignment === H.GR_TEXT_H_ALIGN_RIGHT &&
verticalAlignment === V.GR_TEXT_V_ALIGN_BOTTOM
) {
textAnchor = corners[2]!;
}
const marginLeft = this.GetMarginLeft();
const marginRight = this.GetMarginRight();
const marginTop = this.GetMarginTop();
const marginBottom = this.GetMarginBottom();
if (horizontalAlignment === H.GR_TEXT_H_ALIGN_LEFT) offset.x = marginLeft;
else if (horizontalAlignment === H.GR_TEXT_H_ALIGN_RIGHT) offset.x = -marginRight;
if (verticalAlignment === V.GR_TEXT_V_ALIGN_TOP) offset.y = marginTop;
else if (verticalAlignment === V.GR_TEXT_V_ALIGN_BOTTOM) offset.y = -marginBottom;
const rotated = RotatePoint(offset, this.GetDrawRotation());
return add(textAnchor, rotated);
}
override ViewGetLOD(aLayer: number, aView: PCB_VIEW_FOR_LOD | null): number {
const renderSettings = aView!.GetPainter().GetSettings();
if (aLayer === GAL_LAYER_ID.LAYER_LOCKED_ITEM_SHADOW) {
// Hide shadow if the main layer is not shown
if (!aView!.IsLayerVisible(this.m_layer)) return PCB_TEXTBOX.LOD_HIDE;
// Hide shadow on dimmed tracks
if (renderSettings.GetHighContrast()) {
if (this.m_layer !== renderSettings.GetPrimaryHighContrastLayer())
return PCB_TEXTBOX.LOD_HIDE;
}
}
return PCB_TEXTBOX.LOD_SHOW;
}
override ViewGetLayers(): number[] {
if (this.IsLocked() || (this.GetParentFootprint() && this.GetParentFootprint()!.IsLocked()))
return [this.GetLayer(), GAL_LAYER_ID.LAYER_LOCKED_ITEM_SHADOW];
return [this.GetLayer()];
}
GetShownText(aAllowExtraText: boolean, aDepth = 0): string {
const parentFootprint = this.GetParentFootprint();
const board = this.GetBoard();
const resolver: TextVarResolverFn = (token) => {
if (token.value === 'LAYER') {
token.value = this.GetLayerName();
return true;
}
if (parentFootprint && parentFootprint.ResolveTextVar(token, aDepth + 1)) return true;
if (board!.ResolveTextVar(token, aDepth + 1)) return true;
return false;
};
let text = EDA_TEXT.prototype.GetShownText.call(this, aAllowExtraText, aDepth);
if (this.HasTextVars()) text = ResolveTextVars(text, resolver, { value: aDepth });
const font = this.GetDrawFont(null);
const drawAngle = this.GetDrawRotation();
const corners = this.GetCornersInSequence(drawAngle);
let colWidth = EuclideanNormI(sub(corners[1]!, corners[0]!));
if (this.GetTextAngle().IsHorizontal())
colWidth -= this.GetMarginLeft() + this.GetMarginRight();
else colWidth -= this.GetMarginTop() + this.GetMarginBottom();
const wrapped: OutStr = { value: text };
font.LinebreakText(
wrapped,
colWidth,
this.GetTextSize(),
this.GetTextThickness(),
this.IsBold(),
this.IsItalic(),
);
text = wrapped.value;
// Convert escape markers back to literal ${} and @{} for final display
text = text.replaceAll('<<<ESC_DOLLAR:', '${');
text = text.replaceAll('<<<ESC_AT:', '@{');
return text;
}
override Matches(aSearchData: EDA_SEARCH_DATA, aAuxData: unknown): boolean {
return this.matchesText(unescapeString(this.GetText()), aSearchData);
}
/** Not overridden in C++: a call through `EDA_ITEM` lands on `EDA_ITEM::Replace`, which is false. */
override Replace(aSearchData: EDA_SEARCH_DATA, aAuxData: unknown = null): boolean {
return false;
}
override GetMsgPanelInfo(aFrame: EDA_DRAW_FRAME_LIKE, aList: MSG_PANEL_ITEM[]): void {
const units = aFrame;
// Don't use GetShownText() here; we want to show the user the variable references
aList.push(new MSG_PANEL_ITEM('Text Box', KIUI_EllipsizeStatusText(aFrame, this.GetText())));
if (aFrame.GetName() === PCB_EDIT_FRAME_NAME && this.IsLocked())
aList.push(new MSG_PANEL_ITEM('Status', 'Locked'));
aList.push(new MSG_PANEL_ITEM('Layer', this.GetLayerName()));
aList.push(new MSG_PANEL_ITEM('Mirror', this.IsMirrored() ? 'Yes' : 'No'));
aList.push(new MSG_PANEL_ITEM('Angle', `${this.GetTextAngle().AsDegrees()}`));
aList.push(new MSG_PANEL_ITEM('Font', this.GetFont() ? this.GetFont()!.GetName() : 'Default'));
if (this.GetTextThickness())
aList.push(
new MSG_PANEL_ITEM(
'Text Thickness',
units.MessageTextFromValue(this.GetEffectiveTextPenWidth()),
),
);
else aList.push(new MSG_PANEL_ITEM('Text Thickness', 'Auto'));
aList.push(new MSG_PANEL_ITEM('Text Width', units.MessageTextFromValue(this.GetTextWidth())));
aList.push(new MSG_PANEL_ITEM('Text Height', units.MessageTextFromValue(this.GetTextHeight())));
aList.push(
new MSG_PANEL_ITEM(
'Box Width',
units.MessageTextFromValue(Math.abs(this.GetEnd().x - this.GetStart().x)),
),
);
aList.push(
new MSG_PANEL_ITEM(
'Box Height',
units.MessageTextFromValue(Math.abs(this.GetEnd().y - this.GetStart().y)),
),
);
this.m_stroke.GetMsgPanelInfo(units, aList);
}
override Move(aMoveVector: VECTOR2I): void {
PCB_SHAPE.prototype.Move.call(this, aMoveVector);
EDA_TEXT.prototype.Offset.call(this, aMoveVector);
}
override Rotate(aRotCentre: VECTOR2I, aAngle: EDA_ANGLE): void {
PCB_SHAPE.prototype.Rotate.call(this, aRotCentre, aAngle);
EDA_TEXT.prototype.SetTextAngle.call(this, this.GetTextAngle().add(aAngle).Normalize());
if (this.GetTextAngle().IsCardinal() && this.GetShape() !== SHAPE_T.RECTANGLE) {
// To convert the polygon to its equivalent rectangle, we use GetCornersInSequence( drawAngle )
// but this method uses the polygon bounding box.
// set the line thickness to 0 to get the actual rectangle corner
const lineWidth = this.GetWidth();
this.SetWidth(0);
const drawAngle = this.GetDrawRotation();
const corners = this.GetCornersInSequence(drawAngle);
this.SetWidth(lineWidth);
const diag = sub(corners[2]!, corners[0]!);
const angle = this.GetTextAngle();
this.SetShape(SHAPE_T.RECTANGLE);
this.SetStart(corners[0]!);
if (angle.equals(ANGLE_90))
this.SetEnd({ x: corners[0]!.x + Math.abs(diag.x), y: corners[0]!.y - Math.abs(diag.y) });
else if (angle.equals(ANGLE_180))
this.SetEnd({ x: corners[0]!.x - Math.abs(diag.x), y: corners[0]!.y - Math.abs(diag.y) });
else if (angle.equals(ANGLE_270))
this.SetEnd({ x: corners[0]!.x - Math.abs(diag.x), y: corners[0]!.y + Math.abs(diag.y) });
else
this.SetEnd({ x: corners[0]!.x + Math.abs(diag.x), y: corners[0]!.y + Math.abs(diag.y) });
}
}
override Mirror(aCentre: VECTOR2I, aFlipDirection: FLIP_DIRECTION): void {
// the position and angle are mirrored, but not the text (or its justification)
PCB_SHAPE.prototype.Mirror.call(this, aCentre, aFlipDirection);
if (aFlipDirection === FLIP_DIRECTION.LEFT_RIGHT)
EDA_TEXT.prototype.SetTextAngle.call(this, ANGLE_180.sub(this.GetTextAngle()));
else EDA_TEXT.prototype.SetTextAngle.call(this, this.GetTextAngle().negate());
}
override Flip(aCentre: VECTOR2I, aFlipDirection: FLIP_DIRECTION): void {
PCB_SHAPE.prototype.Flip.call(this, aCentre, aFlipDirection);
if (aFlipDirection === FLIP_DIRECTION.LEFT_RIGHT)
EDA_TEXT.prototype.SetTextAngle.call(this, this.GetTextAngle().negate());
else EDA_TEXT.prototype.SetTextAngle.call(this, ANGLE_180.sub(this.GetTextAngle()));
if (this.IsSideSpecific()) this.SetMirrored(!this.IsMirrored());
}
override HitTest(aPosition: VECTOR2I, aAccuracy?: number): boolean;
override HitTest(aRect: BOX2I, aContained: boolean, aAccuracy?: number): boolean;
override HitTest(aPoly: SHAPE_LINE_CHAIN, aContained: boolean): boolean;
override HitTest(
a: VECTOR2I | BOX2I | SHAPE_LINE_CHAIN,
b?: number | boolean,
c?: number,
): boolean {
if (isBox(a)) {
const rect = a.Clone();
rect.Inflate(c ?? 0);
if (b as boolean) return rect.Contains(this.GetBoundingBox());
return rect.Intersects(this.GetBoundingBox());
}
if (isPoint(a)) {
const rect = this.GetBoundingBox();
rect.Inflate((b as number | undefined) ?? 0);
return rect.Contains(a);
}
return PCB_SHAPE.prototype.HitTest.call(this, a, b as boolean);
}
override GetClass(): string {
return 'PCB_TEXTBOX';
}
/**
* Function TransformTextToPolySet
* Convert the text to a polygonSet describing the actual character strokes (one per segment).
* Used in 3D viewer
* Circles and arcs are approximated by segments
* @param aBuffer = SHAPE_POLY_SET to store the polygon corners
* @param aClearance = the clearance around the text
* @param aError = the maximum error to allow when approximating curves
*/
TransformTextToPolySet(
aBuffer: SHAPE_POLY_SET,
aClearance: number,
aMaxError: number,
aErrorLoc: ERROR_LOC,
): void {
const font = this.GetDrawFont(null);
const penWidth = this.GetEffectiveTextPenWidth();
const attrs = this.GetAttributes();
const shownText = this.GetShownText(true);
// The polygonal shape of a text can have many basic shapes, so combining these shapes can
// be very useful to create a final shape with a lot less vertices to speedup calculations.
// Simplify shapes is not usually always efficient, but in this case it is.
const textShape = new SHAPE_POLY_SET();
const callback_gal = new CALLBACK_GAL(
// Stroke callback
(aPt1: VECTOR2I, aPt2: VECTOR2I) => {
TransformOvalToPolygon(textShape, aPt1, aPt2, penWidth, aMaxError, aErrorLoc);
},
// Triangulation callback
(aPt1: VECTOR2I, aPt2: VECTOR2I, aPt3: VECTOR2I) => {
textShape.NewOutline();
for (const point of [aPt1, aPt2, aPt3]) textShape.Append(point.x, point.y);
},
);
const cache = this.GetRenderCache(font, shownText);
if (cache) callback_gal.DrawGlyphs(cache);
else font.DrawAt(callback_gal, shownText, this.GetDrawPos(), attrs, this.GetFontMetrics());
textShape.Simplify();
if (this.IsKnockout()) {
const finalPoly = new SHAPE_POLY_SET();
this.TransformShapeToPolygon(finalPoly, this.GetLayer(), aClearance, aMaxError, aErrorLoc);
finalPoly.BooleanSubtract(textShape);
aBuffer.Append(finalPoly);
} else {
if (aClearance > 0 || aErrorLoc === ERROR_LOC.ERROR_OUTSIDE) {
if (aErrorLoc === ERROR_LOC.ERROR_OUTSIDE) aClearance += aMaxError;
textShape.Inflate(aClearance, CornerStrategy.ROUND_ALL_CORNERS, aMaxError, true);
}
aBuffer.Append(textShape);
}
}
override TransformShapeToPolygon(
aBuffer: SHAPE_POLY_SET,
aLayer: PCB_LAYER_ID,
aClearance: number,
aMaxError: number,
aErrorLoc: ERROR_LOC,
aIgnoreLineWidth?: boolean,
): void;
/** `EDA_SHAPE::TransformShapeToPolygon`, the overload PCB_SHAPE carries (hidden in C++, kept callable here). */
override TransformShapeToPolygon(
aBuffer: SHAPE_POLY_SET,
aClearance: number,
aError: number,
aErrorLoc: ERROR_LOC,
ignoreLineWidth?: boolean,
includeFill?: boolean,
): void;
override TransformShapeToPolygon(
aBuffer: SHAPE_POLY_SET,
b: number,
c: number,
d: number,
e?: number | boolean,
f?: boolean,
): void {
if (typeof e !== 'number') {
EDA_SHAPE.prototype.TransformShapeToPolygon.call(
this,
aBuffer,
b,
c,
d as ERROR_LOC,
e ?? false,
f ?? false,
);
return;
}
// ( aBuffer, aLayer, aClearance, aMaxError, aErrorLoc, aIgnoreLineWidth )
const aClearance = c;
const aMaxError = d;
const aErrorLoc = e as ERROR_LOC;
// Don't use PCB_SHAPE::TransformShapeToPolygon. We want to treat the textbox as filled even
// if there's no background colour.
const width = this.GetWidth() + 2 * aClearance;
if (this.GetShape() === SHAPE_T.RECTANGLE) {
const pts = this.GetRectCorners();
aBuffer.NewOutline();
for (const pt of pts) aBuffer.Append(pt);
if (this.m_borderEnabled && width > 0) {
// Add in segments
TransformOvalToPolygon(aBuffer, pts[0]!, pts[1]!, width, aMaxError, aErrorLoc);
TransformOvalToPolygon(aBuffer, pts[1]!, pts[2]!, width, aMaxError, aErrorLoc);
TransformOvalToPolygon(aBuffer, pts[2]!, pts[3]!, width, aMaxError, aErrorLoc);
TransformOvalToPolygon(aBuffer, pts[3]!, pts[0]!, width, aMaxError, aErrorLoc);
}
} else if (this.GetShape() === SHAPE_T.POLY) {
// Non-cardinally-rotated rect
aBuffer.NewOutline();
const poly = this.GetPolyShape().Outline(0);
for (let ii = 0; ii < poly.PointCount(); ++ii) aBuffer.Append(poly.GetPoint(ii));
if (this.m_borderEnabled && width > 0) {
for (let ii = 0; ii < poly.SegmentCount(); ++ii) {
const seg = poly.GetSegment(ii);
TransformOvalToPolygon(aBuffer, seg.A, seg.B, width, aMaxError, aErrorLoc);
}
}
}
}
// @copydoc BOARD_ITEM::GetEffectiveShape
override GetEffectiveShape(
aLayer: PCB_LAYER_ID = PCB_LAYER_ID.UNDEFINED_LAYER,
aFlash: FLASHING = FLASHING.DEFAULT,
): SHAPE {
const shape = this.GetEffectiveTextShape();
if (PCB_SHAPE.prototype.GetStroke.call(this).GetWidth() >= 0)
shape.AddShape(PCB_SHAPE.prototype.GetEffectiveShape.call(this, aLayer, aFlash));
return shape;
}
override GetItemDescription(aUnitsProvider: UNITS_PROVIDER | null, aFull: boolean): string {
return `PCB text box '${aFull ? this.GetShownText(false) : KIUI_EllipsizeMenuText(this.GetText())}' on ${this.GetLayerName()}`;
}
override GetMenuImage(): string {
return 'add_textbox'; // BITMAPS::add_textbox
}
override Clone(): PCB_TEXTBOX {
return PCB_TEXTBOX.copyOf(this);
}
///< Tests whether the border is disabled, as configured by the stroke
IsBorderEnabled(): boolean {
return this.m_borderEnabled;
}
///< Disables the border, this is done by changing the stroke internally
SetBorderEnabled(enabled: boolean): void {
this.m_borderEnabled = enabled;
}
SetBorderWidth(aSize: number): void {
this.m_stroke.SetWidth(aSize);
}
GetBorderWidth(): number {
return this.m_stroke.GetWidth();
}
override Similarity(aBoardItem: BOARD_ITEM | EDA_SHAPE): number {
if (!(aBoardItem instanceof BOARD_ITEM))
return EDA_SHAPE.prototype.Similarity.call(this, aBoardItem);
if (aBoardItem.Type() !== this.Type()) return 0.0;
const other = aBoardItem as PCB_TEXTBOX;
let similarity = 1.0;
if (this.m_borderEnabled !== other.m_borderEnabled) similarity *= 0.9;
if (this.GetMarginLeft() !== other.GetMarginLeft()) similarity *= 0.9;
if (this.GetMarginTop() !== other.GetMarginTop()) similarity *= 0.9;
if (this.GetMarginRight() !== other.GetMarginRight()) similarity *= 0.9;
if (this.GetMarginBottom() !== other.GetMarginBottom()) similarity *= 0.9;
similarity *= EDA_TEXT.prototype.Similarity.call(this, other as unknown as EDA_TEXT);
return similarity;
}
/** `operator==( const BOARD_ITEM& )`. */
override equals(aBoardItem: BOARD_ITEM): boolean {
if (aBoardItem.Type() !== this.Type()) return false;
const other = aBoardItem as PCB_TEXTBOX;
return this.equalsTextbox(other);
}
/** `operator==( const PCB_TEXTBOX& )`. */
equalsTextbox(aOther: PCB_TEXTBOX): boolean {
return (
this.m_borderEnabled === aOther.m_borderEnabled &&
this.equalsEdaText(aOther as unknown as EDA_TEXT)
);
}
override getDrawRotation(): EDA_ANGLE {
return this.GetDrawRotation();
}
protected override swapData(aImage: BOARD_ITEM): void {
console.assert(aImage.Type() === KICAD_T.PCB_TEXTBOX_T);
// std::swap( *this, *aImage ): every member of both classes.
const image = aImage as PCB_TEXTBOX;
const mine = PCB_TEXTBOX.copyOf(this);
this.assignPcbTextbox(image);
(this as { m_Uuid: string }).m_Uuid = image.m_Uuid;
image.assignPcbTextbox(mine);
(image as { m_Uuid: string }).m_Uuid = mine.m_Uuid;
}
getFontMetrics(): METRICS {
return this.GetFontMetrics();
}
}
applyMixins(PCB_TEXTBOX, [EDA_TEXT]);
function isBox(a: unknown): a is BOX2I {
return (
typeof (a as BOX2I).Inflate === 'function' && typeof (a as BOX2I).Intersects === 'function'
);
}
function isPoint(a: unknown): a is VECTOR2I {
return typeof (a as VECTOR2I).x === 'number' && !isBox(a);
}
/**
* `static struct PCB_TEXTBOX_DESC` (pcbnew/pcb_textbox.cpp).
*/
(() => {
const lineStyleEnum = ENUM_MAP.Instance<LINE_STYLE>('LINE_STYLE');
if (lineStyleEnum.Choices().GetCount() === 0) {
lineStyleEnum
.Map(LINE_STYLE.SOLID, 'Solid')
.Map(LINE_STYLE.DASH, 'Dashed')
.Map(LINE_STYLE.DOT, 'Dotted')
.Map(LINE_STYLE.DASHDOT, 'Dash-Dot')
.Map(LINE_STYLE.DASHDOTDOT, 'Dash-Dot-Dot');
}
const propMgr = PROPERTY_MANAGER.Instance();
REGISTER_TYPE(PCB_TEXTBOX);
propMgr.AddTypeCast(new TYPE_CAST(PCB_TEXTBOX, PCB_SHAPE));
propMgr.AddTypeCast(new TYPE_CAST(PCB_TEXTBOX, EDA_SHAPE));
propMgr.AddTypeCast(new TYPE_CAST(PCB_TEXTBOX, EDA_TEXT));
propMgr.InheritsAfter(PCB_TEXTBOX, PCB_SHAPE);
propMgr.InheritsAfter(PCB_TEXTBOX, EDA_SHAPE);
propMgr.InheritsAfter(PCB_TEXTBOX, EDA_TEXT);
propMgr.Mask(PCB_TEXTBOX, EDA_SHAPE, 'Shape');
propMgr.Mask(PCB_TEXTBOX, EDA_SHAPE, 'Start X');
propMgr.Mask(PCB_TEXTBOX, EDA_SHAPE, 'Start Y');
propMgr.Mask(PCB_TEXTBOX, EDA_SHAPE, 'End X');
propMgr.Mask(PCB_TEXTBOX, EDA_SHAPE, 'End Y');
propMgr.Mask(PCB_TEXTBOX, EDA_SHAPE, 'Width');
propMgr.Mask(PCB_TEXTBOX, EDA_SHAPE, 'Height');
propMgr.Mask(PCB_TEXTBOX, EDA_SHAPE, 'Line Width');
propMgr.Mask(PCB_TEXTBOX, EDA_SHAPE, 'Line Style');
propMgr.Mask(PCB_TEXTBOX, EDA_SHAPE, 'Filled');
propMgr.Mask(PCB_TEXTBOX, EDA_SHAPE, 'Line Color');
propMgr.Mask(PCB_TEXTBOX, EDA_SHAPE, 'Corner Radius');
propMgr.Mask(PCB_TEXTBOX, EDA_TEXT, 'Color');
propMgr.Mask(PCB_TEXTBOX, PCB_SHAPE, 'Soldermask');
propMgr.Mask(PCB_TEXTBOX, PCB_SHAPE, 'Soldermask Margin Override');
propMgr.AddProperty(
new PROPERTY<PCB_TEXTBOX, boolean, BOARD_ITEM>(
PCB_TEXTBOX,
'Knockout',
'SetIsKnockout',
'IsKnockout',
TYPE_BOOL,
PROPERTY_DISPLAY.PT_DEFAULT,
COORD_TYPES_T.NOT_A_COORD,
BOARD_ITEM,
),
'Text Properties',
);
const borderProps = 'Border Properties';
const lineStyleSetter = 'SetLineStyle' as const;
const lineStyleGetter = 'GetLineStyle' as const;
propMgr.AddProperty(
new PROPERTY<PCB_TEXTBOX, boolean>(
PCB_TEXTBOX,
'Border',
'SetBorderEnabled',
'IsBorderEnabled',
TYPE_BOOL,
),
borderProps,
);
propMgr.AddProperty(
new PROPERTY_ENUM<PCB_TEXTBOX, LINE_STYLE>(
PCB_TEXTBOX,
'Border Style',
lineStyleSetter,
lineStyleGetter,
lineStyleEnum,
),
borderProps,
);
propMgr.AddProperty(
new PROPERTY<PCB_TEXTBOX, number>(
PCB_TEXTBOX,
'Border Width',
'SetBorderWidth',
'GetBorderWidth',
TYPE_INT,
PROPERTY_DISPLAY.PT_SIZE,
),
borderProps,
);
const marginProps = 'Margins';
propMgr.AddProperty(
new PROPERTY<PCB_TEXTBOX, number>(
PCB_TEXTBOX,
'Margin Left',
'SetMarginLeft',
'GetMarginLeft',
TYPE_INT,
PROPERTY_DISPLAY.PT_SIZE,
),
marginProps,
);
propMgr.AddProperty(
new PROPERTY<PCB_TEXTBOX, number>(
PCB_TEXTBOX,
'Margin Top',
'SetMarginTop',
'GetMarginTop',
TYPE_INT,
PROPERTY_DISPLAY.PT_SIZE,
),
marginProps,
);
propMgr.AddProperty(
new PROPERTY<PCB_TEXTBOX, number>(
PCB_TEXTBOX,
'Margin Right',
'SetMarginRight',
'GetMarginRight',
TYPE_INT,
PROPERTY_DISPLAY.PT_SIZE,
),
marginProps,
);
propMgr.AddProperty(
new PROPERTY<PCB_TEXTBOX, number>(
PCB_TEXTBOX,
'Margin Bottom',
'SetMarginBottom',
'GetMarginBottom',
TYPE_INT,
PROPERTY_DISPLAY.PT_SIZE,
),
marginProps,
);
propMgr.Mask(PCB_TEXT, EDA_TEXT, 'Hyperlink');
})();