dialog_fp_lib_table.cpp 26.8 KB
Newer Older
1 2 3 4
/*
 * This program source code file is part of KiCad, a free EDA CAD application.
 *
 * Copyright (C) 2012 SoftPLC Corporation, Dick Hollenbeck <dick@softplc.com>
5
 * Copyright (C) 2013 CERN
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
 * Copyright (C) 2012 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
 */


Dick Hollenbeck's avatar
Dick Hollenbeck committed
27 28
/*  TODO:

29
*)  After any change to uri, reparse the environment variables.
30

Dick Hollenbeck's avatar
Dick Hollenbeck committed
31 32 33 34
*/


#include <set>
35
#include <wx/regex.h>
Dick Hollenbeck's avatar
Dick Hollenbeck committed
36

37
#include <fctsys.h>
38
#include <project.h>
39
#include <3d_viewer.h>      // for KISYS3DMOD
40 41
#include <dialog_fp_lib_table_base.h>
#include <fp_lib_table.h>
42 43
#include <fp_lib_table_lexer.h>
#include <invoke_pcb_dialog.h>
44
#include <grid_tricks.h>
45
#include <confirm.h>
46 47
#include <wizard_add_fplib.h>

48 49 50 51 52 53 54 55 56 57 58 59

/// grid column order is established by this sequence
enum COL_ORDER
{
    COL_NICKNAME,
    COL_URI,
    COL_TYPE,
    COL_OPTIONS,
    COL_DESCR,
    COL_COUNT       // keep as last
};

60

Dick Hollenbeck's avatar
Dick Hollenbeck committed
61 62
/**
 * Class FP_TBL_MODEL
63
 * mixes in FP_LIB_TABLE into wxGridTableBase so the result can be used
Dick Hollenbeck's avatar
Dick Hollenbeck committed
64
 * as a table within wxGrid.
Dick Hollenbeck's avatar
Dick Hollenbeck committed
65
 */
66 67
class FP_TBL_MODEL : public wxGridTableBase, public FP_LIB_TABLE
{
68
    friend class FP_GRID_TRICKS;
69 70

public:
71

72 73
    /**
     * Constructor FP_TBL_MODEL
Dick Hollenbeck's avatar
Dick Hollenbeck committed
74 75
     * is a copy constructor that builds a wxGridTableBase (table model) by wrapping
     * an FP_LIB_TABLE.
76 77 78 79 80 81 82 83
     */
    FP_TBL_MODEL( const FP_LIB_TABLE& aTableToEdit ) :
        FP_LIB_TABLE( aTableToEdit )    // copy constructor
    {
    }

    //-----<wxGridTableBase overloads>-------------------------------------------

84 85
    int         GetNumberRows()     { return rows.size(); }
    int         GetNumberCols()     { return COL_COUNT; }
86 87 88 89 90 91 92 93 94

    wxString    GetValue( int aRow, int aCol )
    {
        if( unsigned( aRow ) < rows.size() )
        {
            const ROW&  r  = rows[aRow];

            switch( aCol )
            {
95 96 97 98 99
            case COL_NICKNAME:  return r.GetNickName();
            case COL_URI:       return r.GetFullURI();
            case COL_TYPE:      return r.GetType();
            case COL_OPTIONS:   return r.GetOptions();
            case COL_DESCR:     return r.GetDescr();
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
            default:
                ;       // fall thru to wxEmptyString
            }
        }

        return wxEmptyString;
    }

    void    SetValue( int aRow, int aCol, const wxString &aValue )
    {
        if( unsigned( aRow ) < rows.size() )
        {
            ROW&  r  = rows[aRow];

            switch( aCol )
            {
116 117 118 119 120
            case COL_NICKNAME:  r.SetNickName( aValue );    break;
            case COL_URI:       r.SetFullURI( aValue );     break;
            case COL_TYPE:      r.SetType( aValue  );       break;
            case COL_OPTIONS:   r.SetOptions( aValue );     break;
            case COL_DESCR:     r.SetDescr( aValue );       break;
121 122 123 124 125 126
            }
        }
    }

    bool IsEmptyCell( int aRow, int aCol )
    {
127
        return !GetValue( aRow, aCol );
128 129 130 131 132 133 134
    }

