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
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 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
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
###############################################################################
# Copyright (c) 2017-2024 by Altair Engineering, Inc.
# All rights reserved.
#
# Altair Engineering, Inc. makes this software available as part of the Vision
# tool platform.  As long as you are a licensee of the Vision tool platform
# you may make copies of the software and modify it to be used within the
# Vision tool platform, but you must include all of this notice on any copy.
# Redistribution without written permission to any third party, with or
# without modification, is not permitted.
# Altair Engineering, Inc. does not warrant that this software is error free
# or fit for any purpose.  Altair Engineering, Inc. disclaims any liability for
# all claims, expenses, losses, damages and costs any user may incur as a
# result of using, copying or modifying the software.
# =============================================================================
#   @plugin
#       Compute Differences
#   @namespace
#       Diff
#   @section
#       Miscellaneous Userware Examples
#   @description
#       Compute and display the differences of the currently loaded database
#       and a binary database (.zdb file).
#       Can be run directly from the command line using the command line options
#       `-userware3 diff.tcl db1.zdb db2.zdb`.
#   @files
#       Diff/diff.tcl
#       Diff/diff_common.tcl
#   @example
#       demo/api/Diff/netlistA.v
#       demo/api/Diff/netlistB.v
#   @tag
#       zdb gui
###############################################################################


# =============================================================================
# Init - Initialize the plugin.
# =============================================================================
#
proc Diff:Init {
    argc
    argv
} {
    global Diff

    set Diff(file)                       ""
    set Diff(merge)                      1
    set Diff(ignoreCase)                 0
    set Diff(ignoreEquivalentPrimitives) 0
    set Diff(normalizeArrays)            0
    set Diff(originalDB)                 {}
    set Diff(db)                         {}
    set Diff(db1)                        {}
    set Diff(db2)                        {}
    set Diff(skipClose)                  0
    set Diff(schem2name)                 "Schem (DB2)"
    set Diff(dir)                        [file join [zos tempdir] diff_[pid]]
    set Diff(diffwindow)                 .diffwindow
    set Diff(diffwindow:image)           {}
    set Diff(diffwindow:files)           {}
    set Diff(diffwindow:index)           0
    set Diff(filter:cells)               1
    set Diff(filter:interfaces)          1
    set Diff(filter:instances)           1
    set Diff(filter:connectivity)        1
    set Diff(diffs)                      [list]

    source [file join [file dirname [info script]] diff_common.tcl]

    Diff:openTab

    gui menu command {"Diff" "Open Tab"} [list Diff:openTab]

    gui popup append     \
        -menuname "Diff" \
        "Show in DB2"    \
        [list Diff:showInOtherDB 2]

    if {$argc == 2} {
        gui database changed [zdb open [lindex $argv 0]]
        set Diff(file) [lindex $argv 1]
        Diff:Run
    }

    gui database registerChangedCallback Diff:closeDBs
}


# =============================================================================
# Finit - Finalize the plugin.
# =============================================================================
#
proc Diff:Finit {} {
    global Diff

    if {[gui window exists "Diff"]} {
        gui window removeCustomWidget "Diff"
    }

    gui database removeChangedCallback Diff:closeDBs

    gui menu  removeEntry {"Diff"}
    gui popup remove -menuname "Diff" "Show in DB2"

    ##
    # Close secondary schem.
    #
    set schem2 [gui window path $Diff(schem2name)]
    if {$schem2 != {}} {
        gui window remove $schem2
    }

    set Diff(skipClose) 1
    if {[zdb valid $Diff(originalDB)]} {
        Diff:removeCellPrefix $Diff(originalDB) "DB1--"
        gui database changed $Diff(originalDB)
    } elseif {$Diff(originalDB) != {}} {
        gui database changed {}
    }
    set Diff(skipClose) 0

    if {[zdb valid $Diff(db)] && ($Diff(db) != [gui database get])} {
        $Diff(db) close
    }
    if {[zdb valid $Diff(db1)] && ($Diff(db1) != [gui database get])} {
        $Diff(db1) close
    }
    if {[zdb valid $Diff(db2)] && ($Diff(db2) != [gui database get])} {
        $Diff(db2) close
    }

    file delete -force -- $Diff(dir)
    destroy $Diff(diffwindow)
    if {$Diff(diffwindow:image) != {}} {
        image delete $Diff(diffwindow:image)
    }

    array unset Diff *
}


