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.

621 lines
23 KiB

  1. /*
  2. * This program source code file is part of KiCad, a free EDA CAD application.
  3. *
  4. * Copyright (C) 1992-2011 jean-pierre Charras <jean-pierre.charras@gipsa-lab.inpg.fr>
  5. * Copyright (C) 2011 Wayne Stambaugh <stambaughw@gmail.com>
  6. * Copyright (C) 1992-2022 KiCad Developers, see AUTHORS.txt for contributors.
  7. *
  8. * This program is free software; you can redistribute it and/or
  9. * modify it under the terms of the GNU General Public License
  10. * as published by the Free Software Foundation; either version 2
  11. * of the License, or (at your option) any later version.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with this program; if not, you may find one here:
  20. * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
  21. * or you may search the http://www.gnu.org website for the version 2 license,
  22. * or you may write to the Free Software Foundation, Inc.,
  23. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
  24. */
  25. #ifndef _SCH_REFERENCE_LIST_H_
  26. #define _SCH_REFERENCE_LIST_H_
  27. #include <map>
  28. #include <lib_symbol.h>
  29. #include <macros.h>
  30. #include <sch_sheet_path.h>
  31. #include <sch_symbol.h>
  32. #include <sch_text.h>
  33. #include <erc_settings.h>
  34. /** Schematic annotation scope options. */
  35. enum ANNOTATE_SCOPE_T
  36. {
  37. ANNOTATE_ALL, ///< Annotate the full schematic
  38. ANNOTATE_CURRENT_SHEET, ///< Annotate the current sheet
  39. ANNOTATE_SELECTION ///< Annotate the selection
  40. };
  41. /** Schematic annotation order options. */
  42. enum ANNOTATE_ORDER_T
  43. {
  44. SORT_BY_X_POSITION, ///< Annotate by X position from left to right.
  45. SORT_BY_Y_POSITION, ///< Annotate by Y position from top to bottom.
  46. UNSORTED, ///< Annotate by position of symbol in the schematic sheet
  47. ///< object list.
  48. };
  49. /** Schematic annotation type options. */
  50. enum ANNOTATE_ALGO_T
  51. {
  52. INCREMENTAL_BY_REF, ///< Annotate incrementally using the first free reference number.
  53. SHEET_NUMBER_X_100, ///< Annotate using the first free reference number starting at
  54. ///< the sheet number * 100.
  55. SHEET_NUMBER_X_1000, ///< Annotate using the first free reference number starting at
  56. ///< the sheet number * 1000.
  57. };
  58. /**
  59. * A helper to define a symbol's reference designator in a schematic.
  60. *
  61. * This helper is required in a complex hierarchy because a symbol can be used more than once
  62. * and its reference depends on the sheet path. This class is used to flatten the schematic
  63. * hierarchy for annotation, net list generation, and bill of material generation.
  64. */
  65. class SCH_REFERENCE
  66. {
  67. public:
  68. SCH_REFERENCE() :
  69. m_sheetPath()
  70. {
  71. m_rootSymbol = nullptr;
  72. m_libPart = nullptr;
  73. m_unit = 0;
  74. m_isNew = false;
  75. m_numRef = 0;
  76. m_flag = 0;
  77. m_sheetNum = 0;
  78. }
  79. SCH_REFERENCE( SCH_SYMBOL* aSymbol, LIB_SYMBOL* aLibSymbol, const SCH_SHEET_PATH& aSheetPath );
  80. SCH_SYMBOL* GetSymbol() const { return m_rootSymbol; }
  81. LIB_SYMBOL* GetLibPart() const { return m_libPart; }
  82. const SCH_SHEET_PATH& GetSheetPath() const { return m_sheetPath; }
  83. SCH_SHEET_PATH& GetSheetPath() { return m_sheetPath; }
  84. int GetUnit() const { return m_unit; }
  85. void SetUnit( int aUnit ) { m_unit = aUnit; }
  86. const wxString GetValue() const { return m_value; }
  87. void SetValue( const wxString& aValue ) { m_value = aValue; }
  88. const wxString GetFootprint() const { return m_footprint; }
  89. void SetFootprint( const wxString& aFP ) { m_footprint = aFP; }
  90. void SetSheetNumber( int aSheetNumber ) { m_sheetNum = aSheetNumber; }
  91. /**
  92. * @return the sheet path containing the symbol item
  93. */
  94. const wxString GetPath() const
  95. {
  96. return m_sheetPath.PathAsString();
  97. }
  98. /**
  99. * @return the full patb of the symbol item
  100. */
  101. const wxString GetFullPath() const
  102. {
  103. return m_sheetPath.PathAsString() + m_symbolUuid.AsString();
  104. }
  105. /**
  106. * Update the annotation of the symbol according the current object state.
  107. */
  108. void Annotate();
  109. /**
  110. * Attempt to split the reference designator into a name (U) and number (1).
  111. *
  112. * If the last character is '?' or not a digit, the reference is tagged as not annotated.
  113. * For symbols with multiple parts per package that are not already annotated, keeps the unit
  114. * number the same. E.g. U?A or U?B
  115. */
  116. void Split();
  117. /**
  118. * Determine if this reference needs to be split or if it likely already has been
  119. *
  120. * @return true if this reference hasn't been split yet
  121. */
  122. bool IsSplitNeeded();
  123. void SetRef( const wxString& aReference ) { m_ref = aReference; }
  124. wxString GetRef() const { return m_ref; }
  125. void SetRefStr( const std::string& aReference ) { m_ref = aReference; }
  126. const char* GetRefStr() const { return m_ref.c_str(); }
  127. ///< Return reference name with unit altogether
  128. wxString GetFullRef() const
  129. {
  130. if( GetSymbol()->GetUnitCount() > 1 )
  131. return GetRef() + GetRefNumber() + LIB_SYMBOL::SubReference( GetUnit() );
  132. else
  133. return GetRef() + GetRefNumber();
  134. }
  135. wxString GetRefNumber() const
  136. {
  137. wxString ref;
  138. if( m_numRef < 0 )
  139. return wxT( "?" );
  140. // To avoid a risk of duplicate, for power symbols the ref number is 0nnn instead of nnn.
  141. // Just because sometimes only power symbols are annotated
  142. if( GetLibPart() && GetLibPart()->IsPower() )
  143. ref = wxT( "0" );
  144. return ref << m_numRef;
  145. }
  146. int CompareValue( const SCH_REFERENCE& item ) const
  147. {
  148. return m_value.Cmp( item.m_value );
  149. }
  150. int CompareRef( const SCH_REFERENCE& item ) const
  151. {
  152. return m_ref.CmpNoCase( item.m_ref );
  153. }
  154. int CompareLibName( const SCH_REFERENCE& item ) const
  155. {
  156. return m_rootSymbol->GetLibId().GetLibItemName().compare(
  157. item.m_rootSymbol->GetLibId().GetLibItemName() );
  158. }
  159. /**
  160. * Return whether this reference refers to the same symbol instance (symbol and sheet) as
  161. * another.
  162. */
  163. bool IsSameInstance( const SCH_REFERENCE& other ) const
  164. {
  165. // Only compare symbol and path.
  166. // We may have changed the unit number or the designator but
  167. // can still be referencing the same instance.
  168. return GetSymbol() == other.GetSymbol()
  169. && GetSheetPath().Path() == other.GetSheetPath().Path();
  170. }
  171. bool IsUnitsLocked()
  172. {
  173. if( m_libPart )
  174. return m_libPart->UnitsLocked();
  175. else
  176. return true; // Assume units locked when we don't have a library
  177. }
  178. private:
  179. friend class SCH_REFERENCE_LIST;
  180. /// Symbol reference prefix, without number (for IC1, this is IC) )
  181. wxString m_ref; // it's private, use the accessors please
  182. SCH_SYMBOL* m_rootSymbol; ///< The symbol associated the reference object.
  183. LIB_SYMBOL* m_libPart; ///< The source symbol from a library.
  184. VECTOR2I m_symbolPos; ///< The physical position of the symbol in schematic
  185. ///< used to annotate by X or Y position
  186. int m_unit; ///< The unit number for symbol with multiple parts
  187. ///< per package.
  188. wxString m_value; ///< The symbol value.
  189. wxString m_footprint; ///< The footprint assigned.
  190. SCH_SHEET_PATH m_sheetPath; ///< The sheet path for this reference.
  191. bool m_isNew; ///< True if not yet annotated.
  192. int m_sheetNum; ///< The sheet number for the reference.
  193. KIID m_symbolUuid; ///< UUID of the symbol.
  194. int m_numRef; ///< The numeric part of the reference designator.
  195. int m_flag;
  196. };
  197. /**
  198. * Define a standard error handler for annotation errors.
  199. */
  200. typedef std::function<void( ERCE_T aType, const wxString& aMsg, SCH_REFERENCE* aItemA,
  201. SCH_REFERENCE* aItemB )> ANNOTATION_ERROR_HANDLER;
  202. /**
  203. * Container to create a flattened list of symbols because in a complex hierarchy, a symbol
  204. * can be used more than once and its reference designator is dependent on the sheet path for
  205. * the same symbol.
  206. *
  207. * This flattened list is used for netlist generation, BOM generation, and schematic annotation.
  208. */
  209. class SCH_REFERENCE_LIST
  210. {
  211. private:
  212. std::vector<SCH_REFERENCE> m_flatList;
  213. public:
  214. SCH_REFERENCE_LIST()
  215. {
  216. }
  217. SCH_REFERENCE& operator[]( int aIndex )
  218. {
  219. return m_flatList[ aIndex ];
  220. }
  221. const SCH_REFERENCE& operator[]( int aIndex ) const
  222. {
  223. return m_flatList[ aIndex ];
  224. }
  225. void Clear()
  226. {
  227. m_flatList.clear();
  228. }
  229. size_t GetCount() const { return m_flatList.size(); }
  230. SCH_REFERENCE& GetItem( int aIdx ) { return m_flatList[aIdx]; }
  231. const SCH_REFERENCE& GetItem( int aIdx ) const { return m_flatList[aIdx]; }
  232. void AddItem( const SCH_REFERENCE& aItem ) { m_flatList.push_back( aItem ); }
  233. /**
  234. * Remove an item from the list of references.
  235. *
  236. * @param aIndex is the index of the item to be removed.
  237. */
  238. void RemoveItem( unsigned int aIndex );
  239. /**
  240. * Return true if aItem exists in this list
  241. * @param aItem Reference to check
  242. * @return true if aItem exists in this list
  243. */
  244. bool Contains( const SCH_REFERENCE& aItem ) const;
  245. /* Sort functions:
  246. * Sort functions are used to sort symbols for annotation or BOM generation. Because
  247. * sorting depends on what we want to do, there are many sort functions.
  248. * Note:
  249. * When creating BOM, symbols are fully annotated. References are something like U3,
  250. * U5 or R4, R8. When annotating, some or all symbols are not annotated, i.e. ref is
  251. * only U or R, with no number.
  252. */
  253. /**
  254. * Attempt to split all reference designators into a name (U) and number (1).
  255. *
  256. * If the last character is '?' or not a digit, the reference is tagged as not annotated.
  257. * For symbols with multiple parts, keeps the unit number intact
  258. * @see SCH_REFERENCE::Split()
  259. */
  260. void SplitReferences()
  261. {
  262. for( unsigned ii = 0; ii < GetCount(); ii++ )
  263. m_flatList[ii].Split();
  264. }
  265. /**
  266. * Treat all symbols in this list as non-annotated. Does not update annotation state of the
  267. * symbols.
  268. * @see SCH_REFERENCE_LIST::UpdateAnnotation
  269. */
  270. void RemoveAnnotation( bool aIncludePowerSymbols )
  271. {
  272. for( unsigned ii = 0; ii < GetCount(); ii++ )
  273. {
  274. if( !m_flatList[ii].m_libPart->IsPower() || aIncludePowerSymbols )
  275. m_flatList[ii].m_isNew = true;
  276. }
  277. }
  278. /**
  279. * Update the symbol references for the schematic project (or the current sheet).
  280. *
  281. * @note This function does not calculate the reference numbers stored in m_numRef so it
  282. * must be called after calculation of new reference numbers.
  283. *
  284. * @see SCH_REFERENCE::Annotate()
  285. */
  286. void UpdateAnnotation()
  287. {
  288. /* update the reference numbers */
  289. for( unsigned ii = 0; ii < GetCount(); ii++ )
  290. m_flatList[ii].Annotate();
  291. }
  292. /**
  293. * @brief Forces reannotation of the provided references. Will also reannotate
  294. * associated multi-unit symbols.
  295. *
  296. * @param aSortOption Define the annotation order. See #ANNOTATE_ORDER_T.
  297. * @param aAlgoOption Define the annotation style. See #ANNOTATE_ALGO_T.
  298. * @param aStartNumber The start number for non-sheet-based annotation styles.
  299. * @param aAdditionalReferences Additional references to check for duplicates
  300. * @param aStartAtCurrent Use m_numRef for each reference as the start number (overrides
  301. * aStartNumber)
  302. * @param aHierarchy Optional sheet path hierarchy for resetting the references'
  303. * sheet numbers based on their sheet's place in the hierarchy. Set
  304. * nullptr if not desired.
  305. */
  306. void ReannotateByOptions( ANNOTATE_ORDER_T aSortOption,
  307. ANNOTATE_ALGO_T aAlgoOption,
  308. int aStartNumber,
  309. const SCH_REFERENCE_LIST& aAdditionalRefs,
  310. bool aStartAtCurrent,
  311. SCH_SHEET_LIST* aHierarchy );
  312. /**
  313. * Convenience function for the Paste Unique functionality. Do not use as a general
  314. * reannotation method.
  315. *
  316. * Replaces any duplicate reference designators with the next available number after the
  317. * present number regardless of configured annotation options.
  318. *
  319. * Multi-unit symbols are reannotated together.
  320. */
  321. void ReannotateDuplicates( const SCH_REFERENCE_LIST& aAdditionalReferences );
  322. /**
  323. * Annotate the references by the provided options.
  324. *
  325. * @param aSortOption Define the annotation order. See #ANNOTATE_ORDER_T.
  326. * @param aAlgoOption Define the annotation style. See #ANNOTATE_ALGO_T.
  327. * @param aStartNumber The start number for non-sheet-based annotation styles.
  328. * @param appendUndo True if the annotation operation should be added to an existing undo,
  329. * false if it should be separately undo-able.
  330. * @param aLockedUnitMap A SCH_MULTI_UNIT_REFERENCE_MAP of reference designator wxStrings
  331. * to SCH_REFERENCE_LISTs. May be an empty map. If not empty, any multi-unit parts
  332. * found in this map will be annotated as a group rather than individually.
  333. * @param aAdditionalReferences Additional references to check for duplicates
  334. * @param aStartAtCurrent Use m_numRef for each reference as the start number (overrides
  335. * aStartNumber)
  336. */
  337. void AnnotateByOptions( enum ANNOTATE_ORDER_T aSortOption,
  338. enum ANNOTATE_ALGO_T aAlgoOption,
  339. int aStartNumber,
  340. SCH_MULTI_UNIT_REFERENCE_MAP aLockedUnitMap,
  341. const SCH_REFERENCE_LIST& aAdditionalRefs,
  342. bool aStartAtCurrent );
  343. /**
  344. * Set the reference designators in the list that have not been annotated.
  345. *
  346. * If a the sheet number is 2 and \a aSheetIntervalId is 100, then the first reference
  347. * designator would be 201 and the last reference designator would be 299 when no overlap
  348. * occurs with sheet number 3. If there are 150 items in sheet number 2, then items are
  349. * referenced U201 to U351, and items in sheet 3 start from U352
  350. *
  351. * @param aUseSheetNum Set to true to start annotation for each sheet at the sheet number
  352. * times \a aSheetIntervalId. Otherwise annotate incrementally.
  353. * @param aSheetIntervalId The per sheet reference designator multiplier.
  354. * @param aStartNumber The number to start with if NOT numbering based on sheet number.
  355. * @param aLockedUnitMap A SCH_MULTI_UNIT_REFERENCE_MAP of reference designator wxStrings
  356. * to SCH_REFERENCE_LISTs. May be an empty map. If not empty, any multi-unit parts
  357. * found in this map will be annotated as a group rather than individually.
  358. * @param aAdditionalRefs Additional references to use for checking that there a reference
  359. * designator doesn't already exist. The caller must ensure that none of the references
  360. * in aAdditionalRefs exist in this list.
  361. * @param aStartAtCurrent Use m_numRef for each reference as the start number (overrides
  362. aStartNumber)
  363. */
  364. void Annotate( bool aUseSheetNum, int aSheetIntervalId, int aStartNumber,
  365. SCH_MULTI_UNIT_REFERENCE_MAP aLockedUnitMap,
  366. const SCH_REFERENCE_LIST& aAdditionalRefs, bool aStartAtCurrent = false );
  367. /**
  368. * Check for annotations errors.
  369. *
  370. * The following annotation error conditions are tested:
  371. * - Symbols not annotated.
  372. * - Symbols having the same reference designator (duplicates).
  373. * - Symbols with multiple parts per package having different reference designators.
  374. * - Symbols with multiple parts per package with invalid part count.
  375. *
  376. * @param aErrorHandler A handler for errors.
  377. * @return The number of errors found.
  378. */
  379. int CheckAnnotation( ANNOTATION_ERROR_HANDLER aErrorHandler );
  380. /**
  381. * Sort the list of references by X position.
  382. *
  383. * Symbols are sorted as follows:
  384. * - Numeric value of reference designator.
  385. * - Sheet number.
  386. * - X coordinate position.
  387. * - Y coordinate position.
  388. * - Time stamp.
  389. */
  390. void SortByXCoordinate()
  391. {
  392. sort( m_flatList.begin(), m_flatList.end(), sortByXPosition );
  393. }
  394. /**
  395. * Sort the list of references by Y position.
  396. *
  397. * Symbols are sorted as follows:
  398. * - Numeric value of reference designator.
  399. * - Sheet number.
  400. * - Y coordinate position.
  401. * - X coordinate position.
  402. * - Time stamp.
  403. */
  404. void SortByYCoordinate()
  405. {
  406. sort( m_flatList.begin(), m_flatList.end(), sortByYPosition );
  407. }
  408. /**
  409. * Sort the flat list by Time Stamp (sheet path + timestamp).
  410. *
  411. * Useful to detect duplicate Time Stamps
  412. */
  413. void SortByTimeStamp()
  414. {
  415. sort( m_flatList.begin(), m_flatList.end(), sortByTimeStamp );
  416. }
  417. /**
  418. * Sort the list of references by value.
  419. *
  420. * Symbols are sorted in the following order:
  421. * - Numeric value of reference designator.
  422. * - Value of symbol.
  423. * - Unit number when symbol has multiple parts.
  424. * - Sheet number.
  425. * - X coordinate position.
  426. * - Y coordinate position.
  427. */
  428. void SortByRefAndValue()
  429. {
  430. sort( m_flatList.begin(), m_flatList.end(), sortByRefAndValue );
  431. }
  432. /**
  433. * Sort the list of references by reference.
  434. *
  435. * Symbols are sorted in the following order:
  436. * - Numeric value of reference designator.
  437. * - Unit number when symbol has multiple parts.
  438. */
  439. void SortByReferenceOnly()
  440. {
  441. sort( m_flatList.begin(), m_flatList.end(), sortByReferenceOnly );
  442. }
  443. /**
  444. * Search the list for a symbol with a given reference.
  445. */
  446. int FindRef( const wxString& aPath ) const;
  447. /**
  448. * Search the sorted list of symbols for a another symbol with the same reference and a
  449. * given part unit. Use this method to manage symbols with multiple parts per package.
  450. *
  451. * @param aIndex is the index in aSymbolsList for of given #SCH_REFERENCE item to test.
  452. * @param aUnit is the given unit number to search.
  453. * @param aIncludeNew true to include references with the "new" flag in the search.
  454. * @return index in aSymbolsList if found or -1 if not found.
  455. */
  456. int FindUnit( size_t aIndex, int aUnit, bool aIncludeNew = false ) const;
  457. /**
  458. * Search the list for a symbol with the given KIID path (as string).
  459. *
  460. * @param aFullPath is the path of the symbol item to search.
  461. * @return an index in m_flatList if found or -1 if not found.
  462. */
  463. int FindRefByFullPath( const wxString& aFullPath ) const;
  464. /**
  465. * Add all the reference designator numbers greater than \a aMinRefId to \a aIdList
  466. * skipping the reference at \a aIndex.
  467. *
  468. * @param aIndex is the current symbol's index to use for reference prefix filtering.
  469. * @param aIdList is the buffer to fill.
  470. * @param aMinRefId is the minimum ID value to store. All values < aMinRefId are ignored.
  471. */
  472. void GetRefsInUse( int aIndex, std::vector<int>& aIdList, int aMinRefId ) const;
  473. /**
  474. * Return all the unit numbers for a given reference, comparing library reference, value,
  475. * reference number and reference prefix.
  476. *
  477. * @param aRef is the index of a symbol to use for reference prefix and number filtering.
  478. */
  479. std::vector<int> GetUnitsMatchingRef( const SCH_REFERENCE& aRef ) const;
  480. /**
  481. * Return the first unused reference number from the properties given in aRef, ensuring
  482. * all of the units in aRequiredUnits are also unused.
  483. *
  484. * @param aIndex The index of the reference item used for the search pattern.
  485. * @param aMinValue The minimum value for the current search.
  486. * @param aRequiredUnits List of units to ensure are free
  487. */
  488. int FindFirstUnusedReference( const SCH_REFERENCE& aRef, int aMinValue,
  489. const std::vector<int>& aRequiredUnits ) const;
  490. std::vector<SYMBOL_INSTANCE_REFERENCE> GetSymbolInstances() const;
  491. #if defined(DEBUG)
  492. void Show( const char* aPrefix = "" )
  493. {
  494. printf( "%s\n", aPrefix );
  495. for( unsigned i=0; i < m_flatList.size(); ++i )
  496. {
  497. SCH_REFERENCE& schref = m_flatList[i];
  498. printf( " [%-2d] ref:%-8s num:%-3d lib_part:%s\n",
  499. i,
  500. schref.m_ref.ToStdString().c_str(),
  501. schref.m_numRef,
  502. TO_UTF8( schref.GetLibPart()->GetName() ) );
  503. }
  504. }
  505. #endif
  506. /**
  507. * Return a shorthand string representing all the references in the list. For instance,
  508. * "R1, R2, R4 - R7, U1"
  509. */
  510. static wxString Shorthand( std::vector<SCH_REFERENCE> aList );
  511. friend class BACK_ANNOTATION;
  512. private:
  513. static bool sortByRefAndValue( const SCH_REFERENCE& item1, const SCH_REFERENCE& item2 );
  514. static bool sortByXPosition( const SCH_REFERENCE& item1, const SCH_REFERENCE& item2 );
  515. static bool sortByYPosition( const SCH_REFERENCE& item1, const SCH_REFERENCE& item2 );
  516. static bool sortByTimeStamp( const SCH_REFERENCE& item1, const SCH_REFERENCE& item2 );
  517. static bool sortByReferenceOnly( const SCH_REFERENCE& item1, const SCH_REFERENCE& item2 );
  518. /**
  519. * Search for the first free reference number in \a aListId of reference numbers in use.
  520. *
  521. * This function just searches for a hole in a list of incremented numbers, this list must
  522. * be sorted by increasing values and each value can be stored only once. The new value
  523. * is added to the list.
  524. *
  525. * @see BuildRefIdInUseList to prepare this list
  526. * @param aIdList The buffer that contains the reference numbers in use.
  527. * @param aFirstValue The first expected free value
  528. * @return The first free (not yet used) value.
  529. */
  530. static int createFirstFreeRefId( std::vector<int>& aIdList, int aFirstValue );
  531. // Used for sorting static sortByTimeStamp function
  532. friend class BACK_ANNOTATE;
  533. };
  534. #endif // _SCH_REFERENCE_LIST_H_