File: schematic_undo_redo.cpp

package info (click to toggle)
kicad 9.0.2%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 769,124 kB
  • sloc: cpp: 960,330; ansic: 121,001; xml: 66,428; python: 18,382; sh: 1,010; awk: 301; asm: 292; makefile: 227; javascript: 167; perl: 10
file content (603 lines) | stat: -rw-r--r-- 20,744 bytes parent folder | download | duplicates (4)
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
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
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
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
592
593
594
595
596
597
598
599
600
601
602
603
/*
 * This program source code file is part of KiCad, a free EDA CAD application.
 *
 * Copyright (C) 2004 Jean-Pierre Charras, jaen-pierre.charras@gipsa-lab.inpg.com
 * Copyright The KiCad Developers, see AUTHORS.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 <sch_actions.h>
#include <sch_edit_frame.h>
#include <tool/tool_manager.h>
#include <schematic.h>
#include <sch_bus_entry.h>
#include <sch_commit.h>
#include <sch_junction.h>
#include <sch_line.h>
#include <sch_bitmap.h>
#include <sch_sheet_pin.h>
#include <sch_table.h>
#include <tools/sch_selection_tool.h>
#include <drawing_sheet/ds_proxy_undo_item.h>
#include <tool/actions.h>
#include <wx/log.h>


/* Functions to undo and redo edit commands.
 *
 *  m_UndoList and m_RedoList handle a std::vector of PICKED_ITEMS_LIST
 *  Each PICKED_ITEMS_LIST handle a std::vector of pickers (class ITEM_PICKER),
 *  that store the list of schematic items that are concerned by the command to
 *  undo or redo and is created for each command to undo (handle also a command
 *  to redo). each picker has a pointer pointing to an item to undo or redo (in
 *  fact: deleted, added or modified), and has a pointer to a copy of this item,
 *  when this item has been modified (the old values of parameters are
 *  therefore saved)
 *
 *  there are 3 cases:
 *  - delete item(s) command
 *  - change item(s) command
 *  - add item(s) command
 *  and 2 cases for block:
 *  - move list of items
 *  - mirror (Y) list of items
 *
 *  Undo command
 *  - delete item(s) command:
 *       =>  deleted items are moved in undo list
 *
 *  - change item(s) command
 *      => A copy of item(s) is made (a DrawPickedStruct list of wrappers)
 *      the .m_Link member of each wrapper points the modified item.
 *      the .m_Item member of each wrapper points the old copy of this item.
 *
 *  - add item(s) command
 *      =>A list of item(s) is made. The .m_Item member of each wrapper points
 *        the new item.
 *
 *  Redo command
 *  - delete item(s) old command:
 *      => deleted items are moved into m_tree
 *
 *  - change item(s) command
 *      => the copy of item(s) is moved in Undo list
 *
 *  - add item(s) command
 *      => The list of item(s) is used to create a deleted list in undo
 *         list(same as a delete command)
 *
 *   Some block operations that change items can be undone without memorized
 *   items, just the coordinates of the transform: move list of items (undo/
 *   redo is made by moving with the opposite move vector) mirror (Y) and flip
 *   list of items (undo/redo is made by mirror or flip items) so they are
 *    handled specifically.
 *
 *  A problem is the hierarchical sheet handling.
 *  the data associated (sub-hierarchy, undo/redo list) is deleted only
 *  when the sheet is really deleted (i.e. when deleted from undo or redo list)
 *  This is handled by its destructor.
 */


/* Used if undo / redo command:
 * swap data between Item and its copy, pointed by its picked item link member
 * swapped data is data modified by editing, so not all values are swapped
 */

