kicad_plugin.cpp 63.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
/*
 * This program source code file is part of KiCad, a free EDA CAD application.
 *
 * Copyright (C) 2012 CERN
 * Copyright (C) 1992-2011 KiCad Developers, see change_log.txt for contributors.
 *
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, you may find one here:
 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 * or you may search the http://www.gnu.org website for the version 2 license,
 * or you may write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
 */

#include <fctsys.h>
#include <kicad_string.h>
#include <common.h>
#include <build_version.h>      // LEGACY_BOARD_FILE_VERSION
#include <macros.h>
#include <3d_struct.h>
32
#include <wildcards_and_files_ext.h>
33
#include <base_units.h>
34 35 36 37 38 39 40 41 42 43

#include <class_board.h>
#include <class_module.h>
#include <class_pcb_text.h>
#include <class_dimension.h>
#include <class_track.h>
#include <class_zone.h>
#include <class_drawsegment.h>
#include <class_mire.h>
#include <class_edge_mod.h>
44
#include <pcb_plot_params.h>
45 46 47 48
#include <zones.h>
#include <kicad_plugin.h>
#include <pcb_parser.h>

49 50
#include <wx/dir.h>
#include <wx/filename.h>
51
#include <wx/wfstream.h>
52 53 54 55 56
#include <boost/ptr_container/ptr_map.hpp>
#include <memory.h>

using namespace std;

57 58 59

#define FMTIU        BOARD_ITEM::FormatInternalUnits

60 61
/**
 * Definition for enabling and disabling footprint library trace output.  See the
62
 * wxWidgets documentation on using the WXTRACE environment variable.
63 64 65
 */
static const wxString traceFootprintLibrary( wxT( "KicadFootprintLib" ) );

66

67 68 69 70 71 72 73 74 75 76 77
/**
 * Class FP_CACHE_ITEM
 * is helper class for creating a footprint library cache.
 *
 * The new footprint library design is a file path of individual module files
 * that contain a single module per file.  This class is a helper only for the
 * footprint portion of the PLUGIN API, and only for the #PCB_IO plugin.  It is
 * private to this implementation file so it is not placed into a header.
 */
class FP_CACHE_ITEM
{
78 79 80
    wxFileName              m_file_name; ///< The the full file name and path of the footprint to cache.
    bool                    m_writable;  ///< Writability status of the footprint file.
    wxDateTime              m_mod_time;  ///< The last file modified time stamp.
81
    auto_ptr< MODULE >      m_module;
82 83 84 85

public:
    FP_CACHE_ITEM( MODULE* aModule, const wxFileName& aFileName );

86 87 88 89 90
    wxString    GetName() const { return m_file_name.GetDirs().Last(); }
    wxFileName  GetFileName() const { return m_file_name; }
    bool        IsModified() const;
    MODULE*     GetModule() const { return m_module.get(); }
    void        UpdateModificationTime() { m_mod_time = m_file_name.GetModificationTime(); }
91 92 93
};


94 95
FP_CACHE_ITEM::FP_CACHE_ITEM( MODULE* aModule, const wxFileName& aFileName ) :
    m_module( aModule )
96 97
{
    m_file_name = aFileName;
98 99 100 101 102

    if( m_file_name.FileExists() )
        m_mod_time = m_file_name.GetModificationTime();
    else
        m_mod_time.Now();
103 104 105 106 107
}


bool FP_CACHE_ITEM::IsModified() const
{
108 109 110
    if( !m_file_name.FileExists() )
        return false;

111
    wxLogTrace( traceFootprintLibrary, wxT( "File '%s', m_mod_time %s-%s, file mod time: %s-%s." ),
112 113 114 115 116
                GetChars( m_file_name.GetFullPath() ),
                GetChars( m_mod_time.FormatDate() ), GetChars( m_mod_time.FormatTime() ),
                GetChars( m_file_name.GetModificationTime().FormatDate() ),
                GetChars( m_file_name.GetModificationTime().FormatTime() ) );

117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
    return m_file_name.GetModificationTime() != m_mod_time;
}


typedef boost::ptr_map< std::string, FP_CACHE_ITEM >  MODULE_MAP;
typedef MODULE_MAP::iterator                          MODULE_ITER;
typedef MODULE_MAP::const_iterator                    MODULE_CITER;


class FP_CACHE
{
    PCB_IO*         m_owner;        /// Plugin object that owns the cache.
    wxFileName      m_lib_path;     /// The path of the library.
    wxDateTime      m_mod_time;     /// Footprint library path modified time stamp.
    MODULE_MAP      m_modules;      /// Map of footprint file name per MODULE*.

public:
    FP_CACHE( PCB_IO* aOwner, const wxString& aLibraryPath );

Ben Harris's avatar
Ben Harris committed
136 137 138
    wxString    GetPath() const { return m_lib_path.GetPath(); }
    wxDateTime  GetLastModificationTime() const { return m_mod_time; }
    bool        IsWritable() const { return m_lib_path.IsOk() && m_lib_path.IsDirWritable(); }
139 140 141 142 143 144 145 146 147 148 149 150 151
    MODULE_MAP& GetModules() { return m_modules; }

    // Most all functions in this class throw IO_ERROR exceptions.  There are no
    // error codes nor user interface calls from here, nor in any PLUGIN.
    // Catch these exceptions higher up please.

    /// save the entire legacy library to m_lib_name;
    void Save();

    void Load();

    void Remove( const wxString& aFootprintName );

152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
    wxDateTime GetLibModificationTime() const;

    /**
     * Function IsModified
     * check if the footprint cache has been modified relative to \a aLibPath
     * and \a aFootprintName.
     *
     * @param aLibPath is a path to test the current cache library path against.
     * @param aFootprintName is the footprint name in the cache to test.  If the footprint
     *                       name is empty, the all the footprint files in the library are
     *                       checked to see if they have been modified.
     * @return true if the cache has been modified.
     */
    bool IsModified( const wxString& aLibPath,
                     const wxString& aFootprintName = wxEmptyString ) const;

    /**
     * Function IsPath
     * checks if \a aPath is the same as the current cache path.
     *
     * This tests paths by converting \a aPath using the native separators.  Internally
     * #FP_CACHE stores the current path using native separators.  This prevents path
     * miscompares on Windows due to the fact that paths can be stored with / instead of \\
     * in the footprint library table.
     *
     * @param aPath is the library path to test against.
     * @return true if \a aPath is the same as the cache path.
     */
    bool IsPath( const wxString& aPath ) const;
181 182 183 184 185 186 187 188 189 190
};


FP_CACHE::FP_CACHE( PCB_IO* aOwner, const wxString& aLibraryPath )
{
    m_owner = aOwner;
    m_lib_path.SetPath( aLibraryPath );
}


191
wxDateTime FP_CACHE::GetLibModificationTime() const
192 193 194 195 196 197 198 199 200
{
    return m_lib_path.GetModificationTime();
}


void FP_CACHE::Save()
{
    if( !m_lib_path.DirExists() && !m_lib_path.Mkdir() )
    {
201
        THROW_IO_ERROR( wxString::Format( _( "Cannot create footprint library path '%s'" ),
202 203 204 205 206
                                          m_lib_path.GetPath().GetData() ) );
    }

    if( !m_lib_path.IsDirWritable() )
    {
207
        THROW_IO_ERROR( wxString::Format( _( "Footprint library path '%s' is read only" ),
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222
                                          GetChars( m_lib_path.GetPath() ) ) );
    }

    for( MODULE_ITER it = m_modules.begin();  it != m_modules.end();  ++it )
    {
        wxFileName fn = it->second->GetFileName();

        if( fn.FileExists() && !it->second->IsModified() )
            continue;

        wxString tempFileName = fn.CreateTempFileName( fn.GetPath() );

        // Allow file output stream to go out of scope to close the file stream before
        // renaming the file.
        {
223 224
            wxLogTrace( traceFootprintLibrary, wxT( "Creating temporary library file %s" ),
                        GetChars( tempFileName ) );
225

226
            FILE_OUTPUTFORMATTER formatter( tempFileName );
227

228 229
            m_owner->SetOutputFormatter( &formatter );
            m_owner->Format( (BOARD_ITEM*) it->second->GetModule() );
230 231 232 233 234 235
        }

        wxRemove( fn.GetFullPath() );     // it is not an error if this does not exist

        if( wxRename( tempFileName, fn.GetFullPath() ) )
        {
236 237 238 239 240 241
            wxString msg = wxString::Format(
                    _( "Cannot rename temporary file '%s' to footprint library file '%s'" ),
                    GetChars( tempFileName ),
                    GetChars( fn.GetFullPath() )
                    );
            THROW_IO_ERROR( msg );
242 243 244 245 246 247 248 249 250 251 252 253 254 255
        }

        it->second->UpdateModificationTime();
        m_mod_time = GetLibModificationTime();
    }
}


void FP_CACHE::Load()
{
    wxDir dir( m_lib_path.GetPath() );

    if( !dir.IsOpened() )
    {
256 257 258 259 260 261
        wxString msg = wxString::Format(
                _( "Footprint library path '%s' does not exist" ),
                GetChars( m_lib_path.GetPath() )
                );

        THROW_IO_ERROR( msg );
262 263 264
    }

    wxString fpFileName;
265
    wxString wildcard = wxT( "*." ) + KiCadFootprintFileExtension;
266

Ben Harris's avatar
Ben Harris committed
267
    if( dir.GetFirst( &fpFileName, wildcard, wxDIR_FILES ) )
268
    {
Ben Harris's avatar
Ben Harris committed
269 270 271 272 273 274
        do
        {
            // prepend the libpath into fullPath
            wxFileName fullPath( m_lib_path.GetPath(), fpFileName );

            FILE_LINE_READER    reader( fullPath.GetFullPath() );
275

Ben Harris's avatar
Ben Harris committed
276
            m_owner->m_parser->SetLineReader( &reader );
277

278 279
            std::string name = TO_UTF8( fullPath.GetName() );
            MODULE*     footprint = (MODULE*) m_owner->m_parser->Parse();
280

281 282 283
            // The footprint name is the file name without the extension.
            footprint->SetFPID( fullPath.GetName() );
            m_modules.insert( name, new FP_CACHE_ITEM( footprint, fullPath ) );
284

Ben Harris's avatar
Ben Harris committed
285
        } while( dir.GetNext( &fpFileName ) );
286

Ben Harris's avatar
Ben Harris committed
287 288 289 290 291
        // Remember the file modification time of library file when the
        // cache snapshot was made, so that in a networked environment we will
        // reload the cache as needed.
        m_mod_time = GetLibModificationTime();
    }
292 293 294 295 296 297 298 299 300 301 302 303
}