    bool InsertRows( size_t aPos = 0, size_t aNumRows = 1 )
    {
        if( aPos < rows.size() )
        {
            rows.insert( rows.begin() + aPos, aNumRows, ROW() );
Dick Hollenbeck's avatar
Dick Hollenbeck committed
135 136 137 138 139 140 141 142 143 144 145 146

            // use the (wxGridStringTable) source Luke.
            if( GetView() )
            {
                wxGridTableMessage msg( this,
                                        wxGRIDTABLE_NOTIFY_ROWS_INSERTED,
                                        aPos,
                                        aNumRows );

                GetView()->ProcessTableMessage( msg );
            }

147 148 149 150 151 152 153
            return true;
        }
        return false;
    }

    bool AppendRows( size_t aNumRows = 1 )
    {
Dick Hollenbeck's avatar
Dick Hollenbeck committed
154 155
        // do not modify aNumRows, original value needed for wxGridTableMessage below
        for( int i = aNumRows; i; --i )
156
            rows.push_back( ROW() );
Dick Hollenbeck's avatar
Dick Hollenbeck committed
157 158 159 160 161 162 163 164 165 166

        if( GetView() )
        {
            wxGridTableMessage msg( this,
                                    wxGRIDTABLE_NOTIFY_ROWS_APPENDED,
                                    aNumRows );

            GetView()->ProcessTableMessage( msg );
        }

167 168 169 170 171
        return true;
    }

    bool DeleteRows( size_t aPos, size_t aNumRows )
    {
Dick Hollenbeck's avatar
Dick Hollenbeck committed
172 173 174
        // aPos may be a large positive, e.g. size_t(-1), and the sum of
        // aPos+aNumRows may wrap here, so both ends of the range are tested.
        if( aPos < rows.size() && aPos + aNumRows <= rows.size() )
175 176 177
        {
            ROWS_ITER start = rows.begin() + aPos;
            rows.erase( start, start + aNumRows );
Dick Hollenbeck's avatar
Dick Hollenbeck committed
178 179 180 181 182 183 184 185 186 187 188

            if( GetView() )
            {
                wxGridTableMessage msg( this,
                                        wxGRIDTABLE_NOTIFY_ROWS_DELETED,
                                        aPos,
                                        aNumRows );

                GetView()->ProcessTableMessage( msg );
            }

189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
            return true;
        }
        return false;
    }

    void Clear()
    {
        rows.clear();
        nickIndex.clear();
    }

    wxString GetColLabelValue( int aCol )
    {
        switch( aCol )
        {
204 205
        case COL_NICKNAME:  return _( "Nickname" );
        case COL_URI:       return _( "Library Path" );
Dick Hollenbeck's avatar
Dick Hollenbeck committed
206

207
        // keep this "Plugin Type" text fairly long so column is sized wide enough
Dick Hollenbeck's avatar
Dick Hollenbeck committed
208
        case COL_TYPE:      return _( "Plugin Type" );
209 210 211
        case COL_OPTIONS:   return _( "Options" );
        case COL_DESCR:     return _( "Description" );
        default:            return wxEmptyString;
212 213 214 215 216 217 218
        }
    }

    //-----</wxGridTableBase overloads>------------------------------------------
};