# -----------------------------------------------------------------------------
# openTab - Open the "Diff" tab.
# -----------------------------------------------------------------------------
#
proc Diff:openTab {} {
    global Diff

    if {[gui window exists "Diff"]} {
        gui window removeCustomWidget "Diff"
    }
    set w [gui window insertCustomWidget -pluginNamespace "Diff" "Diff"]

    ttk::frame $w.left
    ttk::label $w.left.label -text "Secondary Database:"
    ttk::entry $w.left.entry -textvariable Diff(file)
    ttk::button $w.left.browse \
        -text "..." \
        -style Browse.TButton \
        -width 3 \
        -command [list Diff:browseFile]
    ttk::checkbutton $w.left.merge \
        -text "Merge Databases" \
        -variable Diff(merge)
    ttk::checkbutton $w.left.normalizeArrays \
        -text "Normalize array/bus names" \
        -variable Diff(normalizeArrays)
    ttk::checkbutton $w.left.ignoreCase \
        -text "Ignore case" \
        -variable Diff(ignoreCase)
    ttk::checkbutton $w.left.ignoreEquivalentPrimitives \
        -text "Consider primitives with the\nsame function to be equivalent" \
        -variable Diff(ignoreEquivalentPrimitives)
    ttk::button $w.left.compute \
        -text "Compute Differences" \
        -command [list Diff:Run]

    grid $w.left.label   -row 0 -column 0 -columnspan 2 -sticky nw
    grid $w.left.entry   -row 1 -column 0 -sticky new
    grid $w.left.browse  -row 1 -column 1 -sticky new
    grid $w.left.merge   -row 2 -column 0 -columnspan 2 -sticky nw
    grid $w.left.ignoreEquivalentPrimitives \
        -row 3 -column 0 -columnspan 2 -sticky nw
    grid $w.left.ignoreCase \
        -row 4 -column 0 -columnspan 2 -sticky nw
    grid $w.left.normalizeArrays \
        -row 5 -column 0 -columnspan 2 -sticky nw
    grid $w.left.compute -row 6 -column 0 -columnspan 2 -sticky we -pady 8
    grid columnconfigure $w.left 0 -weight 1

    ttk::frame $w.right

    set Diff(t) $w.right.t
    ttk::treeview $w.right.t \
        -columns {A B oid1 oid2} \
        -displaycolumns {A B} \
        -xscrollcommand "$w.right.sx set" \
        -yscrollcommand "$w.right.sy set"
    $w.right.t heading #0  -text "Object"             -anchor w
    $w.right.t heading "A" -text "Primary Database"   -anchor w
    $w.right.t heading "B" -text "Secondary Database" -anchor w
    bind $w.right.t <Double-1> {
        Diff:doubleClick %W %x %y
        break
    }
    bind $w.right.t <ButtonRelease-3> {
        Diff:rightClick %W %X %Y %x %y
    }

    ttk::scrollbar $w.right.sx -orient horizontal \
        -command "$w.right.t xview"
    ttk::scrollbar $w.right.sy -orient vertical \
        -command "$w.right.t yview"

    ttk::frame $w.right.filter
    ttk::label $w.right.filter.label -text "Show Differences:"
    ttk::checkbutton $w.right.filter.cells \
       -text "Cells" \
       -variable Diff(filter:cells) \
       -command "Diff:filterResults"
    ttk::checkbutton $w.right.filter.interfaces \
       -text "Interfaces" \
       -variable Diff(filter:interfaces) \
       -command "Diff:filterResults"
    ttk::checkbutton $w.right.filter.instances \
       -text "Instances" \
       -variable Diff(filter:instances) \
       -command "Diff:filterResults"
    ttk::checkbutton $w.right.filter.connectivity \
       -text "Connectivity" \
       -variable Diff(filter:connectivity) \
       -command "Diff:filterResults"
    pack $w.right.filter.label        -side left
    pack $w.right.filter.cells        -side left -padx {8 0}
    pack $w.right.filter.interfaces   -side left -padx {8 0}
    pack $w.right.filter.instances    -side left -padx {8 0}
    pack $w.right.filter.connectivity -side left -padx {8 0}

    grid $w.right.t      -row 0 -column 0 -sticky news
    grid $w.right.sy     -row 0 -column 1 -sticky ns
    grid $w.right.sx     -row 1 -column 0 -sticky we
    grid $w.right.filter -row 2 -column 0 -sticky news -columnspan 2
    grid rowconfigure    $w.right 0 -weight 1
    grid columnconfigure $w.right 0 -weight 1

    pack $w.left  -side left           -fill y
    pack $w.right -side left -expand 1 -fill both
}