void FP_CACHE::Remove( const wxString& aFootprintName )
{

    std::string footprintName = TO_UTF8( aFootprintName );

    MODULE_CITER it = m_modules.find( footprintName );

    if( it == m_modules.end() )
    {
304 305 306 307 308 309
        wxString msg = wxString::Format(
                _( "library '%s' has no footprint '%s' to delete" ),
                GetChars( m_lib_path.GetPath() ),
                GetChars( aFootprintName )
                );
        THROW_IO_ERROR( msg );
310 311 312 313 314 315 316 317 318
    }

    // Remove the module from the cache and delete the module file from the library.
    wxString fullPath = it->second->GetFileName().GetFullPath();
    m_modules.erase( footprintName );
    wxRemoveFile( fullPath );
}


319 320 321 322 323 324 325 326 327 328 329
bool FP_CACHE::IsPath( const wxString& aPath ) const
{
    // Converts path separators to native path separators
    wxFileName newPath;
    newPath.AssignDir( aPath );

    return m_lib_path == newPath;
}


bool FP_CACHE::IsModified( const wxString& aLibPath, const wxString& aFootprintName ) const
330
{
331 332
    // The library is modified if the library path got deleted or changed.
    if( !m_lib_path.DirExists() || !IsPath( aLibPath ) )
333 334
        return true;

335 336 337
    // If no footprint was specified, check every file modification time against the time
    // it was loaded.
    if( aFootprintName.IsEmpty() )
338
    {
339
        for( MODULE_CITER it = m_modules.begin();  it != m_modules.end();  ++it )
340
        {
341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359
            wxFileName fn = m_lib_path;
            fn.SetName( it->second->GetFileName().GetName() );
            fn.SetExt( KiCadFootprintFileExtension );

            if( !fn.FileExists() )
            {
                wxLogTrace( traceFootprintLibrary,
                            wxT( "Footprint cache file '%s' does not exist." ),
                            fn.GetFullPath().GetData() );
                return true;
            }

            if( it->second->IsModified() )
            {
                wxLogTrace( traceFootprintLibrary,
                            wxT( "Footprint cache file '%s' has been modified." ),
                            fn.GetFullPath().GetData() );
                return true;
            }
360
        }
361 362 363 364
    }
    else
    {
        MODULE_CITER it = m_modules.find( TO_UTF8( aFootprintName ) );
365

366
        if( it == m_modules.end() || it->second->IsModified() )
367 368 369 370 371 372 373
            return true;
    }

    return false;
}


374
void PCB_IO::Save( const wxString& aFileName, BOARD* aBoard, const PROPERTIES* aProperties )
375
{
376
    LOCALE_IO   toggle;     // toggles on, then off, the C locale.
377

378 379 380
    init( aProperties );

    m_board = aBoard;       // after init()
381

382
    FILE_OUTPUTFORMATTER    formatter( aFileName );
383 384 385 386 387 388 389 390 391 392 393 394

    m_out = &formatter;     // no ownership

    m_out->Print( 0, "(kicad_pcb (version %d) (host pcbnew %s)\n", SEXPR_BOARD_FILE_VERSION,
                  formatter.Quotew( GetBuildVersion() ).c_str() );

    Format( aBoard, 1 );

    m_out->Print( 0, ")\n" );
}


395
BOARD_ITEM* PCB_IO::Parse( const wxString& aClipboardSourceInput ) throw( PARSE_ERROR, IO_ERROR )
396 397 398 399 400
{
    std::string input = TO_UTF8( aClipboardSourceInput );

    STRING_LINE_READER  reader( input, wxT( "clipboard" ) );

401
    m_parser->SetLineReader( &reader );
402

403
    return m_parser->Parse();
404 405 406
}


407 408 409
void PCB_IO::Format( BOARD_ITEM* aItem, int aNestLevel ) const
    throw( IO_ERROR )
{
410 411
    LOCALE_IO   toggle;     // public API function, perform anything convenient for caller

412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466
    switch( aItem->Type() )
    {
    case PCB_T:
        format( (BOARD*) aItem, aNestLevel );
        break;

    case PCB_DIMENSION_T:
        format( ( DIMENSION*) aItem, aNestLevel );
        break;

    case PCB_LINE_T:
        format( (DRAWSEGMENT*) aItem, aNestLevel );
        break;

    case PCB_MODULE_EDGE_T:
        format( (EDGE_MODULE*) aItem, aNestLevel );
        break;

    case PCB_TARGET_T:
        format( (PCB_TARGET*) aItem, aNestLevel );
        break;

    case PCB_MODULE_T:
        format( (MODULE*) aItem, aNestLevel );
        break;

    case PCB_PAD_T:
        format( (D_PAD*) aItem, aNestLevel );
        break;

    case PCB_TEXT_T:
        format( (TEXTE_PCB*) aItem, aNestLevel );
        break;

    case PCB_MODULE_TEXT_T:
        format( (TEXTE_MODULE*) aItem, aNestLevel );
        break;

    case PCB_TRACE_T:
    case PCB_VIA_T:
        format( (TRACK*) aItem, aNestLevel );
        break;

    case PCB_ZONE_AREA_T:
        format( (ZONE_CONTAINER*) aItem, aNestLevel );
        break;

    default:
        wxFAIL_MSG( wxT( "Cannot format item " ) + aItem->GetClass() );
    }
}


void PCB_IO::formatLayer( const BOARD_ITEM* aItem ) const
{
467
    if( m_ctl & CTL_STD_LAYER_NAMES )
468
    {
469
        LAYER_NUM layer = aItem->GetLayer();
470 471

        // English layer names should never need quoting.
472
        m_out->Print( 0, " (layer %s)", TO_UTF8( BOARD::GetStandardLayerName( layer ) ) );
473 474 475
    }
    else
        m_out->Print( 0, " (layer %s)", m_out->Quotew( aItem->GetLayerName() ).c_str() );
476 477 478 479 480 481 482 483 484 485
}