219
class FP_GRID_TRICKS : public GRID_TRICKS
220
{
221 222 223
public:
    FP_GRID_TRICKS( wxGrid* aGrid ) :
        GRID_TRICKS( aGrid )
Dick Hollenbeck's avatar
Dick Hollenbeck committed
224
    {
225
    }
Dick Hollenbeck's avatar
Dick Hollenbeck committed
226

227
protected:
228

229 230 231 232 233
    /// handle specialized clipboard text, with leading "(fp_lib_table", OR
    /// spreadsheet formatted text.
    virtual void paste_text( const wxString& cb_text )
    {
        FP_TBL_MODEL*       tbl = (FP_TBL_MODEL*) m_grid->GetTable();
234

235
        size_t  ndx = cb_text.find( wxT( "(fp_lib_table" ) );
Dick Hollenbeck's avatar
Dick Hollenbeck committed
236

237
        if( ndx != std::string::npos )
238
        {
239 240
            // paste the ROWs of s-expression (fp_lib_table), starting
            // at column 0 regardless of current cursor column.
Dick Hollenbeck's avatar
Dick Hollenbeck committed
241

242 243 244 245
            STRING_LINE_READER  slr( TO_UTF8( cb_text ), wxT( "Clipboard" ) );
            FP_LIB_TABLE_LEXER  lexer( &slr );
            FP_LIB_TABLE        tmp_tbl;
            bool                parsed = true;
246

247 248 249 250 251 252
            try
            {
                tmp_tbl.Parse( &lexer );
            }
            catch( PARSE_ERROR& pe )
            {
253
                DisplayError( NULL, pe.errorText );
254 255
                parsed = false;
            }
256

257 258 259
            if( parsed )
            {
                const int cur_row = std::max( getCursorRow(), 0 );
260

261 262 263 264 265 266
                // if clipboard rows would extend past end of current table size...
                if( tmp_tbl.GetCount() > tbl->GetNumberRows() - cur_row )
                {
                    int newRowsNeeded = tmp_tbl.GetCount() - ( tbl->GetNumberRows() - cur_row );
                    tbl->AppendRows( newRowsNeeded );
                }
267

268 269 270 271 272 273 274 275
                for( int i = 0;  i < tmp_tbl.GetCount();  ++i )
                {
                    tbl->At( cur_row+i ) = tmp_tbl.At( i );
                }
            }
            m_grid->AutoSizeColumns( false );
        }
        else
276
        {
277 278
            // paste spreadsheet formatted text.
            GRID_TRICKS::paste_text( cb_text );
279
        }
280 281
    }
};
282 283


284 285 286 287 288 289 290
/**
 * Class DIALOG_FP_LIB_TABLE
 * shows and edits the PCB library tables.  Two tables are expected, one global
 * and one project specific.
 */
class DIALOG_FP_LIB_TABLE : public DIALOG_FP_LIB_TABLE_BASE
{
291 292 293 294 295 296 297

public:
    DIALOG_FP_LIB_TABLE( wxTopLevelWindow* aParent, FP_LIB_TABLE* aGlobal, FP_LIB_TABLE* aProject ) :
        DIALOG_FP_LIB_TABLE_BASE( aParent ),
        m_global( aGlobal ),
        m_project( aProject )
    {
298 299 300 301
        // For user info, shows the table filenames:
        m_PrjTableFilename->SetLabel( Prj().FootprintLibTblName() );
        m_GblTableFilename->SetLabel( FP_LIB_TABLE::GetGlobalTableFileName() );

302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
        // wxGrid only supports user owned tables if they exist past end of ~wxGrid(),
        // so make it a grid owned table.
        m_global_grid->SetTable(  new FP_TBL_MODEL( *aGlobal ),  true );
        m_project_grid->SetTable( new FP_TBL_MODEL( *aProject ), true );

        // add Cut, Copy, and Paste to wxGrids
        m_global_grid->PushEventHandler( new FP_GRID_TRICKS( m_global_grid ) );
        m_project_grid->PushEventHandler( new FP_GRID_TRICKS( m_project_grid ) );

        m_global_grid->AutoSizeColumns( false );
        m_project_grid->AutoSizeColumns( false );

        wxArrayString choices;

        choices.Add( IO_MGR::ShowType( IO_MGR::KICAD ) );
        choices.Add( IO_MGR::ShowType( IO_MGR::GITHUB ) );
        choices.Add( IO_MGR::ShowType( IO_MGR::LEGACY ) );
        choices.Add( IO_MGR::ShowType( IO_MGR::EAGLE ) );
        choices.Add( IO_MGR::ShowType( IO_MGR::GEDA_PCB ) );

        /* PCAD_PLUGIN does not support Footprint*() functions
        choices.Add( IO_MGR::ShowType( IO_MGR::GITHUB ) );
        */

        wxGridCellAttr* attr;

        attr = new wxGridCellAttr;
        attr->SetEditor( new wxGridCellChoiceEditor( choices ) );
        m_project_grid->SetColAttr( COL_TYPE, attr );

        attr = new wxGridCellAttr;
        attr->SetEditor( new wxGridCellChoiceEditor( choices ) );
        m_global_grid->SetColAttr( COL_TYPE, attr );

336
        populateEnvironReadOnlyTable();
337

338 339 340
        for( int i=0; i<2; ++i )
        {
            wxGrid* g = i==0 ? m_global_grid : m_project_grid;
341

342
            // all but COL_OPTIONS, which is edited with Option Editor anyways.
343
            g->AutoSizeColumn( COL_NICKNAME, false );
344 345 346
            g->AutoSizeColumn( COL_TYPE, false );
            g->AutoSizeColumn( COL_URI, false );
            g->AutoSizeColumn( COL_DESCR, false );
347

348
            // would set this to width of title, if it was easily known.
349 350 351 352 353 354
            g->SetColSize( COL_OPTIONS, 80 );
        }

        // This scrunches the dialog hideously, probably due to wxAUI container.
        // Fit();
        // We derive from DIALOG_SHIM so prior size will be used anyways.
355

356
        // select the last selected page
357
        m_auinotebook->SetSelection( m_pageNdx );
358

359
        // fire pageChangedHandler() so m_cur_grid gets set
360 361
        // m_auinotebook->SetSelection will generate a pageChangedHandler()
        // event call later, but too late.
362 363 364
        wxAuiNotebookEvent uneventful;
        pageChangedHandler( uneventful );

365 366 367 368 369
        // Gives a selection for each grid, mainly for delete lib button.
        // Without that, we do not see what lib will be deleted
        m_global_grid->SelectRow(0);
        m_project_grid->SelectRow(0);

370 371
        // for ALT+A handling, we want the initial focus to be on the first selected grid.
        m_cur_grid->SetFocus();
372 373 374 375 376

        // On some windows manager (Unity, XFCE), this dialog is
        // not always raised, depending on this dialog is run.
        // Force it to be raised
        Raise();
377 378 379 380 381 382 383 384 385 386 387 388
    }