# -----------------------------------------------------------------------------
# clearTable - Clear the results table.
# -----------------------------------------------------------------------------
#
proc Diff:clearTable {} {
    global Diff

    if {[winfo exists $Diff(t)]} {
        $Diff(t) delete [$Diff(t) children {}]
    }
}


# -----------------------------------------------------------------------------
# closeDBs - Close all Diff DBs.
# -----------------------------------------------------------------------------
#
proc Diff:closeDBs {
    db
} {
    global Diff

    if {$Diff(skipClose)} {
        return
    }

    Diff:clearTable

    if {[zdb valid $Diff(db)] && ($Diff(db) != [gui database get])} {
        $Diff(db) close
    }
    if {[zdb valid $Diff(db1)] && ($Diff(db1) != [gui database get])} {
        $Diff(db1) close
    }
    if {[zdb valid $Diff(db2)] && ($Diff(db2) != [gui database get])} {
        $Diff(db2) close
    }
    set Diff(db)         {}
    set Diff(db1)        {}
    set Diff(db2)        {}
    set Diff(originalDB) {}

    file delete -force -- $Diff(dir)
}


# =============================================================================
# Run - load two zdb files, compute and display their differences.
# =============================================================================
#
proc Diff:Run {} {
    global Diff

    if {[zdb valid $Diff(originalDB)]} {
        Diff:removeCellPrefix $Diff(originalDB) "DB1--"

        set Diff(skipClose) 1
        gui database changed $Diff(originalDB)
        set Diff(skipClose) 0
    }

    Diff:closeDBs {}

    set db1 [gui database get]
    if {$db1 == {}} {
        zmessage print ERR "No primary database"
        return
    }
    set Diff(originalDB) $db1

    ##
    # try to open both files
    #
    set fname $Diff(file)
    if {$fname == ""} {
        zmessage print ERR "No secondary database"
        return
    }
    set db2 {}
    if {[catch {set db2 [zdb open $fname]} msg]} {
        zmessage print ERR "Cannot open secondary database '$fname': $msg"
        return
    }

    Diff:Diff $db1 $db2
}


# =============================================================================
# Diff - Compute and display the difference of db1 and db2.
# =============================================================================
#
proc Diff:Diff {
    db1
    db2
} {
    global Diff

    set Diff(db1) $db1
    set Diff(db2) $db2

    set Diff(diffs) [list]

    Diff:clearTable

    DiffCommon::Compute \
        $db1 \
        $db2 \
        Diff:show \
        Diff:showList \
        $Diff(ignoreCase) \
        $Diff(ignoreEquivalentPrimitives) \
        $Diff(normalizeArrays)

    Diff:filterResults

    if {$Diff(merge)} {
        set Diff(db) [Diff:mergeDBs]

        set Diff(skipClose) 1
        gui database changed $Diff(db)
        set Diff(skipClose) 0
    } else {
        set Diff(db) {}
    }
}


# -----------------------------------------------------------------------------
# mergeDBs - Merge both databases into one.
# -----------------------------------------------------------------------------
#
proc Diff:mergeDBs {} {
    global Diff

    set db [zdb new]
    Diff:cloneInto $db $Diff(db1) "DB1--"
    Diff:cloneInto $db $Diff(db2) "DB2--"
    return $db
}


