1 /*
2  * This program source code file is part of KiCad, a free EDA CAD application.
3  *
4  * Copyright (C) 2016 Jean-Pierre Charras, jp.charras at wanadoo.fr
5  * Copyright (C) 1992-2021 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 
25 #include <bitmaps.h>
26 #include <core/mirror.h>
27 #include <sch_draw_panel.h>
28 #include <trigo.h>
29 #include <sch_edit_frame.h>
30 #include <plotters/plotter.h>
31 #include <string_utils.h>
32 #include <widgets/msgpanel.h>
33 #include <math/util.h>      // for KiROUND
34 #include <sch_sheet.h>
35 #include <sch_sheet_path.h>
36 #include <sch_sheet_pin.h>
37 #include <sch_symbol.h>
38 #include <sch_painter.h>
39 #include <schematic.h>
40 #include <settings/color_settings.h>
41 #include <trace_helpers.h>
42 #include <pgm_base.h>
43 #include <wx/log.h>
44 
45 #define SHEET_NAME_CANONICAL "Sheet name"
46 #define SHEET_FILE_CANONICAL "Sheet file"
47 #define USER_FIELD_CANONICAL "Field%d"
48 
49 
GetDefaultFieldName(int aFieldNdx,bool aTranslated)50 const wxString SCH_SHEET::GetDefaultFieldName( int aFieldNdx, bool aTranslated )
51 {
52     static void* locale = nullptr;
53     static wxString sheetnameDefault;
54     static wxString sheetfilenameDefault;
55     static wxString userFieldDefault;
56 
57     if( !aTranslated )
58     {
59         switch( aFieldNdx )
60         {
61         case  SHEETNAME:     return SHEET_NAME_CANONICAL;
62         case  SHEETFILENAME: return SHEET_FILE_CANONICAL;
63         default:             return wxString::Format( USER_FIELD_CANONICAL, aFieldNdx );
64         }
65     }
66 
67     // Fetching translations can take a surprising amount of time when loading libraries,
68     // so only do it when necessary.
69     if( Pgm().GetLocale() != locale )
70     {
71         sheetnameDefault     = _( SHEET_NAME_CANONICAL );
72         sheetfilenameDefault = _( SHEET_FILE_CANONICAL );
73         userFieldDefault     = _( USER_FIELD_CANONICAL );
74         locale = Pgm().GetLocale();
75     }
76 
77     // Fixed values for the mandatory fields
78     switch( aFieldNdx )
79     {
80     case  SHEETNAME:     return sheetnameDefault;
81     case  SHEETFILENAME: return sheetfilenameDefault;
82     default:             return wxString::Format( userFieldDefault, aFieldNdx );
83     }
84 }
85 
86 
SCH_SHEET(EDA_ITEM * aParent,const wxPoint & aPos,wxSize aSize,FIELDS_AUTOPLACED aAutoplaceFields)87 SCH_SHEET::SCH_SHEET( EDA_ITEM* aParent, const wxPoint& aPos, wxSize aSize,
88                       FIELDS_AUTOPLACED aAutoplaceFields ) :
89         SCH_ITEM( aParent, SCH_SHEET_T )
90 {
91     m_layer = LAYER_SHEET;
92     m_pos = aPos;
93     m_size = aSize;
94     m_screen = nullptr;
95 
96     for( int i = 0; i < SHEET_MANDATORY_FIELDS; ++i )
97     {
98         m_fields.emplace_back( aPos, i, this, GetDefaultFieldName( i ) );
99         m_fields.back().SetVisible( true );
100 
101         if( i == SHEETNAME )
102             m_fields.back().SetLayer( LAYER_SHEETNAME );
103         else if( i == SHEETFILENAME )
104             m_fields.back().SetLayer( LAYER_SHEETFILENAME );
105         else
106             m_fields.back().SetLayer( LAYER_SHEETFIELDS );
107     }
108 
109     m_fieldsAutoplaced = aAutoplaceFields;
110     AutoAutoplaceFields( nullptr );
111 
112     m_borderWidth = 0;
113     m_borderColor = COLOR4D::UNSPECIFIED;
114     m_backgroundColor = COLOR4D::UNSPECIFIED;
115 }
116 
117 
SCH_SHEET(const SCH_SHEET & aSheet)118 SCH_SHEET::SCH_SHEET( const SCH_SHEET& aSheet ) :
119     SCH_ITEM( aSheet )
120 {
121     m_pos = aSheet.m_pos;
122     m_size = aSheet.m_size;
123     m_layer = aSheet.m_layer;
124     const_cast<KIID&>( m_Uuid ) = aSheet.m_Uuid;
125     m_fields = aSheet.m_fields;
126     m_fieldsAutoplaced = aSheet.m_fieldsAutoplaced;
127     m_screen = aSheet.m_screen;
128 
129     for( SCH_SHEET_PIN* pin : aSheet.m_pins )
130     {
131         m_pins.emplace_back( new SCH_SHEET_PIN( *pin ) );
132         m_pins.back()->SetParent( this );
133     }
134 
135     for( SCH_FIELD& field : m_fields )
136         field.SetParent( this );
137 
138     m_borderWidth = aSheet.m_borderWidth;
139     m_borderColor = aSheet.m_borderColor;
140     m_backgroundColor = aSheet.m_backgroundColor;
141     m_instances = aSheet.m_instances;
142 
143     if( m_screen )
144         m_screen->IncRefCount();
145 }
146 
147 
~SCH_SHEET()148 SCH_SHEET::~SCH_SHEET()
149 {
150     // also, look at the associated sheet & its reference count
151     // perhaps it should be deleted also.
152     if( m_screen )
153     {
154         m_screen->DecRefCount();
155 
156         if( m_screen->GetRefCount() == 0 )
157             delete m_screen;
158     }
159 
160     // We own our pins; delete them
161     for( SCH_SHEET_PIN* pin : m_pins )
162         delete pin;
163 }
164 
165 
Clone() const166 EDA_ITEM* SCH_SHEET::Clone() const
167 {
168     return new SCH_SHEET( *this );
169 }
170 
171 
SetScreen(SCH_SCREEN * aScreen)172 void SCH_SHEET::SetScreen( SCH_SCREEN* aScreen )
173 {
174     if( aScreen == m_screen )
175         return;
176 
177     if( m_screen != nullptr )
178     {
179         m_screen->DecRefCount();
180 
181         if( m_screen->GetRefCount() == 0 )
182         {
183             delete m_screen;
184             m_screen = nullptr;
185         }
186     }
187 
188     m_screen = aScreen;
189 
190     if( m_screen )
191         m_screen->IncRefCount();
192 }
193 
194 
GetScreenCount() const195 int SCH_SHEET::GetScreenCount() const
196 {
197     if( m_screen == nullptr )
198         return 0;
199 
200     return m_screen->GetRefCount();
201 }
202 
203 
IsRootSheet() const204 bool SCH_SHEET::IsRootSheet() const
205 {
206     wxCHECK_MSG( Schematic(), false, "Can't call IsRootSheet without setting a schematic" );
207 
208     return &Schematic()->Root() == this;
209 }
210 
211 
GetContextualTextVars(wxArrayString * aVars) const212 void SCH_SHEET::GetContextualTextVars( wxArrayString* aVars ) const
213 {
214     for( int i = 0; i < SHEET_MANDATORY_FIELDS; ++i )
215         aVars->push_back( m_fields[i].GetCanonicalName().Upper() );
216 
217     for( size_t i = SHEET_MANDATORY_FIELDS; i < m_fields.size(); ++i )
218         aVars->push_back( m_fields[i].GetName() );
219 
220     aVars->push_back( wxT( "#" ) );
221     aVars->push_back( wxT( "##" ) );
222     m_screen->GetTitleBlock().GetContextualTextVars( aVars );
223 }
224 
225 
ResolveTextVar(wxString * token,int aDepth) const226 bool SCH_SHEET::ResolveTextVar( wxString* token, int aDepth ) const
227 {
228     for( int i = 0; i < SHEET_MANDATORY_FIELDS; ++i )
229     {
230         if( token->IsSameAs( m_fields[i].GetCanonicalName().Upper() ) )
231         {
232             *token = m_fields[i].GetShownText( aDepth + 1 );
233             return true;
234         }
235     }
236 
237     for( size_t i = SHEET_MANDATORY_FIELDS; i < m_fields.size(); ++i )
238     {
239         if( token->IsSameAs( m_fields[i].GetName() ) )
240         {
241             *token = m_fields[i].GetShownText( aDepth + 1 );
242             return true;
243         }
244     }
245 
246     PROJECT *project = &Schematic()->Prj();
247 
248     if( m_screen->GetTitleBlock().TextVarResolver( token, project ) )
249     {
250         return true;
251     }
252 
253     if( token->IsSameAs( wxT( "#" ) ) )
254     {
255         for( const SCH_SHEET_PATH& sheet : Schematic()->GetSheets() )
256         {
257             if( sheet.Last() == this )   // Current sheet path found
258             {
259                 *token = wxString::Format( "%s", sheet.GetPageNumber() );
260                 return true;
261             }
262         }
263     }
264     else if( token->IsSameAs( wxT( "##" ) ) )
265     {
266         SCH_SHEET_LIST sheetList = Schematic()->GetSheets();
267         *token = wxString::Format( wxT( "%d" ), (int) sheetList.size() );
268         return true;
269     }
270 
271     return false;
272 }
273 
274 
UsesDefaultStroke() const275 bool SCH_SHEET::UsesDefaultStroke() const
276 {
277     return m_borderWidth == 0 && m_borderColor == COLOR4D::UNSPECIFIED;
278 }
279 
280 
SwapData(SCH_ITEM * aItem)281 void SCH_SHEET::SwapData( SCH_ITEM* aItem )
282 {
283     wxCHECK_RET( aItem->Type() == SCH_SHEET_T,
284                  wxString::Format( wxT( "SCH_SHEET object cannot swap data with %s object." ),
285                                    aItem->GetClass() ) );
286 
287     SCH_SHEET* sheet = ( SCH_SHEET* ) aItem;
288 
289     std::swap( m_pos, sheet->m_pos );
290     std::swap( m_size, sheet->m_size );
291     m_fields.swap( sheet->m_fields );
292     std::swap( m_fieldsAutoplaced, sheet->m_fieldsAutoplaced );
293     m_pins.swap( sheet->m_pins );
294 
295     // Update parent pointers after swapping.
296     for( SCH_SHEET_PIN* sheetPin : m_pins )
297         sheetPin->SetParent( this );
298 
299     for( SCH_SHEET_PIN* sheetPin : sheet->m_pins )
300         sheetPin->SetParent( sheet );
301 
302     for( SCH_FIELD& field : m_fields )
303         field.SetParent( this );
304 
305     for( SCH_FIELD& field : sheet->m_fields )
306         field.SetParent( sheet );
307 
308     std::swap( m_borderWidth, sheet->m_borderWidth );
309     std::swap( m_borderColor, sheet->m_borderColor );
310     std::swap( m_backgroundColor, sheet->m_backgroundColor );
311     std::swap( m_instances, sheet->m_instances );
312 }
313 
314 
AddPin(SCH_SHEET_PIN * aSheetPin)315 void SCH_SHEET::AddPin( SCH_SHEET_PIN* aSheetPin )
316 {
317     wxASSERT( aSheetPin != nullptr );
318     wxASSERT( aSheetPin->Type() == SCH_SHEET_PIN_T );
319 
320     aSheetPin->SetParent( this );
321     m_pins.push_back( aSheetPin );
322     renumberPins();
323 }
324 
325 
RemovePin(const SCH_SHEET_PIN * aSheetPin)326 void SCH_SHEET::RemovePin( const SCH_SHEET_PIN* aSheetPin )
327 {
328     wxASSERT( aSheetPin != nullptr );
329     wxASSERT( aSheetPin->Type() == SCH_SHEET_PIN_T );
330 
331     for( auto i = m_pins.begin(); i < m_pins.end(); ++i )
332     {
333         if( *i == aSheetPin )
334         {
335             m_pins.erase( i );
336             renumberPins();
337             return;
338         }
339     }
340 }
341 
342 
HasPin(const wxString & aName) const343 bool SCH_SHEET::HasPin( const wxString& aName ) const
344 {
345     for( SCH_SHEET_PIN* pin : m_pins )
346     {
347         if( pin->GetText().CmpNoCase( aName ) == 0 )
348             return true;
349     }
350 
351     return false;
352 }
353 
354 
doIsConnected(const wxPoint & aPosition) const355 bool SCH_SHEET::doIsConnected( const wxPoint& aPosition ) const
356 {
357     for( SCH_SHEET_PIN* sheetPin : m_pins )
358     {
359         if( sheetPin->GetPosition() == aPosition )
360             return true;
361     }
362 
363     return false;
364 }
365 
366 
IsVerticalOrientation() const367 bool SCH_SHEET::IsVerticalOrientation() const
368 {
369     int leftRight = 0;
370     int topBottom = 0;
371 
372     for( SCH_SHEET_PIN* pin : m_pins )
373     {
374         switch( pin->GetSide() )
375         {
376         case SHEET_SIDE::LEFT:   leftRight++; break;
377         case SHEET_SIDE::RIGHT:  leftRight++; break;
378         case SHEET_SIDE::TOP:    topBottom++; break;
379         case SHEET_SIDE::BOTTOM: topBottom++; break;
380         default:                              break;
381         }
382     }
383 
384     return topBottom > 0 && leftRight == 0;
385 }
386 
387 
HasUndefinedPins() const388 bool SCH_SHEET::HasUndefinedPins() const
389 {
390     for( SCH_SHEET_PIN* pin : m_pins )
391     {
392         /* Search the schematic for a hierarchical label corresponding to this sheet label. */
393         const SCH_HIERLABEL* HLabel = nullptr;
394 
395         for( SCH_ITEM* aItem : m_screen->Items().OfType( SCH_HIER_LABEL_T ) )
396         {
397             if( !pin->GetText().CmpNoCase( static_cast<SCH_HIERLABEL*>( aItem )->GetText() ) )
398             {
399                 HLabel = static_cast<SCH_HIERLABEL*>( aItem );
400                 break;
401             }
402         }
403 
404         if( HLabel == nullptr ) // Corresponding hierarchical label not found.
405             return true;
406     }
407 
408     return false;
409 }
410 
411 
bumpToNextGrid(const int aVal,const int aDirection)412 int bumpToNextGrid( const int aVal, const int aDirection )
413 {
414     constexpr int gridSize = Mils2iu( 50 );
415 
416     int base = aVal / gridSize;
417     int excess = abs( aVal % gridSize );
418 
419     if( aDirection > 0 )
420     {
421         return ( base + 1 ) * gridSize;
422     }
423     else if( excess > 0 )
424     {
425         return ( base ) * gridSize;
426     }
427     else
428     {
429         return ( base - 1 ) * gridSize;
430     }
431 }
432 
433 
GetMinWidth(bool aFromLeft) const434 int SCH_SHEET::GetMinWidth( bool aFromLeft ) const
435 {
436     int pinsLeft = m_pos.x + m_size.x;
437     int pinsRight = m_pos.x;
438 
439     for( size_t i = 0; i < m_pins.size();  i++ )
440     {
441         SHEET_SIDE edge = m_pins[i]->GetSide();
442 
443         if( edge == SHEET_SIDE::TOP || edge == SHEET_SIDE::BOTTOM )
444         {
445             EDA_RECT pinRect = m_pins[i]->GetBoundingBox();
446 
447             pinsLeft = std::min( pinsLeft, pinRect.GetLeft() );
448             pinsRight = std::max( pinsRight, pinRect.GetRight() );
449         }
450     }
451 
452     pinsLeft = bumpToNextGrid( pinsLeft, -1 );
453     pinsRight = bumpToNextGrid( pinsRight, 1 );
454 
455     int pinMinWidth;
456 
457     if( pinsLeft >= pinsRight )
458         pinMinWidth = 0;
459     else if( aFromLeft )
460         pinMinWidth = pinsRight - m_pos.x;
461     else
462         pinMinWidth = m_pos.x + m_size.x - pinsLeft;
463 
464     return std::max( pinMinWidth, Mils2iu( MIN_SHEET_WIDTH ) );
465 }
466 
467 
GetMinHeight(bool aFromTop) const468 int SCH_SHEET::GetMinHeight( bool aFromTop ) const
469 {
470     int pinsTop = m_pos.y + m_size.y;
471     int pinsBottom = m_pos.y;
472 
473     for( size_t i = 0; i < m_pins.size();  i++ )
474     {
475         SHEET_SIDE edge = m_pins[i]->GetSide();
476 
477         if( edge == SHEET_SIDE::RIGHT || edge == SHEET_SIDE::LEFT )
478         {
479             EDA_RECT pinRect = m_pins[i]->GetBoundingBox();
480 
481             pinsTop = std::min( pinsTop, pinRect.GetTop() );
482             pinsBottom = std::max( pinsBottom, pinRect.GetBottom() );
483         }
484     }
485 
486     pinsTop = bumpToNextGrid( pinsTop, -1 );
487     pinsBottom = bumpToNextGrid( pinsBottom, 1 );
488 
489     int pinMinHeight;
490 
491     if( pinsTop >= pinsBottom )
492         pinMinHeight = 0;
493     else if( aFromTop )
494         pinMinHeight = pinsBottom - m_pos.y;
495     else
496         pinMinHeight = m_pos.y + m_size.y - pinsTop;
497 
498     return std::max( pinMinHeight, Mils2iu( MIN_SHEET_HEIGHT ) );
499 }
500 
501 
CleanupSheet()502 void SCH_SHEET::CleanupSheet()
503 {
504     std::vector<SCH_SHEET_PIN*> pins = m_pins;
505 
506     m_pins.clear();
507 
508     for( SCH_SHEET_PIN* pin : pins )
509     {
510         /* Search the schematic for a hierarchical label corresponding to this sheet label. */
511         const SCH_HIERLABEL* HLabel = nullptr;
512 
513         for( SCH_ITEM* aItem : m_screen->Items().OfType( SCH_HIER_LABEL_T ) )
514         {
515             if( pin->GetText().CmpNoCase( static_cast<SCH_HIERLABEL*>( aItem )->GetText() ) == 0 )
516             {
517                 HLabel = static_cast<SCH_HIERLABEL*>( aItem );
518                 break;
519             }
520         }
521 
522         if( HLabel )
523             m_pins.push_back( pin );
524     }
525 }
526 
527 
GetPin(const wxPoint & aPosition)528 SCH_SHEET_PIN* SCH_SHEET::GetPin( const wxPoint& aPosition )
529 {
530     for( SCH_SHEET_PIN* pin : m_pins )
531     {
532         if( pin->HitTest( aPosition ) )
533             return pin;
534     }
535 
536     return nullptr;
537 }
538 
539 
GetPenWidth() const540 int SCH_SHEET::GetPenWidth() const
541 {
542     if( GetBorderWidth() > 0 )
543         return GetBorderWidth();
544 
545     if( Schematic() )
546         return Schematic()->Settings().m_DefaultLineWidth;
547 
548     return Mils2iu( DEFAULT_LINE_WIDTH_MILS );
549 }
550 
551 
AutoplaceFields(SCH_SCREEN * aScreen,bool aManual)552 void SCH_SHEET::AutoplaceFields( SCH_SCREEN* aScreen, bool aManual )
553 {
554     wxSize textSize = m_fields[ SHEETNAME ].GetTextSize();
555     int    borderMargin = KiROUND( GetPenWidth() / 2.0 ) + 4;
556     int    margin = borderMargin + KiROUND( std::max( textSize.x, textSize.y ) * 0.5 );
557 
558     if( IsVerticalOrientation() )
559     {
560         m_fields[ SHEETNAME ].SetTextPos( m_pos + wxPoint( -margin, m_size.y ) );
561         m_fields[ SHEETNAME ].SetHorizJustify( GR_TEXT_HJUSTIFY_LEFT );
562         m_fields[ SHEETNAME ].SetVertJustify(GR_TEXT_VJUSTIFY_BOTTOM );
563         m_fields[ SHEETNAME ].SetTextAngle( TEXT_ANGLE_VERT );
564     }
565     else
566     {
567         m_fields[ SHEETNAME ].SetTextPos( m_pos + wxPoint( 0, -margin ) );
568         m_fields[ SHEETNAME ].SetHorizJustify( GR_TEXT_HJUSTIFY_LEFT );
569         m_fields[ SHEETNAME ].SetVertJustify(GR_TEXT_VJUSTIFY_BOTTOM );
570         m_fields[ SHEETNAME ].SetTextAngle( TEXT_ANGLE_HORIZ );
571     }
572 
573     textSize = m_fields[ SHEETFILENAME ].GetTextSize();
574     margin = borderMargin + KiROUND( std::max( textSize.x, textSize.y ) * 0.4 );
575 
576     if( IsVerticalOrientation() )
577     {
578         m_fields[ SHEETFILENAME ].SetTextPos( m_pos + wxPoint( m_size.x + margin, m_size.y ) );
579         m_fields[ SHEETFILENAME ].SetHorizJustify( GR_TEXT_HJUSTIFY_LEFT );
580         m_fields[ SHEETFILENAME ].SetVertJustify(GR_TEXT_VJUSTIFY_TOP );
581         m_fields[ SHEETFILENAME ].SetTextAngle( TEXT_ANGLE_VERT );
582     }
583     else
584     {
585         m_fields[ SHEETFILENAME ].SetTextPos( m_pos + wxPoint( 0, m_size.y + margin ) );
586         m_fields[ SHEETFILENAME ].SetHorizJustify( GR_TEXT_HJUSTIFY_LEFT );
587         m_fields[ SHEETFILENAME ].SetVertJustify(GR_TEXT_VJUSTIFY_TOP );
588         m_fields[ SHEETFILENAME ].SetTextAngle( TEXT_ANGLE_HORIZ );
589     }
590 
591     m_fieldsAutoplaced = FIELDS_AUTOPLACED_AUTO;
592 }
593 
594 
ViewGetLayers(int aLayers[],int & aCount) const595 void SCH_SHEET::ViewGetLayers( int aLayers[], int& aCount ) const
596 {
597     aCount      = 4;
598     aLayers[0]  = LAYER_HIERLABEL;
599     aLayers[1]  = LAYER_SHEET;
600     aLayers[2]  = LAYER_SHEET_BACKGROUND;
601     aLayers[3]  = LAYER_SELECTION_SHADOWS;
602 }
603 
604 
GetBodyBoundingBox() const605 const EDA_RECT SCH_SHEET::GetBodyBoundingBox() const
606 {
607     wxPoint  end;
608     EDA_RECT box( m_pos, m_size );
609     int      lineWidth = GetPenWidth();
610     int      textLength = 0;
611 
612     // Calculate bounding box X size:
613     end.x = std::max( m_size.x, textLength );
614 
615     // Calculate bounding box pos:
616     end.y = m_size.y;
617     end += m_pos;
618 
619     box.SetEnd( end );
620     box.Inflate( lineWidth / 2 );
621 
622     return box;
623 }
624 
625 
GetBoundingBox() const626 const EDA_RECT SCH_SHEET::GetBoundingBox() const
627 {
628     EDA_RECT box = GetBodyBoundingBox();
629 
630     for( const SCH_FIELD& field : m_fields )
631         box.Merge( field.GetBoundingBox() );
632 
633     return box;
634 }
635 
636 
GetRotationCenter() const637 wxPoint SCH_SHEET::GetRotationCenter() const
638 {
639     EDA_RECT box( m_pos, m_size );
640     return box.GetCenter();
641 }
642 
643 
SymbolCount() const644 int SCH_SHEET::SymbolCount() const
645 {
646     int n = 0;
647 
648     if( m_screen )
649     {
650         for( SCH_ITEM* aItem : m_screen->Items().OfType( SCH_SYMBOL_T ) )
651         {
652             SCH_SYMBOL* symbol = (SCH_SYMBOL*) aItem;
653 
654             if( symbol->GetField( VALUE_FIELD )->GetText().GetChar( 0 ) != '#' )
655                 n++;
656         }
657 
658         for( SCH_ITEM* aItem : m_screen->Items().OfType( SCH_SHEET_T ) )
659             n += static_cast<const SCH_SHEET*>( aItem )->SymbolCount();
660     }
661 
662     return n;
663 }
664 
665 
SearchHierarchy(const wxString & aFilename,SCH_SCREEN ** aScreen)666 bool SCH_SHEET::SearchHierarchy( const wxString& aFilename, SCH_SCREEN** aScreen )
667 {
668     if( m_screen )
669     {
670         // Only check the root sheet once and don't recurse.
671         if( !GetParent() )
672         {
673             if( m_screen && m_screen->GetFileName().Cmp( aFilename ) == 0 )
674             {
675                 *aScreen = m_screen;
676                 return true;
677             }
678         }
679 
680         for( SCH_ITEM* aItem : m_screen->Items().OfType( SCH_SHEET_T ) )
681         {
682             SCH_SHEET*  sheet  = static_cast<SCH_SHEET*>( aItem );
683             SCH_SCREEN* screen = sheet->m_screen;
684 
685             // Must use the screen's path (which is always absolute) rather than the
686             // sheet's (which could be relative).
687             if( screen && screen->GetFileName().Cmp( aFilename ) == 0 )
688             {
689                 *aScreen = screen;
690                 return true;
691             }
692 
693             if( sheet->SearchHierarchy( aFilename, aScreen ) )
694                 return true;
695         }
696     }
697 
698     return false;
699 }
700 
701 
LocatePathOfScreen(SCH_SCREEN * aScreen,SCH_SHEET_PATH * aList)702 bool SCH_SHEET::LocatePathOfScreen( SCH_SCREEN* aScreen, SCH_SHEET_PATH* aList )
703 {
704     if( m_screen )
705     {
706         aList->push_back( this );
707 
708         if( m_screen == aScreen )
709             return true;
710 
711         for( auto item : m_screen->Items().OfType( SCH_SHEET_T ) )
712         {
713             SCH_SHEET* sheet = static_cast<SCH_SHEET*>( item );
714 
715             if( sheet->LocatePathOfScreen( aScreen, aList ) )
716             {
717                 return true;
718             }
719         }
720 
721         aList->pop_back();
722     }
723 
724     return false;
725 }
726 
727 
CountSheets() const728 int SCH_SHEET::CountSheets() const
729 {
730     int count = 1; //1 = this!!
731 
732     if( m_screen )
733     {
734         for( SCH_ITEM* aItem : m_screen->Items().OfType( SCH_SHEET_T ) )
735             count += static_cast<SCH_SHEET*>( aItem )->CountSheets();
736     }
737 
738     return count;
739 }
740 
741 
GetMsgPanelInfo(EDA_DRAW_FRAME * aFrame,std::vector<MSG_PANEL_ITEM> & aList)742 void SCH_SHEET::GetMsgPanelInfo( EDA_DRAW_FRAME* aFrame, std::vector<MSG_PANEL_ITEM>& aList )
743 {
744     aList.emplace_back( _( "Sheet Name" ), m_fields[ SHEETNAME ].GetText() );
745 
746     if( SCH_EDIT_FRAME* schframe = dynamic_cast<SCH_EDIT_FRAME*>( aFrame ) )
747     {
748         SCH_SHEET_PATH path = schframe->GetCurrentSheet();
749         path.push_back( this );
750 
751         aList.emplace_back( _( "Hierarchical Path" ), path.PathHumanReadable( false ) );
752     }
753 
754     aList.emplace_back( _( "File Name" ), m_fields[ SHEETFILENAME ].GetText() );
755 }
756 
757 
Move(const wxPoint & aMoveVector)758 void SCH_SHEET::Move( const wxPoint& aMoveVector )
759 {
760     m_pos += aMoveVector;
761 
762     for( SCH_SHEET_PIN* pin : m_pins )
763         pin->Move( aMoveVector );
764 
765     for( SCH_FIELD& field : m_fields )
766         field.Move( aMoveVector );
767 }
768 
769 
Rotate(const wxPoint & aCenter)770 void SCH_SHEET::Rotate( const wxPoint& aCenter )
771 {
772     wxPoint prev = m_pos;
773 
774     RotatePoint( &m_pos, aCenter, 900 );
775     RotatePoint( &m_size.x, &m_size.y, 900 );
776 
777     if( m_size.x < 0 )
778     {
779         m_pos.x += m_size.x;
780         m_size.x = -m_size.x;
781     }
782 
783     if( m_size.y < 0 )
784     {
785         m_pos.y += m_size.y;
786         m_size.y = -m_size.y;
787     }
788 
789     // Pins must be rotated first as that's how we determine vertical vs horizontal
790     // orientation for auto-placement
791     for( SCH_SHEET_PIN* sheetPin : m_pins )
792         sheetPin->Rotate( aCenter );
793 
794     if( m_fieldsAutoplaced == FIELDS_AUTOPLACED_AUTO )
795     {
796         AutoplaceFields( /* aScreen */ nullptr, /* aManual */ false );
797     }
798     else
799     {
800         // Move the fields to the new position because the parent itself has moved.
801         for( SCH_FIELD& field : m_fields )
802         {
803             wxPoint pos = field.GetTextPos();
804             pos.x -= prev.x - m_pos.x;
805             pos.y -= prev.y - m_pos.y;
806             field.SetTextPos( pos );
807         }
808     }
809 }
810 
811 
MirrorVertically(int aCenter)812 void SCH_SHEET::MirrorVertically( int aCenter )
813 {
814     int dy = m_pos.y;
815 
816     MIRROR( m_pos.y, aCenter );
817     m_pos.y -= m_size.y;
818     dy -= m_pos.y;     // 0,dy is the move vector for this transform
819 
820     for( SCH_SHEET_PIN* sheetPin : m_pins )
821         sheetPin->MirrorVertically( aCenter );
822 
823     for( SCH_FIELD& field : m_fields )
824     {
825         wxPoint pos = field.GetTextPos();
826         pos.y -= dy;
827         field.SetTextPos( pos );
828     }
829 }
830 
831 
MirrorHorizontally(int aCenter)832 void SCH_SHEET::MirrorHorizontally( int aCenter )
833 {
834     int dx = m_pos.x;
835 
836     MIRROR( m_pos.x, aCenter );
837     m_pos.x -= m_size.x;
838     dx -= m_pos.x;     // dx,0 is the move vector for this transform
839 
840     for( SCH_SHEET_PIN* sheetPin : m_pins )
841         sheetPin->MirrorHorizontally( aCenter );
842 
843     for( SCH_FIELD& field : m_fields )
844     {
845         wxPoint pos = field.GetTextPos();
846         pos.x -= dx;
847         field.SetTextPos( pos );
848     }
849 }
850 
851 
SetPosition(const wxPoint & aPosition)852 void SCH_SHEET::SetPosition( const wxPoint& aPosition )
853 {
854     // Remember the sheet and all pin sheet positions must be
855     // modified. So use Move function to do that.
856     Move( aPosition - m_pos );
857 }
858 
859 
Resize(const wxSize & aSize)860 void SCH_SHEET::Resize( const wxSize& aSize )
861 {
862     if( aSize == m_size )
863         return;
864 
865     m_size = aSize;
866 
867     // Move the fields if we're in autoplace mode
868     if( m_fieldsAutoplaced == FIELDS_AUTOPLACED_AUTO )
869         AutoplaceFields( /* aScreen */ nullptr, /* aManual */ false );
870 
871     // Move the sheet labels according to the new sheet size.
872     for( SCH_SHEET_PIN* sheetPin : m_pins )
873         sheetPin->ConstrainOnEdge( sheetPin->GetPosition() );
874 }
875 
876 
Matches(const wxFindReplaceData & aSearchData,void * aAuxData) const877 bool SCH_SHEET::Matches( const wxFindReplaceData& aSearchData, void* aAuxData ) const
878 {
879     wxLogTrace( traceFindItem, wxT( "  item " ) + GetSelectMenuText( EDA_UNITS::MILLIMETRES ) );
880 
881     // Sheets are searchable via the child field and pin item text.
882     return false;
883 }
884 
885 
renumberPins()886 void SCH_SHEET::renumberPins()
887 {
888     int id = 2;
889 
890     for( SCH_SHEET_PIN* pin : m_pins )
891     {
892         pin->SetNumber( id );
893         id++;
894     }
895 }
896 
897 
GetEndPoints(std::vector<DANGLING_END_ITEM> & aItemList)898 void SCH_SHEET::GetEndPoints( std::vector <DANGLING_END_ITEM>& aItemList )
899 {
900     for( SCH_SHEET_PIN* sheetPin : m_pins )
901     {
902         wxCHECK2_MSG( sheetPin->Type() == SCH_SHEET_PIN_T, continue,
903                       wxT( "Invalid item in schematic sheet pin list.  Bad programmer!" ) );
904 
905         sheetPin->GetEndPoints( aItemList );
906     }
907 }
908 
909 
UpdateDanglingState(std::vector<DANGLING_END_ITEM> & aItemList,const SCH_SHEET_PATH * aPath)910 bool SCH_SHEET::UpdateDanglingState( std::vector<DANGLING_END_ITEM>& aItemList,
911                                      const SCH_SHEET_PATH* aPath )
912 {
913     bool changed = false;
914 
915     for( SCH_SHEET_PIN* sheetPin : m_pins )
916         changed |= sheetPin->UpdateDanglingState( aItemList );
917 
918     return changed;
919 }
920 
921 
GetConnectionPoints() const922 std::vector<wxPoint> SCH_SHEET::GetConnectionPoints() const
923 {
924     std::vector<wxPoint> retval;
925 
926     for( SCH_SHEET_PIN* sheetPin : m_pins )
927         retval.push_back( sheetPin->GetPosition() );
928 
929     return retval;
930 }
931 
932 
Visit(INSPECTOR aInspector,void * testData,const KICAD_T aFilterTypes[])933 SEARCH_RESULT SCH_SHEET::Visit( INSPECTOR aInspector, void* testData, const KICAD_T aFilterTypes[] )
934 {
935     KICAD_T stype;
936 
937     for( const KICAD_T* p = aFilterTypes;  (stype = *p) != EOT;   ++p )
938     {
939         // If caller wants to inspect my type
940         if( stype == SCH_LOCATE_ANY_T || stype == Type() )
941         {
942             if( SEARCH_RESULT::QUIT == aInspector( this, nullptr ) )
943                 return SEARCH_RESULT::QUIT;
944         }
945 
946         if( stype == SCH_LOCATE_ANY_T || stype == SCH_FIELD_T )
947         {
948             // Test the sheet fields.
949             for( SCH_FIELD& field : m_fields )
950             {
951                 if( SEARCH_RESULT::QUIT == aInspector( &field, this ) )
952                     return SEARCH_RESULT::QUIT;
953             }
954         }
955 
956         if( stype == SCH_LOCATE_ANY_T || stype == SCH_SHEET_PIN_T )
957         {
958             // Test the sheet labels.
959             for( SCH_SHEET_PIN* sheetPin : m_pins )
960             {
961                 if( SEARCH_RESULT::QUIT == aInspector( sheetPin, this ) )
962                     return SEARCH_RESULT::QUIT;
963             }
964         }
965     }
966 
967     return SEARCH_RESULT::CONTINUE;
968 }
969 
970 
RunOnChildren(const std::function<void (SCH_ITEM *)> & aFunction)971 void SCH_SHEET::RunOnChildren( const std::function<void( SCH_ITEM* )>& aFunction )
972 {
973     for( SCH_FIELD& field : m_fields )
974         aFunction( &field );
975 
976     for( SCH_SHEET_PIN* pin : m_pins )
977         aFunction( pin );
978 }
979 
980 
GetSelectMenuText(EDA_UNITS aUnits) const981 wxString SCH_SHEET::GetSelectMenuText( EDA_UNITS aUnits ) const
982 {
983     return wxString::Format( _( "Hierarchical Sheet %s" ),
984                              m_fields[ SHEETNAME ].GetText() );
985 }
986 
987 
GetMenuImage() const988 BITMAPS SCH_SHEET::GetMenuImage() const
989 {
990     return BITMAPS::add_hierarchical_subsheet;
991 }
992 
993 
HitTest(const wxPoint & aPosition,int aAccuracy) const994 bool SCH_SHEET::HitTest( const wxPoint& aPosition, int aAccuracy ) const
995 {
996     EDA_RECT rect = GetBodyBoundingBox();
997 
998     rect.Inflate( aAccuracy );
999 
1000     return rect.Contains( aPosition );
1001 }
1002 
1003 
HitTest(const EDA_RECT & aRect,bool aContained,int aAccuracy) const1004 bool SCH_SHEET::HitTest( const EDA_RECT& aRect, bool aContained, int aAccuracy ) const
1005 {
1006     EDA_RECT rect = aRect;
1007 
1008     rect.Inflate( aAccuracy );
1009 
1010     if( aContained )
1011         return rect.Contains( GetBodyBoundingBox() );
1012 
1013     return rect.Intersects( GetBodyBoundingBox() );
1014 }
1015 
1016 
Plot(PLOTTER * aPlotter) const1017 void SCH_SHEET::Plot( PLOTTER* aPlotter ) const
1018 {
1019     wxString msg;
1020     wxPoint  pos;
1021     auto*    settings = dynamic_cast<KIGFX::SCH_RENDER_SETTINGS*>( aPlotter->RenderSettings() );
1022     bool     override = settings ? settings->m_OverrideItemColors : false;
1023     COLOR4D  borderColor = GetBorderColor();
1024     COLOR4D  backgroundColor = GetBackgroundColor();
1025 
1026     if( override || borderColor == COLOR4D::UNSPECIFIED )
1027         borderColor = aPlotter->RenderSettings()->GetLayerColor( LAYER_SHEET );
1028 
1029     if( override || backgroundColor == COLOR4D::UNSPECIFIED )
1030         backgroundColor = aPlotter->RenderSettings()->GetLayerColor( LAYER_SHEET_BACKGROUND );
1031 
1032     // Do not fill shape in B&W mode, otherwise texts are unreadable
1033     bool fill = aPlotter->GetColorMode();
1034 
1035     if( fill )
1036     {
1037         aPlotter->SetColor( backgroundColor );
1038         aPlotter->Rect( m_pos, m_pos + m_size, FILL_T::FILLED_SHAPE, 1 );
1039     }
1040 
1041     aPlotter->SetColor( borderColor );
1042 
1043     int penWidth = std::max( GetPenWidth(), aPlotter->RenderSettings()->GetMinPenWidth() );
1044     aPlotter->Rect( m_pos, m_pos + m_size, FILL_T::NO_FILL, penWidth );
1045 
1046     // Plot sheet pins
1047     for( SCH_SHEET_PIN* sheetPin : m_pins )
1048         sheetPin->Plot( aPlotter );
1049 
1050     // Plot the fields
1051     for( const SCH_FIELD& field : m_fields )
1052         field.Plot( aPlotter );
1053 }
1054 
1055 
Print(const RENDER_SETTINGS * aSettings,const wxPoint & aOffset)1056 void SCH_SHEET::Print( const RENDER_SETTINGS* aSettings, const wxPoint& aOffset )
1057 {
1058     wxDC*       DC = aSettings->GetPrintDC();
1059     wxPoint     pos = m_pos + aOffset;
1060     int         lineWidth = std::max( GetPenWidth(), aSettings->GetDefaultPenWidth() );
1061     const auto* settings = dynamic_cast<const KIGFX::SCH_RENDER_SETTINGS*>( aSettings );
1062     bool        override = settings && settings->m_OverrideItemColors;
1063     COLOR4D     border = GetBorderColor();
1064     COLOR4D     background = GetBackgroundColor();
1065 
1066     if( override || border == COLOR4D::UNSPECIFIED )
1067         border = aSettings->GetLayerColor( LAYER_SHEET );
1068 
1069     if( override || background == COLOR4D::UNSPECIFIED )
1070         background = aSettings->GetLayerColor( LAYER_SHEET_BACKGROUND );
1071 
1072     if( GetGRForceBlackPenState() )     // printing in black & white
1073         background = COLOR4D::UNSPECIFIED;
1074 
1075     if( background != COLOR4D::UNSPECIFIED )
1076     {
1077         GRFilledRect( nullptr, DC, pos.x, pos.y, pos.x + m_size.x, pos.y + m_size.y, 0,
1078                       background, background );
1079     }
1080 
1081     GRRect( nullptr, DC, pos.x, pos.y, pos.x + m_size.x, pos.y + m_size.y, lineWidth, border );
1082 
1083     for( SCH_FIELD& field : m_fields )
1084         field.Print( aSettings, aOffset );
1085 
1086     for( SCH_SHEET_PIN* sheetPin : m_pins )
1087         sheetPin->Print( aSettings, aOffset );
1088 }
1089 
1090 
operator =(const SCH_ITEM & aItem)1091 SCH_SHEET& SCH_SHEET::operator=( const SCH_ITEM& aItem )
1092 {
1093     wxCHECK_MSG( Type() == aItem.Type(), *this,
1094                  wxT( "Cannot assign object type " ) + aItem.GetClass() + wxT( " to type " ) +
1095                  GetClass() );
1096 
1097     if( &aItem != this )
1098     {
1099         SCH_ITEM::operator=( aItem );
1100 
1101         SCH_SHEET* sheet = (SCH_SHEET*) &aItem;
1102 
1103         m_pos = sheet->m_pos;
1104         m_size = sheet->m_size;
1105         m_fields = sheet->m_fields;
1106 
1107         for( SCH_SHEET_PIN* pin : sheet->m_pins )
1108         {
1109             m_pins.emplace_back( new SCH_SHEET_PIN( *pin ) );
1110             m_pins.back()->SetParent( this );
1111         }
1112 
1113         for( const SCH_SHEET_INSTANCE& instance : sheet->m_instances )
1114             m_instances.emplace_back( instance );
1115     }
1116 
1117     return *this;
1118 }
1119 
1120 
operator <(const SCH_ITEM & aItem) const1121 bool SCH_SHEET::operator <( const SCH_ITEM& aItem ) const
1122 {
1123     if( Type() != aItem.Type() )
1124         return Type() < aItem.Type();
1125 
1126     auto sheet = static_cast<const SCH_SHEET*>( &aItem );
1127 
1128     if (m_fields[ SHEETNAME ].GetText() != sheet->m_fields[ SHEETNAME ].GetText() )
1129         return m_fields[ SHEETNAME ].GetText() < sheet->m_fields[ SHEETNAME ].GetText();
1130 
1131     if (m_fields[ SHEETFILENAME ].GetText() != sheet->m_fields[ SHEETFILENAME ].GetText() )
1132         return m_fields[ SHEETFILENAME ].GetText() < sheet->m_fields[ SHEETFILENAME ].GetText();
1133 
1134     return false;
1135 }
1136 
1137 
AddInstance(const SCH_SHEET_PATH & aSheetPath)1138 bool SCH_SHEET::AddInstance( const SCH_SHEET_PATH& aSheetPath )
1139 {
1140     wxCHECK( aSheetPath.IsFullPath(), false );
1141 
1142     for( const SCH_SHEET_INSTANCE& instance : m_instances )
1143     {
1144         // if aSheetPath is found, nothing to do:
1145         if( instance.m_Path == aSheetPath.PathWithoutRootUuid() )
1146             return false;
1147     }
1148 
1149     wxLogTrace( traceSchSheetPaths, wxT( "Adding instance `%s` to sheet `%s`." ),
1150                 aSheetPath.PathWithoutRootUuid().AsString(),
1151                 ( GetName().IsEmpty() ) ? wxT( "root" ) : GetName() );
1152 
1153     SCH_SHEET_INSTANCE instance;
1154 
1155     instance.m_Path = aSheetPath.PathWithoutRootUuid();
1156 
1157     // This entry does not exist: add it with an empty page number.
1158     m_instances.emplace_back( instance );
1159     return true;
1160 }
1161 
1162 
GetPageNumber(const SCH_SHEET_PATH & aSheetPath) const1163 wxString SCH_SHEET::GetPageNumber( const SCH_SHEET_PATH& aSheetPath ) const
1164 {
1165     wxCHECK( aSheetPath.IsFullPath(), wxEmptyString );
1166 
1167     wxString pageNumber;
1168     KIID_PATH path = aSheetPath.PathWithoutRootUuid();
1169 
1170     for( const SCH_SHEET_INSTANCE& instance : m_instances )
1171     {
1172         if( instance.m_Path == path )
1173         {
1174             pageNumber = instance.m_PageNumber;
1175             break;
1176         }
1177     }
1178 
1179     return pageNumber;
1180 }
1181 
1182 
SetPageNumber(const SCH_SHEET_PATH & aSheetPath,const wxString & aPageNumber)1183 void SCH_SHEET::SetPageNumber( const SCH_SHEET_PATH& aSheetPath, const wxString& aPageNumber )
1184 {
1185     wxCHECK( aSheetPath.IsFullPath(), /* void */ );
1186 
1187     KIID_PATH path = aSheetPath.PathWithoutRootUuid();
1188 
1189     for( SCH_SHEET_INSTANCE& instance : m_instances )
1190     {
1191         if( instance.m_Path == path )
1192         {
1193             instance.m_PageNumber = aPageNumber;
1194             break;
1195         }
1196     }
1197 }
1198 
1199 
ComparePageNum(const wxString & aPageNumberA,const wxString & aPageNumberB)1200 int SCH_SHEET::ComparePageNum( const wxString& aPageNumberA, const wxString& aPageNumberB )
1201 {
1202     if( aPageNumberA == aPageNumberB )
1203         return 0; // A == B
1204 
1205     // First sort numerically if the page numbers are integers
1206     long pageA, pageB;
1207     bool isIntegerPageA = aPageNumberA.ToLong( &pageA );
1208     bool isIntegerPageB = aPageNumberB.ToLong( &pageB );
1209 
1210     if( isIntegerPageA && isIntegerPageB )
1211     {
1212         if( pageA < pageB )
1213             return -1; //A < B
1214         else
1215             return 1; // A > B
1216     }
1217 
1218     // Numerical page numbers always before strings
1219     if( isIntegerPageA )
1220         return -1; //A < B
1221     else if( isIntegerPageB )
1222         return 1; // A > B
1223 
1224     // If not numeric, then sort as strings using natural sort
1225     int result = StrNumCmp( aPageNumberA, aPageNumberB );
1226 
1227     if( result > 0 )
1228         return 1; // A > B
1229 
1230     return -1; //A < B
1231 }
1232 
1233 
1234 #if defined(DEBUG)
1235 
Show(int nestLevel,std::ostream & os) const1236 void SCH_SHEET::Show( int nestLevel, std::ostream& os ) const
1237 {
1238     // XML output:
1239     wxString s = GetClass();
1240 
1241     NestedSpace( nestLevel, os ) << '<' << s.Lower().mb_str() << ">" << " sheet_name=\""
1242                                  << TO_UTF8( m_fields[ SHEETNAME ].GetText() ) << '"' << ">\n";
1243 
1244     // show all the pins, and check the linked list integrity
1245     for( SCH_SHEET_PIN* sheetPin : m_pins )
1246         sheetPin->Show( nestLevel + 1, os );
1247 
1248     NestedSpace( nestLevel, os ) << "</" << s.Lower().mb_str() << ">\n" << std::flush;
1249 }
1250 
1251 #endif
1252