    ~DIALOG_FP_LIB_TABLE()
    {
        // Delete the GRID_TRICKS.
        // Any additional event handlers should be popped before the window is deleted.
        m_global_grid->PopEventHandler( true );
        m_project_grid->PopEventHandler( true );
    }


private:
Dick Hollenbeck's avatar
Dick Hollenbeck committed
389
    typedef FP_LIB_TABLE::ROW   ROW;
390

391 392
    /// If the cursor is not on a valid cell, because there are no rows at all, return -1,
    /// else return a 0 based column index.
393
    int getCursorCol() const
394
    {
395
        return m_cur_grid->GetGridCursorCol();
396 397
    }

398 399
    /// If the cursor is not on a valid cell, because there are no rows at all, return -1,
    /// else return a 0 based row index.
400
    int getCursorRow() const
401
    {
402
        return m_cur_grid->GetGridCursorRow();
403
    }
404

405 406 407 408 409 410 411 412
    /**
     * Function verifyTables
     * trims important fields, removes blank row entries, and checks for duplicates.
     * @return bool - true if tables are OK, else false.
     */
    bool verifyTables()
    {
        for( int t=0; t<2; ++t )
413
        {
414
            FP_TBL_MODEL& model = t==0 ? *global_model() : *project_model();
415 416

            for( int r = 0; r < model.GetNumberRows(); )
417
            {
418 419
                wxString nick = model.GetValue( r, COL_NICKNAME ).Trim( false ).Trim();
                wxString uri  = model.GetValue( r, COL_URI ).Trim( false ).Trim();
420

421
                if( !nick || !uri )
422
                {
423
                    // Delete the "empty" row, where empty means missing nick or uri.
424 425 426 427 428 429 430 431 432 433
                    // This also updates the UI which could be slow, but there should only be a few
                    // rows to delete, unless the user fell asleep on the Add Row
                    // button.
                    model.DeleteRows( r, 1 );
                }
                else if( nick.find(':') != size_t(-1) )
                {
                    wxString msg = wxString::Format(
                        _( "Illegal character '%s' found in Nickname: '%s' in row %d" ),
                        wxT( ":" ), GetChars( nick ), r );
434

435
                    // show the tabbed panel holding the grid we have flunked:
436
                    if( &model != cur_model() )
437
                    {
438
                        m_auinotebook->SetSelection( &model == global_model() ? 0 : 1 );
439 440
                    }

441
                    // go to the problematic row
442
                    m_cur_grid->SetGridCursor( r, 0 );
443 444
                    m_cur_grid->SelectBlock( r, 0, r, 0 );
                    m_cur_grid->MakeCellVisible( r, 0 );
445

446 447 448 449 450
                    wxMessageDialog errdlg( this, msg, _( "No Colon in Nicknames" ) );
                    errdlg.ShowModal();
                    return false;
                }
                else
451
                {
452 453 454 455 456 457 458
                    // set the trimmed values back into the table so they get saved to disk.
                    model.SetValue( r, COL_NICKNAME, nick );
                    model.SetValue( r, COL_URI, uri );
                    ++r;        // this row was OK.
                }
            }
        }
459

460 461 462
        // check for duplicate nickNames, separately in each table.
        for( int t=0; t<2; ++t )
        {
463
            FP_TBL_MODEL& model = t==0 ? *global_model() : *project_model();
464

465 466
            for( int r1 = 0; r1 < model.GetNumberRows() - 1;  ++r1 )
            {
467
                wxString    nick1 = model.GetValue( r1, COL_NICKNAME );
468

469 470 471
                for( int r2=r1+1; r2 < model.GetNumberRows();  ++r2 )
                {
                    wxString    nick2 = model.GetValue( r2, COL_NICKNAME );
472

473
                    if( nick1 == nick2 )
474
                    {
475 476 477 478
                        wxString msg = wxString::Format(
                            _( "Duplicate Nickname: '%s' in rows %d and %d" ),
                            GetChars( nick1 ), r1+1, r2+1
                            );
479

480
                        // show the tabbed panel holding the grid we have flunked:
481
                        if( &model != cur_model() )
482
                        {
483
                            m_auinotebook->SetSelection( &model == global_model() ? 0 : 1 );
484
                        }
485

486
                        // go to the lower of the two rows, it is technically the duplicate:
487
                        m_cur_grid->SetGridCursor( r2, 0 );
488 489 490 491 492 493
                        m_cur_grid->SelectBlock( r2, 0, r2, 0 );
                        m_cur_grid->MakeCellVisible( r2, 0 );

                        wxMessageDialog errdlg( this, msg, _( "Please Delete or Modify One" ) );
                        errdlg.ShowModal();
                        return false;
494 495 496 497
                    }
                }
            }
        }
498 499

        return true;
Dick Hollenbeck's avatar
Dick Hollenbeck committed
500
    }
Dick Hollenbeck's avatar
Dick Hollenbeck committed
501

502 503
    //-----<event handlers>----------------------------------

504 505
    void onKeyDown( wxKeyEvent& ev )
    {
506 507 508 509 510 511 512 513
#if 0
        // send the key to the current grid
        ((wxEvtHandler*)m_cur_grid)->ProcessEvent( ev );
#else
        // or no:
        // m_cur_grid has the focus most of the time anyways, so above not needed.
        ev.Skip();
#endif
514 515
    }

516 517
    void pageChangedHandler( wxAuiNotebookEvent& event )
    {
518 519
        m_pageNdx = m_auinotebook->GetSelection();
        m_cur_grid = ( m_pageNdx == 0 ) ? m_global_grid : m_project_grid;
520 521
    }

522
    void appendRowHandler( wxCommandEvent& event )
523
    {
524 525 526 527
        if( m_cur_grid->AppendRows( 1 ) )
        {
            int last_row = m_cur_grid->GetNumberRows() - 1;

528
            // wx documentation is wrong, SetGridCursor does not make visible.
529
            m_cur_grid->MakeCellVisible( last_row, 0 );
530
            m_cur_grid->SetGridCursor( last_row, 0 );
531
            m_cur_grid->SelectRow( m_cur_grid->GetGridCursorRow() );
532
        }
533 534
    }

535
    void deleteRowHandler( wxCommandEvent& event )
536
    {
537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556
#if 1
        int currRow = getCursorRow();
        wxArrayInt selectedRows	= m_cur_grid->GetSelectedRows();

        if( selectedRows.size() == 0 && getCursorRow() >= 0 )
            selectedRows.Add( getCursorRow() );

        std::sort( selectedRows.begin(), selectedRows.end() );

        for( int ii = selectedRows.GetCount()-1; ii >= 0; ii-- )
        {
            int row = selectedRows[ii];
            m_cur_grid->DeleteRows( row, 1 );
        }

        if( currRow >= m_cur_grid->GetNumberRows() )
            m_cur_grid->SetGridCursor(m_cur_grid->GetNumberRows()-1, getCursorCol() );

        m_cur_grid->SelectRow( m_cur_grid->GetGridCursorRow() );
#else
557 558 559
        int rowCount = m_cur_grid->GetNumberRows();
        int curRow   = getCursorRow();

Dick Hollenbeck's avatar
Dick Hollenbeck committed
560 561 562
        if( curRow >= 0 )
        {
            m_cur_grid->DeleteRows( curRow );
563

Dick Hollenbeck's avatar
Dick Hollenbeck committed
564
            if( curRow && curRow == rowCount - 1 )
565
            {
Dick Hollenbeck's avatar
Dick Hollenbeck committed
566
                m_cur_grid->SetGridCursor( curRow-1, getCursorCol() );
567
            }
Dick Hollenbeck's avatar
Dick Hollenbeck committed
568
        }
569
#endif
570 571
    }

572
    void moveUpHandler( wxCommandEvent& event )
573
    {
574
        int curRow = getCursorRow();
Dick Hollenbeck's avatar
Dick Hollenbeck committed
575 576
        if( curRow >= 1 )
        {
577
            int curCol = getCursorCol();
Dick Hollenbeck's avatar
Dick Hollenbeck committed
578

579
            FP_TBL_MODEL* tbl = cur_model();
Dick Hollenbeck's avatar
Dick Hollenbeck committed
580

581
            ROW move_me = tbl->rows[curRow];
Dick Hollenbeck's avatar
Dick Hollenbeck committed
582

583 584 585
            tbl->rows.erase( tbl->rows.begin() + curRow );
            --curRow;
            tbl->rows.insert( tbl->rows.begin() + curRow, move_me );
Dick Hollenbeck's avatar
Dick Hollenbeck committed
586 587 588

            if( tbl->GetView() )
            {
589
                // fire a msg to cause redrawing
Dick Hollenbeck's avatar
Dick Hollenbeck committed
590 591 592 593 594 595 596
                wxGridTableMessage msg( tbl,
                                        wxGRIDTABLE_NOTIFY_ROWS_INSERTED,
                                        curRow,
                                        0 );

                tbl->GetView()->ProcessTableMessage( msg );
            }
597

598
            m_cur_grid->MakeCellVisible( curRow, curCol );
599
            m_cur_grid->SetGridCursor( curRow, curCol );
600
            m_cur_grid->SelectRow( getCursorRow() );
Dick Hollenbeck's avatar
Dick Hollenbeck committed
601
        }
602 603
    }

604
    void moveDownHandler( wxCommandEvent& event )
605
    {
606
        FP_TBL_MODEL* tbl = cur_model();
607

608
        int curRow = getCursorRow();
609 610
        if( unsigned( curRow + 1 ) < tbl->rows.size() )
        {
611
            int curCol  = getCursorCol();
612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629

            ROW move_me = tbl->rows[curRow];

            tbl->rows.erase( tbl->rows.begin() + curRow );
             ++curRow;
            tbl->rows.insert( tbl->rows.begin() + curRow, move_me );

            if( tbl->GetView() )
            {
                // fire a msg to cause redrawing
                wxGridTableMessage msg( tbl,
                                        wxGRIDTABLE_NOTIFY_ROWS_INSERTED,
                                        curRow - 1,
                                        0 );

                tbl->GetView()->ProcessTableMessage( msg );
            }

630
            m_cur_grid->MakeCellVisible( curRow, curCol );
631
            m_cur_grid->SetGridCursor( curRow, curCol );
632
            m_cur_grid->SelectRow( getCursorRow() );
633
        }
634 635
    }

636
    void optionsEditor( wxCommandEvent& event )
637
    {
638
        FP_TBL_MODEL*   tbl = cur_model();
639

640 641 642 643
        if( tbl->GetNumberRows() )
        {
            int     curRow = getCursorRow();
            ROW&    row    = tbl->rows[curRow];
644

645 646
            wxString        result;
            const wxString& options = row.GetOptions();
647

648
            InvokePluginOptionsEditor( this, row.GetNickName(), row.GetType(), options, &result );
649

650 651 652
            if( options != result )
            {
                row.SetOptions( result );
653

654 655 656 657
                // all but options:
                m_cur_grid->AutoSizeColumn( COL_NICKNAME, false );
                m_cur_grid->AutoSizeColumn( COL_URI, false );
                m_cur_grid->AutoSizeColumn( COL_TYPE, false );
658

659 660
                // On Windows, the grid is not refresh,
                // so force resfresh after a change
661
#ifdef __WINDOWS__
662
                Refresh();
663
#endif
664
            }
Dick Hollenbeck's avatar
Dick Hollenbeck committed
665 666
        }
    }
667

668
    void OnClickLibraryWizard( wxCommandEvent& event );
669

670
    void onCancelButtonClick( wxCommandEvent& event )
671
    {
Dick Hollenbeck's avatar
Dick Hollenbeck committed
672
        EndModal( 0 );
673 674
    }

675
    void onCancelCaptionButtonClick( wxCloseEvent& event )
676
    {
677
        EndModal( 0 );
678 679
    }

680
    void onOKButtonClick( wxCommandEvent& event )
681
    {
Dick Hollenbeck's avatar
Dick Hollenbeck committed
682
        int dialogRet = 0;
683

684 685 686
        // stuff any pending cell editor text into the table.
        m_cur_grid->SaveEditControlValue();

687
        if( verifyTables() )
Dick Hollenbeck's avatar
Dick Hollenbeck committed
688
        {
689
            if( *global_model() != *m_global )
690 691
            {
                dialogRet |= 1;
692

693
                *m_global  = *global_model();
694 695
                m_global->reindex();
            }
696

697
            if( *project_model() != *m_project )
698 699
            {
                dialogRet |= 2;
Dick Hollenbeck's avatar
Dick Hollenbeck committed
700

701
                *m_project = *project_model();
702 703
                m_project->reindex();
            }
704

705 706
            EndModal( dialogRet );
        }
707 708
    }

Dick Hollenbeck's avatar
Dick Hollenbeck committed
709 710 711 712 713 714 715 716 717 718
    /// Populate the readonly environment variable table with names and values
    /// by examining all the full_uri columns.
    void populateEnvironReadOnlyTable()
    {
        wxRegEx re( wxT( ".*?\\$\\{(.+?)\\}.*?" ), wxRE_ADVANCED );
        wxASSERT( re.IsValid() );   // wxRE_ADVANCED is required.

        std::set< wxString >        unique;
        typedef std::set<wxString>::const_iterator      SET_CITER;

719
        // clear the table
Dick Hollenbeck's avatar
Dick Hollenbeck committed
720 721
        m_path_subs_grid->DeleteRows( 0, m_path_subs_grid->GetNumberRows() );

722 723 724 725 726
        FP_TBL_MODEL*   gbl = global_model();
        FP_TBL_MODEL*   prj = project_model();

        int gblRowCount = gbl->GetNumberRows();
        int prjRowCount = prj->GetNumberRows();
Dick Hollenbeck's avatar
Dick Hollenbeck committed
727 728 729 730
        int row;

        for( row = 0;  row < gblRowCount;  ++row )
        {
731
            wxString uri = gbl->GetValue( row, COL_URI );
Dick Hollenbeck's avatar
Dick Hollenbeck committed
732 733 734 735 736 737 738 739 740 741 742 743

            while( re.Matches( uri ) )
            {
                wxString envvar = re.GetMatch( uri, 1 );

                // ignore duplicates
                unique.insert( envvar );

                // delete the last match and search again
                uri.Replace( re.GetMatch( uri, 0 ), wxEmptyString );
            }
        }
744

Dick Hollenbeck's avatar
Dick Hollenbeck committed
745 746
        for( row = 0;  row < prjRowCount;  ++row )
        {
747
            wxString uri = prj->GetValue( row, COL_URI );
Dick Hollenbeck's avatar
Dick Hollenbeck committed
748 749 750 751 752 753 754 755 756 757 758 759 760

            while( re.Matches( uri ) )
            {
                wxString envvar = re.GetMatch( uri, 1 );

                // ignore duplicates
                unique.insert( envvar );

                // delete the last match and search again
                uri.Replace( re.GetMatch( uri, 0 ), wxEmptyString );
            }
        }

761 762 763
        // Make sure this special environment variable shows up even if it was
        // not used yet.  It is automatically set by KiCad to the directory holding
        // the current project.
764
        unique.insert( PROJECT_VAR_NAME );
765
        unique.insert( FP_LIB_TABLE::GlobalPathEnvVariableName() );
766
        // This special environment variable is used to locate 3d shapes
767
        unique.insert( KISYS3DMOD );
768

Dick Hollenbeck's avatar
Dick Hollenbeck committed
769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785
        m_path_subs_grid->AppendRows( unique.size() );

        row = 0;
        for( SET_CITER it = unique.begin();  it != unique.end();  ++it, ++row )
        {
            wxString    evName = *it;
            wxString    evValue;

            m_path_subs_grid->SetCellValue( row, 0, evName );

            if( wxGetEnv( evName, &evValue ) )
                m_path_subs_grid->SetCellValue( row, 1, evValue );
        }

        m_path_subs_grid->AutoSizeColumns();
    }

786
    //-----</event handlers>---------------------------------
787

788
    // caller's tables are modified only on OK button and successful verification.
789 790 791
    FP_LIB_TABLE*       m_global;
    FP_LIB_TABLE*       m_project;

792 793 794
    FP_TBL_MODEL*       global_model()  const   { return (FP_TBL_MODEL*) m_global_grid->GetTable(); }
    FP_TBL_MODEL*       project_model() const   { return (FP_TBL_MODEL*) m_project_grid->GetTable(); }
    FP_TBL_MODEL*       cur_model() const       { return (FP_TBL_MODEL*) m_cur_grid->GetTable(); }
795 796