# -----------------------------------------------------------------------------
# cloneInto - Clone $db into $target_db while appending $prefix to all module
#             names.
# -----------------------------------------------------------------------------
#
proc Diff:cloneInto {
    target_db
    db
    prefix
} {
    $db foreach cell c {
        set name [$db oid oname $c]
        $db oper rename $c $prefix$name
    }
    $db oper rename -updateOIDs

    $db cloneDB -into $target_db
}


# -----------------------------------------------------------------------------
# browseFile - open file dialog to select a zdb file
# -----------------------------------------------------------------------------
#
proc Diff:browseFile {} {
    global Diff

    set fname [gui window fileDialog openFile "Select Zdb Binfile" \
        {{"Binfile" {.zdb}}}]
    if {$fname != {}} {
        set Diff(file) $fname
    }
}


# -----------------------------------------------------------------------------
# parent - lookup parent node (create it if it doesn't exist)
# -----------------------------------------------------------------------------
#
proc Diff:parent {
    path
    class
} {
    global Diff

    set t $Diff(t)

    set parent {}
    foreach {text oid1 oid2} $path {
        set found 0
        foreach item [$t children $parent] {
            if {[$t item $item -text] == $text} {
                set parent $item
                set found  1
            }
        }
        if {!$found} {
            set parent [$t insert $parent end \
                -text $text \
                -open 0 \
                -values [list {} {} $oid1 $oid2]]
        }
    }

    return $parent
}


# -----------------------------------------------------------------------------
# show - show difference
# -----------------------------------------------------------------------------
#
proc Diff:show {
    class
    path
    sub
    val1
    val2
    obj1
    obj2
    {parent1 {}}
    {parent2 {}}
} {
    global Diff

    lappend Diff(diffs) \
        [list item $class $path $sub $val1 $val2 $obj1 $obj2 $parent1 $parent2]
}


# -----------------------------------------------------------------------------
# showList - show difference lists
# -----------------------------------------------------------------------------
#
proc Diff:showList {
    class
    path
    sub
    list1
    list2
    obj1
    obj2
    pairwise
} {
    global Diff

    lappend Diff(diffs) \
        [list list $class $path $sub $list1 $list2 $obj1 $obj2 $pairwise]
}


# -----------------------------------------------------------------------------
# isFilteredOut -
# -----------------------------------------------------------------------------
#
proc Diff:isFilteredOut {
    class
} {
    global Diff

    switch -exact -- $class {
        "CELLS" {
            return [expr {!$Diff(filter:cells)}]
        }
        "INTERFACES" {
            return [expr {!$Diff(filter:interfaces)}]
        }
        "INSTANCES" {
            return [expr {!$Diff(filter:instances)}]
        }
        "CONNECTIVITY" {
            return [expr {!$Diff(filter:connectivity)}]
        }
        default {}
    }

    return 0
}


# -----------------------------------------------------------------------------
# filterResults - Show/hide results based on the current filter settings.
# -----------------------------------------------------------------------------
#
proc Diff:filterResults {} {
    global Diff

    Diff:clearTable

    set table $Diff(t)

    foreach diff $Diff(diffs) {
        set class [lindex $diff 1]
        if {[Diff:isFilteredOut $class]} {
            continue
        }

        set type  [lindex $diff 0]
        switch -exact -- $type {
            "item" {
                lassign $diff \
                    type class path sub val1 val2 obj1 obj2 parent1 parent2

                set parent [Diff:parent $path $class]
                $table insert $parent end \
                    -text $sub \
                    -values [list $val1 $val2 $obj1 $obj2 $parent1 $parent2]
            }
            "list" {
                lassign $diff \
                    type class path sub list1 list2 obj1 obj2 pairwise

                set parent [Diff:parent $path $class]

                set s [$table insert $parent end \
                    -text $sub \
                    -open 0 \
                    -values [list {} {} $obj1 $obj2]]

                if {$pairwise} {
                    foreach it1 $list1 it2 $list2 {
                        set node [$table insert $s end \
                            -values [list $it1 $it2 $it1 $it2 $obj1 $obj2]]
                    }
                } else {
                    foreach it $list1 {
                        set node [$table insert $s end \
                            -values [list $it missing $it {} $obj1 $obj2]]
                    }
                    foreach it $list2 {
                        set node [$table insert $s end \
                            -values [list missing $it {} $it $obj1 $obj2]]
                    }
                }
            }
            default {}
        }
    }
}