void SCH_EDIT_FRAME::SaveCopyInUndoList( SCH_SCREEN* aScreen, SCH_ITEM* aItem,
                                         UNDO_REDO aCommandType, bool aAppend,
                                         bool aDirtyConnectivity )
{
    PICKED_ITEMS_LIST* commandToUndo = nullptr;

    wxCHECK( aItem, /* void */ );

    if( aDirtyConnectivity )
    {
        if( !aItem->IsConnectivityDirty() && aItem->Connection()
            && ( aItem->Connection()->Name() == m_highlightedConn
                 || aItem->Connection()->HasDriverChanged() ) )
        {
            m_highlightedConnChanged = true;
        }

        aItem->SetConnectivityDirty();
    }

    PICKED_ITEMS_LIST* lastUndo = PopCommandFromUndoList();

    // If the last stack was empty, use that one instead of creating a new stack
    if( lastUndo )
    {
        if( aAppend || !lastUndo->GetCount() )
            commandToUndo = lastUndo;
        else
            PushCommandToUndoList( lastUndo );
    }

    if( !commandToUndo )
    {
        commandToUndo = new PICKED_ITEMS_LIST();
    }

    ITEM_PICKER itemWrapper( aScreen, aItem, aCommandType );
    itemWrapper.SetFlags( aItem->GetFlags() );

    switch( aCommandType )
    {
    case UNDO_REDO::CHANGED: /* Create a copy of item */
        itemWrapper.SetLink( aItem->Duplicate( true ) );
        commandToUndo->PushItem( itemWrapper );
        break;

    case UNDO_REDO::NEWITEM:
    case UNDO_REDO::DELETED:
        commandToUndo->PushItem( itemWrapper );
        break;

    default:
        wxFAIL_MSG( wxString::Format( wxT( "SaveCopyInUndoList() error (unknown code %X)" ),
                                      aCommandType ) );
        break;
    }

    if( commandToUndo->GetCount() )
    {
        /* Save the copy in undo list */
        PushCommandToUndoList( commandToUndo );

        /* Clear redo list, because after new save there is no redo to do */
        ClearUndoORRedoList( REDO_LIST );
    }
    else
    {
        delete commandToUndo;
    }
}


void SCH_EDIT_FRAME::SaveCopyInUndoList( const PICKED_ITEMS_LIST& aItemsList,
                                         UNDO_REDO aTypeCommand, bool aAppend,
                                         bool aDirtyConnectivity )
{
    PICKED_ITEMS_LIST* commandToUndo = nullptr;

    if( !aItemsList.GetCount() )
        return;

    PICKED_ITEMS_LIST* lastUndo = PopCommandFromUndoList();

    // If the last stack was empty, use that one instead of creating a new stack
    if( lastUndo )
    {
        if( aAppend || !lastUndo->GetCount() )
            commandToUndo = lastUndo;
        else
            PushCommandToUndoList( lastUndo );
    }

    if( !commandToUndo )
    {
        commandToUndo = new PICKED_ITEMS_LIST();
        commandToUndo->SetDescription( aItemsList.GetDescription() );
    }

    // Copy picker list:
    if( !commandToUndo->GetCount() )
    {
        commandToUndo->CopyList( aItemsList );

        for( const std::unique_ptr<SCH_ITEM>& item : GetRepeatItems() )
        {
            EDA_ITEM* repeatItemClone = item->Clone();
            repeatItemClone->SetFlags( UR_TRANSIENT );

            ITEM_PICKER repeatItemPicker( nullptr, repeatItemClone, UNDO_REDO::REPEAT_ITEM );
            commandToUndo->PushItem( repeatItemPicker );
        }
    }
    else
    {
        // Unless we are appending, in which case, get the picker items
        for( unsigned ii = 0; ii < aItemsList.GetCount(); ii++ )
            commandToUndo->PushItem( aItemsList.GetItemWrapper( ii) );
    }

    // Verify list, and creates data if needed
    for( unsigned ii = 0; ii < commandToUndo->GetCount(); ii++ )
    {
        SCH_ITEM* sch_item = dynamic_cast<SCH_ITEM*>( commandToUndo->GetPickedItem( ii ) );

        // Common items implemented in EDA_DRAW_FRAME will not be SCH_ITEMs.
        if( !sch_item )
            continue;

        UNDO_REDO command = commandToUndo->GetPickedItemStatus( ii );

        if( command == UNDO_REDO::UNSPECIFIED )
        {
            command = aTypeCommand;
            commandToUndo->SetPickedItemStatus( command, ii );
        }

        switch( command )
        {
        case UNDO_REDO::CHANGED:

            /* If needed, create a copy of item, and put in undo list
             * in the picker, as link
             * If this link is not null, the copy is already done
             */
            if( commandToUndo->GetPickedItemLink( ii ) == nullptr )
                commandToUndo->SetPickedItemLink( sch_item->Duplicate( true ), ii );

            wxASSERT( commandToUndo->GetPickedItemLink( ii ) );
            break;

        case UNDO_REDO::NEWITEM:
        case UNDO_REDO::DELETED:
        case UNDO_REDO::PAGESETTINGS:
        case UNDO_REDO::REPEAT_ITEM:
            break;

        default:
            wxFAIL_MSG( wxString::Format( wxT( "Unknown undo/redo command %d" ), command ) );
            break;
        }
    }

    if( commandToUndo->GetCount() )
    {
        /* Save the copy in undo list */
        PushCommandToUndoList( commandToUndo );

        /* Clear redo list, because after new save there is no redo to do */
        ClearUndoORRedoList( REDO_LIST );
    }
    else    // Should not occur
    {
        delete commandToUndo;
    }
}