void PCB_IO::format( BOARD* aBoard, int aNestLevel ) const
    throw( IO_ERROR )
{
    m_out->Print( 0, "\n" );

    m_out->Print( aNestLevel, "(general\n" );
    m_out->Print( aNestLevel+1, "(links %d)\n", aBoard->GetRatsnestsCount() );
486
    m_out->Print( aNestLevel+1, "(no_connects %d)\n", aBoard->GetUnconnectedNetCount() );
487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510

    // Write Bounding box info
    m_out->Print( aNestLevel+1,  "(area %s %s %s %s)\n",
                  FMTIU( aBoard->GetBoundingBox().GetX() ).c_str(),
                  FMTIU( aBoard->GetBoundingBox().GetY() ).c_str(),
                  FMTIU( aBoard->GetBoundingBox().GetRight() ).c_str(),
                  FMTIU( aBoard->GetBoundingBox().GetBottom() ).c_str() );
    m_out->Print( aNestLevel+1, "(thickness %s)\n",
                  FMTIU( aBoard->GetDesignSettings().GetBoardThickness() ).c_str() );

    m_out->Print( aNestLevel+1, "(drawings %d)\n", aBoard->m_Drawings.GetCount() );
    m_out->Print( aNestLevel+1, "(tracks %d)\n", aBoard->GetNumSegmTrack() );
    m_out->Print( aNestLevel+1, "(zones %d)\n", aBoard->GetNumSegmZone() );
    m_out->Print( aNestLevel+1, "(modules %d)\n", aBoard->m_Modules.GetCount() );
    m_out->Print( aNestLevel+1, "(nets %d)\n", aBoard->GetNetCount() );
    m_out->Print( aNestLevel, ")\n\n" );

    aBoard->GetPageSettings().Format( m_out, aNestLevel, m_ctl );
    aBoard->GetTitleBlock().Format( m_out, aNestLevel, m_ctl );

    // Layers.
    m_out->Print( aNestLevel, "(layers\n" );

    // Save only the used copper layers from front to back.
511
    for( LAYER_NUM layer = LAST_COPPER_LAYER; layer >= FIRST_COPPER_LAYER; --layer)
512
    {
513
        LAYER_MSK mask = GetLayerMask( layer );
514 515
        if( mask & aBoard->GetEnabledLayers() )
        {
516
            m_out->Print( aNestLevel+1, "(%d %s %s", layer,
517 518 519 520
                          m_out->Quotew( aBoard->GetLayerName( layer ) ).c_str(),
                          LAYER::ShowType( aBoard->GetLayerType( layer ) ) );

            if( !( aBoard->GetVisibleLayers() & mask ) )
521
                m_out->Print( 0, " hide" );
522 523 524 525 526 527

            m_out->Print( 0, ")\n" );
        }
    }

    // Save used non-copper layers in the order they are defined.
528
    for( LAYER_NUM layer = FIRST_NON_COPPER_LAYER; layer <= LAST_NON_COPPER_LAYER; ++layer)
529
    {
530
        LAYER_MSK mask = GetLayerMask( layer );
531 532 533 534 535 536
        if( mask & aBoard->GetEnabledLayers() )
        {
            m_out->Print( aNestLevel+1, "(%d %s user", layer,
                          m_out->Quotew( aBoard->GetLayerName( layer ) ).c_str() );

            if( !( aBoard->GetVisibleLayers() & mask ) )
537
                m_out->Print( 0, " hide" );
538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591

            m_out->Print( 0, ")\n" );
        }
    }

    m_out->Print( aNestLevel, ")\n\n" );

    // Setup
    m_out->Print( aNestLevel, "(setup\n" );

    // Save current default track width, for compatibility with older Pcbnew version;
    m_out->Print( aNestLevel+1, "(last_trace_width %s)\n",
                  FMTIU( aBoard->GetCurrentTrackWidth() ).c_str() );

    // Save custom tracks width list (the first is not saved here: this is the netclass value
    for( unsigned ii = 1; ii < aBoard->m_TrackWidthList.size(); ii++ )
        m_out->Print( aNestLevel+1, "(user_trace_width %s)\n",
                      FMTIU( aBoard->m_TrackWidthList[ii] ).c_str() );

    m_out->Print( aNestLevel+1, "(trace_clearance %s)\n",
                  FMTIU( aBoard->m_NetClasses.GetDefault()->GetClearance() ).c_str() );

    // ZONE_SETTINGS
    m_out->Print( aNestLevel+1, "(zone_clearance %s)\n",
                  FMTIU( aBoard->GetZoneSettings().m_ZoneClearance ).c_str() );
    m_out->Print( aNestLevel+1, "(zone_45_only %s)\n",
                  aBoard->GetZoneSettings().m_Zone_45_Only ? "yes" : "no" );

    m_out->Print( aNestLevel+1, "(trace_min %s)\n",
                  FMTIU( aBoard->GetDesignSettings().m_TrackMinWidth ).c_str() );

    m_out->Print( aNestLevel+1, "(segment_width %s)\n",
                  FMTIU( aBoard->GetDesignSettings().m_DrawSegmentWidth ).c_str() );
    m_out->Print( aNestLevel+1, "(edge_width %s)\n",
                  FMTIU( aBoard->GetDesignSettings().m_EdgeSegmentWidth ).c_str() );

    // Save current default via size, for compatibility with older Pcbnew version;
    m_out->Print( aNestLevel+1, "(via_size %s)\n",
                  FMTIU( aBoard->m_NetClasses.GetDefault()->GetViaDiameter() ).c_str() );
    m_out->Print( aNestLevel+1, "(via_drill %s)\n",
                  FMTIU( aBoard->m_NetClasses.GetDefault()->GetViaDrill() ).c_str() );
    m_out->Print( aNestLevel+1, "(via_min_size %s)\n",
                  FMTIU( aBoard->GetDesignSettings().m_ViasMinSize ).c_str() );
    m_out->Print( aNestLevel+1, "(via_min_drill %s)\n",
                  FMTIU( aBoard->GetDesignSettings().m_ViasMinDrill ).c_str() );

    // Save custom vias diameters list (the first is not saved here: this is
    // the netclass value
    for( unsigned ii = 1; ii < aBoard->m_ViasDimensionsList.size(); ii++ )
        m_out->Print( aNestLevel+1, "(user_via %s %s)\n",
                      FMTIU( aBoard->m_ViasDimensionsList[ii].m_Diameter ).c_str(),
                      FMTIU( aBoard->m_ViasDimensionsList[ii].m_Drill ).c_str() );

    // for old versions compatibility:
592 593
    if( aBoard->GetDesignSettings().m_BlindBuriedViaAllowed )
        m_out->Print( aNestLevel+1, "(blind_buried_vias_allowed yes)\n" );
594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627
    m_out->Print( aNestLevel+1, "(uvia_size %s)\n",
                  FMTIU( aBoard->m_NetClasses.GetDefault()->GetuViaDiameter() ).c_str() );
    m_out->Print( aNestLevel+1, "(uvia_drill %s)\n",
                  FMTIU( aBoard->m_NetClasses.GetDefault()->GetuViaDrill() ).c_str() );
    m_out->Print( aNestLevel+1, "(uvias_allowed %s)\n",
                  ( aBoard->GetDesignSettings().m_MicroViasAllowed ) ? "yes" : "no" );
    m_out->Print( aNestLevel+1, "(uvia_min_size %s)\n",
                  FMTIU( aBoard->GetDesignSettings().m_MicroViasMinSize ).c_str() );
    m_out->Print( aNestLevel+1, "(uvia_min_drill %s)\n",
                  FMTIU( aBoard->GetDesignSettings().m_MicroViasMinDrill ).c_str() );

    m_out->Print( aNestLevel+1, "(pcb_text_width %s)\n",
                  FMTIU( aBoard->GetDesignSettings().m_PcbTextWidth ).c_str() );
    m_out->Print( aNestLevel+1, "(pcb_text_size %s %s)\n",
                  FMTIU( aBoard->GetDesignSettings().m_PcbTextSize.x ).c_str(),
                  FMTIU( aBoard->GetDesignSettings().m_PcbTextSize.y ).c_str() );

    m_out->Print( aNestLevel+1, "(mod_edge_width %s)\n",
                  FMTIU( aBoard->GetDesignSettings().m_ModuleSegmentWidth ).c_str() );
    m_out->Print( aNestLevel+1, "(mod_text_size %s %s)\n",
                  FMTIU( aBoard->GetDesignSettings().m_ModuleTextSize.x ).c_str(),
                  FMTIU( aBoard->GetDesignSettings().m_ModuleTextSize.y ).c_str() );
    m_out->Print( aNestLevel+1, "(mod_text_width %s)\n",
                  FMTIU( aBoard->GetDesignSettings().m_ModuleTextWidth ).c_str() );

    m_out->Print( aNestLevel+1, "(pad_size %s %s)\n",
                  FMTIU( aBoard->GetDesignSettings().m_Pad_Master.GetSize().x ).c_str(),
                  FMTIU( aBoard->GetDesignSettings().m_Pad_Master.GetSize().y ).c_str() );
    m_out->Print( aNestLevel+1, "(pad_drill %s)\n",
                  FMTIU( aBoard->GetDesignSettings().m_Pad_Master.GetDrillSize().x ).c_str() );

    m_out->Print( aNestLevel+1, "(pad_to_mask_clearance %s)\n",
                  FMTIU( aBoard->GetDesignSettings().m_SolderMaskMargin ).c_str() );

628 629 630 631
    if( aBoard->GetDesignSettings().m_SolderMaskMinWidth )
        m_out->Print( aNestLevel+1, "(solder_mask_min_width %s)\n",
                      FMTIU( aBoard->GetDesignSettings().m_SolderMaskMinWidth ).c_str() );

632 633 634 635 636
    if( aBoard->GetDesignSettings().m_SolderPasteMargin != 0 )
        m_out->Print( aNestLevel+1, "(pad_to_paste_clearance %s)\n",
                      FMTIU( aBoard->GetDesignSettings().m_SolderPasteMargin ).c_str() );

    if( aBoard->GetDesignSettings().m_SolderPasteMarginRatio != 0 )
637
        m_out->Print( aNestLevel+1, "(pad_to_paste_clearance_ratio %s)\n",
638
                      Double2Str( aBoard->GetDesignSettings().m_SolderPasteMarginRatio ).c_str() );
639 640

    m_out->Print( aNestLevel+1, "(aux_axis_origin %s %s)\n",
641 642 643
                  FMTIU( aBoard->GetAuxOrigin().x ).c_str(),
                  FMTIU( aBoard->GetAuxOrigin().y ).c_str() );

644 645 646 647
    if( aBoard->GetGridOrigin().x || aBoard->GetGridOrigin().y )
        m_out->Print( aNestLevel+1, "(grid_origin %s %s)\n",
                      FMTIU( aBoard->GetGridOrigin().x ).c_str(),
                      FMTIU( aBoard->GetGridOrigin().y ).c_str() );
648 649 650 651

    m_out->Print( aNestLevel+1, "(visible_elements %X)\n",
                  aBoard->GetDesignSettings().GetVisibleElements() );

652
    aBoard->GetPlotOptions().Format( m_out, aNestLevel+1 );
653

654 655 656 657 658
    m_out->Print( aNestLevel, ")\n\n" );

    int netcount = aBoard->GetNetCount();

    for( int i = 0;  i < netcount;  ++i )
659 660
    {
        NETINFO_ITEM*   net = aBoard->FindNet( i );
661
        m_out->Print( aNestLevel, "(net %d %s)\n",
662 663 664
                      net->GetNet(),
                      m_out->Quotew( net->GetNetname() ).c_str() );
    }
665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686

    m_out->Print( 0, "\n" );

    // Save the default net class first.
    aBoard->m_NetClasses.GetDefault()->Format( m_out, aNestLevel, m_ctl );

    // Save the rest of the net classes alphabetically.
    for( NETCLASSES::const_iterator it = aBoard->m_NetClasses.begin();
         it != aBoard->m_NetClasses.end();
         ++it )
    {
        NETCLASS* netclass = it->second;
        netclass->Format( m_out, aNestLevel, m_ctl );
    }

    // Save the modules.
    for( MODULE* module = aBoard->m_Modules;  module;  module = (MODULE*) module->Next() )
    {
        Format( module, aNestLevel );
        m_out->Print( 0, "\n" );
    }

687 688 689 690
    // Save the graphical items on the board (not owned by a module)
    for( BOARD_ITEM* item = aBoard->m_Drawings;  item;  item = item->Next() )
        Format( item, aNestLevel );

691 692
    if( aBoard->m_Drawings.GetCount() )
        m_out->Print( 0, "\n" );
693

694 695 696 697 698 699
    // Do not save MARKER_PCBs, they can be regenerated easily.

    // Save the tracks and vias.
    for( TRACK* track = aBoard->m_Track;  track; track = track->Next() )
        Format( track, aNestLevel );

700 701 702
    if( aBoard->m_Track.GetCount() )
        m_out->Print( 0, "\n" );

703 704 705 706 707 708 709 710 711 712 713 714 715
    /// @todo Add warning here that the old segment filed zones are no longer supported and
    ///       will not be saved.

    // Save the polygon (which are the newer technology) zones.
    for( int i=0;  i < aBoard->GetAreaCount();  ++i )
        Format( aBoard->GetArea( i ), aNestLevel );
}