# -----------------------------------------------------------------------------
# removeCellPrefix - Remove the given prefix from all cell names.
# -----------------------------------------------------------------------------
#
proc Diff:removeCellPrefix {
    db
    prefix
} {
    set start [string length $prefix]
    $db foreach cell c {
        set name [$db oid oname $c]
        if {[string match "$prefix*" $name]} {
            $db oper rename $c [string range $name $start end]
        }
    }
    $db oper rename -updateOIDs
}


# -----------------------------------------------------------------------------
# doubleClick - Double click handler.
# -----------------------------------------------------------------------------
#
proc Diff:doubleClick {
    w
    x
    y
} {
    global Diff

    set item [$w identify item $x $y]
    if {$item == {}} {
        return
    }

    if {$Diff(db) != {}} {
        $Diff(db) hilight * deleteAll 0
        $Diff(db) hilight * deleteAll 1
    }

    set obj  [$w item $item -values]
    set obj1 [lindex $obj 2]
    set obj2 [lindex $obj 3]

    if {$obj1 == {}} {
        ##
        # use parent object if set
        #
        set obj1 [lindex $obj 4]
    }
    set schem1 [gui window defaultClassWindow Schem]
    gui window title DB1
    if {$obj1 != {}} {
        if {$Diff(db) != {}} {
            if {[$Diff(db) oid type $obj1 ] eq "module"} {
                set mod [$Diff(db) oid searchTreeBased $obj1]
                gui schem setCurrentModule -window $schem1 $mod
            } else {
                $Diff(db) hilight $obj1 set 0
                Diff:zoom $schem1 [list $obj1]
            }
        } else {
            Diff:zoom $schem1 [list $obj1]
        }
    } else {
        gui schem setCurrentModule -window $schem1 {}
    }

    if {$Diff(db) != {}} {
        if {$obj2 == {}} {
            ##
            # use parent object if set
            #
            set obj2 [lindex $obj 5]
        }
        set schem2 [Diff:openSecondVisu]

        if {$obj2 != {}} {
            if {[$Diff(db) oid type $obj2 ] eq "module"} {
                set mod [$Diff(db) oid searchTreeBased $obj2]
                gui schem setCurrentModule -window $schem2 $mod
            } else {
                $Diff(db) hilight $obj2 set 1
                Diff:zoom $schem2 [list $obj2]
            }
        } else {
            gui schem setCurrentModule -window $schem2 {}
        }
    }

    gui highlight changed

    if {($Diff(db) != {}) && ($obj1 != {}) && ($obj2 != {})} {
        set nlv1 [gui schem nlv -window $schem1]
        set nlv2 [gui schem nlv -window $schem2]

        set layout [$nlv1 gsave -string]
        set zoom   [$nlv1 zoom]
        set scroll [$nlv1 scrollpos]

        $nlv2 increment
        $nlv2 grestore -string $layout
        $nlv2 show
        $nlv2 zoom $zoom
        $nlv2 scrollpos {*}$scroll

        if {[$Diff(db) oid type $obj2 ] ne "module"} {
            Diff:zoom $schem2 [list $obj2]
        }
    }
}


# -----------------------------------------------------------------------------
# zoom - Make $oids visible in $schem.
# -----------------------------------------------------------------------------
#
proc Diff:zoom {
    schem
    oids
} {
    gui zoomTo -window $schem $oids
    gui schem zoom -window $schem -0.2
}


# -----------------------------------------------------------------------------
# openSecondVisu - open the second visualizer if not already open
# -----------------------------------------------------------------------------
#
proc Diff:openSecondVisu {} {
    global Diff

    set slave [gui window path $Diff(schem2name)]
    if {$slave != {}} {
        gui window show $slave
        return $slave
    }

    gui popup append     \
        -menuname "Diff" \
        "Show in DB2"    \
        [list Diff:showInOtherDB 1]

    set schem  [gui window defaultClassWindow Schem]
    set tab2   [gui window split $schem right]
    set schem2 [gui window new "Schem" -tabwindow $tab2]
    gui window rename $schem2 $Diff(schem2name)

    return $schem2
}