void SCH_EDIT_FRAME::PutDataInPreviousState( PICKED_ITEMS_LIST* aList )
{
    std::vector<SCH_ITEM*> bulkAddedItems;
    std::vector<SCH_ITEM*> bulkRemovedItems;
    std::vector<SCH_ITEM*> bulkChangedItems;
    std::set<SCH_TABLE*>   changedTables;
    bool                   dirtyConnectivity = false;
    bool                   rebuildHierarchyNavigator = false;
    bool                   refreshHierarchy = false;
    SCH_CLEANUP_FLAGS      connectivityCleanUp = NO_CLEANUP;
    SCH_SHEET_LIST         sheets;
    bool                   clearedRepeatItems = false;

    // Undo in the reverse order of list creation: (this can allow stacked changes like the
    // same item can be changed and deleted in the same complex command).
    // After hitting 0, subtracting 1 will roll the value over to its max representation
    for( unsigned ii = aList->GetCount() - 1; ii < std::numeric_limits<unsigned>::max(); ii-- )
    {
        UNDO_REDO   status = aList->GetPickedItemStatus( ii );
        EDA_ITEM*   eda_item = aList->GetPickedItem( ii );
        SCH_SCREEN* screen = dynamic_cast<SCH_SCREEN*>( aList->GetScreenForItem( ii ) );

        eda_item->SetFlags( aList->GetPickerFlags( ii ) );
        eda_item->ClearEditFlags();
        eda_item->ClearTempFlags();

        // Set connectable object connectivity status.
        auto propagateConnectivityDamage =
                [&]( SCH_ITEM* schItem )
                {
                    if( schItem->IsConnectable() )
                    {
                        schItem->SetConnectivityDirty();

                        if( schItem->Type() == SCH_SYMBOL_T )
                        {
                            SCH_SYMBOL* symbol = static_cast<SCH_SYMBOL*>( schItem );

                            wxCHECK( symbol, /* void */ );

                            for( SCH_PIN* pin : symbol->GetPins() )
                                pin->SetConnectivityDirty();
                        }
                        else if( schItem->Type() == SCH_SHEET_T )
                        {
                            SCH_SHEET* sheet = static_cast<SCH_SHEET*>( schItem );

                            wxCHECK( sheet, /* void */ );

                            for( SCH_SHEET_PIN* pin : sheet->GetPins() )
                                pin->SetConnectivityDirty();
                        }

                        m_highlightedConnChanged = true;
                        dirtyConnectivity = true;

                        // Do a local clean up if there are any connectable objects in the commit
                        if( connectivityCleanUp == NO_CLEANUP )
                            connectivityCleanUp = LOCAL_CLEANUP;

                        // Do a full rebauild of the connectivity if there is a sheet in the commit
                        if( schItem->Type() == SCH_SHEET_T )
                            connectivityCleanUp = GLOBAL_CLEANUP;
                    }
                    else if( schItem->Type() == SCH_RULE_AREA_T )
                    {
                        dirtyConnectivity = true;
                    }
                };

        SCH_ITEM* schItem = dynamic_cast<SCH_ITEM*>( eda_item );

        if( status == UNDO_REDO::NEWITEM )
        {
            if( schItem )
                propagateConnectivityDamage( schItem );

            // If we are removing the current sheet, get out first
            if( eda_item->Type() == SCH_SHEET_T )
            {
                rebuildHierarchyNavigator = true;
                refreshHierarchy = true;

                if( static_cast<SCH_SHEET*>( eda_item )->GetScreen() == GetScreen() )
                    GetToolManager()->PostAction( SCH_ACTIONS::leaveSheet );
            }

            RemoveFromScreen( eda_item, screen );
            aList->SetPickedItemStatus( UNDO_REDO::DELETED, ii );

            bulkRemovedItems.emplace_back( schItem );
        }
        else if( status == UNDO_REDO::DELETED )
        {
            if( eda_item->Type() == SCH_SHEET_T )
            {
                rebuildHierarchyNavigator = true;
                refreshHierarchy = true;
            }

            if( schItem )
                propagateConnectivityDamage( schItem );

            // deleted items are re-inserted on undo
            AddToScreen( eda_item, screen );
            aList->SetPickedItemStatus( UNDO_REDO::NEWITEM, ii );

            bulkAddedItems.emplace_back( schItem );
        }
        else if( status == UNDO_REDO::PAGESETTINGS )
        {
            // Lazy eval of sheet list; this is expensive even when unsorted
            if( sheets.empty() )
                sheets = m_schematic->Hierarchy();

            SCH_SHEET_PATH undoSheet = sheets.FindSheetForScreen( screen );

            if( GetCurrentSheet() != undoSheet )
            {
                SetCurrentSheet( undoSheet );
                DisplayCurrentSheet();
            }

            // swap current settings with stored settings
            DS_PROXY_UNDO_ITEM  alt_item( this );
            DS_PROXY_UNDO_ITEM* item = static_cast<DS_PROXY_UNDO_ITEM*>( eda_item );
            item->Restore( this );
            *item = std::move( alt_item );
        }
        else if( status == UNDO_REDO::REPEAT_ITEM )
        {
            if( !clearedRepeatItems )
            {
                ClearRepeatItemsList();
                clearedRepeatItems = true;
            }

            if( schItem )
            {
                propagateConnectivityDamage( schItem );
                AddCopyForRepeatItem( schItem );

                if( schItem->Type() == SCH_SHEET_T )
                {
                    rebuildHierarchyNavigator = true;
                    refreshHierarchy = true;
                }
            }
        }
        else if( schItem )
        {
            SCH_ITEM* itemCopy = dynamic_cast<SCH_ITEM*>( aList->GetPickedItemLink( ii ) );

            wxCHECK2( itemCopy, continue );

            if( schItem->HasConnectivityChanges( itemCopy, &GetCurrentSheet() ) )
                propagateConnectivityDamage( schItem );

            // The root sheet is a pseudo object that owns the root screen object but is not on
            // the root screen so do not attempt to remove it from the screen it owns.
            if( schItem != &Schematic().Root() )
                RemoveFromScreen( schItem, screen );

            switch( status )
            {
            case UNDO_REDO::CHANGED:
                if( schItem->Type() == SCH_SHEET_T )
                {
                    const SCH_SHEET* origSheet = static_cast<const SCH_SHEET*>( schItem );
                    const SCH_SHEET* copySheet = static_cast<const SCH_SHEET*>( itemCopy );

                    wxCHECK2( origSheet && copySheet, continue );

                    if( ( origSheet->GetName() != copySheet->GetName() )
                      || ( origSheet->GetFileName() != copySheet->GetFileName() )
                      || origSheet->HasPageNumberChanges( *copySheet ) )
                    {
                        rebuildHierarchyNavigator = true;
                    }

                    // Sheet name changes do not require rebuilding the hiearchy.
                    if( ( origSheet->GetFileName() != copySheet->GetFileName() )
                      || origSheet->HasPageNumberChanges( *copySheet ) )
                    {
                        refreshHierarchy = true;
                    }
                }

                schItem->SwapData( itemCopy );
                bulkChangedItems.emplace_back( schItem );

                // Special cases for items which have instance data
                if( schItem->GetParent() && schItem->GetParent()->Type() == SCH_SYMBOL_T
                  && schItem->Type() == SCH_FIELD_T )
                {
                    SCH_FIELD*  field = static_cast<SCH_FIELD*>( schItem );
                    SCH_SYMBOL* symbol = static_cast<SCH_SYMBOL*>( schItem->GetParent() );

                    if( field->GetId() == REFERENCE_FIELD )
                    {
                        // Lazy eval of sheet list; this is expensive even when unsorted
                        if( sheets.empty() )
                            sheets = m_schematic->Hierarchy();

                        SCH_SHEET_PATH sheet = sheets.FindSheetForScreen( screen );
                        symbol->SetRef( &sheet, field->GetText() );
                    }

                    bulkChangedItems.emplace_back( symbol );
                }

                break;

            default:
                wxFAIL_MSG( wxString::Format( wxT( "Unknown undo/redo command %d" ),
                                              aList->GetPickedItemStatus( ii ) ) );
                break;
            }

            if( schItem->Type() == SCH_SYMBOL_T )
            {
                SCH_SYMBOL* sym = static_cast<SCH_SYMBOL*>( schItem );
                sym->UpdatePins();
            }

            if( schItem != &Schematic().Root() )
                AddToScreen( schItem, screen );
        }
    }

    GetCanvas()->GetView()->ClearHiddenFlags();

    // Notify our listeners
    if( bulkAddedItems.size() > 0 )
        Schematic().OnItemsAdded( bulkAddedItems );

    if( bulkRemovedItems.size() > 0 )
        Schematic().OnItemsRemoved( bulkRemovedItems );

    if( bulkChangedItems.size() > 0 )
        Schematic().OnItemsChanged( bulkChangedItems );

    if( refreshHierarchy )
        Schematic().RefreshHierarchy();

    if( dirtyConnectivity )
    {
        wxLogTrace( wxS( "CONN_PROFILE" ),
                    wxS( "Undo/redo %s clean up connectivity rebuild." ),
                    ( connectivityCleanUp == LOCAL_CLEANUP ) ? wxS( "local" ) : wxS( "global" ) );

        SCH_COMMIT localCommit( m_toolManager );

        RecalculateConnections( &localCommit, connectivityCleanUp );

        if( connectivityCleanUp == GLOBAL_CLEANUP )
            SetSheetNumberAndCount();
    }

    // Update the hierarchy navigator when there are sheet changes.
    if( rebuildHierarchyNavigator )
        UpdateHierarchyNavigator();
}