void PCB_IO::format( DIMENSION* aDimension, int aNestLevel ) const
    throw( IO_ERROR )
{
    m_out->Print( aNestLevel, "(dimension %s (width %s)",
716 717
                  FMT_IU( aDimension->GetValue() ).c_str(),
                  FMT_IU( aDimension->GetWidth() ).c_str() );
718 719 720 721 722 723 724 725

    formatLayer( aDimension );

    if( aDimension->GetTimeStamp() )
        m_out->Print( 0, " (tstamp %lX)", aDimension->GetTimeStamp() );

    m_out->Print( 0, "\n" );

726
    Format( (TEXTE_PCB*) &aDimension->Text(), aNestLevel+1 );
727 728

    m_out->Print( aNestLevel+1, "(feature1 (pts (xy %s %s) (xy %s %s)))\n",
729 730 731 732
                  FMT_IU( aDimension->m_featureLineDO.x ).c_str(),
                  FMT_IU( aDimension->m_featureLineDO.y ).c_str(),
                  FMT_IU( aDimension->m_featureLineDF.x ).c_str(),
                  FMT_IU( aDimension->m_featureLineDF.y ).c_str() );
733 734

    m_out->Print( aNestLevel+1, "(feature2 (pts (xy %s %s) (xy %s %s)))\n",
735 736 737 738
                  FMT_IU( aDimension->m_featureLineGO.x ).c_str(),
                  FMT_IU( aDimension->m_featureLineGO.y ).c_str(),
                  FMT_IU( aDimension->m_featureLineGF.x ).c_str(),
                  FMT_IU( aDimension->m_featureLineGF.y ).c_str() );
739 740

    m_out->Print( aNestLevel+1, "(crossbar (pts (xy %s %s) (xy %s %s)))\n",
741 742 743 744
                  FMT_IU( aDimension->m_crossBarO.x ).c_str(),
                  FMT_IU( aDimension->m_crossBarO.y ).c_str(),
                  FMT_IU( aDimension->m_crossBarF.x ).c_str(),
                  FMT_IU( aDimension->m_crossBarF.y ).c_str() );
745 746

    m_out->Print( aNestLevel+1, "(arrow1a (pts (xy %s %s) (xy %s %s)))\n",
747 748 749 750
                  FMT_IU( aDimension->m_arrowD1O.x ).c_str(),
                  FMT_IU( aDimension->m_arrowD1O.y ).c_str(),
                  FMT_IU( aDimension->m_arrowD1F.x ).c_str(),
                  FMT_IU( aDimension->m_arrowD1F.y ).c_str() );
751 752

    m_out->Print( aNestLevel+1, "(arrow1b (pts (xy %s %s) (xy %s %s)))\n",
753 754 755 756
                  FMT_IU( aDimension->m_arrowD2O.x ).c_str(),
                  FMT_IU( aDimension->m_arrowD2O.y ).c_str(),
                  FMT_IU( aDimension->m_arrowD2F.x ).c_str(),
                  FMT_IU( aDimension->m_arrowD2F.y ).c_str() );
757 758

    m_out->Print( aNestLevel+1, "(arrow2a (pts (xy %s %s) (xy %s %s)))\n",
759 760 761 762
                  FMT_IU( aDimension->m_arrowG1O.x ).c_str(),
                  FMT_IU( aDimension->m_arrowG1O.y ).c_str(),
                  FMT_IU( aDimension->m_arrowG1F.x ).c_str(),
                  FMT_IU( aDimension->m_arrowG1F.y ).c_str() );
763 764

    m_out->Print( aNestLevel+1, "(arrow2b (pts (xy %s %s) (xy %s %s)))\n",
765 766 767 768
                  FMT_IU( aDimension->m_arrowG2O.x ).c_str(),
                  FMT_IU( aDimension->m_arrowG2O.y ).c_str(),
                  FMT_IU( aDimension->m_arrowG2F.x ).c_str(),
                  FMT_IU( aDimension->m_arrowG2F.y ).c_str() );
769 770 771 772 773 774 775 776 777 778 779 780 781

    m_out->Print( aNestLevel, ")\n" );
}


void PCB_IO::format( DRAWSEGMENT* aSegment, int aNestLevel ) const
    throw( IO_ERROR )
{
    unsigned i;

    switch( aSegment->GetShape() )
    {
    case S_SEGMENT:  // Line
782
        m_out->Print( aNestLevel, "(gr_line (start %s) (end %s)",
783
                      FMT_IU( aSegment->GetStart() ).c_str(),
784 785 786 787 788
                      FMT_IU( aSegment->GetEnd() ).c_str() );

        if( aSegment->GetAngle() != 0.0 )
            m_out->Print( 0, " (angle %s)", FMT_ANGLE( aSegment->GetAngle() ).c_str() );

789 790 791
        break;

    case S_CIRCLE:  // Circle
792
        m_out->Print( aNestLevel, "(gr_circle (center %s) (end %s)",
793 794 795 796 797
                      FMT_IU( aSegment->GetStart() ).c_str(),
                      FMT_IU( aSegment->GetEnd() ).c_str() );
        break;

    case S_ARC:     // Arc
798
        m_out->Print( aNestLevel, "(gr_arc (start %s) (end %s) (angle %s)",
799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845
                      FMT_IU( aSegment->GetStart() ).c_str(),
                      FMT_IU( aSegment->GetEnd() ).c_str(),
                      FMT_ANGLE( aSegment->GetAngle() ).c_str() );
        break;

    case S_POLYGON: // Polygon
        m_out->Print( aNestLevel, "(gr_poly (pts" );

        for( i = 0;  i < aSegment->GetPolyPoints().size();  ++i )
            m_out->Print( 0, " (xy %s)", FMT_IU( aSegment->GetPolyPoints()[i] ).c_str() );

        m_out->Print( 0, ")" );
        break;

    case S_CURVE:   // Bezier curve
        m_out->Print( aNestLevel, "(gr_curve (pts (xy %s) (xy %s) (xy %s) (xy %s))",
                      FMT_IU( aSegment->GetStart() ).c_str(),
                      FMT_IU( aSegment->GetBezControl1() ).c_str(),
                      FMT_IU( aSegment->GetBezControl2() ).c_str(),
                      FMT_IU( aSegment->GetEnd() ).c_str() );
        break;

    default:
        wxFAIL_MSG( wxT( "Cannot format invalid DRAWSEGMENT type." ) );
    };

    formatLayer( aSegment );

    if( aSegment->GetWidth() != 0 )
        m_out->Print( 0, " (width %s)", FMT_IU( aSegment->GetWidth() ).c_str() );

    if( aSegment->GetTimeStamp() )
        m_out->Print( 0, " (tstamp %lX)", aSegment->GetTimeStamp() );

    if( aSegment->GetStatus() )
        m_out->Print( 0, " (status %X)", aSegment->GetStatus() );

    m_out->Print( 0, ")\n" );
}


void PCB_IO::format( EDGE_MODULE* aModuleDrawing, int aNestLevel ) const
    throw( IO_ERROR )
{
    switch( aModuleDrawing->GetShape() )
    {
    case S_SEGMENT:  // Line
846
        m_out->Print( aNestLevel, "(fp_line (start %s) (end %s)",
847 848 849 850 851
                      FMT_IU( aModuleDrawing->GetStart0() ).c_str(),
                      FMT_IU( aModuleDrawing->GetEnd0() ).c_str() );
        break;

    case S_CIRCLE:  // Circle
852
        m_out->Print( aNestLevel, "(fp_circle (center %s) (end %s)",
853 854 855 856 857
                      FMT_IU( aModuleDrawing->GetStart0() ).c_str(),
                      FMT_IU( aModuleDrawing->GetEnd0() ).c_str() );
        break;

    case S_ARC:     // Arc
858
        m_out->Print( aNestLevel, "(fp_arc (start %s) (end %s) (angle %s)",
859 860 861 862 863 864 865 866 867
                      FMT_IU( aModuleDrawing->GetStart0() ).c_str(),
                      FMT_IU( aModuleDrawing->GetEnd0() ).c_str(),
                      FMT_ANGLE( aModuleDrawing->GetAngle() ).c_str() );
        break;

    case S_POLYGON: // Polygon
        m_out->Print( aNestLevel, "(fp_poly (pts" );

        for( unsigned i = 0;  i < aModuleDrawing->GetPolyPoints().size();  ++i )
Dick Hollenbeck's avatar
Dick Hollenbeck committed
868 869 870 871 872 873 874 875
        {
            int nestLevel = 0;

            if( i && !(i%4) )   // newline every 4(pts)
            {
                nestLevel = aNestLevel + 1;
                m_out->Print( 0, "\n" );
            }
876

Dick Hollenbeck's avatar
Dick Hollenbeck committed
877 878 879 880 881
            m_out->Print( nestLevel, "%s(xy %s)",
                          nestLevel ? "" : " ",
                          FMT_IU( aModuleDrawing->GetPolyPoints()[i] ).c_str() );
        }
        m_out->Print( 0, ")" );
882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900
        break;

    case S_CURVE:   // Bezier curve
        m_out->Print( aNestLevel, "(fp_curve (pts (xy %s) (xy %s) (xy %s) (xy %s))",
                      FMT_IU( aModuleDrawing->GetStart0() ).c_str(),
                      FMT_IU( aModuleDrawing->GetBezControl1() ).c_str(),
                      FMT_IU( aModuleDrawing->GetBezControl2() ).c_str(),
                      FMT_IU( aModuleDrawing->GetEnd0() ).c_str() );
        break;

    default:
        wxFAIL_MSG( wxT( "Cannot format invalid DRAWSEGMENT type." ) );
    };

    formatLayer( aModuleDrawing );

    if( aModuleDrawing->GetWidth() != 0 )
        m_out->Print( 0, " (width %s)", FMT_IU( aModuleDrawing->GetWidth() ).c_str() );

901 902
    /*  11-Nov-2021 remove if no one whines after a couple of months.  Simple graphic items
        perhaps do not need these.
903 904 905 906 907
    if( aModuleDrawing->GetTimeStamp() )
        m_out->Print( 0, " (tstamp %lX)", aModuleDrawing->GetTimeStamp() );

    if( aModuleDrawing->GetStatus() )
        m_out->Print( 0, " (status %X)", aModuleDrawing->GetStatus() );
908
    */
909 910 911 912 913 914 915 916 917 918 919 920 921 922

    m_out->Print( 0, ")\n" );
}


void PCB_IO::format( PCB_TARGET* aTarget, int aNestLevel ) const
    throw( IO_ERROR )
{
    m_out->Print( aNestLevel, "(target %s (at %s) (size %s)",
                  ( aTarget->GetShape() ) ? "x" : "plus",
                  FMT_IU( aTarget->GetPosition() ).c_str(),
                  FMT_IU( aTarget->GetSize() ).c_str() );

    if( aTarget->GetWidth() != 0 )
923
        m_out->Print( 0, " (width %s)", FMT_IU( aTarget->GetWidth() ).c_str() );
924 925 926 927

    formatLayer( aTarget );

    if( aTarget->GetTimeStamp() )
928
        m_out->Print( 0, " (tstamp %lX)", aTarget->GetTimeStamp() );
929

930
    m_out->Print( 0, ")\n" );
931 932 933 934 935 936
}