# -----------------------------------------------------------------------------
# showInOtherDB - show $oids in other DB
# -----------------------------------------------------------------------------
#
proc Diff:showInOtherDB {
    otherDB
    oids
} {
    global Diff

    set db $Diff(db)
    if {$db == {}} {
        return
    }

    set otheroids {}
    foreach oid $oids {
        if {$otherDB == 1} {
            set otheroid [string map {"DB2--" "DB1--"} $oid]
            set schem [gui window defaultClassWindow Schem]
        } else {
            set otheroid [string map {"DB1--" "DB2--"} $oid]
            set schem [Diff:openSecondVisu]
        }
        if {![catch {set otheroid [$db oid create $otheroid]}]} {
            lappend otheroids $otheroid
        }
    }

    if {$otheroids != {}} {
        Diff:zoom $schem $otheroids
        gui goto -class Schem $otheroids
    } else {
        gui schem setCurrentModule -window $schem {}
    }
}


# -----------------------------------------------------------------------------
# rightClick - Right click handler.
# -----------------------------------------------------------------------------
#
proc Diff:rightClick {
    w
    X
    Y
    x
    y
} {
    global Diff

    if {$Diff(db) == {}} {
        return
    }
    set item [$w identify item $x $y]
    if {$item == {}} {
        return
    }

    $w selection set $item

    set obj  [$w item $item -values]
    set obj1 [lindex $obj 2]
    set obj2 [lindex $obj 3]

    if {($obj1 == {}) || \
        ([$Diff(db) oid type $obj1] != "module") || \
        ($obj2 == {}) || \
        ([$Diff(db) oid type $obj2] != "module") \
    } {
        return
    }

    destroy $w.menu
    menu $w.menu

    set name [string range [$w item $item -text] 7 end]
    $w.menu add command \
        -label "Compute graphical diff" \
        -command [list Diff:computeGraphicalDiff $name $obj1 $obj2]

    $w.menu post $X $Y
}


# -----------------------------------------------------------------------------
# computeGraphicalDiff -
# -----------------------------------------------------------------------------
#
proc Diff:computeGraphicalDiff {
    name
    oid1
    oid2
} {
    global Diff

    set mod1 [Diff:treeOid $Diff(db) $oid1]
    set mod2 [Diff:treeOid $Diff(db) $oid2]
    if {($mod1 == {}) || ($mod2 == {})} {
        return
    }

    $Diff(db) hilight * deleteAll 0
    $Diff(db) hilight * deleteAll 1

    set dir [file join $Diff(dir) [zos sanitizeFilename $name]]
    if {![file exists $dir]} {
        file mkdir $dir

        Diff:createImages $Diff(db) $dir [list $mod1 db1 $mod2 db2]

        zprogress begin
        zprogress push "Create diff images" 1.0
        Diff:createDiffImages $dir db1 db2 diff
        if {[zprogress pop]} {
            file delete -force -- $dir
            zprogress end
            return
        }
        zprogress end
    }

    set w $Diff(diffwindow)
    if {![winfo exists $w]} {
        toplevel $w
        ttk::frame $w.page
        ttk::button $w.page.prev  -text "Prev" -command [list Diff:page -1]
        ttk::button $w.page.next  -text "Next" -command [list Diff:page +1]
        ttk::label  $w.page.label -text "Page ?"
        label $w.page.label1 -text "Only in DB1"       -bg #FFFFFF -fg #FF0000
        label $w.page.label2 -text "Only in DB2"       -bg #FFFFFF -fg #0000FF
        label $w.page.label3 -text "Both in DB1 & DB2" -bg #FFFFFF -fg #000000
        grid $w.page.prev   -row 0 -column 0 -sticky news
        grid $w.page.next   -row 0 -column 1 -sticky news
        grid $w.page.label  -row 0 -column 2 -sticky news -padx 4
        grid $w.page.label1 -row 0 -column 3 -sticky news -padx 4
        grid $w.page.label2 -row 0 -column 4 -sticky news -padx 4
        grid $w.page.label3 -row 0 -column 5 -sticky news -padx {4 0}
        grid rowconfigure    $w.page 0 -weight 1
        grid columnconfigure $w.page 2 -weight 1

        ttk::frame $w.display
        canvas $w.display.canvas
        gui window autoscroll $w.display $w.display.canvas
        $w.display.canvas create image 0 0 -anchor nw -tags {image}

        grid $w.page    -row 0 -column 0 -sticky news
        grid $w.display -row 1 -column 0 -sticky news
        grid rowconfigure    $w 1 -weight 1
        grid columnconfigure $w 0 -weight 1
    }
    wm title $w "Graphical differences for Module $name"

    set Diff(diffwindow:files) {}
    set Diff(diffwindow:index) 0
    for {set page 1} {1} {incr page} {
        set fname [Diff:getFname [file join $Diff(dir) $name] diff $page]
        if {$fname == ""} {
            break
        }
        lappend Diff(diffwindow:files) $fname
    }

    Diff:page 0
}


