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.

362 lines
12 KiB

Fix issues with zone filling connectivity locking Two issues found with the locking system used to prevent access to stale connectivity data during the zone fill process: 1) a std::mutex has undefined behavior if you try to use it to guard against access from the same thread. Because of the use of wx event loops (and coroutines) it is entirely possible, and in some situations inevitable, that the same thread will try to redraw the ratsnest in the middle of zone refilling. 2) The mutex was only guarding the ZONE_FILLER::Fill method, but the callers of that method also do connectivity updates as part of the COMMIT::Push. Redrawing the ratsnest after the Fill but before the Push will result in stale connectivity pointers to zone filled areas. Fixed (1) by switching to a trivial spinlock implementation. Spinlocks would generally not be desirable if the contention for the connectivity data crossed thread boundaries, but at the moment I believe it's guaranteed that the reads and writes to connectivity that are guarded by this lock happen from the main UI thread. The writes are also quite rare compared to reads, and reads are generally fast, so I'm not really worried about the UI thread spinning for any real amount of time. Fixed (2) by moving the locking location up to the call sites of ZONE_FILLER::Fill. This issue was quite difficult to reproduce, but I found a fairly reliable way: It only happens (for me) on Windows, MSYS2 build, with wxWidgets 3.0 It also only happens if I restrict PcbNew to use 2 CPU cores. With those conditions, I can reproduce the issue described in #6471 by repeatedly editing a zone properties and changing its net. The crash is especially easy to trigger if you press some keys (such as 'e' for edit) while the progress dialog is displayed. It's easiest to do this in a debug build as the slower KiCad is running, the bigger the window is to trigger this bug. Fixes https://gitlab.com/kicad/code/kicad/-/issues/6471 Fixes https://gitlab.com/kicad/code/kicad/-/issues/7048
5 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
Fix issues with zone filling connectivity locking Two issues found with the locking system used to prevent access to stale connectivity data during the zone fill process: 1) a std::mutex has undefined behavior if you try to use it to guard against access from the same thread. Because of the use of wx event loops (and coroutines) it is entirely possible, and in some situations inevitable, that the same thread will try to redraw the ratsnest in the middle of zone refilling. 2) The mutex was only guarding the ZONE_FILLER::Fill method, but the callers of that method also do connectivity updates as part of the COMMIT::Push. Redrawing the ratsnest after the Fill but before the Push will result in stale connectivity pointers to zone filled areas. Fixed (1) by switching to a trivial spinlock implementation. Spinlocks would generally not be desirable if the contention for the connectivity data crossed thread boundaries, but at the moment I believe it's guaranteed that the reads and writes to connectivity that are guarded by this lock happen from the main UI thread. The writes are also quite rare compared to reads, and reads are generally fast, so I'm not really worried about the UI thread spinning for any real amount of time. Fixed (2) by moving the locking location up to the call sites of ZONE_FILLER::Fill. This issue was quite difficult to reproduce, but I found a fairly reliable way: It only happens (for me) on Windows, MSYS2 build, with wxWidgets 3.0 It also only happens if I restrict PcbNew to use 2 CPU cores. With those conditions, I can reproduce the issue described in #6471 by repeatedly editing a zone properties and changing its net. The crash is especially easy to trigger if you press some keys (such as 'e' for edit) while the progress dialog is displayed. It's easiest to do this in a debug build as the slower KiCad is running, the bigger the window is to trigger this bug. Fixes https://gitlab.com/kicad/code/kicad/-/issues/6471 Fixes https://gitlab.com/kicad/code/kicad/-/issues/7048
5 years ago
  1. /*
  2. * This program source code file is part of KiCad, a free EDA CAD application.
  3. *
  4. * Copyright (C) 2017-2023 KiCad Developers, see AUTHORS.txt for contributors.
  5. *
  6. * This program is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU General Public License
  8. * as published by the Free Software Foundation; either version 2
  9. * of the License, or (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program; if not, you may find one here:
  18. * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
  19. * or you may search the http://www.gnu.org website for the version 2 license,
  20. * or you may write to the Free Software Foundation, Inc.,
  21. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
  22. */
  23. #include <core/spinlock.h>
  24. #include <connectivity/connectivity_data.h>
  25. #include <tools/zone_create_helper.h>
  26. #include <tool/tool_manager.h>
  27. #include <zone.h>
  28. #include <pcb_shape.h>
  29. #include <footprint.h>
  30. #include <board_commit.h>
  31. #include <board_design_settings.h>
  32. #include <pcb_painter.h>
  33. #include <tools/pcb_actions.h>
  34. #include <tools/pcb_selection_tool.h>
  35. ZONE_CREATE_HELPER::ZONE_CREATE_HELPER( DRAWING_TOOL& aTool, PARAMS& aParams ):
  36. m_tool( aTool ),
  37. m_params( aParams ),
  38. m_parentView( *aTool.getView() )
  39. {
  40. m_parentView.Add( &m_previewItem );
  41. }
  42. ZONE_CREATE_HELPER::~ZONE_CREATE_HELPER()
  43. {
  44. // remove the preview from the view
  45. m_parentView.SetVisible( &m_previewItem, false );
  46. m_parentView.Remove( &m_previewItem );
  47. }
  48. void ZONE_CREATE_HELPER::setUniquePriority( ZONE_SETTINGS& aZoneInfo )
  49. {
  50. PCB_BASE_EDIT_FRAME* frame = m_tool.getEditFrame<PCB_BASE_EDIT_FRAME>();
  51. BOARD* board = frame->GetBoard();
  52. // By default, new zones get the first unused priority
  53. std::set<unsigned> priorities;
  54. for( ZONE* zone : board->Zones() )
  55. {
  56. if( zone->GetTeardropAreaType() == TEARDROP_TYPE::TD_NONE
  57. && ( zone->GetLayerSet() & LSET::AllCuMask() ).any()
  58. && !zone->GetIsRuleArea() )
  59. {
  60. priorities.insert( zone->GetAssignedPriority() );
  61. }
  62. }
  63. unsigned priority = 0;
  64. for( unsigned exist_priority : priorities )
  65. {
  66. if( priority != exist_priority )
  67. break;
  68. ++priority;
  69. }
  70. aZoneInfo.m_ZonePriority = priority;
  71. }
  72. std::unique_ptr<ZONE> ZONE_CREATE_HELPER::createNewZone( bool aKeepout )
  73. {
  74. PCB_BASE_EDIT_FRAME* frame = m_tool.getEditFrame<PCB_BASE_EDIT_FRAME>();
  75. BOARD* board = frame->GetBoard();
  76. BOARD_ITEM_CONTAINER* parent = m_tool.m_frame->GetModel();
  77. KIGFX::VIEW_CONTROLS* controls = m_tool.GetManager()->GetViewControls();
  78. std::set<int> highlightedNets = board->GetHighLightNetCodes();
  79. // Get the current default settings for zones
  80. ZONE_SETTINGS zoneInfo = board->GetDesignSettings().GetDefaultZoneSettings();
  81. zoneInfo.m_Layers.reset().set( m_params.m_layer ); // TODO(JE) multilayer defaults?
  82. zoneInfo.m_NetcodeSelection = highlightedNets.empty() ? -1 : *highlightedNets.begin();
  83. zoneInfo.SetIsRuleArea( m_params.m_keepout );
  84. if( m_params.m_mode != ZONE_MODE::GRAPHIC_POLYGON
  85. && ( zoneInfo.m_Layers & LSET::AllCuMask() ).any() )
  86. {
  87. setUniquePriority( zoneInfo );
  88. }
  89. // If we don't have a net from highlighting, maybe we can get one from the selection
  90. PCB_SELECTION_TOOL* selectionTool = m_tool.GetManager()->GetTool<PCB_SELECTION_TOOL>();
  91. if( selectionTool && !selectionTool->GetSelection().Empty()
  92. && zoneInfo.m_NetcodeSelection == -1 )
  93. {
  94. EDA_ITEM* item = *selectionTool->GetSelection().GetItems().begin();
  95. if( BOARD_CONNECTED_ITEM* bci = dynamic_cast<BOARD_CONNECTED_ITEM*>( item ) )
  96. zoneInfo.m_NetcodeSelection = bci->GetNetCode();
  97. }
  98. if( m_params.m_mode != ZONE_MODE::GRAPHIC_POLYGON )
  99. {
  100. // Show options dialog
  101. int dialogResult;
  102. if( m_params.m_keepout )
  103. dialogResult = InvokeRuleAreaEditor( frame, &zoneInfo );
  104. else if( ( zoneInfo.m_Layers & LSET::AllCuMask() ).any() )
  105. dialogResult = InvokeCopperZonesEditor( frame, &zoneInfo );
  106. else
  107. dialogResult = InvokeNonCopperZonesEditor( frame, &zoneInfo );
  108. if( dialogResult == wxID_CANCEL )
  109. return nullptr;
  110. controls->WarpMouseCursor( controls->GetCursorPosition(), true );
  111. frame->GetCanvas()->SetFocus();
  112. }
  113. wxASSERT( !m_tool.m_isFootprintEditor || ( parent->Type() == PCB_FOOTPRINT_T ) );
  114. std::unique_ptr<ZONE> newZone = std::make_unique<ZONE>( parent );
  115. // Apply the selected settings
  116. zoneInfo.ExportSetting( *newZone );
  117. return newZone;
  118. }
  119. std::unique_ptr<ZONE> ZONE_CREATE_HELPER::createZoneFromExisting( const ZONE& aSrcZone )
  120. {
  121. BOARD* board = m_tool.getModel<BOARD>();
  122. std::unique_ptr<ZONE> newZone = std::make_unique<ZONE>( board );
  123. ZONE_SETTINGS zoneSettings;
  124. zoneSettings << aSrcZone;
  125. zoneSettings.ExportSetting( *newZone );
  126. return newZone;
  127. }
  128. void ZONE_CREATE_HELPER::performZoneCutout( ZONE& aZone, const ZONE& aCutout )
  129. {
  130. BOARD_COMMIT commit( &m_tool );
  131. std::vector<ZONE*> newZones;
  132. // Clear the selection before removing the old zone
  133. auto toolMgr = m_tool.GetManager();
  134. toolMgr->RunAction( PCB_ACTIONS::selectionClear );
  135. SHAPE_POLY_SET originalOutline( *aZone.Outline() );
  136. originalOutline.BooleanSubtract( *aCutout.Outline(), SHAPE_POLY_SET::PM_FAST );
  137. // After substracting the hole, originalOutline can have more than one main outline.
  138. // But a zone can have only one main outline, so create as many zones as originalOutline
  139. // contains main outlines:
  140. for( int outline = 0; outline < originalOutline.OutlineCount(); outline++ )
  141. {
  142. auto newZoneOutline = new SHAPE_POLY_SET;
  143. newZoneOutline->AddOutline( originalOutline.Outline( outline ) );
  144. // Add holes (if any) to the new zone outline:
  145. for (int hole = 0; hole < originalOutline.HoleCount( outline ) ; hole++ )
  146. newZoneOutline->AddHole( originalOutline.CHole( outline, hole ) );
  147. auto newZone = new ZONE( aZone );
  148. newZone->SetOutline( newZoneOutline );
  149. newZone->SetLocalFlags( 1 );
  150. newZone->HatchBorder();
  151. newZone->UnFill();
  152. newZones.push_back( newZone );
  153. commit.Add( newZone );
  154. }
  155. commit.Remove( &aZone );
  156. commit.Push( _( "Add Zone Cutout" ) );
  157. // Select the new zone and set it as the source for the next cutout
  158. if( newZones.empty() )
  159. {
  160. m_params.m_sourceZone = nullptr;
  161. }
  162. else
  163. {
  164. m_params.m_sourceZone = newZones[0];
  165. toolMgr->RunAction<EDA_ITEM*>( PCB_ACTIONS::selectItem, newZones[0] );
  166. }
  167. }
  168. void ZONE_CREATE_HELPER::commitZone( std::unique_ptr<ZONE> aZone )
  169. {
  170. switch ( m_params.m_mode )
  171. {
  172. case ZONE_MODE::CUTOUT:
  173. // For cutouts, subtract from the source
  174. performZoneCutout( *m_params.m_sourceZone, *aZone );
  175. break;
  176. case ZONE_MODE::ADD:
  177. case ZONE_MODE::SIMILAR:
  178. {
  179. BOARD_COMMIT commit( &m_tool );
  180. aZone->HatchBorder();
  181. commit.Add( aZone.get() );
  182. commit.Push( _( "Add a zone" ) );
  183. m_tool.GetManager()->RunAction<EDA_ITEM*>( PCB_ACTIONS::selectItem, aZone.release() );
  184. break;
  185. }
  186. case ZONE_MODE::GRAPHIC_POLYGON:
  187. {
  188. BOARD_COMMIT commit( &m_tool );
  189. BOARD* board = m_tool.getModel<BOARD>();
  190. PCB_LAYER_ID layer = m_params.m_layer;
  191. PCB_SHAPE* poly = new PCB_SHAPE( m_tool.m_frame->GetModel() );
  192. poly->SetShape( SHAPE_T::POLY );
  193. poly->SetFilled( layer != Edge_Cuts && layer != F_CrtYd && layer != B_CrtYd );
  194. poly->SetStroke( STROKE_PARAMS( board->GetDesignSettings().GetLineThickness( layer ),
  195. LINE_STYLE::SOLID ) );
  196. poly->SetLayer( layer );
  197. poly->SetPolyShape( *aZone->Outline() );
  198. commit.Add( poly );
  199. commit.Push( _( "Add Polygon" ) );
  200. m_tool.GetManager()->RunAction<EDA_ITEM*>( PCB_ACTIONS::selectItem, poly );
  201. break;
  202. }
  203. }
  204. }
  205. bool ZONE_CREATE_HELPER::OnFirstPoint( POLYGON_GEOM_MANAGER& aMgr )
  206. {
  207. // if we don't have a zone, create one
  208. if( !m_zone )
  209. {
  210. if( m_params.m_sourceZone )
  211. m_zone = createZoneFromExisting( *m_params.m_sourceZone );
  212. else
  213. m_zone = createNewZone( m_params.m_keepout );
  214. if( m_zone )
  215. {
  216. m_tool.GetManager()->RunAction( PCB_ACTIONS::selectionClear );
  217. // set up properties from zone
  218. const auto& settings = *m_parentView.GetPainter()->GetSettings();
  219. COLOR4D color = settings.GetColor( nullptr, m_zone->GetFirstLayer() );
  220. m_previewItem.SetStrokeColor( COLOR4D::WHITE );
  221. m_previewItem.SetFillColor( color.WithAlpha( 0.2 ) );
  222. m_parentView.SetVisible( &m_previewItem, true );
  223. aMgr.SetLeaderMode( m_tool.Is45Limited() ? POLYGON_GEOM_MANAGER::LEADER_MODE::DEG45
  224. : POLYGON_GEOM_MANAGER::LEADER_MODE::DIRECT );
  225. }
  226. }
  227. return m_zone != nullptr;
  228. }
  229. void ZONE_CREATE_HELPER::OnGeometryChange( const POLYGON_GEOM_MANAGER& aMgr )
  230. {
  231. // Handle a cancel-interactive
  232. if( m_zone && !aMgr.IsPolygonInProgress() )
  233. {
  234. m_zone = nullptr;
  235. m_parentView.SetVisible( &m_previewItem, false );
  236. return;
  237. }
  238. // send the points to the preview item
  239. m_previewItem.SetPoints( aMgr.GetLockedInPoints(), aMgr.GetLeaderLinePoints(),
  240. aMgr.GetLoopLinePoints() );
  241. m_parentView.Update( &m_previewItem, KIGFX::GEOMETRY );
  242. }
  243. void ZONE_CREATE_HELPER::OnComplete( const POLYGON_GEOM_MANAGER& aMgr )
  244. {
  245. auto& finalPoints = aMgr.GetLockedInPoints();
  246. if( finalPoints.PointCount() < 3 )
  247. {
  248. // just scrap the zone in progress
  249. m_zone = nullptr;
  250. }
  251. else
  252. {
  253. // if m_params.m_mode == DRAWING_TOOL::ZONE_MODE::CUTOUT, m_zone will be merged to the
  254. // existing zone as a new hole.
  255. m_zone->Outline()->NewOutline();
  256. auto* outline = m_zone->Outline();
  257. for( int i = 0; i < finalPoints.PointCount(); ++i )
  258. outline->Append( finalPoints.CPoint( i ) );
  259. // In DEG45 mode, we may have intermediate points in the leader that should be included
  260. // as they are shown in the preview. These typically maintain the 45 constraint
  261. if( aMgr.GetLeaderMode() == POLYGON_GEOM_MANAGER::LEADER_MODE::DEG45 )
  262. {
  263. const SHAPE_LINE_CHAIN leaderPts = aMgr.GetLeaderLinePoints();
  264. for( int i = 1; i < leaderPts.PointCount(); i++ )
  265. outline->Append( leaderPts.CPoint( i ) );
  266. const SHAPE_LINE_CHAIN loopPts = aMgr.GetLoopLinePoints();
  267. for( int i = 1; i < loopPts.PointCount() - 1; i++ )
  268. outline->Append( loopPts.CPoint( i ) );
  269. }
  270. SHAPE_LINE_CHAIN& chain = outline->Outline( 0 );
  271. chain.SetClosed( true );
  272. chain.Simplify( true );
  273. // Remove the start point if it lies on the line between neighbouring points.
  274. // Simplify doesn't handle that currently.
  275. if( chain.PointCount() >= 3 )
  276. {
  277. SEG seg( chain.CPoint( -1 ), chain.CPoint( 1 ) );
  278. if( seg.LineDistance( chain.CPoint( 0 ) ) <= 1 )
  279. chain.Remove( 0 );
  280. }
  281. // hand the zone over to the committer
  282. commitZone( std::move( m_zone ) );
  283. m_zone = nullptr;
  284. }
  285. m_parentView.SetVisible( &m_previewItem, false );
  286. }