void PCB_IO::format( MODULE* aModule, int aNestLevel ) const
    throw( IO_ERROR )
{
937
    if( !( m_ctl & CTL_OMIT_INITIAL_COMMENTS ) )
938
    {
939 940 941 942 943 944 945 946 947
        const wxArrayString* initial_comments = aModule->GetInitialComments();

        if( initial_comments )
        {
            for( unsigned i=0;  i<initial_comments->GetCount();  ++i )
                m_out->Print( aNestLevel, "%s\n",  TO_UTF8( (*initial_comments)[i] ) );

            m_out->Print( 0, "\n" );    // improve readability?
        }
948 949
    }

950
    m_out->Print( aNestLevel, "(module %s",
951
                  m_out->Quotes( aModule->GetFPID().Format() ).c_str() );
952 953

    if( aModule->IsLocked() )
954
        m_out->Print( 0, " locked" );
955 956

    if( aModule->IsPlaced() )
957
        m_out->Print( 0, " placed" );
958 959 960

    formatLayer( aModule );

961 962 963
    if( !( m_ctl & CTL_OMIT_TSTAMPS ) )
    {
        m_out->Print( 0, " (tedit %lX) (tstamp %lX)\n",
964
                       aModule->GetLastEditTime(), aModule->GetTimeStamp() );
965 966 967
    }
    else
        m_out->Print( 0, "\n" );
968

969
    m_out->Print( aNestLevel+1, "(at %s", FMT_IU( aModule->GetPosition() ).c_str() );
970

971 972
    if( aModule->GetOrientation() != 0.0 )
        m_out->Print( 0, " %s", FMT_ANGLE( aModule->GetOrientation() ).c_str() );
973 974 975

    m_out->Print( 0, ")\n" );

976
    if( !aModule->GetDescription().IsEmpty() )
977
        m_out->Print( aNestLevel+1, "(descr %s)\n",
978
                      m_out->Quotew( aModule->GetDescription() ).c_str() );
979

980
    if( !aModule->GetKeywords().IsEmpty() )
981
        m_out->Print( aNestLevel+1, "(tags %s)\n",
982
                      m_out->Quotew( aModule->GetKeywords() ).c_str() );
983

Dick Hollenbeck's avatar
Dick Hollenbeck committed
984
    if( !( m_ctl & CTL_OMIT_PATH ) && !!aModule->GetPath() )
985
        m_out->Print( aNestLevel+1, "(path %s)\n",
986
                      m_out->Quotew( aModule->GetPath() ).c_str() );
987

988 989
    if( aModule->GetPlacementCost90() != 0 )
        m_out->Print( aNestLevel+1, "(autoplace_cost90 %d)\n", aModule->GetPlacementCost90() );
990

991 992
    if( aModule->GetPlacementCost180() != 0 )
        m_out->Print( aNestLevel+1, "(autoplace_cost180 %d)\n", aModule->GetPlacementCost180() );
993 994 995 996 997 998 999 1000 1001 1002

    if( aModule->GetLocalSolderMaskMargin() != 0 )
        m_out->Print( aNestLevel+1, "(solder_mask_margin %s)\n",
                      FMT_IU( aModule->GetLocalSolderMaskMargin() ).c_str() );

    if( aModule->GetLocalSolderPasteMargin() != 0 )
        m_out->Print( aNestLevel+1, "(solder_paste_margin %s)\n",
                      FMT_IU( aModule->GetLocalSolderPasteMargin() ).c_str() );

    if( aModule->GetLocalSolderPasteMarginRatio() != 0 )
1003
        m_out->Print( aNestLevel+1, "(solder_paste_ratio %s)\n",
1004
                      Double2Str( aModule->GetLocalSolderPasteMarginRatio() ).c_str() );
1005 1006 1007 1008 1009

    if( aModule->GetLocalClearance() != 0 )
        m_out->Print( aNestLevel+1, "(clearance %s)\n",
                      FMT_IU( aModule->GetLocalClearance() ).c_str() );

1010 1011
    if( aModule->GetZoneConnection() != UNDEFINED_CONNECTION )
        m_out->Print( aNestLevel+1, "(zone_connect %d)\n", aModule->GetZoneConnection() );
1012

1013
    if( aModule->GetThermalWidth() != 0 )
1014
        m_out->Print( aNestLevel+1, "(thermal_width %s)\n",
1015
                      FMT_IU( aModule->GetThermalWidth() ).c_str() );
1016

1017
    if( aModule->GetThermalGap() != 0 )
1018
        m_out->Print( aNestLevel+1, "(thermal_gap %s)\n",
1019
                      FMT_IU( aModule->GetThermalGap() ).c_str() );
1020 1021

    // Attributes
1022
    if( aModule->GetAttributes() != MOD_DEFAULT )
1023 1024 1025
    {
        m_out->Print( aNestLevel+1, "(attr" );

1026
        if( aModule->GetAttributes() & MOD_CMS )
1027 1028
            m_out->Print( 0, " smd" );

1029
        if( aModule->GetAttributes() & MOD_VIRTUAL )
1030 1031 1032 1033 1034
            m_out->Print( 0, " virtual" );

        m_out->Print( 0, ")\n" );
    }

1035 1036
    Format( (BOARD_ITEM*) &aModule->Reference(), aNestLevel+1 );
    Format( (BOARD_ITEM*) &aModule->Value(), aNestLevel+1 );
1037 1038

    // Save drawing elements.
1039
    for( BOARD_ITEM* gr = aModule->GraphicalItems();  gr;  gr = gr->Next() )
1040 1041 1042
        Format( gr, aNestLevel+1 );

    // Save pads.
1043
    for( D_PAD* pad = aModule->Pads();  pad;  pad = pad->Next() )
1044
        format( pad, aNestLevel+1 );
1045 1046

    // Save 3D info.
1047
    for( S3D_MASTER* t3D = aModule->Models();  t3D;  t3D = t3D->Next() )
1048 1049 1050 1051 1052 1053
    {
        if( !t3D->m_Shape3DName.IsEmpty() )
        {
            m_out->Print( aNestLevel+1, "(model %s\n",
                          m_out->Quotew( t3D->m_Shape3DName ).c_str() );

1054
            m_out->Print( aNestLevel+2, "(at (xyz %s %s %s))\n",
1055 1056 1057
                          Double2Str( t3D->m_MatPosition.x ).c_str(),
                          Double2Str( t3D->m_MatPosition.y ).c_str(),
                          Double2Str( t3D->m_MatPosition.z ).c_str() );
1058

1059
            m_out->Print( aNestLevel+2, "(scale (xyz %s %s %s))\n",
1060 1061 1062
                          Double2Str( t3D->m_MatScale.x ).c_str(),
                          Double2Str( t3D->m_MatScale.y ).c_str(),
                          Double2Str( t3D->m_MatScale.z ).c_str() );
1063

1064
            m_out->Print( aNestLevel+2, "(rotate (xyz %s %s %s))\n",
1065 1066 1067
                          Double2Str( t3D->m_MatRotation.x ).c_str(),
                          Double2Str( t3D->m_MatRotation.y ).c_str(),
                          Double2Str( t3D->m_MatRotation.z ).c_str() );
1068 1069 1070 1071 1072 1073 1074 1075 1076

            m_out->Print( aNestLevel+1, ")\n" );
        }
    }

    m_out->Print( aNestLevel, ")\n" );
}


1077
void PCB_IO::formatLayers( LAYER_MSK aLayerMask, int aNestLevel ) const
1078 1079
    throw( IO_ERROR )
{
1080 1081 1082 1083 1084 1085
    std::string  output;

    if( aNestLevel == 0 )
        output += ' ';

    output += "(layers";
1086

1087
    LAYER_MSK cuMask = ALL_CU_LAYERS;
1088 1089 1090 1091 1092 1093 1094 1095

    if( m_board )
        cuMask &= m_board->GetEnabledLayers();

    // output copper layers first, then non copper

    if( ( aLayerMask & cuMask ) == cuMask )
    {
1096
        output += " *.Cu";
1097 1098 1099 1100
        aLayerMask &= ~ALL_CU_LAYERS;       // clear bits, so they are not output again below
    }
    else if( ( aLayerMask & cuMask ) == (LAYER_BACK | LAYER_FRONT) )
    {
1101
        output += " F&B.Cu";
1102 1103 1104 1105 1106
        aLayerMask &= ~(LAYER_BACK | LAYER_FRONT);
    }

    if( ( aLayerMask & (ADHESIVE_LAYER_BACK | ADHESIVE_LAYER_FRONT)) == (ADHESIVE_LAYER_BACK | ADHESIVE_LAYER_FRONT) )
    {
1107
        output += " *.Adhes";
1108 1109 1110 1111 1112
        aLayerMask &= ~(ADHESIVE_LAYER_BACK | ADHESIVE_LAYER_FRONT);
    }

    if( ( aLayerMask & (SOLDERPASTE_LAYER_BACK | SOLDERPASTE_LAYER_FRONT)) == (SOLDERPASTE_LAYER_BACK | SOLDERPASTE_LAYER_FRONT) )
    {
1113
        output += " *.Paste";
1114 1115 1116 1117 1118
        aLayerMask &= ~(SOLDERPASTE_LAYER_BACK | SOLDERPASTE_LAYER_FRONT);
    }

    if( ( aLayerMask & (SILKSCREEN_LAYER_BACK | SILKSCREEN_LAYER_FRONT)) == (SILKSCREEN_LAYER_BACK | SILKSCREEN_LAYER_FRONT) )
    {
1119
        output += " *.SilkS";
1120 1121 1122 1123 1124
        aLayerMask &= ~(SILKSCREEN_LAYER_BACK | SILKSCREEN_LAYER_FRONT);
    }

    if( ( aLayerMask & (SOLDERMASK_LAYER_BACK | SOLDERMASK_LAYER_FRONT)) == (SOLDERMASK_LAYER_BACK | SOLDERMASK_LAYER_FRONT) )
    {
1125
        output += " *.Mask";
1126 1127 1128 1129 1130 1131
        aLayerMask &= ~(SOLDERMASK_LAYER_BACK | SOLDERMASK_LAYER_FRONT);
    }

    // output any individual layers not handled in wildcard combos above

    if( m_board )
1132
        aLayerMask &= m_board->GetEnabledLayers();
1133 1134 1135

    wxString layerName;

1136
    for( LAYER_NUM layer = FIRST_LAYER; layer < NB_PCB_LAYERS; ++layer )
1137
    {
1138
        if( aLayerMask & GetLayerMask( layer ) )
1139
        {
1140
            if( m_board && !( m_ctl & CTL_STD_LAYER_NAMES ) )
1141 1142 1143
                layerName = m_board->GetLayerName( layer );

            else    // I am being called from FootprintSave()
1144
                layerName = BOARD::GetStandardLayerName( layer );
1145

1146 1147
            output += ' ';
            output += m_out->Quotew( layerName );
1148 1149 1150
        }
    }

1151
    m_out->Print( aNestLevel, "%s)", output.c_str() );
1152 1153 1154
}


