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.

613 lines
20 KiB

18 years ago
18 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
  1. /*
  2. * This program source code file is part of KiCad, a free EDA CAD application.
  3. *
  4. * Copyright (C) 2019-2021 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-3.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. /**
  24. * @file pcbnew/cross-probing.cpp
  25. * @brief Cross probing functions to handle communication to and from Eeschema.
  26. * Handle messages between Pcbnew and Eeschema via a socket, the port numbers are
  27. * KICAD_PCB_PORT_SERVICE_NUMBER (currently 4242) (Eeschema to Pcbnew)
  28. * KICAD_SCH_PORT_SERVICE_NUMBER (currently 4243) (Pcbnew to Eeschema)
  29. * Note: these ports must be enabled for firewall protection
  30. */
  31. #include <board.h>
  32. #include <board_design_settings.h>
  33. #include <footprint.h>
  34. #include <pad.h>
  35. #include <pcb_track.h>
  36. #include <zone.h>
  37. #include <collectors.h>
  38. #include <eda_dde.h>
  39. #include <kiface_base.h>
  40. #include <kiway_express.h>
  41. #include <netlist_reader/pcb_netlist.h>
  42. #include <netlist_reader/board_netlist_updater.h>
  43. #include <painter.h>
  44. #include <pcb_edit_frame.h>
  45. #include <pcbnew_settings.h>
  46. #include <render_settings.h>
  47. #include <tool/tool_manager.h>
  48. #include <tools/pcb_actions.h>
  49. #include <tools/pcb_selection_tool.h>
  50. #include <netlist_reader/netlist_reader.h>
  51. #include <wx/log.h>
  52. /* Execute a remote command send by Eeschema via a socket,
  53. * port KICAD_PCB_PORT_SERVICE_NUMBER
  54. * cmdline = received command from Eeschema
  55. * Commands are
  56. * $PART: "reference" put cursor on component
  57. * $PIN: "pin name" $PART: "reference" put cursor on the footprint pin
  58. * $NET: "net name" highlight the given net (if highlight tool is active)
  59. * $CLEAR Clear existing highlight
  60. * They are a keyword followed by a quoted string.
  61. */
  62. void PCB_EDIT_FRAME::ExecuteRemoteCommand( const char* cmdline )
  63. {
  64. char line[1024];
  65. wxString msg;
  66. wxString modName;
  67. char* idcmd;
  68. char* text;
  69. int netcode = -1;
  70. bool multiHighlight = false;
  71. FOOTPRINT* footprint = nullptr;
  72. PAD* pad = nullptr;
  73. BOARD* pcb = GetBoard();
  74. CROSS_PROBING_SETTINGS& crossProbingSettings = GetPcbNewSettings()->m_CrossProbing;
  75. KIGFX::VIEW* view = m_toolManager->GetView();
  76. KIGFX::RENDER_SETTINGS* renderSettings = view->GetPainter()->GetSettings();
  77. strncpy( line, cmdline, sizeof(line) - 1 );
  78. line[sizeof(line) - 1] = 0;
  79. idcmd = strtok( line, " \n\r" );
  80. text = strtok( nullptr, "\"\n\r" );
  81. if( idcmd == nullptr )
  82. return;
  83. if( strcmp( idcmd, "$NET:" ) == 0 )
  84. {
  85. if( !crossProbingSettings.auto_highlight )
  86. return;
  87. wxString net_name = FROM_UTF8( text );
  88. NETINFO_ITEM* netinfo = pcb->FindNet( net_name );
  89. if( netinfo )
  90. {
  91. netcode = netinfo->GetNetCode();
  92. std::vector<MSG_PANEL_ITEM> items;
  93. netinfo->GetMsgPanelInfo( this, items );
  94. SetMsgPanel( items );
  95. }
  96. }
  97. if( strcmp( idcmd, "$NETS:" ) == 0 )
  98. {
  99. if( !crossProbingSettings.auto_highlight )
  100. return;
  101. wxStringTokenizer netsTok = wxStringTokenizer( FROM_UTF8( text ), "," );
  102. bool first = true;
  103. while( netsTok.HasMoreTokens() )
  104. {
  105. NETINFO_ITEM* netinfo = pcb->FindNet( netsTok.GetNextToken() );
  106. if( netinfo )
  107. {
  108. if( first )
  109. {
  110. // TODO: Once buses are included in netlist, show bus name
  111. std::vector<MSG_PANEL_ITEM> items;
  112. netinfo->GetMsgPanelInfo( this, items );
  113. SetMsgPanel( items );
  114. first = false;
  115. pcb->SetHighLightNet( netinfo->GetNetCode() );
  116. renderSettings->SetHighlight( true, netinfo->GetNetCode() );
  117. multiHighlight = true;
  118. }
  119. else
  120. {
  121. pcb->SetHighLightNet( netinfo->GetNetCode(), true );
  122. renderSettings->SetHighlight( true, netinfo->GetNetCode(), true );
  123. }
  124. }
  125. }
  126. netcode = -1;
  127. }
  128. else if( strcmp( idcmd, "$PIN:" ) == 0 )
  129. {
  130. wxString pinName = FROM_UTF8( text );
  131. text = strtok( nullptr, " \n\r" );
  132. if( text && strcmp( text, "$PART:" ) == 0 )
  133. text = strtok( nullptr, "\"\n\r" );
  134. modName = FROM_UTF8( text );
  135. footprint = pcb->FindFootprintByReference( modName );
  136. if( footprint )
  137. pad = footprint->FindPadByNumber( pinName );
  138. if( pad )
  139. netcode = pad->GetNetCode();
  140. if( footprint == nullptr )
  141. msg.Printf( _( "%s not found" ), modName );
  142. else if( pad == nullptr )
  143. msg.Printf( _( "%s pin %s not found" ), modName, pinName );
  144. else
  145. msg.Printf( _( "%s pin %s found" ), modName, pinName );
  146. SetStatusText( msg );
  147. }
  148. else if( strcmp( idcmd, "$PART:" ) == 0 )
  149. {
  150. pcb->ResetNetHighLight();
  151. modName = FROM_UTF8( text );
  152. footprint = pcb->FindFootprintByReference( modName );
  153. if( footprint )
  154. msg.Printf( _( "%s found" ), modName );
  155. else
  156. msg.Printf( _( "%s not found" ), modName );
  157. SetStatusText( msg );
  158. }
  159. else if( strcmp( idcmd, "$SHEET:" ) == 0 )
  160. {
  161. msg.Printf( _( "Selecting all from sheet \"%s\"" ), FROM_UTF8( text ) );
  162. wxString sheetUIID( FROM_UTF8( text ) );
  163. SetStatusText( msg );
  164. GetToolManager()->RunAction( PCB_ACTIONS::selectOnSheetFromEeschema, true,
  165. static_cast<void*>( &sheetUIID ) );
  166. return;
  167. }
  168. else if( strcmp( idcmd, "$CLEAR" ) == 0 )
  169. {
  170. if( renderSettings->IsHighlightEnabled() )
  171. {
  172. renderSettings->SetHighlight( false );
  173. view->UpdateAllLayersColor();
  174. }
  175. if( pcb->IsHighLightNetON() )
  176. {
  177. pcb->ResetNetHighLight();
  178. SetMsgPanel( pcb );
  179. }
  180. GetCanvas()->Refresh();
  181. return;
  182. }
  183. BOX2I bbox = { { 0, 0 }, { 0, 0 } };
  184. if( footprint )
  185. {
  186. bbox = footprint->GetBoundingBox( true, false ); // No invisible text in bbox calc
  187. if( pad )
  188. m_toolManager->RunAction( PCB_ACTIONS::highlightItem, true, (void*) pad );
  189. else
  190. m_toolManager->RunAction( PCB_ACTIONS::highlightItem, true, (void*) footprint );
  191. }
  192. else if( netcode > 0 || multiHighlight )
  193. {
  194. if( !multiHighlight )
  195. {
  196. renderSettings->SetHighlight( ( netcode >= 0 ), netcode );
  197. pcb->SetHighLightNet( netcode );
  198. }
  199. else
  200. {
  201. // Just pick the first one for area calculation
  202. netcode = *pcb->GetHighLightNetCodes().begin();
  203. }
  204. pcb->HighLightON();
  205. auto merge_area =
  206. [netcode, &bbox]( BOARD_CONNECTED_ITEM* aItem )
  207. {
  208. if( aItem->GetNetCode() == netcode )
  209. {
  210. if( bbox.GetWidth() == 0 )
  211. bbox = aItem->GetBoundingBox();
  212. else
  213. bbox.Merge( aItem->GetBoundingBox() );
  214. }
  215. };
  216. if( crossProbingSettings.center_on_items )
  217. {
  218. for( ZONE* zone : pcb->Zones() )
  219. merge_area( zone );
  220. for( PCB_TRACK* track : pcb->Tracks() )
  221. merge_area( track );
  222. for( FOOTPRINT* fp : pcb->Footprints() )
  223. {
  224. for( PAD* p : fp->Pads() )
  225. merge_area( p );
  226. }
  227. }
  228. }
  229. else
  230. {
  231. renderSettings->SetHighlight( false );
  232. }
  233. if( crossProbingSettings.center_on_items && bbox.GetWidth() > 0 && bbox.GetHeight() > 0 )
  234. {
  235. if( crossProbingSettings.zoom_to_fit )
  236. {
  237. //#define DEFAULT_PCBNEW_CODE // Un-comment for normal full zoom KiCad algorithm
  238. #ifdef DEFAULT_PCBNEW_CODE
  239. auto bbSize = bbox.Inflate( bbox.GetWidth() * 0.2f ).GetSize();
  240. auto screenSize = view->ToWorld( GetCanvas()->GetClientSize(), false );
  241. // The "fabs" on x ensures the right answer when the view is flipped
  242. screenSize.x = std::max( 10.0, fabs( screenSize.x ) );
  243. screenSize.y = std::max( 10.0, screenSize.y );
  244. double ratio = std::max( fabs( bbSize.x / screenSize.x ),
  245. fabs( bbSize.y / screenSize.y ) );
  246. // Try not to zoom on every cross-probe; it gets very noisy
  247. if( crossProbingSettings.zoom_to_fit && ( ratio < 0.5 || ratio > 1.0 ) )
  248. view->SetScale( view->GetScale() / ratio );
  249. #endif // DEFAULT_PCBNEW_CODE
  250. #ifndef DEFAULT_PCBNEW_CODE // Do the scaled zoom
  251. auto bbSize = bbox.Inflate( bbox.GetWidth() * 0.2f ).GetSize();
  252. auto screenSize = view->ToWorld( GetCanvas()->GetClientSize(), false );
  253. // This code tries to come up with a zoom factor that doesn't simply zoom in
  254. // to the cross probed component, but instead shows a reasonable amount of the
  255. // circuit around it to provide context. This reduces or eliminates the need
  256. // to manually change the zoom because it's too close.
  257. // Using the default text height as a constant to compare against, use the
  258. // height of the bounding box of visible items for a footprint to figure out
  259. // if this is a big footprint (like a processor) or a small footprint (like a resistor).
  260. // This ratio is not useful by itself as a scaling factor. It must be "bent" to
  261. // provide good scaling at varying component sizes. Bigger components need less
  262. // scaling than small ones.
  263. double currTextHeight = Millimeter2iu( DEFAULT_TEXT_SIZE );
  264. double compRatio = bbSize.y / currTextHeight; // Ratio of component to text height
  265. // This will end up as the scaling factor we apply to "ratio".
  266. double compRatioBent = 1.0;
  267. // This is similar to the original KiCad code that scaled the zoom to make sure
  268. // components were visible on screen. It's simply a ratio of screen size to
  269. // component size, and its job is to zoom in to make the component fullscreen.
  270. // Earlier in the code the component BBox is given a 20% margin to add some
  271. // breathing room. We compare the height of this enlarged component bbox to the
  272. // default text height. If a component will end up with the sides clipped, we
  273. // adjust later to make sure it fits on screen.
  274. //
  275. // The "fabs" on x ensures the right answer when the view is flipped
  276. screenSize.x = std::max( 10.0, fabs( screenSize.x ) );
  277. screenSize.y = std::max( 10.0, screenSize.y );
  278. double ratio = std::max( -1.0, fabs( bbSize.y / screenSize.y ) );
  279. // Original KiCad code for how much to scale the zoom
  280. double kicadRatio = std::max( fabs( bbSize.x / screenSize.x ),
  281. fabs( bbSize.y / screenSize.y ) );
  282. // LUT to scale zoom ratio to provide reasonable schematic context. Must work
  283. // with footprints of varying sizes (e.g. 0402 package and 200 pin BGA).
  284. // "first" is used as the input and "second" as the output
  285. //
  286. // "first" = compRatio (footprint height / default text height)
  287. // "second" = Amount to scale ratio by
  288. std::vector<std::pair<double, double>> lut{
  289. { 1, 8 },
  290. { 1.5, 5 },
  291. { 3, 3 },
  292. { 4.5, 2.5 },
  293. { 8, 2.0 },
  294. { 12, 1.7 },
  295. { 16, 1.5 },
  296. { 24, 1.3 },
  297. { 32, 1.0 },
  298. };
  299. std::vector<std::pair<double, double>>::iterator it;
  300. compRatioBent = lut.back().second; // Large component default
  301. if( compRatio >= lut.front().first )
  302. {
  303. // Use LUT to do linear interpolation of "compRatio" within "first", then
  304. // use that result to linearly interpolate "second" which gives the scaling
  305. // factor needed.
  306. for( it = lut.begin(); it < lut.end() - 1; it++ )
  307. {
  308. if( it->first <= compRatio && next( it )->first >= compRatio )
  309. {
  310. double diffx = compRatio - it->first;
  311. double diffn = next( it )->first - it->first;
  312. compRatioBent =
  313. it->second + ( next( it )->second - it->second ) * diffx / diffn;
  314. break; // We have our interpolated value
  315. }
  316. }
  317. }
  318. else
  319. {
  320. compRatioBent = lut.front().second; // Small component default
  321. }
  322. // If the width of the part we're probing is bigger than what the screen width will be
  323. // after the zoom, then punt and use the KiCad zoom algorithm since it guarantees the
  324. // part's width will be encompassed within the screen. This will apply to parts that
  325. // are much wider than they are tall.
  326. if( bbSize.x > screenSize.x * ratio * compRatioBent )
  327. {
  328. // Use standard KiCad zoom algorithm for parts too wide to fit screen/
  329. ratio = kicadRatio;
  330. compRatioBent = 1.0; // Reset so we don't modify the "KiCad" ratio
  331. wxLogTrace( "CROSS_PROBE_SCALE",
  332. "Part TOO WIDE for screen. Using normal KiCad zoom ratio: %1.5f",
  333. ratio );
  334. }
  335. // Now that "compRatioBent" holds our final scaling factor we apply it to the original
  336. // fullscreen zoom ratio to arrive at the final ratio itself.
  337. ratio *= compRatioBent;
  338. bool alwaysZoom = false; // DEBUG - allows us to minimize zooming or not
  339. // Try not to zoom on every cross-probe; it gets very noisy
  340. if( ( ratio < 0.5 || ratio > 1.0 ) || alwaysZoom )
  341. view->SetScale( view->GetScale() / ratio );
  342. #endif // ifndef DEFAULT_PCBNEW_CODE
  343. }
  344. FocusOnLocation( (wxPoint) bbox.Centre() );
  345. }
  346. view->UpdateAllLayersColor();
  347. // Ensure the display is refreshed, because in some installs the refresh is done only
  348. // when the gal canvas has the focus, and that is not the case when crossprobing from
  349. // Eeschema:
  350. GetCanvas()->Refresh();
  351. }
  352. std::string FormatProbeItem( BOARD_ITEM* aItem )
  353. {
  354. FOOTPRINT* footprint;
  355. if( !aItem )
  356. return "$CLEAR: \"HIGHLIGHTED\""; // message to clear highlight state
  357. switch( aItem->Type() )
  358. {
  359. case PCB_FOOTPRINT_T:
  360. footprint = (FOOTPRINT*) aItem;
  361. return StrPrintf( "$PART: \"%s\"", TO_UTF8( footprint->GetReference() ) );
  362. case PCB_PAD_T:
  363. {
  364. footprint = static_cast<FOOTPRINT*>( aItem->GetParent() );
  365. wxString pad = static_cast<PAD*>( aItem )->GetNumber();
  366. return StrPrintf( "$PART: \"%s\" $PAD: \"%s\"", TO_UTF8( footprint->GetReference() ),
  367. TO_UTF8( pad ) );
  368. }
  369. case PCB_FP_TEXT_T:
  370. {
  371. footprint = static_cast<FOOTPRINT*>( aItem->GetParent() );
  372. FP_TEXT* text = static_cast<FP_TEXT*>( aItem );
  373. const char* text_key;
  374. /* This can't be a switch since the break need to pull out
  375. * from the outer switch! */
  376. if( text->GetType() == FP_TEXT::TEXT_is_REFERENCE )
  377. text_key = "$REF:";
  378. else if( text->GetType() == FP_TEXT::TEXT_is_VALUE )
  379. text_key = "$VAL:";
  380. else
  381. break;
  382. return StrPrintf( "$PART: \"%s\" %s \"%s\"", TO_UTF8( footprint->GetReference() ), text_key,
  383. TO_UTF8( text->GetText() ) );
  384. }
  385. default:
  386. break;
  387. }
  388. return "";
  389. }
  390. void PCB_EDIT_FRAME::SendMessageToEESCHEMA( BOARD_ITEM* aSyncItem )
  391. {
  392. std::string packet = FormatProbeItem( aSyncItem );
  393. if( !packet.empty() )
  394. {
  395. if( Kiface().IsSingle() )
  396. {
  397. SendCommand( MSG_TO_SCH, packet );
  398. }
  399. else
  400. {
  401. // Typically ExpressMail is going to be s-expression packets, but since
  402. // we have existing interpreter of the cross probe packet on the other
  403. // side in place, we use that here.
  404. Kiway().ExpressMail( FRAME_SCH, MAIL_CROSS_PROBE, packet, this );
  405. }
  406. }
  407. }
  408. void PCB_EDIT_FRAME::SendCrossProbeNetName( const wxString& aNetName )
  409. {
  410. std::string packet = StrPrintf( "$NET: \"%s\"", TO_UTF8( aNetName ) );
  411. if( !packet.empty() )
  412. {
  413. if( Kiface().IsSingle() )
  414. {
  415. SendCommand( MSG_TO_SCH, packet );
  416. }
  417. else
  418. {
  419. // Typically ExpressMail is going to be s-expression packets, but since
  420. // we have existing interpreter of the cross probe packet on the other
  421. // side in place, we use that here.
  422. Kiway().ExpressMail( FRAME_SCH, MAIL_CROSS_PROBE, packet, this );
  423. }
  424. }
  425. }
  426. void PCB_EDIT_FRAME::KiwayMailIn( KIWAY_EXPRESS& mail )
  427. {
  428. std::string& payload = mail.GetPayload();
  429. switch( mail.Command() )
  430. {
  431. case MAIL_PCB_GET_NETLIST:
  432. {
  433. NETLIST netlist;
  434. STRING_FORMATTER sf;
  435. for( FOOTPRINT* footprint : GetBoard()->Footprints() )
  436. {
  437. if( footprint->GetAttributes() & FP_BOARD_ONLY )
  438. continue; // Don't add board-only footprints to the netlist
  439. COMPONENT* component = new COMPONENT( footprint->GetFPID(), footprint->GetReference(),
  440. footprint->GetValue(), footprint->GetPath(), {} );
  441. for( PAD* pad : footprint->Pads() )
  442. {
  443. const wxString& netname = pad->GetShortNetname();
  444. if( !netname.IsEmpty() )
  445. {
  446. component->AddNet( pad->GetNumber(), netname, pad->GetPinFunction(),
  447. pad->GetPinType() );
  448. }
  449. }
  450. netlist.AddComponent( component );
  451. }
  452. netlist.Format( "pcb_netlist", &sf, 0, CTL_OMIT_FILTERS );
  453. payload = sf.GetString();
  454. break;
  455. }
  456. case MAIL_PCB_UPDATE_LINKS:
  457. try
  458. {
  459. NETLIST netlist;
  460. FetchNetlistFromSchematic( netlist, wxEmptyString );
  461. BOARD_NETLIST_UPDATER updater( this, GetBoard() );
  462. updater.SetLookupByTimestamp( false );
  463. updater.SetDeleteUnusedFootprints( false );
  464. updater.SetReplaceFootprints( false );
  465. updater.UpdateNetlist( netlist );
  466. bool dummy;
  467. OnNetlistChanged( updater, &dummy );
  468. }
  469. catch( const IO_ERROR& )
  470. {
  471. assert( false ); // should never happen
  472. return;
  473. }
  474. break;
  475. case MAIL_CROSS_PROBE:
  476. ExecuteRemoteCommand( payload.c_str() );
  477. break;
  478. case MAIL_PCB_UPDATE:
  479. m_toolManager->RunAction( ACTIONS::updatePcbFromSchematic, true );
  480. break;
  481. case MAIL_IMPORT_FILE:
  482. {
  483. // Extract file format type and path (plugin type and path separated with \n)
  484. size_t split = payload.find( '\n' );
  485. wxCHECK( split != std::string::npos, /*void*/ );
  486. int importFormat;
  487. try
  488. {
  489. importFormat = std::stoi( payload.substr( 0, split ) );
  490. }
  491. catch( std::invalid_argument& )
  492. {
  493. wxFAIL;
  494. importFormat = -1;
  495. }
  496. std::string path = payload.substr( split + 1 );
  497. wxASSERT( !path.empty() );
  498. if( importFormat >= 0 )
  499. importFile( path, importFormat );
  500. break;
  501. }
  502. // many many others.
  503. default:
  504. ;
  505. }
  506. }