You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

455 lines
17 KiB

4 years ago
4 years ago
  1. /*
  2. * This program source code file is part of KiCad, a free EDA CAD application.
  3. *
  4. * Copyright (C) 2013 Jean-Pierre Charras, jp.charras at wanadoo.fr
  5. * Copyright (C) 2004-2023 KiCad Developers, see AUTHORS.txt for contributors.
  6. *
  7. * This program is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU General Public License
  9. * as published by the Free Software Foundation; either version 2
  10. * of the License, or (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program; if not, you may find one here:
  19. * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
  20. * or you may search the http://www.gnu.org website for the version 2 license,
  21. * or you may write to the Free Software Foundation, Inc.,
  22. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
  23. */
  24. #ifndef EDA_TEXT_H_
  25. #define EDA_TEXT_H_
  26. #include <memory>
  27. #include <vector>
  28. #include <outline_mode.h>
  29. #include <eda_search_data.h>
  30. #include <font/glyph.h>
  31. #include <font/text_attributes.h>
  32. class OUTPUTFORMATTER;
  33. class SHAPE_COMPOUND;
  34. class SHAPE_POLY_SET;
  35. // These are only here for algorithmic safety, not to tell the user what to do.
  36. // PL_EDITOR has the least resolution (its internal units are microns), so the min size is chosen
  37. // to yield 1 in PL_EDITOR.
  38. // The max size chosen is somewhat arbitrary, but no one has complained yet.
  39. #define TEXT_MIN_SIZE_MM 0.001 ///< Minimum text size (1 micron).
  40. #define TEXT_MAX_SIZE_MM 250.0 ///< Maximum text size in mm (~10 inches)
  41. namespace KIGFX
  42. {
  43. class RENDER_SETTINGS;
  44. class COLOR4D;
  45. }
  46. namespace KIFONT
  47. {
  48. class METRICS;
  49. }
  50. using KIGFX::RENDER_SETTINGS;
  51. using KIGFX::COLOR4D;
  52. // part of the kicad_plugin.h family of defines.
  53. // See kicad_plugin.h for the choice of the value
  54. // When set when calling EDA_TEXT::Format, disable writing the "hide" keyword in save file
  55. #define CTL_OMIT_HIDE (1 << 6)
  56. /**
  57. * This is the "default-of-the-default" hardcoded text size; individual application define their
  58. * own default policy starting with this (usually with a user option or project).
  59. */
  60. #define DEFAULT_SIZE_TEXT 50 // default text height (in mils, i.e. 1/1000")
  61. /**
  62. * A mix-in class (via multiple inheritance) that handles texts such as labels, parts,
  63. * components, or footprints. Because it's a mix-in class, care is used to provide
  64. * function names (accessors) that to not collide with function names likely to be seen
  65. * in the combined derived classes.
  66. */
  67. class EDA_TEXT
  68. {
  69. public:
  70. EDA_TEXT( const EDA_IU_SCALE& aIuScale, const wxString& aText = wxEmptyString );
  71. EDA_TEXT( const EDA_TEXT& aText );
  72. virtual ~EDA_TEXT();
  73. EDA_TEXT& operator=( const EDA_TEXT& aItem );
  74. /**
  75. * Return the string associated with the text object.
  76. *
  77. * @return a const wxString reference containing the string of the item.
  78. */
  79. virtual const wxString& GetText() const { return m_text; }
  80. /**
  81. * Return the string actually shown after processing of the base text.
  82. *
  83. * @param aAllowExtraText is true to allow adding more text than the initial expanded text,
  84. * for intance a title, a prefix for texts in display functions.
  85. * False to disable any added text (for instance when writing the shown text in netlists).
  86. * @param aDepth is used to prevent infinite recursions and loops when expanding
  87. * text variables.
  88. */
  89. virtual wxString GetShownText( bool aAllowExtraText, int aDepth = 0 ) const
  90. {
  91. return m_shown_text;
  92. }
  93. /**
  94. * Indicates the ShownText has text var references which need to be processed.
  95. */
  96. bool HasTextVars() const { return m_shown_text_has_text_var_refs; }
  97. virtual void SetText( const wxString& aText );
  98. /**
  99. * The TextThickness is that set by the user. The EffectiveTextPenWidth also factors
  100. * in bold text and thickness clamping.
  101. */
  102. void SetTextThickness( int aWidth );
  103. int GetTextThickness() const { return m_attributes.m_StrokeWidth; };
  104. /**
  105. * The EffectiveTextPenWidth uses the text thickness if > 1 or aDefaultPenWidth.
  106. */
  107. int GetEffectiveTextPenWidth( int aDefaultPenWidth = 0 ) const;
  108. virtual void SetTextAngle( const EDA_ANGLE& aAngle );
  109. const EDA_ANGLE& GetTextAngle() const { return m_attributes.m_Angle; }
  110. // For property system:
  111. void SetTextAngleDegrees( double aOrientation )
  112. {
  113. SetTextAngle( EDA_ANGLE( aOrientation, DEGREES_T ) );
  114. }
  115. double GetTextAngleDegrees() const { return m_attributes.m_Angle.AsDegrees(); }
  116. void SetItalic( bool aItalic );
  117. bool IsItalic() const { return m_attributes.m_Italic; }
  118. void SetBold( bool aBold );
  119. bool IsBold() const { return m_attributes.m_Bold; }
  120. virtual void SetVisible( bool aVisible );
  121. virtual bool IsVisible() const { return m_attributes.m_Visible; }
  122. void SetMirrored( bool isMirrored );
  123. bool IsMirrored() const { return m_attributes.m_Mirrored; }
  124. /**
  125. * @param aAllow true if ok to use multiline option, false if ok to use only single line
  126. * text. (Single line is faster in calculations than multiline.)
  127. */
  128. void SetMultilineAllowed( bool aAllow );
  129. bool IsMultilineAllowed() const { return m_attributes.m_Multiline; }
  130. void SetHorizJustify( GR_TEXT_H_ALIGN_T aType );
  131. GR_TEXT_H_ALIGN_T GetHorizJustify() const { return m_attributes.m_Halign; };
  132. void SetVertJustify( GR_TEXT_V_ALIGN_T aType );
  133. GR_TEXT_V_ALIGN_T GetVertJustify() const { return m_attributes.m_Valign; };
  134. void SetKeepUpright( bool aKeepUpright );
  135. bool IsKeepUpright() const { return m_attributes.m_KeepUpright; }
  136. void FlipHJustify()
  137. {
  138. if( GetHorizJustify() == GR_TEXT_H_ALIGN_RIGHT )
  139. SetHorizJustify( GR_TEXT_H_ALIGN_LEFT );
  140. else if( GetHorizJustify() == GR_TEXT_H_ALIGN_LEFT )
  141. SetHorizJustify( GR_TEXT_H_ALIGN_RIGHT );
  142. }
  143. /**
  144. * Set the text attributes from another instance.
  145. */
  146. void SetAttributes( const EDA_TEXT& aSrc, bool aSetPosition = true );
  147. /**
  148. * Swap the text attributes of the two involved instances.
  149. */
  150. void SwapAttributes( EDA_TEXT& aTradingPartner );
  151. void SwapText( EDA_TEXT& aTradingPartner );
  152. void CopyText( const EDA_TEXT& aSrc );
  153. void SetAttributes( const TEXT_ATTRIBUTES& aTextAttrs ) { m_attributes = aTextAttrs; }
  154. const TEXT_ATTRIBUTES& GetAttributes() const { return m_attributes; }
  155. /**
  156. * Helper function used in search and replace dialog.
  157. *
  158. * Perform a text replace using the find and replace criteria in \a aSearchData.
  159. *
  160. * @param aSearchData A reference to a EDA_SEARCH_DATA object containing the
  161. * search and replace criteria.
  162. * @return True if the text item was modified, otherwise false.
  163. */
  164. bool Replace( const EDA_SEARCH_DATA& aSearchData );
  165. bool IsDefaultFormatting() const;
  166. void SetFont( KIFONT::FONT* aFont );
  167. KIFONT::FONT* GetFont() const { return m_attributes.m_Font; }
  168. wxString GetFontName() const;
  169. void SetFontIndex( int aIdx );
  170. int GetFontIndex() const;
  171. void SetLineSpacing( double aLineSpacing );
  172. double GetLineSpacing() const { return m_attributes.m_LineSpacing; }
  173. void SetTextSize( VECTOR2I aNewSize, bool aEnforceMinTextSize = true );
  174. VECTOR2I GetTextSize() const { return m_attributes.m_Size; }
  175. void SetTextWidth( int aWidth );
  176. int GetTextWidth() const { return m_attributes.m_Size.x; }
  177. void SetTextHeight( int aHeight );
  178. int GetTextHeight() const { return m_attributes.m_Size.y; }
  179. void SetTextColor( const COLOR4D& aColor ) { m_attributes.m_Color = aColor; }
  180. COLOR4D GetTextColor() const { return m_attributes.m_Color; }
  181. void SetTextPos( const VECTOR2I& aPoint );
  182. const VECTOR2I& GetTextPos() const { return m_pos; }
  183. void SetTextX( int aX );
  184. void SetTextY( int aY );
  185. void Offset( const VECTOR2I& aOffset );
  186. void Empty();
  187. static GR_TEXT_H_ALIGN_T MapHorizJustify( int aHorizJustify );
  188. static GR_TEXT_V_ALIGN_T MapVertJustify( int aVertJustify );
  189. /**
  190. * Print this text object to the device context \a aDC.
  191. *
  192. * @param aDC the current Device Context.
  193. * @param aOffset draw offset (usually (0,0)).
  194. * @param aColor text color.
  195. * @param aDisplay_mode #FILLED or #SKETCH.
  196. */
  197. void Print( const RENDER_SETTINGS* aSettings, const VECTOR2I& aOffset, const COLOR4D& aColor,
  198. OUTLINE_MODE aDisplay_mode = FILLED );
  199. /**
  200. * build a list of segments (SHAPE_SEGMENT) to describe a text shape.
  201. * @param aTriangulate: true to build also the triangulation of each shape
  202. * @param aUseTextRotation: true to use the actual text draw rotation.
  203. * false to build a list of shape for a not rotated text ("native" shapes).
  204. */
  205. std::shared_ptr<SHAPE_COMPOUND> GetEffectiveTextShape( bool aTriangulate = true,
  206. const BOX2I& aBBox = BOX2I(),
  207. const EDA_ANGLE& aAngle = ANGLE_0 ) const;
  208. /**
  209. * Test if \a aPoint is within the bounds of this object.
  210. *
  211. * @param aPoint A VECTOR2I to test.
  212. * @param aAccuracy Amount to inflate the bounding box.
  213. * @return true if a hit, else false.
  214. */
  215. virtual bool TextHitTest( const VECTOR2I& aPoint, int aAccuracy = 0 ) const;
  216. /**
  217. * Test if object bounding box is contained within or intersects \a aRect.
  218. *
  219. * @param aRect Rect to test against.
  220. * @param aContains Test for containment instead of intersection if true.
  221. * @param aAccuracy Amount to inflate the bounding box.
  222. * @return true if a hit, else false.
  223. */
  224. virtual bool TextHitTest( const BOX2I& aRect, bool aContains, int aAccuracy = 0 ) const;
  225. /**
  226. * Useful in multiline texts to calculate the full text or a line area (for zones filling,
  227. * locate functions....)
  228. *
  229. * @param aLine The line of text to consider. Pass -1 for all lines.
  230. * @param aInvertY Invert the Y axis when calculating bounding box.
  231. * @return the rect containing the line of text (i.e. the position and the size of one line)
  232. * this rectangle is calculated for 0 orient text.
  233. * If orientation is not 0 the rect must be rotated to match the physical area
  234. */
  235. BOX2I GetTextBox( int aLine = -1, bool aInvertY = false ) const;
  236. /**
  237. * Return the distance between two lines of text.
  238. *
  239. * Calculates the distance (pitch) between two lines of text. This distance includes the
  240. * interline distance plus room for characters like j, {, and [. It also used for single
  241. * line text, to calculate the text bounding box.
  242. */
  243. int GetInterline() const;
  244. /**
  245. * @return a wxString with the style name( Normal, Italic, Bold, Bold+Italic).
  246. */
  247. wxString GetTextStyleName() const;
  248. /**
  249. * Populate \a aPositions with the position of each line of a multiline text, according
  250. * to the vertical justification and the rotation of the whole text.
  251. *
  252. * @param aPositions is the list to populate by the VECTOR2I positions.
  253. * @param aLineCount is the number of lines (not recalculated here for efficiency reasons.
  254. */
  255. void GetLinePositions( std::vector<VECTOR2I>& aPositions, int aLineCount ) const;
  256. /**
  257. * Return the levenstein distance between two texts.
  258. *
  259. * Return a value of 0.0 - 1.0 where 1.0 is a perfect match.
  260. */
  261. double Levenshtein( const EDA_TEXT& aOther ) const;
  262. double Similarity( const EDA_TEXT& aOther ) const;
  263. /**
  264. * Output the object to \a aFormatter in s-expression form.
  265. *
  266. * @param aFormatter The #OUTPUTFORMATTER object to write to.
  267. * @param aNestLevel The indentation next level.
  268. * @param aControlBits The control bit definition for object specific formatting.
  269. * @throw IO_ERROR on write error.
  270. */
  271. virtual void Format( OUTPUTFORMATTER* aFormatter, int aNestLevel, int aControlBits ) const;
  272. virtual EDA_ANGLE GetDrawRotation() const { return GetTextAngle(); }
  273. virtual VECTOR2I GetDrawPos() const { return GetTextPos(); }
  274. virtual void ClearRenderCache();
  275. virtual void ClearBoundingBoxCache();
  276. std::vector<std::unique_ptr<KIFONT::GLYPH>>*
  277. GetRenderCache( const KIFONT::FONT* aFont, const wxString& forResolvedText,
  278. const VECTOR2I& aOffset = { 0, 0 } ) const;
  279. // Support for reading the cache from disk.
  280. void SetupRenderCache( const wxString& aResolvedText, const KIFONT::FONT* aFont,
  281. const EDA_ANGLE& aAngle, const VECTOR2I& aOffset );
  282. void AddRenderCacheGlyph( const SHAPE_POLY_SET& aPoly );
  283. int Compare( const EDA_TEXT* aOther ) const;
  284. bool operator==( const EDA_TEXT& aRhs ) const { return Compare( &aRhs ) == 0; }
  285. bool operator<( const EDA_TEXT& aRhs ) const { return Compare( &aRhs ) < 0; }
  286. bool operator>( const EDA_TEXT& aRhs ) const { return Compare( &aRhs ) > 0; }
  287. virtual bool HasHyperlink() const { return !m_hyperlink.IsEmpty(); }
  288. wxString GetHyperlink() const { return m_hyperlink; }
  289. void SetHyperlink( wxString aLink ) { m_hyperlink = aLink; }
  290. void RemoveHyperlink() { m_hyperlink = wxEmptyString; }
  291. /**
  292. * Check if aURL is a valid hyperlink.
  293. *
  294. * @param aURL String to validate
  295. * @return true if aURL is a valid hyperlink
  296. */
  297. static bool ValidateHyperlink( const wxString& aURL );
  298. /**
  299. * Check if aHref is a valid internal hyperlink.
  300. *
  301. * @param aHref String to validate
  302. * @param aDestination [optional] pointer to populate with the destination page
  303. * @return true if aHref is a valid internal hyperlink. Does *not* check if the destination
  304. * page actually exists.
  305. */
  306. static bool IsGotoPageHref( const wxString& aHref, wxString* aDestination = nullptr );
  307. /**
  308. * Generate a href to a page in the current schematic.
  309. *
  310. * @param aDestination Destination sheet's page number.
  311. * @return A hyperlink href string that goes to the specified page.
  312. */
  313. static wxString GotoPageHref( const wxString& aDestination );
  314. protected:
  315. virtual KIFONT::FONT* getDrawFont() const;
  316. virtual const KIFONT::METRICS& getFontMetrics() const;
  317. virtual void cacheShownText();
  318. /**
  319. * Print each line of this EDA_TEXT.
  320. *
  321. * @param aOffset draw offset (usually (0,0)).
  322. * @param aColor text color.
  323. * @param aFillMode FILLED or SKETCH
  324. * @param aText the single line of text to draw.
  325. * @param aPos the position of this line ).
  326. */
  327. void printOneLineOfText( const RENDER_SETTINGS* aSettings, const VECTOR2I& aOffset,
  328. const COLOR4D& aColor, OUTLINE_MODE aFillMode, const wxString& aText,
  329. const VECTOR2I& aPos );
  330. protected:
  331. /**
  332. * A hyperlink URL. If empty, this text object is not a hyperlink.
  333. */
  334. wxString m_hyperlink;
  335. private:
  336. wxString m_text;
  337. wxString m_shown_text; // Cache of unescaped text for efficient access
  338. bool m_shown_text_has_text_var_refs;
  339. std::reference_wrapper<const EDA_IU_SCALE> m_IuScale;
  340. mutable wxString m_render_cache_text;
  341. mutable const KIFONT::FONT* m_render_cache_font;
  342. mutable EDA_ANGLE m_render_cache_angle;
  343. mutable VECTOR2I m_render_cache_offset;
  344. mutable std::vector<std::unique_ptr<KIFONT::GLYPH>> m_render_cache;
  345. mutable bool m_bounding_box_cache_valid;
  346. mutable VECTOR2I m_bounding_box_cache_pos;
  347. mutable int m_bounding_box_cache_line;
  348. mutable bool m_bounding_box_cache_inverted;
  349. mutable BOX2I m_bounding_box_cache;
  350. TEXT_ATTRIBUTES m_attributes;
  351. VECTOR2I m_pos;
  352. };
  353. extern std::ostream& operator<<( std::ostream& aStream, const EDA_TEXT& aAttributes );
  354. template<>
  355. struct std::hash<EDA_TEXT>
  356. {
  357. std::size_t operator()( const EDA_TEXT& aText ) const
  358. {
  359. return hash_val( aText.GetText(), aText.GetAttributes(), aText.GetTextPos().x,
  360. aText.GetTextPos().y );
  361. }
  362. };
  363. #endif // EDA_TEXT_H_