1155 1156 1157
void PCB_IO::format( D_PAD* aPad, int aNestLevel ) const
    throw( IO_ERROR )
{
1158
    const char* shape;
1159 1160 1161

    switch( aPad->GetShape() )
    {
1162 1163 1164 1165
    case PAD_CIRCLE:    shape = "circle";       break;
    case PAD_RECT:      shape = "rect";         break;
    case PAD_OVAL:      shape = "oval";         break;
    case PAD_TRAPEZOID: shape = "trapezoid";    break;
1166 1167 1168 1169 1170

    default:
        THROW_IO_ERROR( wxString::Format( _( "unknown pad type: %d"), aPad->GetShape() ) );
    }

1171
    const char* type;
1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184

    switch( aPad->GetAttribute() )
    {
    case PAD_STANDARD:          type = "thru_hole";      break;
    case PAD_SMD:               type = "smd";            break;
    case PAD_CONN:              type = "connect";        break;
    case PAD_HOLE_NOT_PLATED:   type = "np_thru_hole";   break;

    default:
        THROW_IO_ERROR( wxString::Format( _( "unknown pad attribute: %d" ),
                                          aPad->GetAttribute() ) );
    }

1185
    m_out->Print( aNestLevel, "(pad %s %s %s",
1186
                  m_out->Quotew( aPad->GetPadName() ).c_str(),
1187
                  type, shape );
1188
    m_out->Print( 0, " (at %s", FMT_IU( aPad->GetPos0() ).c_str() );
1189 1190 1191 1192

    if( aPad->GetOrientation() != 0.0 )
        m_out->Print( 0, " %s", FMT_ANGLE( aPad->GetOrientation() ).c_str() );

1193
    m_out->Print( 0, ")" );
1194
    m_out->Print( 0, " (size %s)", FMT_IU( aPad->GetSize() ).c_str() );
1195 1196 1197 1198 1199

    if( (aPad->GetDelta().GetWidth()) != 0 || (aPad->GetDelta().GetHeight() != 0 ) )
        m_out->Print( 0, " (rect_delta %s )", FMT_IU( aPad->GetDelta() ).c_str() );

    wxSize sz = aPad->GetDrillSize();
1200
    wxPoint shapeoffset = aPad->GetOffset();
1201

1202
    if( (sz.GetWidth() > 0) || (sz.GetHeight() > 0) ||
1203
        (shapeoffset.x != 0) || (shapeoffset.y != 0) )
1204
    {
1205
        m_out->Print( 0, " (drill" );
1206

1207 1208 1209
        if( aPad->GetDrillShape() == PAD_OVAL )
            m_out->Print( 0, " oval" );

1210 1211 1212 1213 1214
        if( sz.GetWidth() > 0 )
            m_out->Print( 0,  " %s", FMT_IU( sz.GetWidth() ).c_str() );

        if( sz.GetHeight() > 0  && sz.GetWidth() != sz.GetHeight() )
            m_out->Print( 0,  " %s", FMT_IU( sz.GetHeight() ).c_str() );
1215

1216
        if( (shapeoffset.x != 0) || (shapeoffset.y != 0) )
1217
            m_out->Print( 0, " (offset %s)", FMT_IU( aPad->GetOffset() ).c_str() );
1218

1219
        m_out->Print( 0, ")" );
1220 1221
    }

1222
    formatLayers( aPad->GetLayerMask(), 0 );
1223

1224
    std::string output;
1225

1226
    // Unconnected pad is default net so don't save it.
1227
    if( !(m_ctl & CTL_OMIT_NETS) && aPad->GetNet() != 0 )
Dick Hollenbeck's avatar
Dick Hollenbeck committed
1228
        StrPrintf( &output, " (net %d %s)", aPad->GetNet(), m_out->Quotew( aPad->GetNetname() ).c_str() );
1229

1230
    if( aPad->GetPadToDieLength() != 0 )
Dick Hollenbeck's avatar
Dick Hollenbeck committed
1231
        StrPrintf( &output, " (die_length %s)", FMT_IU( aPad->GetPadToDieLength() ).c_str() );
1232 1233

    if( aPad->GetLocalSolderMaskMargin() != 0 )
Dick Hollenbeck's avatar
Dick Hollenbeck committed
1234
        StrPrintf( &output, " (solder_mask_margin %s)", FMT_IU( aPad->GetLocalSolderMaskMargin() ).c_str() );
1235 1236

    if( aPad->GetLocalSolderPasteMargin() != 0 )
Dick Hollenbeck's avatar
Dick Hollenbeck committed
1237
        StrPrintf( &output, " (solder_paste_margin %s)", FMT_IU( aPad->GetLocalSolderPasteMargin() ).c_str() );
1238 1239

    if( aPad->GetLocalSolderPasteMarginRatio() != 0 )
Dick Hollenbeck's avatar
Dick Hollenbeck committed
1240
        StrPrintf( &output, " (solder_paste_margin_ratio %s)",
1241
                Double2Str( aPad->GetLocalSolderPasteMarginRatio() ).c_str() );
1242 1243

    if( aPad->GetLocalClearance() != 0 )
Dick Hollenbeck's avatar
Dick Hollenbeck committed
1244
        StrPrintf( &output, " (clearance %s)", FMT_IU( aPad->GetLocalClearance() ).c_str() );
1245 1246

    if( aPad->GetZoneConnection() != UNDEFINED_CONNECTION )
Dick Hollenbeck's avatar
Dick Hollenbeck committed
1247
        StrPrintf( &output, " (zone_connect %d)", aPad->GetZoneConnection() );
1248 1249

    if( aPad->GetThermalWidth() != 0 )
Dick Hollenbeck's avatar
Dick Hollenbeck committed
1250
        StrPrintf( &output, " (thermal_width %s)", FMT_IU( aPad->GetThermalWidth() ).c_str() );
1251 1252

    if( aPad->GetThermalGap() != 0 )
Dick Hollenbeck's avatar
Dick Hollenbeck committed
1253
        StrPrintf( &output, " (thermal_gap %s)", FMT_IU( aPad->GetThermalGap() ).c_str() );
1254

1255 1256 1257
    if( output.size() )
    {
        m_out->Print( 0, "\n" );
Dick Hollenbeck's avatar
Dick Hollenbeck committed
1258
        m_out->Print( aNestLevel+1, "%s", output.c_str()+1 );   // +1 skips 1st space on 1st element
1259 1260 1261
    }

    m_out->Print( 0, ")\n" );
1262 1263 1264 1265 1266 1267
}


void PCB_IO::format( TEXTE_PCB* aText, int aNestLevel ) const
    throw( IO_ERROR )
{
1268
    m_out->Print( aNestLevel, "(gr_text %s (at %s",
1269
                  m_out->Quotew( aText->GetText() ).c_str(),
1270
                  FMT_IU( aText->GetTextPosition() ).c_str() );
1271 1272 1273 1274 1275

    if( aText->GetOrientation() != 0.0 )
        m_out->Print( 0, " %s", FMT_ANGLE( aText->GetOrientation() ).c_str() );

    m_out->Print( 0, ")" );
1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298

    formatLayer( aText );

    if( aText->GetTimeStamp() )
        m_out->Print( 0, " (tstamp %lX)", aText->GetTimeStamp() );

    m_out->Print( 0, "\n" );

    aText->EDA_TEXT::Format( m_out, aNestLevel, m_ctl );

    m_out->Print( aNestLevel, ")\n" );
}


void PCB_IO::format( TEXTE_MODULE* aText, int aNestLevel ) const
    throw( IO_ERROR )
{
    MODULE*  parent = (MODULE*) aText->GetParent();
    double   orient = aText->GetOrientation();
    wxString type;

    switch( aText->GetType() )
    {
1299 1300 1301
    case TEXTE_MODULE::TEXT_is_REFERENCE: type = wxT( "reference" );     break;
    case TEXTE_MODULE::TEXT_is_VALUE:     type = wxT( "value" );         break;
    default:                              type = wxT( "user" );
1302 1303 1304 1305 1306 1307 1308
    }

    // Due to the Pcbnew history, m_Orient is saved in screen value
    // but it is handled as relative to its parent footprint
    if( parent )
        orient += parent->GetOrientation();

1309
    m_out->Print( aNestLevel, "(fp_text %s %s (at %s",
1310 1311
                  m_out->Quotew( type ).c_str(),
                  m_out->Quotew( aText->GetText() ).c_str(),
1312 1313 1314 1315
                  FMT_IU( aText->GetPos0() ).c_str() );

    if( orient != 0.0 )
        m_out->Print( 0, " %s", FMT_ANGLE( orient ).c_str() );
1316

1317
    m_out->Print( 0, ")" );
1318 1319 1320 1321 1322 1323
    formatLayer( aText );

    if( !aText->IsVisible() )
        m_out->Print( 0, " hide" );

    m_out->Print( 0, "\n" );
1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335

    aText->EDA_TEXT::Format( m_out, aNestLevel, m_ctl );

    m_out->Print( aNestLevel, ")\n" );
}


void PCB_IO::format( TRACK* aTrack, int aNestLevel ) const
    throw( IO_ERROR )
{
    if( aTrack->Type() == PCB_VIA_T )
    {
1336
        LAYER_NUM layer1, layer2;
1337 1338 1339 1340 1341 1342 1343

        SEGVIA* via = (SEGVIA*) aTrack;
        BOARD* board = (BOARD*) via->GetParent();

        wxCHECK_RET( board != 0, wxT( "Via " ) + via->GetSelectMenuText() +
                     wxT( " has no parent." ) );

1344 1345
        m_out->Print( aNestLevel, "(via" );

1346 1347 1348 1349
        via->ReturnLayerPair( &layer1, &layer2 );

        switch( aTrack->GetShape() )
        {
1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360
        case VIA_THROUGH:           //  Default shape not saved.
            break;

        case VIA_BLIND_BURIED:
            m_out->Print( 0, " blind" );
            break;

        case VIA_MICROVIA:
            m_out->Print( 0, " micro" );
            break;

1361 1362 1363 1364
        default:
            THROW_IO_ERROR( wxString::Format( _( "unknown via type %d"  ), aTrack->GetShape() ) );
        }

1365
        m_out->Print( 0, " (at %s) (size %s)",
1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399
                      FMT_IU( aTrack->GetStart() ).c_str(),
                      FMT_IU( aTrack->GetWidth() ).c_str() );

        if( aTrack->GetDrill() != UNDEFINED_DRILL_DIAMETER )
            m_out->Print( 0, " (drill %s)", FMT_IU( aTrack->GetDrill() ).c_str() );

        m_out->Print( 0, " (layers %s %s)",
                      m_out->Quotew( m_board->GetLayerName( layer1 ) ).c_str(),
                      m_out->Quotew( m_board->GetLayerName( layer2 ) ).c_str() );
    }
    else
    {
        m_out->Print( aNestLevel, "(segment (start %s) (end %s) (width %s)",
                      FMT_IU( aTrack->GetStart() ).c_str(), FMT_IU( aTrack->GetEnd() ).c_str(),
                      FMT_IU( aTrack->GetWidth() ).c_str() );

        m_out->Print( 0, " (layer %s)", m_out->Quotew( aTrack->GetLayerName() ).c_str() );
    }

    m_out->Print( 0, " (net %d)", aTrack->GetNet() );

    if( aTrack->GetTimeStamp() != 0 )
        m_out->Print( 0, " (tstamp %lX)", aTrack->GetTimeStamp() );

    if( aTrack->GetStatus() != 0 )
        m_out->Print( 0, " (status %X)", aTrack->GetStatus() );

    m_out->Print( 0, ")\n" );
}