# -----------------------------------------------------------------------------
# treeOid - Create a tree-based OID.
# -----------------------------------------------------------------------------
#
proc Diff:treeOid {db oid} {
    if {[$db oid isTopRoot $oid]} {
        return $oid
    }

    set tOid {}
    catch {
        set tOid [$db oid searchTreeBased $oid]
    }

    if {($tOid != {}) && (![$db oid isnull $tOid])} {
        return $tOid
    }

    zmessage print ERR "Cannot transform $oid into a tree-based OID"
    return {}
}


# -----------------------------------------------------------------------------
# page - Switch page in diff window.
# -----------------------------------------------------------------------------
#
proc Diff:page {
    delta
} {
    global Diff

    set w $Diff(diffwindow)

    set count [llength $Diff(diffwindow:files)]
    set index [expr {$Diff(diffwindow:index) + $delta}]
    set index [expr {max(0, min(($count - 1), $index))}]
    set Diff(diffwindow:index) $index

    $w.page.label configure -text "Page [expr {$index + 1}] / $count"
    if {$index > 0} {
        $w.page.prev configure -state normal
    } else {
        $w.page.prev configure -state disabled
    }
    if {$index < ($count - 1)} {
        $w.page.next configure -state normal
    } else {
        $w.page.next configure -state disabled
    }

    set fname [lindex $Diff(diffwindow:files) $index]
    if {$Diff(diffwindow:image) != {}} {
        image delete $Diff(diffwindow:image)
        set Diff(diffwindow:image) {}
    }
    set Diff(diffwindow:image) [image create photo -file $fname]

    $w.display.canvas itemconfigure image -image $Diff(diffwindow:image)
    $w.display.canvas configure -scrollregion [$w.display.canvas bbox image]
}


# -----------------------------------------------------------------------------
# createImages -
# -----------------------------------------------------------------------------
#
proc Diff:createImages {
    db
    dir
    oid_prefix_list
} {
    ##
    # Set global settings such that the schematics
    # - don't show instance/net/pin names
    # - are more stable
    #
    set key_value {
        nlv:showcellname     0
        nlv:showinstname     0
        nlv:showpinname      0
        nlv:showportname     1
        nlv:shownetname      0
        nlv:shownetnamepin   0
        nlv:showhidenetnames 0
        nlv:showripindex     0
        nlv:showpagenumbers  0
        nlv:showmarks        0
        nlv:dropshadow       0
        nlv:netattrwire      0
        nlv:netattrpin       0
        nlv:scaleNetAttr     0
        nlv:showattribute    0
        nlv:showval          0
        nlv:showpgtype       0
        nlv:pinpermute       0
        nlv:showBulk         none
        nlv:onGrid           1
    }
    set original_settings [dict create]
    foreach {key value} $key_value {
        dict set original_settings $key [gui settings get $key]
        gui settings set $key $value
    }

    set schem [gui window new Schem]
    foreach {oid prefix} $oid_prefix_list {
        gui schem setCurrentModule -window $schem $oid
        gui schem zoom -window $schem 1
        gui export photo [file join $dir ${prefix}.png] $schem auto png
    }
    gui window remove $schem

    ##
    # Restore global settings.
    #
    foreach {key value} $key_value {
        gui settings set $key [dict get $original_settings $key]
    }
}