    wxGrid*             m_cur_grid;     ///< changed based on tab choice
797
    static int          m_pageNdx;      ///< Remember the last notebook page selected during a session
798 799
};

800 801
int DIALOG_FP_LIB_TABLE::m_pageNdx = 0;

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 846
void DIALOG_FP_LIB_TABLE::OnClickLibraryWizard( wxCommandEvent& event )
{
    wxArrayString envVariableList;

    // Build the environment variables in use:
    for( int ii = 0; ii <  m_path_subs_grid->GetTable()->GetRowsCount(); ii ++ )
        envVariableList.Add( m_path_subs_grid->GetCellValue( wxGridCellCoords( ii, 0 ) ) );

    WIZARD_FPLIB_TABLE dlg( this, envVariableList );

    if( ! dlg.RunWizard( dlg.GetFirstPage() ) )
        return;     // Aborted by user

    wxGrid* libgrid = m_cur_grid;
    FP_TBL_MODEL*  tbl = (FP_TBL_MODEL*) libgrid->GetTable();

    // Import fp library list
    int idx = 0;
    wxArrayString libDescr;   // Will contain nickname, URI, plugin

    while( dlg.GetLibDescr( idx++, libDescr ) )
    {
        if( ! libDescr[0].IsEmpty() && m_cur_grid->AppendRows( 1 ) )
        {
            int last_row = libgrid->GetNumberRows() - 1;

            // Add the nickname: currently make it from filename
            tbl->SetValue( last_row, COL_NICKNAME, libDescr[0] );
            // Add the full path:
            tbl->SetValue( last_row, COL_URI, libDescr[1] );
            // Add the plugin name:
            tbl->SetValue( last_row, COL_TYPE, libDescr[2] );

            libgrid->MakeCellVisible( last_row, 0 );
            libgrid->SetGridCursor( last_row, 0 );
        }

        libDescr.Clear();
    }

    libgrid->SelectRow( libgrid->GetGridCursorRow() );
}


847
int InvokePcbLibTableEditor( wxTopLevelWindow* aParent, FP_LIB_TABLE* aGlobal, FP_LIB_TABLE* aProject )
848
{
Dick Hollenbeck's avatar
Dick Hollenbeck committed
849
    DIALOG_FP_LIB_TABLE dlg( aParent, aGlobal, aProject );
850

Dick Hollenbeck's avatar
Dick Hollenbeck committed
851
    int dialogRet = dlg.ShowModal();    // returns value passed to EndModal() above
852

Dick Hollenbeck's avatar
Dick Hollenbeck committed
853
    return dialogRet;
854
}