void PCB_IO::format( ZONE_CONTAINER* aZone, int aNestLevel ) const
    throw( IO_ERROR )
{
1400 1401 1402
    // Save the NET info; For keepout zones, net code and net name are irrelevant
    // so be sure a dummy value is stored, just for ZONE_CONTAINER compatibility
    // (perhaps netcode and netname should be not stored)
1403
    m_out->Print( aNestLevel, "(zone (net %d) (net_name %s)",
1404
                  aZone->GetIsKeepout() ? 0 : aZone->GetNet(),
1405
                  m_out->Quotew( aZone->GetIsKeepout() ? wxT("") : aZone->GetNetName() ).c_str() );
1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422

    formatLayer( aZone );

    m_out->Print( 0, " (tstamp %lX)", aZone->GetTimeStamp() );

    // Save the outline aux info
    std::string hatch;

    switch( aZone->GetHatchStyle() )
    {
    default:
    case CPolyLine::NO_HATCH:       hatch = "none";    break;
    case CPolyLine::DIAGONAL_EDGE:  hatch = "edge";    break;
    case CPolyLine::DIAGONAL_FULL:  hatch = "full";    break;
    }

    m_out->Print( 0, " (hatch %s %s)\n", hatch.c_str(),
1423
                  FMT_IU( aZone->Outline()->GetHatchPitch() ).c_str() );
1424 1425

    if( aZone->GetPriority() > 0 )
1426
        m_out->Print( aNestLevel+1, "(priority %d)\n", aZone->GetPriority() );
1427

1428
    m_out->Print( aNestLevel+1, "(connect_pads" );
1429 1430 1431 1432

    switch( aZone->GetPadConnection() )
    {
    default:
1433 1434 1435
    case THERMAL_PAD:       // Default option not saved or loaded.
        break;

1436 1437 1438 1439
    case THT_THERMAL:
        m_out->Print( 0, " thru_hole_only" );
        break;

1440 1441 1442 1443 1444 1445 1446
    case PAD_IN_ZONE:
        m_out->Print( 0, " yes" );
        break;

    case PAD_NOT_IN_ZONE:
        m_out->Print( 0, " no" );
        break;
1447 1448
    }

1449 1450
    m_out->Print( 0, " (clearance %s))\n",
                  FMT_IU( aZone->GetZoneClearance() ).c_str() );
1451 1452 1453 1454

    m_out->Print( aNestLevel+1, "(min_thickness %s)\n",
                  FMT_IU( aZone->GetMinThickness() ).c_str() );

1455 1456
    if( aZone->GetIsKeepout() )
    {
1457
        m_out->Print( aNestLevel+1, "(keepout (tracks %s) (vias %s) (copperpour %s))\n",
1458 1459
                      aZone->GetDoNotAllowTracks() ? "not_allowed" : "allowed",
                      aZone->GetDoNotAllowVias() ? "not_allowed" : "allowed",
1460
                      aZone->GetDoNotAllowCopperPour() ? "not_allowed" : "allowed" );
1461 1462
    }

1463 1464 1465 1466 1467 1468 1469 1470
    m_out->Print( aNestLevel+1, "(fill" );

    // Default is not filled.
    if( aZone->IsFilled() )
        m_out->Print( 0, " yes" );

    // Default is polygon filled.
    if( aZone->GetFillMode() )
1471
        m_out->Print( 0, " (mode segment)" );
1472

1473
    m_out->Print( 0, " (arc_segments %d) (thermal_gap %s) (thermal_bridge_width %s)",
1474
                  aZone->GetArcSegmentCount(),
1475 1476 1477
                  FMT_IU( aZone->GetThermalReliefGap() ).c_str(),
                  FMT_IU( aZone->GetThermalReliefCopperBridge() ).c_str() );

1478
    if( aZone->GetCornerSmoothingType() != ZONE_SETTINGS::SMOOTHING_NONE )
1479
    {
1480
        m_out->Print( 0, " (smoothing" );
1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495

        switch( aZone->GetCornerSmoothingType() )
        {
        case ZONE_SETTINGS::SMOOTHING_CHAMFER:
            m_out->Print( 0, " chamfer" );
            break;

        case ZONE_SETTINGS::SMOOTHING_FILLET:
            m_out->Print( 0,  " fillet" );
            break;

        default:
            THROW_IO_ERROR( wxString::Format( _( "unknown zone corner smoothing type %d"  ),
                                              aZone->GetCornerSmoothingType() ) );
        }
1496
        m_out->Print( 0, ")" );
1497 1498

        if( aZone->GetCornerRadius() != 0 )
1499
            m_out->Print( 0, " (radius %s)",
1500
                          FMT_IU( aZone->GetCornerRadius() ).c_str() );
1501 1502
    }

1503
    m_out->Print( 0, ")\n" );
1504

1505
    const CPOLYGONS_LIST& cv = aZone->Outline()->m_CornersList;
1506
    int newLine = 0;
1507

1508
    if( cv.GetCornersCount() )
1509 1510 1511 1512
    {
        m_out->Print( aNestLevel+1, "(polygon\n");
        m_out->Print( aNestLevel+2, "(pts\n" );

1513
        for( unsigned it = 0; it < cv.GetCornersCount(); ++it )
1514
        {
1515 1516
            if( newLine == 0 )
                m_out->Print( aNestLevel+3, "(xy %s %s)",
1517
                              FMT_IU( cv.GetX( it ) ).c_str(), FMT_IU( cv.GetY( it ) ).c_str() );
1518 1519
            else
                m_out->Print( 0, " (xy %s %s)",
1520
                              FMT_IU( cv.GetX( it ) ).c_str(), FMT_IU( cv.GetY( it ) ).c_str() );
1521 1522 1523 1524 1525 1526 1527 1528 1529 1530

            if( newLine < 4 )
            {
                newLine += 1;
            }
            else
            {
                newLine = 0;
                m_out->Print( 0, "\n" );
            }
1531

1532
            if( cv.IsEndContour( it ) )
1533
            {
1534 1535 1536
                if( newLine != 0 )
                    m_out->Print( 0, "\n" );

1537 1538
                m_out->Print( aNestLevel+2, ")\n" );

1539
                if( it+1 != cv.GetCornersCount() )
1540
                {
1541
                    newLine = 0;
1542 1543
                    m_out->Print( aNestLevel+1, ")\n" );
                    m_out->Print( aNestLevel+1, "(polygon\n" );
1544
                    m_out->Print( aNestLevel+2, "(pts" );
1545 1546 1547 1548 1549 1550 1551 1552
                }
            }
        }

        m_out->Print( aNestLevel+1, ")\n" );
    }

    // Save the PolysList
1553
    const CPOLYGONS_LIST& fv = aZone->GetFilledPolysList();
1554
    newLine = 0;
1555

1556
    if( fv.GetCornersCount() )
1557 1558 1559 1560
    {
        m_out->Print( aNestLevel+1, "(filled_polygon\n" );
        m_out->Print( aNestLevel+2, "(pts\n" );

1561
        for( unsigned it = 0; it < fv.GetCornersCount();  ++it )
1562
        {
1563 1564
            if( newLine == 0 )
                m_out->Print( aNestLevel+3, "(xy %s %s)",
1565
                              FMT_IU( fv.GetX( it ) ).c_str(), FMT_IU( fv.GetY( it ) ).c_str() );
1566 1567
            else
                m_out->Print( 0, " (xy %s %s)",
1568
                              FMT_IU( fv.GetX( it ) ).c_str(), FMT_IU( fv.GetY( it ) ).c_str() );
1569 1570 1571 1572 1573 1574 1575 1576 1577 1578

            if( newLine < 4 )
            {
                newLine += 1;
            }
            else
            {
                newLine = 0;
                m_out->Print( 0, "\n" );
            }
1579

1580
            if( fv.IsEndContour( it ) )
1581
            {
1582 1583 1584
                if( newLine != 0 )
                    m_out->Print( 0, "\n" );

1585 1586
                m_out->Print( aNestLevel+2, ")\n" );

1587
                if( it+1 != fv.GetCornersCount() )
1588
                {
1589
                    newLine = 0;
1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600
                    m_out->Print( aNestLevel+1, ")\n" );
                    m_out->Print( aNestLevel+1, "(filled_polygon\n" );
                    m_out->Print( aNestLevel+2, "(pts\n" );
                }
            }
        }

        m_out->Print( aNestLevel+1, ")\n" );
    }

    // Save the filling segments list
1601
    const std::vector< SEGMENT >& segs = aZone->FillSegments();
1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620

    if( segs.size() )
    {
        m_out->Print( aNestLevel+1, "(fill_segments\n" );

        for( std::vector< SEGMENT >::const_iterator it = segs.begin();  it != segs.end();  ++it )
        {
            m_out->Print( aNestLevel+2, "(pts (xy %s) (xy %s))\n",
                          FMT_IU( it->m_Start ).c_str(),
                          FMT_IU( it->m_End ).c_str() );
        }

        m_out->Print( aNestLevel+1, ")\n" );
    }

    m_out->Print( aNestLevel, ")\n" );
}


1621
PCB_IO::PCB_IO() :
1622
    m_cache( 0 ),
1623
    m_ctl( CTL_FOR_BOARD ),         // expecting to OUTPUTFORMAT into BOARD files.