void SCH_EDIT_FRAME::RollbackSchematicFromUndo()
{
    PICKED_ITEMS_LIST* undo = PopCommandFromUndoList();

    // Skip empty frames
    while( undo && !undo->GetCount() )
    {
        delete undo;
        undo = PopCommandFromUndoList();
    }

    if( undo )
    {
        PutDataInPreviousState( undo );
        undo->ClearListAndDeleteItems( []( EDA_ITEM* aItem )
                                       {
                                           delete aItem;
                                       } );

        delete undo;

        m_toolManager->GetTool<SCH_SELECTION_TOOL>()->RebuildSelection();
    }

    GetCanvas()->Refresh();
}


void SCH_EDIT_FRAME::ClearUndoORRedoList( UNDO_REDO_LIST whichList, int aItemCount )
{
    if( aItemCount == 0 )
        return;

    UNDO_REDO_CONTAINER& list = ( whichList == UNDO_LIST ) ? m_undoList : m_redoList;

    if( aItemCount < 0 )
    {
        list.ClearCommandList();
    }
    else
    {
        for( int ii = 0; ii < aItemCount; ii++ )
        {
            if( list.m_CommandsList.size() == 0 )
                break;

            PICKED_ITEMS_LIST* curr_cmd = list.m_CommandsList[0];
            list.m_CommandsList.erase( list.m_CommandsList.begin() );

            curr_cmd->ClearListAndDeleteItems( []( EDA_ITEM* aItem )
                                               {
                                                   delete aItem;
                                               } );
            delete curr_cmd;    // Delete command
        }
    }
}