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.

628 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-2023 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. bool IsMultiUnit() const { return GetLibPart()->GetUnitCount() > 1; }
  87. const wxString GetValue() const { return m_value; }
  88. void SetValue( const wxString& aValue ) { m_value = aValue; }
  89. const wxString GetFootprint() const { return m_footprint; }
  90. void SetFootprint( const wxString& aFP ) { m_footprint = aFP; }
  91. void SetSheetNumber( int aSheetNumber ) { m_sheetNum = aSheetNumber; }
  92. /**
  93. * @return the sheet path containing the symbol item
  94. */
  95. const wxString GetPath() const
  96. {
  97. return m_sheetPath.PathAsString();
  98. }
  99. /**
  100. * @return the full patb of the symbol item
  101. */
  102. const wxString GetFullPath() const
  103. {
  104. return m_sheetPath.PathAsString() + m_symbolUuid.AsString();
  105. }
  106. /*
  107. * Compares by full path to make std::set work
  108. */
  109. bool operator<( const SCH_REFERENCE& aRef ) const { return GetFullPath() < aRef.GetFullPath(); }
  110. /**
  111. * Update the annotation of the symbol according the current object state.
  112. */
  113. void Annotate();
  114. /**
  115. * Verify the reference should always be automatically annotated.
  116. *
  117. * @return true if the symbol reference should always be automatically annotated otherwise
  118. * false.
  119. */
  120. bool AlwaysAnnotate() const;
  121. /**
  122. * Attempt to split the reference designator into a name (U) and number (1).
  123. *
  124. * If the last character is '?' or not a digit, the reference is tagged as not annotated.
  125. * For symbols with multiple parts per package that are not already annotated, keeps the unit
  126. * number the same. E.g. U?A or U?B
  127. */
  128. void Split();
  129. /**
  130. * Determine if this reference needs to be split or if it likely already has been
  131. *
  132. * @return true if this reference hasn't been split yet
  133. */
  134. bool IsSplitNeeded();
  135. void SetRef( const wxString& aReference ) { m_ref = aReference; }
  136. wxString GetRef() const { return m_ref; }
  137. void SetRefStr( const std::string& aReference ) { m_ref = aReference; }
  138. const char* GetRefStr() const { return m_ref.c_str(); }
  139. ///< Return reference name with unit altogether
  140. wxString GetFullRef() const
  141. {
  142. wxString refNum = m_numRefStr;
  143. if( refNum.IsEmpty() )
  144. refNum << m_numRef;
  145. if( GetSymbol()->GetUnitCount() > 1 )
  146. return GetRef() + refNum + GetSymbol()->SubReference( GetUnit() );
  147. else
  148. return GetRef() + refNum;
  149. }
  150. wxString GetRefNumber() const
  151. {
  152. wxString ref;
  153. if( m_numRef < 0 )
  154. return wxT( "?" );
  155. // To avoid a risk of duplicate, for power symbols the ref number is 0nnn instead of nnn.
  156. // Just because sometimes only power symbols are annotated
  157. if( GetLibPart() && GetLibPart()->IsPower() )
  158. ref = wxT( "0" );
  159. return ref << m_numRef;
  160. }
  161. int CompareValue( const SCH_REFERENCE& item ) const
  162. {
  163. return m_value.Cmp( item.m_value );
  164. }
  165. int CompareRef( const SCH_REFERENCE& item ) const
  166. {
  167. return m_ref.CmpNoCase( item.m_ref );
  168. }
  169. int CompareLibName( const SCH_REFERENCE& item ) const
  170. {
  171. return m_rootSymbol->GetLibId().GetLibItemName().compare(
  172. item.m_rootSymbol->GetLibId().GetLibItemName() );
  173. }
  174. /**
  175. * Return whether this reference refers to the same symbol instance (symbol and sheet) as
  176. * another.
  177. */
  178. bool IsSameInstance( const SCH_REFERENCE& other ) const
  179. {
  180. // Only compare symbol and path.
  181. // We may have changed the unit number or the designator but
  182. // can still be referencing the same instance.
  183. return GetSymbol() == other.GetSymbol()
  184. && GetSheetPath().Path() == other.GetSheetPath().Path();
  185. }
  186. bool IsUnitsLocked()
  187. {
  188. if( m_libPart )
  189. return m_libPart->UnitsLocked();
  190. else
  191. return true; // Assume units locked when we don't have a library
  192. }
  193. private:
  194. friend class SCH_REFERENCE_LIST;
  195. /// Symbol reference prefix, without number (for IC1, this is IC) )
  196. wxString m_ref; // it's private, use the accessors please
  197. SCH_SYMBOL* m_rootSymbol; ///< The symbol associated the reference object.
  198. LIB_SYMBOL* m_libPart; ///< The source symbol from a library.
  199. VECTOR2I m_symbolPos; ///< The physical position of the symbol in schematic
  200. ///< used to annotate by X or Y position
  201. int m_unit; ///< The unit number for symbol with multiple parts
  202. ///< per package.
  203. wxString m_value; ///< The symbol value.
  204. wxString m_footprint; ///< The footprint assigned.
  205. SCH_SHEET_PATH m_sheetPath; ///< The sheet path for this reference.
  206. bool m_isNew; ///< True if not yet annotated.
  207. int m_sheetNum; ///< The sheet number for the reference.
  208. KIID m_symbolUuid; ///< UUID of the symbol.
  209. int m_numRef; ///< The numeric part of the reference designator.
  210. wxString m_numRefStr; ///< The numeric part in original string form (may have leading zeroes)
  211. int m_flag;
  212. };
  213. /**
  214. * Define a standard error handler for annotation errors.
  215. */
  216. typedef std::function<void( ERCE_T aType, const wxString& aMsg, SCH_REFERENCE* aItemA,
  217. SCH_REFERENCE* aItemB )> ANNOTATION_ERROR_HANDLER;
  218. /**
  219. * Container to create a flattened list of symbols because in a complex hierarchy, a symbol
  220. * can be used more than once and its reference designator is dependent on the sheet path for
  221. * the same symbol.
  222. *
  223. * This flattened list is used for netlist generation, BOM generation, and schematic annotation.
  224. */
  225. class SCH_REFERENCE_LIST
  226. {
  227. public:
  228. SCH_REFERENCE_LIST()
  229. {
  230. }
  231. SCH_REFERENCE& operator[]( int aIndex )
  232. {
  233. return m_flatList[ aIndex ];
  234. }
  235. const SCH_REFERENCE& operator[]( int aIndex ) const
  236. {
  237. return m_flatList[ aIndex ];
  238. }
  239. void Clear()
  240. {
  241. m_flatList.clear();
  242. }
  243. size_t GetCount() const { return m_flatList.size(); }
  244. SCH_REFERENCE& GetItem( int aIdx ) { return m_flatList[aIdx]; }
  245. const SCH_REFERENCE& GetItem( int aIdx ) const { return m_flatList[aIdx]; }
  246. void AddItem( const SCH_REFERENCE& aItem ) { m_flatList.push_back( aItem ); }
  247. /**
  248. * Remove an item from the list of references.
  249. *
  250. * @param aIndex is the index of the item to be removed.
  251. */
  252. void RemoveItem( unsigned int aIndex );
  253. /**
  254. * Return true if aItem exists in this list
  255. * @param aItem Reference to check
  256. * @return true if aItem exists in this list
  257. */
  258. bool Contains( const SCH_REFERENCE& aItem ) const;
  259. /* Sort functions:
  260. * Sort functions are used to sort symbols for annotation or BOM generation. Because
  261. * sorting depends on what we want to do, there are many sort functions.
  262. * Note:
  263. * When creating BOM, symbols are fully annotated. References are something like U3,
  264. * U5 or R4, R8. When annotating, some or all symbols are not annotated, i.e. ref is
  265. * only U or R, with no number.
  266. */
  267. /**
  268. * Attempt to split all reference designators into a name (U) and number (1).
  269. *
  270. * If the last character is '?' or not a digit, the reference is tagged as not annotated.
  271. * For symbols with multiple parts, keeps the unit number intact
  272. * @see SCH_REFERENCE::Split()
  273. */
  274. void SplitReferences()
  275. {
  276. for( unsigned ii = 0; ii < GetCount(); ii++ )
  277. m_flatList[ii].Split();
  278. }
  279. /**
  280. * Treat all symbols in this list as non-annotated. Does not update annotation state of the
  281. * symbols.
  282. * @see SCH_REFERENCE_LIST::UpdateAnnotation
  283. */
  284. void RemoveAnnotation()
  285. {
  286. for( unsigned ii = 0; ii < GetCount(); ii++ )
  287. m_flatList[ii].m_isNew = true;
  288. }
  289. /**
  290. * Update the symbol references for the schematic project (or the current sheet).
  291. *
  292. * @note This function does not calculate the reference numbers stored in m_numRef so it
  293. * must be called after calculation of new reference numbers.
  294. *
  295. * @see SCH_REFERENCE::Annotate()
  296. */
  297. void UpdateAnnotation()
  298. {
  299. /* update the reference numbers */
  300. for( unsigned ii = 0; ii < GetCount(); ii++ )
  301. m_flatList[ii].Annotate();
  302. }
  303. /**
  304. * @brief Forces reannotation of the provided references. Will also reannotate
  305. * associated multi-unit symbols.
  306. *
  307. * @param aSortOption Define the annotation order. See #ANNOTATE_ORDER_T.
  308. * @param aAlgoOption Define the annotation style. See #ANNOTATE_ALGO_T.
  309. * @param aStartNumber The start number for non-sheet-based annotation styles.
  310. * @param aAdditionalReferences Additional references to check for duplicates
  311. * @param aStartAtCurrent Use m_numRef for each reference as the start number (overrides
  312. * aStartNumber)
  313. * @param aHierarchy Optional sheet path hierarchy for resetting the references'
  314. * sheet numbers based on their sheet's place in the hierarchy. Set
  315. * nullptr if not desired.
  316. */
  317. void ReannotateByOptions( ANNOTATE_ORDER_T aSortOption,
  318. ANNOTATE_ALGO_T aAlgoOption,
  319. int aStartNumber,
  320. const SCH_REFERENCE_LIST& aAdditionalRefs,
  321. bool aStartAtCurrent,
  322. SCH_SHEET_LIST* aHierarchy );
  323. /**
  324. * Convenience function for the Paste Unique functionality. Do not use as a general
  325. * reannotation method.
  326. *
  327. * Replaces any duplicate reference designators with the next available number after the
  328. * present number regardless of configured annotation options.
  329. *
  330. * Multi-unit symbols are reannotated together.
  331. */
  332. void ReannotateDuplicates( const SCH_REFERENCE_LIST& aAdditionalReferences );
  333. /**
  334. * Annotate the references by the provided options.
  335. *
  336. * @param aSortOption Define the annotation order. See #ANNOTATE_ORDER_T.
  337. * @param aAlgoOption Define the annotation style. See #ANNOTATE_ALGO_T.
  338. * @param aStartNumber The start number for non-sheet-based annotation styles.
  339. * @param appendUndo True if the annotation operation should be added to an existing undo,
  340. * false if it should be separately undo-able.
  341. * @param aLockedUnitMap A SCH_MULTI_UNIT_REFERENCE_MAP of reference designator wxStrings
  342. * to SCH_REFERENCE_LISTs. May be an empty map. If not empty, any multi-unit parts
  343. * found in this map will be annotated as a group rather than individually.
  344. * @param aAdditionalReferences Additional references to check for duplicates
  345. * @param aStartAtCurrent Use m_numRef for each reference as the start number (overrides
  346. * aStartNumber)
  347. */
  348. void AnnotateByOptions( enum ANNOTATE_ORDER_T aSortOption,
  349. enum ANNOTATE_ALGO_T aAlgoOption,
  350. int aStartNumber,
  351. SCH_MULTI_UNIT_REFERENCE_MAP aLockedUnitMap,
  352. const SCH_REFERENCE_LIST& aAdditionalRefs,
  353. bool aStartAtCurrent );
  354. /**
  355. * Set the reference designators in the list that have not been annotated.
  356. *
  357. * If a the sheet number is 2 and \a aSheetIntervalId is 100, then the first reference
  358. * designator would be 201 and the last reference designator would be 299 when no overlap
  359. * occurs with sheet number 3. If there are 150 items in sheet number 2, then items are
  360. * referenced U201 to U351, and items in sheet 3 start from U352
  361. *
  362. * @param aUseSheetNum Set to true to start annotation for each sheet at the sheet number
  363. * times \a aSheetIntervalId. Otherwise annotate incrementally.
  364. * @param aSheetIntervalId The per sheet reference designator multiplier.
  365. * @param aStartNumber The number to start with if NOT numbering based on sheet number.
  366. * @param aLockedUnitMap A SCH_MULTI_UNIT_REFERENCE_MAP of reference designator wxStrings
  367. * to SCH_REFERENCE_LISTs. May be an empty map. If not empty, any multi-unit parts
  368. * found in this map will be annotated as a group rather than individually.
  369. * @param aAdditionalRefs Additional references to use for checking that there a reference
  370. * designator doesn't already exist. The caller must ensure that none of the references
  371. * in aAdditionalRefs exist in this list.
  372. * @param aStartAtCurrent Use m_numRef for each reference as the start number (overrides
  373. aStartNumber)
  374. */
  375. void Annotate( bool aUseSheetNum, int aSheetIntervalId, int aStartNumber,
  376. SCH_MULTI_UNIT_REFERENCE_MAP aLockedUnitMap,
  377. const SCH_REFERENCE_LIST& aAdditionalRefs, bool aStartAtCurrent = false );
  378. /**
  379. * Check for annotations errors.
  380. *
  381. * The following annotation error conditions are tested:
  382. * - Symbols not annotated.
  383. * - Symbols having the same reference designator (duplicates).
  384. * - Symbols with multiple parts per package having different reference designators.
  385. * - Symbols with multiple parts per package with invalid part count.
  386. *
  387. * @param aErrorHandler A handler for errors.
  388. * @return The number of errors found.
  389. */
  390. int CheckAnnotation( ANNOTATION_ERROR_HANDLER aErrorHandler );
  391. /**
  392. * Sort the list of references by X position.
  393. *
  394. * Symbols are sorted as follows:
  395. * - Numeric value of reference designator.
  396. * - Sheet number.
  397. * - X coordinate position.
  398. * - Y coordinate position.
  399. * - Time stamp.
  400. */
  401. void SortByXCoordinate()
  402. {
  403. sort( m_flatList.begin(), m_flatList.end(), sortByXPosition );
  404. }
  405. /**
  406. * Sort the list of references by Y position.
  407. *
  408. * Symbols are sorted as follows:
  409. * - Numeric value of reference designator.
  410. * - Sheet number.
  411. * - Y coordinate position.
  412. * - X coordinate position.
  413. * - Time stamp.
  414. */
  415. void SortByYCoordinate()
  416. {
  417. sort( m_flatList.begin(), m_flatList.end(), sortByYPosition );
  418. }
  419. /**
  420. * Sort the flat list by Time Stamp (sheet path + timestamp).
  421. *
  422. * Useful to detect duplicate Time Stamps
  423. */
  424. void SortByTimeStamp()
  425. {
  426. sort( m_flatList.begin(), m_flatList.end(), sortByTimeStamp );
  427. }
  428. /**
  429. * Sort the list of references by value.
  430. *
  431. * Symbols are sorted in the following order:
  432. * - Numeric value of reference designator.
  433. * - Value of symbol.
  434. * - Unit number when symbol has multiple parts.
  435. * - Sheet number.
  436. * - X coordinate position.
  437. * - Y coordinate position.
  438. */
  439. void SortByRefAndValue()
  440. {
  441. sort( m_flatList.begin(), m_flatList.end(), sortByRefAndValue );
  442. }
  443. /**
  444. * Sort the list of references by reference.
  445. *
  446. * Symbols are sorted in the following order:
  447. * - Numeric value of reference designator.
  448. * - Unit number when symbol has multiple parts.
  449. */
  450. void SortByReferenceOnly()
  451. {
  452. sort( m_flatList.begin(), m_flatList.end(), sortByReferenceOnly );
  453. }
  454. /**
  455. * Search the list for a symbol with a given reference.
  456. */
  457. int FindRef( const wxString& aPath ) const;
  458. /**
  459. * Search the list for a symbol with the given KIID path (as string).
  460. *
  461. * @param aFullPath is the path of the symbol item to search.
  462. * @return an index in m_flatList if found or -1 if not found.
  463. */
  464. int FindRefByFullPath( const wxString& aFullPath ) const;
  465. /**
  466. * Add all the reference designator numbers greater than \a aMinRefId to \a aIdList
  467. * skipping the reference at \a aIndex.
  468. *
  469. * @param aIndex is the current symbol's index to use for reference prefix filtering.
  470. * @param aIdList is the buffer to fill.
  471. * @param aMinRefId is the minimum ID value to store. All values < aMinRefId are ignored.
  472. */
  473. void GetRefsInUse( int aIndex, std::vector<int>& aIdList, int aMinRefId ) const;
  474. /**
  475. * Return all the unit numbers for a given reference, comparing library reference, value,
  476. * reference number and reference prefix.
  477. *
  478. * @param aRef is the index of a symbol to use for reference prefix and number filtering.
  479. */
  480. std::vector<int> GetUnitsMatchingRef( const SCH_REFERENCE& aRef ) const;
  481. /**
  482. * Return the first unused reference number from the properties given in aRef, ensuring
  483. * all of the units in aRequiredUnits are also unused.
  484. *
  485. * @param aIndex The index of the reference item used for the search pattern.
  486. * @param aMinValue The minimum value for the current search.
  487. * @param aRequiredUnits List of units to ensure are free
  488. */
  489. int FindFirstUnusedReference( const SCH_REFERENCE& aRef, int aMinValue,
  490. const std::vector<int>& aRequiredUnits ) const;
  491. std::vector<SCH_SYMBOL_INSTANCE> GetSymbolInstances() const;
  492. #if defined(DEBUG)
  493. void Show( const char* aPrefix = "" );
  494. #endif
  495. /**
  496. * Return a shorthand string representing all the references in the list. For instance,
  497. * "R1, R2, R4 - R7, U1"
  498. * @param spaced Add spaces between references
  499. */
  500. static wxString Shorthand( std::vector<SCH_REFERENCE> aList, const wxString& refDelimiter,
  501. const wxString& refRangeDelimiter );
  502. friend class BACK_ANNOTATION;
  503. typedef std::vector<SCH_REFERENCE>::iterator iterator;
  504. typedef std::vector<SCH_REFERENCE>::const_iterator const_iterator;
  505. iterator begin() { return m_flatList.begin(); }
  506. iterator end() { return m_flatList.end(); }
  507. const_iterator begin() const { return m_flatList.begin(); }
  508. const_iterator end() const { return m_flatList.end(); }
  509. iterator erase( iterator position ) { return m_flatList.erase( position ); }
  510. iterator erase( iterator first, iterator last ) { return m_flatList.erase( first, last ); }
  511. private:
  512. static bool sortByRefAndValue( const SCH_REFERENCE& item1, const SCH_REFERENCE& item2 );
  513. static bool sortByXPosition( const SCH_REFERENCE& item1, const SCH_REFERENCE& item2 );
  514. static bool sortByYPosition( const SCH_REFERENCE& item1, const SCH_REFERENCE& item2 );
  515. static bool sortByTimeStamp( const SCH_REFERENCE& item1, const SCH_REFERENCE& item2 );
  516. static bool sortByReferenceOnly( const SCH_REFERENCE& item1, const SCH_REFERENCE& item2 );
  517. /**
  518. * Search for the first free reference number in \a aListId of reference numbers in use.
  519. *
  520. * This function just searches for a hole in a list of incremented numbers, this list must
  521. * be sorted by increasing values and each value can be stored only once. The new value
  522. * is added to the list.
  523. *
  524. * @see BuildRefIdInUseList to prepare this list
  525. * @param aIdList The buffer that contains the reference numbers in use.
  526. * @param aFirstValue The first expected free value
  527. * @return The first free (not yet used) value.
  528. */
  529. static int createFirstFreeRefId( std::vector<int>& aIdList, int aFirstValue );
  530. // Used for sorting static sortByTimeStamp function
  531. friend class BACK_ANNOTATE;
  532. std::vector<SCH_REFERENCE> m_flatList;
  533. };
  534. #endif // _SCH_REFERENCE_LIST_H_