# -----------------------------------------------------------------------------
# getFname -
# -----------------------------------------------------------------------------
#
proc Diff:getFname {
    dir
    prefix
    page
} {
    set fname [file join $dir ${prefix}_page${page}.png]
    if {[file exists $fname]} {
        return $fname
    }

    if {$page == 1} {
        set fname [file join $dir ${prefix}.png]
        if {[file exists $fname]} {
            return $fname
        }
    }

    return ""
}


# -----------------------------------------------------------------------------
# createDiffImages -
# -----------------------------------------------------------------------------
#
proc Diff:createDiffImages {
    dir
    prefix1
    prefix2
    prefixDiff
} {
    set pages 0
    for {set page 1} {1} {incr page} {
        set fname1 [Diff:getFname $dir $prefix1 $page]
        set fname2 [Diff:getFname $dir $prefix2 $page]
        if {($fname1 == "") && ($fname2 == "")} {
            break
        }
        incr pages
    }
    if {$pages == 0} {
        return
    }

    for {set page 1} {$page <= $pages} {incr page} {
        zprogress push "Page $page/$pages" [expr {double($page) / $pages}]

        zprogress push "Load image1" 0.1
        set w1     1
        set h1     1
        set data1  {{#FFFFFF}}
        set fname1 [Diff:getFname $dir $prefix1 $page]
        if {$fname1 != ""} {
            set image [image create photo -file $fname1]
            set w1    [image width  $image]
            set h1    [image height $image]
            set data1 [$image data -grayscale]
            image delete $image
        }
        if {[zprogress pop]} {
            ##
            # "Page" push
            #
            zprogress pop
            break
        }

        zprogress push "Load image2" 0.2
        set w2     1
        set h2     1
        set data2  {{#FFFFFF}}
        set fname2 [Diff:getFname $dir $prefix2 $page]
        if {$fname2 != ""} {
            set image [image create photo -file $fname2]
            set w2    [image width  $image]
            set h2    [image height $image]
            set data2 [$image data -grayscale]
            image delete $image
        }
        if {[zprogress pop]} {
            ##
            # "Page" push
            #
            zprogress pop
            break
        }

        zprogress push "Compute diff" 0.9
        set w    [expr {max($w1, $w2)}]
        set h    [expr {max($h1, $h2)}]
        set data {}
        foreach row1 $data1 row2 $data2 {
            zprogress push "" [expr {(1 + [llength $data]) / $h}]
            set row {}
            foreach color1 $row1 color2 $row2 {
                if {$color1 == {}} {
                    set color1 #FFFFFF
                }
                if {$color2 == {}} {
                    set color2 #FFFFFF
                }

                scan [string range $color1 1 2] %x gray
                set black1 [expr {$gray <= 127}]

                if {$color1 == $color2} {
                    if {$black1} {
                        lappend row #000000
                    } else {
                        lappend row #FFFFFF
                    }
                    continue
                }

                scan [string range $color2 1 2] %x gray
                set black2 [expr {$gray <= 127}]

                if {$black1} {
                    if {$black2} {
                        lappend row #000000
                    } else {
                        lappend row #FF0000
                    }
                } elseif {$black2} {
                    lappend row #0000FF
                } else {
                    lappend row #FFFFFF
                }
            }
            while {[llength $row] < $w} {
                lappend row #FFFFFF
            }
            lappend data $row
            if {[zprogress pop]} {
                break
            }
        }
        if {[zprogress pop]} {
            ##
            # "Page" push
            #
            zprogress pop
            break
        }

        zprogress push "Write diff image" 1.0
        set image [image create photo -width $w -height $h]
        $image put $data
        $image write [file join $dir ${prefixDiff}_page${page}.png] -format png
        image delete $image
        if {[zprogress pop]} {
            ##
            # "Page" push
            #
            zprogress pop
            break
        }

        ##
        # "Page" push
        #
        zprogress pop
    }
}


# =============================================================================
# Call the initialization procedure.
# =============================================================================
#
Diff:Init $argc $argv