1624
    m_parser( new PCB_PARSER() )
1625 1626 1627 1628 1629 1630 1631 1632
{
    init( 0 );
    m_out = &m_sf;
}


PCB_IO::PCB_IO( int aControlFlags ) :
    m_cache( 0 ),
1633 1634
    m_ctl( aControlFlags ),
    m_parser( new PCB_PARSER() )
1635
{
1636
    init( 0 );
1637 1638 1639 1640
    m_out = &m_sf;
}


1641 1642 1643
PCB_IO::~PCB_IO()
{
    delete m_cache;
1644
    delete m_parser;
1645 1646 1647
}


1648
BOARD* PCB_IO::Load( const wxString& aFileName, BOARD* aAppendToMe, const PROPERTIES* aProperties )
1649
{
1650
    FILE_LINE_READER    reader( aFileName );
1651

1652 1653
    init( aProperties );

1654 1655 1656 1657
    m_parser->SetLineReader( &reader );
    m_parser->SetBoard( aAppendToMe );

    BOARD* board = dynamic_cast<BOARD*>( m_parser->Parse() );
1658 1659 1660 1661 1662
    wxASSERT( board );

    // Give the filename to the board if it's new
    if( !aAppendToMe )
        board->SetFileName( aFileName );
1663

1664
    return board;
1665
}
1666 1667


1668
void PCB_IO::init( const PROPERTIES* aProperties )
1669 1670 1671 1672 1673 1674
{
    m_board = NULL;
    m_props = aProperties;
}


1675
void PCB_IO::cacheLib( const wxString& aLibraryPath, const wxString& aFootprintName )
1676
{
1677
    if( !m_cache || m_cache->IsModified( aLibraryPath, aFootprintName ) )
1678 1679 1680 1681 1682 1683 1684 1685 1686
    {
        // a spectacular episode in memory management:
        delete m_cache;
        m_cache = new FP_CACHE( this, aLibraryPath );
        m_cache->Load();
    }
}


1687
wxArrayString PCB_IO::FootprintEnumerate( const wxString& aLibraryPath, const PROPERTIES* aProperties )
1688
{
1689
    LOCALE_IO   toggle;     // toggles on, then off, the C locale.
1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708

    init( aProperties );

    cacheLib( aLibraryPath );

    const MODULE_MAP& mods = m_cache->GetModules();

    wxArrayString ret;

    for( MODULE_CITER it = mods.begin();  it != mods.end();  ++it )
    {
        ret.Add( FROM_UTF8( it->first.c_str() ) );
    }

    return ret;
}


MODULE* PCB_IO::FootprintLoad( const wxString& aLibraryPath, const wxString& aFootprintName,
1709
                               const PROPERTIES* aProperties )
1710
{
1711
    LOCALE_IO   toggle;     // toggles on, then off, the C locale.
1712 1713 1714

    init( aProperties );

1715
    cacheLib( aLibraryPath, aFootprintName );
1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731

    const MODULE_MAP& mods = m_cache->GetModules();

    MODULE_CITER it = mods.find( TO_UTF8( aFootprintName ) );

    if( it == mods.end() )
    {
        return NULL;
    }

    // copy constructor to clone the already loaded MODULE
    return new MODULE( *it->second->GetModule() );
}


void PCB_IO::FootprintSave( const wxString& aLibraryPath, const MODULE* aFootprint,
1732
                            const PROPERTIES* aProperties )
1733
{
1734
    LOCALE_IO   toggle;     // toggles on, then off, the C locale.
1735 1736 1737

    init( aProperties );

1738 1739 1740 1741
    // In this public PLUGIN API function, we can safely assume it was
    // called for saving into a library path.
    m_ctl = CTL_FOR_LIBRARY;

1742 1743 1744 1745
    cacheLib( aLibraryPath );

    if( !m_cache->IsWritable() )
    {
1746 1747 1748 1749 1750 1751
        wxString msg = wxString::Format(
                _( "Library '%s' is read only" ),
                GetChars( aLibraryPath )
                );

        THROW_IO_ERROR( msg );
1752 1753
    }

1754
    std::string footprintName = aFootprint->GetFPID().GetFootprintName();
1755 1756 1757 1758

    MODULE_MAP& mods = m_cache->GetModules();

    // Quietly overwrite module and delete module file from path for any by same name.
1759 1760
    wxFileName fn( aLibraryPath, FROM_UTF8( aFootprint->GetFPID().GetFootprintName().c_str() ),
                   KiCadFootprintFileExtension );
1761 1762 1763

    if( !fn.IsOk() )
    {
1764
        THROW_IO_ERROR( wxString::Format( _( "Footprint file name '%s' is not valid." ),
1765 1766 1767 1768 1769
                                          GetChars( fn.GetFullPath() ) ) );
    }

    if( fn.FileExists() && !fn.IsFileWritable() )
    {
1770
        THROW_IO_ERROR( wxString::Format( _( "user does not have write permission to delete file '%s' " ),
1771 1772 1773 1774 1775 1776 1777
                                          GetChars( fn.GetFullPath() ) ) );
    }

    MODULE_CITER it = mods.find( footprintName );

    if( it != mods.end() )
    {
1778 1779
        wxLogTrace( traceFootprintLibrary, wxT( "Removing footprint library file '%s'." ),
                    fn.GetFullPath().GetData() );
1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795
        mods.erase( footprintName );
        wxRemoveFile( fn.GetFullPath() );
    }

    // I need my own copy for the cache
    MODULE* module = new MODULE( *aFootprint );

    // and it's time stamp must be 0, it should have no parent, orientation should
    // be zero, and it should be on the front layer.
    module->SetTimeStamp( 0 );
    module->SetParent( 0 );
    module->SetOrientation( 0 );

    if( module->GetLayer() != LAYER_N_FRONT )
        module->Flip( module->GetPosition() );

1796 1797
    wxLogTrace( traceFootprintLibrary, wxT( "Creating s-expression footprint file: %s." ),
                fn.GetFullPath().GetData() );
1798 1799 1800 1801 1802
    mods.insert( footprintName, new FP_CACHE_ITEM( module, fn ) );
    m_cache->Save();
}


1803
void PCB_IO::FootprintDelete( const wxString& aLibraryPath, const wxString& aFootprintName, const PROPERTIES* aProperties )
1804 1805 1806 1807 1808 1809 1810 1811 1812
{
    LOCALE_IO   toggle;     // toggles on, then off, the C locale.

    init( NULL );

    cacheLib( aLibraryPath );

    if( !m_cache->IsWritable() )
    {
1813
        THROW_IO_ERROR( wxString::Format( _( "Library '%s' is read only" ),
1814 1815 1816 1817 1818 1819 1820
                                          aLibraryPath.GetData() ) );
    }

    m_cache->Remove( aFootprintName );
}


1821
void PCB_IO::FootprintLibCreate( const wxString& aLibraryPath, const PROPERTIES* aProperties )
1822 1823 1824
{
    if( wxDir::Exists( aLibraryPath ) )
    {
1825
        THROW_IO_ERROR( wxString::Format( _( "cannot overwrite library path '%s'" ),
1826 1827 1828
                                          aLibraryPath.GetData() ) );
    }

1829
    LOCALE_IO   toggle;
1830 1831 1832 1833 1834 1835 1836 1837 1838

    init( aProperties );

    delete m_cache;
    m_cache = new FP_CACHE( this, aLibraryPath );
    m_cache->Save();
}


1839
bool PCB_IO::FootprintLibDelete( const wxString& aLibraryPath, const PROPERTIES* aProperties )
1840 1841 1842 1843 1844 1845
{
    wxFileName fn;
    fn.SetPath( aLibraryPath );

    // Return if there is no library path to delete.
    if( !fn.DirExists() )
1846
        return false;
1847 1848 1849

    if( !fn.IsDirWritable() )
    {
1850
        THROW_IO_ERROR( wxString::Format( _( "user does not have permission to delete directory '%s'" ),
1851 1852 1853 1854 1855 1856 1857
                                          aLibraryPath.GetData() ) );
    }

    wxDir dir( aLibraryPath );

    if( dir.HasSubDirs() )
    {
1858
        THROW_IO_ERROR( wxString::Format( _( "library directory '%s' has unexpected sub-directories" ),
1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874
                                          aLibraryPath.GetData() ) );
    }

    // All the footprint files must be deleted before the directory can be deleted.
    if( dir.HasFiles() )
    {
        unsigned      i;
        wxFileName    tmp;
        wxArrayString files;

        wxDir::GetAllFiles( aLibraryPath, &files );

        for( i = 0;  i < files.GetCount();  i++ )
        {
            tmp = files[i];

1875
            if( tmp.GetExt() != KiCadFootprintFileExtension )
1876
            {
1877
                THROW_IO_ERROR( wxString::Format( _( "unexpected file '%s' was found in library path '%s'" ),
1878 1879 1880 1881 1882 1883 1884 1885 1886 1887
                                                  files[i].GetData(), aLibraryPath.GetData() ) );
            }
        }

        for( i = 0;  i < files.GetCount();  i++ )
        {
            wxRemoveFile( files[i] );
        }
    }

1888 1889
    wxLogTrace( traceFootprintLibrary, wxT( "Removing footprint library '%s'" ),
                aLibraryPath.GetData() );
1890 1891 1892 1893 1894

    // Some of the more elaborate wxRemoveFile() crap puts up its own wxLog dialog
    // we don't want that.  we want bare metal portability with no UI here.
    if( !wxRmdir( aLibraryPath ) )
    {
1895
        THROW_IO_ERROR( wxString::Format( _( "footprint library '%s' cannot be deleted" ),
1896 1897 1898 1899 1900 1901 1902 1903 1904 1905
                                          aLibraryPath.GetData() ) );
    }

    // For some reason removing a directory in Windows is not immediately updated.  This delay
    // prevents an error when attempting to immediately recreate the same directory when over
    // writing an existing library.
#ifdef __WINDOWS__
    wxMilliSleep( 250L );
#endif

1906
    if( m_cache && !m_cache->IsPath( aLibraryPath ) )
1907 1908 1909 1910
    {
        delete m_cache;
        m_cache = NULL;
    }
1911 1912

    return true;
1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925
}


bool PCB_IO::IsFootprintLibWritable( const wxString& aLibraryPath )
{
    LOCALE_IO   toggle;

    init( NULL );

    cacheLib( aLibraryPath );

    return m_cache->IsWritable();
}