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
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
/*
 * Copyright (C) 2008-2011 Robert Ancell
 *
 * 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. See http://www.gnu.org/copyleft/gpl.html the full text of the
 * license.
 */

#include <glib/gi18n.h>

#include "math-buttons.h"
#include "math-converter.h"
#include "math-variable-popup.h"
#include "financial.h"
#include "mp-serializer.h"
#include "utility.h"

enum {
    PROP_0,
    PROP_EQUATION,
    PROP_MODE,
    PROP_PROGRAMMING_BASE
};

static GType button_mode_type;

#define MAXBITS 64      /* Bit panel: number of bit fields. */

struct MathButtonsPrivate
{
    MathEquation *equation;

    ButtonMode mode;
    gint programming_base;

    MathConverter *converter;

    CtkBuilder *basic_ui, *advanced_ui, *financial_ui, *programming_ui;

    CtkWidget *bas_panel, *adv_panel, *fin_panel, *prog_panel;
    CtkWidget *active_panel;

    CtkWidget *shift_left_menu, *shift_right_menu;

    CtkWidget *function_menu;
    CtkWidget *const_menu;

    GList *superscript_toggles;
    GList *subscript_toggles;

    CtkWidget *base_combo;
    CtkWidget *base_label;
    CtkWidget *bit_panel;
    CtkWidget *bit_labels[MAXBITS];

    CtkWidget *character_code_dialog;
    CtkWidget *character_code_entry;
};

G_DEFINE_TYPE_WITH_PRIVATE (MathButtons, math_buttons, CTK_TYPE_BOX);

#define UI_BASIC_RESOURCE_PATH       "/org/cafe/calculator/ui/buttons-basic.ui"
#define UI_ADVANCED_RESOURCE_PATH    "/org/cafe/calculator/ui/buttons-advanced.ui"
#define UI_FINANCIAL_RESOURCE_PATH   "/org/cafe/calculator/ui/buttons-financial.ui"
#define UI_PROGRAMMING_RESOURCE_PATH "/org/cafe/calculator/ui/buttons-programming.ui"

#define GET_WIDGET(ui, name) \
          CTK_WIDGET(ctk_builder_get_object((ui), (name)))

#define WM_WIDTH_FACTOR  10
#define WM_HEIGHT_FACTOR 30

typedef enum
{
    NUMBER,
    NUMBER_BOLD,
    OPERATOR,
    FUNCTION,
    MEMORY,
    GROUP,
    ACTION
} ButtonClass;

typedef struct {
    const char *widget_name;
    const char *data;
    ButtonClass class;<--- struct member 'ButtonData::class' is never used.
    const char *tooltip;
} ButtonData;

static ButtonData button_data[] = {
    {"pi",                 "π", NUMBER,
      /* Tooltip for the Pi button */
      N_("Pi [Ctrl+P]")},
    {"eulers_number",      "e", NUMBER,
      /* Tooltip for the Euler's Number button */
      N_("Euler’s Number")},
    {"imaginary",          "i", NUMBER, NULL},
    {"numeric_point", NULL, NUMBER, NULL},
    {"subscript", NULL, NUMBER_BOLD,
      /* Tooltip for the subscript button */
      N_("Subscript mode [Alt]")},
    {"superscript", NULL, NUMBER_BOLD,
      /* Tooltip for the superscript button */
      N_("Superscript mode [Ctrl]")},
    {"exponential", NULL, NUMBER_BOLD,
      /* Tooltip for the scientific exponent button */
      N_("Scientific exponent [Ctrl+E]")},
    {"add",                "+", OPERATOR,
      /* Tooltip for the add button */
      N_("Add [+]")},
    {"subtract",           "−", OPERATOR,
      /* Tooltip for the subtract button */
      N_("Subtract [-]")},
    {"multiply",           "×", OPERATOR,
      /* Tooltip for the multiply button */
      N_("Multiply [*]")},
    {"divide",             "÷", OPERATOR,
      /* Tooltip for the divide button */
      N_("Divide [/]")},
    {"modulus_divide",     " mod ", OPERATOR,
      /* Tooltip for the modulus divide button */
      N_("Modulus divide")},
    {"function",           NULL, FUNCTION,
      /* Tooltip for the additional functions button */
      N_("Additional Functions")},
    {"const",           NULL, FUNCTION,
      /* Tooltip for the additional constant button */
      N_("Additional constants")},
    {"x_pow_y",            "^", FUNCTION,
      /* Tooltip for the exponent button */
      N_("Exponent [^ or **]")},
    {"x_squared",          "²", FUNCTION,
      /* Tooltip for the square button */
      N_("Square [Ctrl+2]")},
    {"percentage",         "%", NUMBER,
      /* Tooltip for the percentage button */
      N_("Percentage [%]")},
    {"factorial",          "!", FUNCTION,
      /* Tooltip for the factorial button */
      N_("Factorial [!]")},
    {"abs",                "|", FUNCTION,
      /* Tooltip for the absolute value button */
      N_("Absolute value [|]")},
    {"arg",                "Arg ", FUNCTION,
      /* Tooltip for the complex argument component button */
      N_("Complex argument")},
    {"conjugate",          "conj ", FUNCTION,
      /* Tooltip for the complex conjugate button */
      N_("Complex conjugate")},
    {"root",               "√", FUNCTION,
      /* Tooltip for the root button */
      N_("Root [Ctrl+R]")},
    {"square_root",        "√", FUNCTION,
      /* Tooltip for the square root button */
      N_("Square root [Ctrl+R]")},
    {"logarithm",          "log ", FUNCTION,
      /* Tooltip for the logarithm button */
      N_("Logarithm")},
    {"natural_logarithm",  "ln ", FUNCTION,
      /* Tooltip for the natural logarithm button */
      N_("Natural Logarithm")},
    {"sine",               "sin ", FUNCTION,
      /* Tooltip for the sine button */
      N_("Sine")},
    {"cosine",             "cos ", FUNCTION,
      /* Tooltip for the cosine button */
      N_("Cosine")},
    {"tangent",            "tan ", FUNCTION,
      /* Tooltip for the tangent button */
      N_("Tangent")},
    {"hyperbolic_sine",    "sinh ", FUNCTION,
      /* Tooltip for the hyperbolic sine button */
      N_("Hyperbolic Sine")},
    {"hyperbolic_cosine",  "cosh ", FUNCTION,
      /* Tooltip for the hyperbolic cosine button */
      N_("Hyperbolic Cosine")},
    {"hyperbolic_tangent", "tanh ", FUNCTION,
      /* Tooltip for the hyperbolic tangent button */
      N_("Hyperbolic Tangent")},
    {"inverse_sine", "asin ", FUNCTION,
      /* Tooltip for the inverse sine button */
      N_("Inverse Sine")},
    {"inverse_cosine", "acos ", FUNCTION,
      /* Tooltip for the inverse cosine button */
      N_("Inverse Cosine")},
    {"inverse_tangent", "atan ", FUNCTION,
      /* Tooltip for the inverse tangent button */
      N_("Inverse Tangent")},
    {"inverse",            "⁻¹", FUNCTION,
      /* Tooltip for the inverse button */
      N_("Inverse [Ctrl+I]")},
    {"and",                "∧", OPERATOR,
      /* Tooltip for the boolean AND button */
      N_("Boolean AND")},
    {"or",                 "∨", OPERATOR,
      /* Tooltip for the boolean OR button */
      N_("Boolean OR")},
    {"xor",                "⊻", OPERATOR,
      /* Tooltip for the exclusive OR button */
      N_("Boolean Exclusive OR")},
    {"not",                "¬", FUNCTION,
      /* Tooltip for the boolean NOT button */
      N_("Boolean NOT")},
    {"integer_portion",    "int ", FUNCTION,
      /* Tooltip for the integer component button */
      N_("Integer Component")},
    {"fractional_portion", "frac ", FUNCTION,
      /* Tooltip for the fractional component button */
      N_("Fractional Component")},
    {"real_portion",       "Re ", FUNCTION,
      /* Tooltip for the real component button */
      N_("Real Component")},
    {"imaginary_portion",  "Im ", FUNCTION,
      /* Tooltip for the imaginary component button */
      N_("Imaginary Component")},
    {"ones_complement",    "ones ", FUNCTION,
      /* Tooltip for the ones' complement button */
      N_("Ones' Complement")},
    {"twos_complement",    "twos ", FUNCTION,
      /* Tooltip for the two's complement button */
      N_("Two's Complement")},
    {"trunc",              "trunc ", FUNCTION,
      /* Tooltip for the truncate button */
      N_("Truncate")},
    {"start_group",        "(", GROUP,
      /* Tooltip for the start group button */
      N_("Start Group [(]")},
    {"end_group",          ")", GROUP,
      /* Tooltip for the end group button */
      N_("End Group [)]")},
    {"memory", NULL, MEMORY,
      /* Tooltip for the memory button */
      N_("Memory")},
    {"character", NULL, MEMORY,
      /* Tooltip for the insert character code button */
      N_("Insert Character Code")},
    {"result", NULL, ACTION,
      /* Tooltip for the solve button */
      N_("Calculate Result")},
    {"factor", NULL, ACTION,
      /* Tooltip for the factor button */
      N_("Factorize [Ctrl+F]")},
    {"clear", NULL, GROUP,
      /* Tooltip for the clear button */
      N_("Clear Display [Escape]")},
    {"undo", NULL, GROUP,
      /* Tooltip for the undo button */
      N_("Undo [Ctrl+Z]")},
    {"shift_left", NULL, ACTION,
      /* Tooltip for the shift left button */
      N_("Shift Left [<<]")},
    {"shift_right", NULL, ACTION,
      /* Tooltip for the shift right button */
      N_("Shift Right [>>]")},
    {"finc_compounding_term", NULL, FUNCTION,
      /* Tooltip for the compounding term button */
      N_("Compounding Term")},
    {"finc_double_declining_depreciation", NULL, FUNCTION,
      /* Tooltip for the double declining depreciation button */
      N_("Double Declining Depreciation")},
    {"finc_future_value", NULL, FUNCTION,
      /* Tooltip for the future value button */
      N_("Future Value")},
    {"finc_term", NULL, FUNCTION,
      /* Tooltip for the financial term button */
      N_("Financial Term")},
    {"finc_sum_of_the_years_digits_depreciation", NULL, FUNCTION,
      /* Tooltip for the sum of the years digits depreciation button */
      N_("Sum of the Years Digits Depreciation")},
    {"finc_straight_line_depreciation", NULL, FUNCTION,
      /* Tooltip for the straight line depreciation button */
      N_("Straight Line Depreciation")},
    {"finc_periodic_interest_rate", NULL, FUNCTION,
      /* Tooltip for the periodic interest rate button */
      N_("Periodic Interest Rate")},
    {"finc_present_value", NULL, FUNCTION,
      /* Tooltip for the present value button */
      N_("Present Value")},
    {"finc_periodic_payment", NULL, FUNCTION,
      /* Tooltip for the periodic payment button */
      N_("Periodic Payment")},
    {"finc_gross_profit_margin", NULL, FUNCTION,
      /* Tooltip for the gross profit margin button */
      N_("Gross Profit Margin")},
    {NULL, NULL, 0, NULL}
};

/* The names of each field in the dialogs for the financial functions */
static char *finc_dialog_fields[][5] = {
    {"ctrm_pint", "ctrm_fv",     "ctrm_pv",    NULL,         NULL},
    {"ddb_cost",  "ddb_life",    "ddb_period", NULL,         NULL},
    {"fv_pmt",    "fv_pint",     "fv_n",       NULL,         NULL},
    {"gpm_cost",  "gpm_margin",  NULL,         NULL,         NULL},
    {"pmt_prin",  "pmt_pint",    "pmt_n",      NULL,         NULL},
    {"pv_pmt",    "pv_pint",     "pv_n",       NULL,         NULL},
    {"rate_fv",   "rate_pv",     "rate_n",     NULL,         NULL},
    {"sln_cost",  "sln_salvage", "sln_life",   NULL,         NULL},
    {"syd_cost",  "syd_salvage", "syd_life",   "syd_period", NULL},
    {"term_pmt",  "term_fv",     "term_pint",  NULL,         NULL},
    {NULL,        NULL,          NULL,         NULL,         NULL}
};


MathButtons *
math_buttons_new(MathEquation *equation)
{
    return g_object_new(math_buttons_get_type(), "equation", equation, NULL);
}

static void
set_data(CtkBuilder *ui, const gchar *object_name, const gchar *name, const char *value)
{
    GObject *object;
    object = ctk_builder_get_object(ui, object_name);
    if (object)
        g_object_set_data(object, name, GINT_TO_POINTER(value));
}


static void
set_int_data(CtkBuilder *ui, const gchar *object_name, const gchar *name, gint value)
{
    GObject *object;
    object = ctk_builder_get_object(ui, object_name);
    if (object)
        g_object_set_data(object, name, GINT_TO_POINTER(value));
}


static void
load_finc_dialogs(MathButtons *buttons)
{
    int i, j;

    set_int_data(buttons->priv->financial_ui, "ctrm_dialog", "finc_dialog", FINC_CTRM_DIALOG);
    set_int_data(buttons->priv->financial_ui, "ddb_dialog", "finc_dialog", FINC_DDB_DIALOG);
    set_int_data(buttons->priv->financial_ui, "fv_dialog", "finc_dialog", FINC_FV_DIALOG);
    set_int_data(buttons->priv->financial_ui, "gpm_dialog", "finc_dialog", FINC_GPM_DIALOG);
    set_int_data(buttons->priv->financial_ui, "pmt_dialog", "finc_dialog", FINC_PMT_DIALOG);
    set_int_data(buttons->priv->financial_ui, "pv_dialog", "finc_dialog", FINC_PV_DIALOG);
    set_int_data(buttons->priv->financial_ui, "rate_dialog", "finc_dialog", FINC_RATE_DIALOG);
    set_int_data(buttons->priv->financial_ui, "sln_dialog", "finc_dialog", FINC_SLN_DIALOG);
    set_int_data(buttons->priv->financial_ui, "syd_dialog", "finc_dialog", FINC_SYD_DIALOG);
    set_int_data(buttons->priv->financial_ui, "term_dialog", "finc_dialog", FINC_TERM_DIALOG);

    for (i = 0; finc_dialog_fields[i][0] != NULL; i++) {
        for (j = 0; finc_dialog_fields[i][j]; j++) {
            GObject *o;
            o = ctk_builder_get_object (buttons->priv->financial_ui, finc_dialog_fields[i][j]);
            g_object_set_data(o, "finc_field", GINT_TO_POINTER(j));
            g_object_set_data(o, "finc_dialog", GINT_TO_POINTER(i));
        }
    }
}


static void
update_bit_panel(MathButtons *buttons)
{
    MPNumber x;
    gboolean enabled;
    guint64 bits;
    int i;
    GString *label;<--- Shadowed declaration
    gint base;

    if (!buttons->priv->bit_panel)
        return;

    enabled = math_equation_get_number(buttons->priv->equation, &x);

    if (enabled) {
        MPNumber max, fraction;

        mp_set_from_unsigned_integer(G_MAXUINT64, &max);
        mp_fractional_part(&x, &fraction);
        if (mp_is_negative(&x) || mp_is_greater_than(&x, &max) || !mp_is_zero(&fraction))
            enabled = FALSE;
        else
            bits = mp_cast_to_unsigned_int(&x);
    }

    ctk_widget_set_sensitive(buttons->priv->bit_panel, enabled);
    ctk_widget_set_sensitive(buttons->priv->base_label, enabled);

    if (!enabled)
        return;

    for (i = 0; i < MAXBITS; i++) {
        const gchar *label;<--- Shadow variable

        if (bits & (1LLU << (MAXBITS-i-1)))
            label = " 1";
        else
            label = " 0";
        ctk_label_set_text(CTK_LABEL(buttons->priv->bit_labels[i]), label);
    }

    base = math_equation_get_base(buttons->priv->equation);
    label = g_string_new("");
    if (base != 8) {
        if (label->len != 0)
            g_string_append(label, " = ");
        g_string_append_printf(label, "%" G_GINT64_MODIFIER "o", bits);
        g_string_append(label, "₈");
    }
    if (base != 10) {
        if (label->len != 0)
            g_string_append(label, " = ");
        g_string_append_printf(label, "%" G_GINT64_MODIFIER "u", bits);
        g_string_append(label, "₁₀");
    }
    if (base != 16) {
        if (label->len != 0)
            g_string_append(label, " = ");
        g_string_append_printf(label, "%" G_GINT64_MODIFIER "X", bits);
        g_string_append(label, "₁₆");
    }

    ctk_label_set_text(CTK_LABEL(buttons->priv->base_label), label->str);
    g_string_free(label, TRUE);
}


static void
display_changed_cb(MathEquation *equation, GParamSpec *spec, MathButtons *buttons)
{
    update_bit_panel(buttons);
}


static void
base_combobox_changed_cb(CtkWidget *combo, MathButtons *buttons)
{
    gint value;
    CtkTreeModel *model;
    CtkTreeIter iter;

    model = ctk_combo_box_get_model(CTK_COMBO_BOX(combo));
    ctk_combo_box_get_active_iter(CTK_COMBO_BOX(combo), &iter);
    ctk_tree_model_get(model, &iter, 1, &value, -1);

    math_buttons_set_programming_base(buttons, value);
}


static void
base_changed_cb(MathEquation *equation, GParamSpec *spec, MathButtons *buttons)
{
    CtkTreeModel *model;
    CtkTreeIter iter;
    gboolean valid;

    if (buttons->priv->mode != PROGRAMMING)
        return;

    model = ctk_combo_box_get_model(CTK_COMBO_BOX(buttons->priv->base_combo));
    valid = ctk_tree_model_get_iter_first(model, &iter);
    buttons->priv->programming_base = math_equation_get_base(buttons->priv->equation);

    while (valid) {
        gint v;

        ctk_tree_model_get(model, &iter, 1, &v, -1);
        if (v == buttons->priv->programming_base)
            break;
        valid = ctk_tree_model_iter_next(model, &iter);
    }
    if (!valid)
        valid = ctk_tree_model_get_iter_first(model, &iter);<--- Variable 'valid' is assigned a value that is never used.

    ctk_combo_box_set_active_iter(CTK_COMBO_BOX(buttons->priv->base_combo), &iter);
}


static CtkWidget *
load_mode(MathButtons *buttons, ButtonMode mode)
{
    CtkBuilder *builder, **builder_ptr;
    gint i;
    gchar *name;
    const gchar *path;
    static gchar *objects[] = { "button_panel", "character_code_dialog", "currency_dialog",
                                "ctrm_dialog", "ddb_dialog", "fv_dialog", "gpm_dialog",
                                "pmt_dialog", "pv_dialog", "rate_dialog", "sln_dialog",
                                "syd_dialog", "term_dialog", "adjustment1", "adjustment2", NULL };
    CtkWidget *widget, **panel;
    GError *error = NULL;

    switch (mode) {
    default:
    case BASIC:
        builder_ptr = &buttons->priv->basic_ui;
        path = UI_BASIC_RESOURCE_PATH;
        panel = &buttons->priv->bas_panel;
        break;
    case ADVANCED:
        builder_ptr = &buttons->priv->advanced_ui;
        path = UI_ADVANCED_RESOURCE_PATH;
        panel = &buttons->priv->adv_panel;
        break;
    case FINANCIAL:
        builder_ptr = &buttons->priv->financial_ui;
        path = UI_FINANCIAL_RESOURCE_PATH;
        panel = &buttons->priv->fin_panel;
        break;
    case PROGRAMMING:
        builder_ptr = &buttons->priv->programming_ui;
        path = UI_PROGRAMMING_RESOURCE_PATH;
        panel = &buttons->priv->prog_panel;
        break;
    }

    if (*panel)
        goto out;

    builder = *builder_ptr = ctk_builder_new();
    // FIXME: Show dialog if failed to load
    ctk_builder_add_objects_from_resource(builder, path, objects, &error);
    if (error) {
        g_warning("Error loading button UI: %s", error->message);
        g_clear_error(&error);
    }
    *panel = GET_WIDGET(builder, "button_panel");
    ctk_box_pack_end(CTK_BOX(buttons), *panel, TRUE, TRUE, 0);

    /* Configure buttons */
    for (i = 0; button_data[i].widget_name != NULL; i++) {
        GObject *object;
        CtkWidget *button;

        name = g_strdup_printf("calc_%s_button", button_data[i].widget_name);
        object = ctk_builder_get_object(*builder_ptr, name);
        g_free(name);

        if (!object)
            continue;
        button = CTK_WIDGET(object);
        if (button_data[i].data)
            g_object_set_data(object, "calc_text", (gpointer) button_data[i].data);

        if (button_data[i].tooltip)
            ctk_widget_set_tooltip_text(button, _(button_data[i].tooltip));

        atk_object_set_name(ctk_widget_get_accessible(button), button_data[i].widget_name);
    }

    /* Set special button data */
    for (i = 0; i < 16; i++) {
        CtkWidget *button;

        name = g_strdup_printf("calc_%d_button", i);
        button = GET_WIDGET(builder, name);
        if (button) {
            gchar buffer[7];
            gint len;

            g_object_set_data(G_OBJECT(button), "calc_digit", GINT_TO_POINTER(i));
            len = g_unichar_to_utf8(math_equation_get_digit_text(buttons->priv->equation, i), buffer);
            buffer[len] = '\0';
            ctk_button_set_label(CTK_BUTTON(button), buffer);
        }
        g_free(name);
    }
    widget = GET_WIDGET(builder, "calc_numeric_point_button");
    if (widget) {
        MpSerializer *serializer = math_equation_get_serializer(buttons->priv->equation);
        gchar buffer[7];
        gint len;
        len = g_unichar_to_utf8(mp_serializer_get_radix(serializer), buffer);
        buffer[len] = '\0';
        ctk_button_set_label(CTK_BUTTON(widget), buffer);
    }

    widget = GET_WIDGET(builder, "calc_superscript_button");
    if (widget) {
        buttons->priv->superscript_toggles = g_list_append(buttons->priv->superscript_toggles, widget);
        if (math_equation_get_number_mode(buttons->priv->equation) == SUPERSCRIPT)
            ctk_toggle_button_set_active(CTK_TOGGLE_BUTTON(widget), TRUE);
    }
    widget = GET_WIDGET(builder, "calc_subscript_button");
    if (widget) {
        buttons->priv->subscript_toggles = g_list_append(buttons->priv->subscript_toggles, widget);
        if (math_equation_get_number_mode(buttons->priv->equation) == SUBSCRIPT)
            ctk_toggle_button_set_active(CTK_TOGGLE_BUTTON(widget), TRUE);
    }

    /* put the icon name "process-stop" in the buttons
       button1, button3, button5, button7, button9,
       button11, button13, button15, button17, button19
       taken from buttons-financial.ui */
    for (i = 1; i < 20; i++) {
        if (i % 2) {
            widget = GET_WIDGET (builder, g_strdup_printf ("button%d",i));
            if (CTK_IS_BUTTON(widget))
                ctk_button_set_image (CTK_BUTTON (widget),
                                      ctk_image_new_from_icon_name ("process-stop", CTK_ICON_SIZE_BUTTON));
        }
    }

    if (mode == PROGRAMMING) {
        CtkListStore *model;
        CtkTreeIter iter;
        CtkCellRenderer *renderer;

        buttons->priv->base_label = GET_WIDGET(builder, "base_label");
        buttons->priv->character_code_dialog = GET_WIDGET(builder, "character_code_dialog");
        buttons->priv->character_code_entry = GET_WIDGET(builder, "character_code_entry");

        buttons->priv->bit_panel = GET_WIDGET(builder, "bit_table");
        for (i = 0; i < MAXBITS; i++) {
            name = g_strdup_printf("bit_label_%d", i);
            buttons->priv->bit_labels[i] = GET_WIDGET(builder, name);
            g_free(name);
            name = g_strdup_printf("bit_eventbox_%d", i);
            set_int_data(builder, name, "bit_index", i);
        }

        buttons->priv->base_combo = GET_WIDGET(builder, "base_combo");
        model = ctk_list_store_new(2, G_TYPE_STRING, G_TYPE_INT, G_TYPE_INT);
        ctk_combo_box_set_model(CTK_COMBO_BOX(buttons->priv->base_combo), CTK_TREE_MODEL(model));
        ctk_list_store_append(CTK_LIST_STORE(model), &iter);
        ctk_list_store_set(CTK_LIST_STORE(model), &iter, 0,
                           /* Number display mode combo: Binary, e.g. 10011010010₂ */
                           _("Binary"), 1, 2, -1);
        ctk_list_store_append(CTK_LIST_STORE(model), &iter);
        ctk_list_store_set(CTK_LIST_STORE(model), &iter, 0,
                           /* Number display mode combo: Octal, e.g. 2322₈ */
                           _("Octal"), 1, 8, -1);
        ctk_list_store_append(CTK_LIST_STORE(model), &iter);
        ctk_list_store_set(CTK_LIST_STORE(model), &iter, 0,
                           /* Number display mode combo: Decimal, e.g. 1234 */
                           _("Decimal"), 1, 10, -1);
        ctk_list_store_append(CTK_LIST_STORE(model), &iter);
        ctk_list_store_set(CTK_LIST_STORE(model), &iter, 0,
                           /* Number display mode combo: Hexadecimal, e.g. 4D2₁₆ */
                           _("Hexadecimal"), 1, 16, -1);
        renderer = ctk_cell_renderer_text_new();
        ctk_cell_layout_pack_start(CTK_CELL_LAYOUT(buttons->priv->base_combo), renderer, TRUE);
        ctk_cell_layout_add_attribute(CTK_CELL_LAYOUT(buttons->priv->base_combo), renderer, "text", 0);

        g_signal_connect(buttons->priv->base_combo, "changed", G_CALLBACK(base_combobox_changed_cb), buttons);
        g_signal_connect(buttons->priv->equation, "notify::base", G_CALLBACK(base_changed_cb), buttons);
        base_changed_cb(buttons->priv->equation, NULL, buttons);
    }

    /* Setup financial functions */
    if (mode == FINANCIAL) {
        load_finc_dialogs(buttons);

        set_data(builder, "calc_finc_compounding_term_button", "finc_dialog", "ctrm_dialog");
        set_data(builder, "calc_finc_double_declining_depreciation_button", "finc_dialog", "ddb_dialog");
        set_data(builder, "calc_finc_future_value_button", "finc_dialog", "fv_dialog");
        set_data(builder, "calc_finc_gross_profit_margin_button", "finc_dialog", "gpm_dialog");
        set_data(builder, "calc_finc_periodic_payment_button", "finc_dialog", "pmt_dialog");
        set_data(builder, "calc_finc_present_value_button", "finc_dialog", "pv_dialog");
        set_data(builder, "calc_finc_periodic_interest_rate_button", "finc_dialog", "rate_dialog");
        set_data(builder, "calc_finc_straight_line_depreciation_button", "finc_dialog", "sln_dialog");
        set_data(builder, "calc_finc_sum_of_the_years_digits_depreciation_button", "finc_dialog", "syd_dialog");
        set_data(builder, "calc_finc_term_button", "finc_dialog", "term_dialog");
    }

    ctk_builder_connect_signals(builder, buttons);

    display_changed_cb(buttons->priv->equation, NULL, buttons);

out:
    return *panel;
}


static void
converter_changed_cb(MathConverter *converter, MathButtons *buttons)
{
    Unit *from_unit, *to_unit;

    math_converter_get_conversion(converter, &from_unit, &to_unit);
    if (buttons->priv->mode == FINANCIAL) {
        math_equation_set_source_currency(buttons->priv->equation, unit_get_name(from_unit));
        math_equation_set_target_currency(buttons->priv->equation, unit_get_name(to_unit));
    }
    else {
        math_equation_set_source_units(buttons->priv->equation, unit_get_name(from_unit));
        math_equation_set_target_units(buttons->priv->equation, unit_get_name(to_unit));
    }

    g_object_unref(from_unit);
    g_object_unref(to_unit);
}


static void
load_buttons(MathButtons *buttons)
{
    CtkWidget *panel;

    if (!ctk_widget_get_visible(CTK_WIDGET(buttons)))
        return;

    if (!buttons->priv->converter) {
        buttons->priv->converter = math_converter_new(buttons->priv->equation);
        g_signal_connect(buttons->priv->converter, "changed", G_CALLBACK(converter_changed_cb), buttons);
        ctk_box_pack_start(CTK_BOX(buttons), CTK_WIDGET(buttons->priv->converter), FALSE, TRUE, 0);
    }

    panel = load_mode(buttons, buttons->priv->mode);
    if (buttons->priv->active_panel == panel)
        return;

    /* Hide old buttons */
    if (buttons->priv->active_panel)
        ctk_widget_hide(buttons->priv->active_panel);

    /* Load and display new buttons */
    buttons->priv->active_panel = panel;
    if (panel)
        ctk_widget_show(panel);
}


void
math_buttons_set_mode(MathButtons *buttons, ButtonMode mode)
{
    g_return_if_fail(buttons != NULL);

    if (buttons->priv->mode == mode)
        return;

    buttons->priv->mode = mode;

    if (mode == PROGRAMMING)
        math_equation_set_base(buttons->priv->equation, buttons->priv->programming_base);
    else
        math_equation_set_base(buttons->priv->equation, 10);

    load_buttons(buttons);

    ctk_widget_set_visible(CTK_WIDGET(buttons->priv->converter), mode == ADVANCED || mode == FINANCIAL);
    if (mode == ADVANCED) {
        math_converter_set_category(buttons->priv->converter, NULL);
        math_converter_set_conversion(buttons->priv->converter,
                                      math_equation_get_source_units(buttons->priv->equation),
                                      math_equation_get_target_units(buttons->priv->equation));
    }
    else if (mode == FINANCIAL) {
        math_converter_set_category(buttons->priv->converter, "currency");
        math_converter_set_conversion(buttons->priv->converter,
                                      math_equation_get_source_currency(buttons->priv->equation),
                                      math_equation_get_target_currency(buttons->priv->equation));
    }

    g_object_notify(G_OBJECT(buttons), "mode");
}


ButtonMode
math_buttons_get_mode(MathButtons *buttons)
{
    return buttons->priv->mode;
}


void
math_buttons_set_programming_base(MathButtons *buttons, gint base)
{
    g_return_if_fail(buttons != NULL);

    if (base == buttons->priv->programming_base)
        return;

    buttons->priv->programming_base = base;

    g_settings_set_int(g_settings_var, "base", math_buttons_get_programming_base(buttons));

    if (buttons->priv->mode == PROGRAMMING)
        math_equation_set_base(buttons->priv->equation, base);
}


gint
math_buttons_get_programming_base(MathButtons *buttons)
{
    g_return_val_if_fail(buttons != NULL, 10);
    return buttons->priv->programming_base;
}


void exponent_cb(CtkWidget *widget, MathButtons *buttons);
G_MODULE_EXPORT
void
exponent_cb(CtkWidget *widget, MathButtons *buttons)
{
    math_equation_insert_exponent(buttons->priv->equation);
}


void subtract_cb(CtkWidget *widget, MathButtons *buttons);
G_MODULE_EXPORT
void
subtract_cb(CtkWidget *widget, MathButtons *buttons)
{
    math_equation_insert_subtract(buttons->priv->equation);
}


void button_cb(CtkWidget *widget, MathButtons *buttons);
G_MODULE_EXPORT
void
button_cb(CtkWidget *widget, MathButtons *buttons)
{
    math_equation_insert(buttons->priv->equation, g_object_get_data(G_OBJECT(widget), "calc_text"));
}


void solve_cb(CtkWidget *widget, MathButtons *buttons);
G_MODULE_EXPORT
void
solve_cb(CtkWidget *widget, MathButtons *buttons)
{
    math_equation_solve(buttons->priv->equation);
}


void clear_cb(CtkWidget *widget, MathButtons *buttons);
G_MODULE_EXPORT
void
clear_cb(CtkWidget *widget, MathButtons *buttons)
{
    math_equation_clear(buttons->priv->equation);
}


void delete_cb(CtkWidget *widget, MathButtons *buttons);
G_MODULE_EXPORT
void
delete_cb(CtkWidget *widget, MathButtons *buttons)
{
    math_equation_delete(buttons->priv->equation);
}


void undo_cb(CtkWidget *widget, MathButtons *buttons);
G_MODULE_EXPORT
void
undo_cb(CtkWidget *widget, MathButtons *buttons)
{
    math_equation_undo(buttons->priv->equation);
}


static void
shift_cb(CtkWidget *widget, MathButtons *buttons)
{
    math_equation_shift(buttons->priv->equation, GPOINTER_TO_INT(g_object_get_data(G_OBJECT(widget), "shiftcount")));
}

static void
popup_button_menu(CtkWidget *widget, CtkMenu *menu)
{
    ctk_menu_popup_at_widget (menu,
                              widget,
                              CDK_GRAVITY_SOUTH_WEST,
                              CDK_GRAVITY_NORTH_WEST,
                              NULL);
}


void memory_cb(CtkWidget *widget, MathButtons *buttons);
G_MODULE_EXPORT
void
memory_cb(CtkWidget *widget, MathButtons *buttons)
{
    MathVariablePopup *popup;
    CtkAllocation allocation;
    gint x, y;

    popup = math_variable_popup_new(buttons->priv->equation);
    ctk_window_set_transient_for(CTK_WINDOW(popup), CTK_WINDOW(ctk_widget_get_toplevel(widget)));

    ctk_widget_get_allocation(widget, &allocation);
    cdk_window_get_root_coords(ctk_widget_get_window(widget), allocation.x, allocation.y, &x, &y);
    ctk_window_move(CTK_WINDOW(popup), x, y);
    ctk_widget_show(CTK_WIDGET(popup));
}


void shift_left_cb(CtkWidget *widget, MathButtons *buttons);
G_MODULE_EXPORT
void
shift_left_cb(CtkWidget *widget, MathButtons *buttons)
{
    if (!buttons->priv->shift_left_menu) {
        gint i;
        CtkWidget *menu;

        menu = buttons->priv->shift_left_menu = ctk_menu_new();
        ctk_menu_set_reserve_toggle_size(CTK_MENU(menu), FALSE);

        for (i = 1; i < 16; i++) {
            CtkWidget *item, *label;
            gchar *format, *text;

            if (i < 10) {
                /* Left Shift Popup: Menu item to shift left by n places (n < 10) */
                format = ngettext("_%d place", "_%d places", i);
            }
            else {
                /* Left Shift Popup: Menu item to shift left by n places (n >= 10) */
                format = ngettext("%d place", "%d places", i);
            }
            text = g_strdup_printf(format, i);
            label = ctk_label_new_with_mnemonic(text);

            item = ctk_menu_item_new();
            g_object_set_data(G_OBJECT(item), "shiftcount", GINT_TO_POINTER(i));
            ctk_container_add(CTK_CONTAINER(item), label);
            ctk_menu_shell_append(CTK_MENU_SHELL(menu), item);
            g_signal_connect(item, "activate", G_CALLBACK(shift_cb), buttons);

            ctk_widget_show(label);
            ctk_widget_show(item);
            g_free(text);
        }
    }

    popup_button_menu(widget, CTK_MENU(buttons->priv->shift_left_menu));
}


void shift_right_cb(CtkWidget *widget, MathButtons *buttons);
G_MODULE_EXPORT
void
shift_right_cb(CtkWidget *widget, MathButtons *buttons)
{
    if (!buttons->priv->shift_right_menu) {
        gint i;
        CtkWidget *menu;

        menu = buttons->priv->shift_right_menu = ctk_menu_new();
        ctk_menu_set_reserve_toggle_size(CTK_MENU(menu), FALSE);

        for (i = 1; i < 16; i++) {
            CtkWidget *item, *label;
            gchar *format, *text;

            if (i < 10) {
                /* Right Shift Popup: Menu item to shift right by n places (n < 10) */
                format = ngettext("_%d place", "_%d places", i);
            }
            else {
                /* Right Shift Popup: Menu item to shift right by n places (n >= 10) */
                format = ngettext("%d place", "%d places", i);
            }
            text = g_strdup_printf(format, i);
            label = ctk_label_new_with_mnemonic(text);

            item = ctk_menu_item_new();
            g_object_set_data(G_OBJECT(item), "shiftcount", GINT_TO_POINTER(-i));
            ctk_container_add(CTK_CONTAINER(item), label);
            ctk_menu_shell_append(CTK_MENU_SHELL(menu), item);
            g_signal_connect(item, "activate", G_CALLBACK(shift_cb), buttons);

            ctk_widget_show(label);
            ctk_widget_show(item);
            g_free(text);
        }
    }

    popup_button_menu(widget, CTK_MENU(buttons->priv->shift_right_menu));
}


static void
insert_function_cb(CtkWidget *widget, MathButtons *buttons)
{
    math_equation_insert(buttons->priv->equation, g_object_get_data(G_OBJECT(widget), "function"));
}


void function_cb(CtkWidget *widget, MathButtons *buttons);
G_MODULE_EXPORT
void
function_cb(CtkWidget *widget, MathButtons *buttons)
{
    if (!buttons->priv->function_menu) {
        gint i;
        CtkWidget *menu;
        struct
        {
            gchar *name, *function;
        } functions[] =
        {
            { /* Tooltip for the integer component button */
              N_("Integer Component"), "int " },
            { /* Tooltip for the fractional component button */
              N_("Fractional Component"), "frac " },
            { /* Tooltip for the round button */
              N_("Round"), "round " },
            { /* Tooltip for the floor button */
              N_("Floor"), "floor " },
            { /* Tooltip for the ceiling button */
              N_("Ceiling"), "ceil " },
            { /* Tooltip for the ceiling button */
              N_("Sign"), "sgn " },
            { NULL, NULL }
        };

        menu = buttons->priv->function_menu = ctk_menu_new();
        ctk_menu_set_reserve_toggle_size(CTK_MENU(menu), FALSE);

        for (i = 0; functions[i].name != NULL; i++) {
            CtkWidget *item;

            item = ctk_menu_item_new_with_label(_(functions[i].name));
            g_object_set_data(G_OBJECT(item), "function", g_strdup(functions[i].function));
            ctk_menu_shell_append(CTK_MENU_SHELL(menu), item);
            g_signal_connect(item, "activate", G_CALLBACK(insert_function_cb), buttons);
            ctk_widget_show(item);
        }
    }

    popup_button_menu(widget, CTK_MENU(buttons->priv->function_menu));
}

static void
insert_const_cb(CtkWidget *widget, MathButtons *buttons)
{
    math_equation_insert(buttons->priv->equation, g_object_get_data(G_OBJECT(widget), "const"));
}


void const_cb(CtkWidget *widget, MathButtons *buttons);
G_MODULE_EXPORT
void
const_cb(CtkWidget *widget, MathButtons *buttons)
{
    if (!buttons->priv->const_menu) {
        gint i;
        CtkWidget *menu;
        struct
        {
            gchar *name, *constant, *tooltip;
        } constants[] =
        {
            { /* Tooltip for the c₀ component button */
              N_("Velocity of Light"), "c₀", N_("299,792,458 m/s") },
            { /* Tooltip for the μ₀ component button */
              N_("Magnetic constant"), "μ₀", N_("1.2566370614×10⁻⁶ N/A²") },
            { /* Tooltip for the ε₀ button */
              N_("Electric constant"), "ε₀", N_("8.85418782×10⁻¹² s⁴A²/m³kg") },
            { /* Tooltip for the G button */
              N_("Newtonian constant of gravitation"), "G",  N_("6.67408×10⁻¹¹ m³/(s²kg)") },
            { /* Tooltip for the h button */
              N_("Planck constant"), "h", N_("6.62607004×10⁻³⁴ m²kg/s") },
            { /* Tooltip for the e button */
              N_("Elementary charge"), "e", N_("1.6021766208(98)×10⁻¹⁹ C") },
            { /* Tooltip for the mₑ button */
              N_("Electron mass"), "mₑ", N_("9.10938356×10⁻³¹ kg") },
            { /* Tooltip for the mₚ button */
              N_("Proton mass"), "mₚ", N_("1.672621898(21)×10⁻²⁷ kg") },
            { /* Tooltip for the Nₐ button */
              N_("Avogadro constant"), "Nₐ", N_("6.02214086×10²³ mol⁻¹") },
            { NULL, NULL, NULL }
        };

        menu = buttons->priv->const_menu = ctk_menu_new();
        ctk_menu_set_reserve_toggle_size(CTK_MENU(menu), FALSE);

        for (i = 0; constants[i].name != NULL; i++) {
            CtkWidget *item;

            item = ctk_menu_item_new_with_label(_(constants[i].name));
            ctk_widget_set_tooltip_text(item, _(constants[i].tooltip));
            g_object_set_data(G_OBJECT(item), "const", g_strdup(constants[i].constant));
            ctk_menu_shell_append(CTK_MENU_SHELL(menu), item);
            g_signal_connect(item, "activate", G_CALLBACK(insert_const_cb), buttons);
            ctk_widget_show(item);
        }
    }

    popup_button_menu(widget, CTK_MENU(buttons->priv->const_menu));
}

void factorize_cb(CtkWidget *widget, MathButtons *buttons);
G_MODULE_EXPORT
void
factorize_cb(CtkWidget *widget, MathButtons *buttons)
{
    math_equation_factorize(buttons->priv->equation);
}


void digit_cb(CtkWidget *widget, MathButtons *buttons);
G_MODULE_EXPORT
void
digit_cb(CtkWidget *widget, MathButtons *buttons)
{
    math_equation_insert_digit(buttons->priv->equation, GPOINTER_TO_INT(g_object_get_data(G_OBJECT(widget), "calc_digit")));
}


void numeric_point_cb(CtkWidget *widget, MathButtons *buttons);
G_MODULE_EXPORT
void
numeric_point_cb(CtkWidget *widget, MathButtons *buttons)
{
    math_equation_insert_numeric_point(buttons->priv->equation);
}



void finc_cb(CtkWidget *widget, MathButtons *buttons);
G_MODULE_EXPORT
void
finc_cb(CtkWidget *widget, MathButtons *buttons)
{
    gchar *name;

    name = g_object_get_data(G_OBJECT(widget), "finc_dialog");
    ctk_dialog_run(CTK_DIALOG(GET_WIDGET(buttons->priv->financial_ui, name)));
    ctk_widget_hide(CTK_WIDGET(GET_WIDGET(buttons->priv->financial_ui, name)));
}


void insert_character_code_cb(CtkWidget *widget, MathButtons *buttons);
G_MODULE_EXPORT
void
insert_character_code_cb(CtkWidget *widget, MathButtons *buttons)
{
    ctk_window_present(CTK_WINDOW(buttons->priv->character_code_dialog));
}


void finc_activate_cb(CtkWidget *widget, MathButtons *buttons);
G_MODULE_EXPORT
void
finc_activate_cb(CtkWidget *widget, MathButtons *buttons)
{
    gint dialog, field;

    dialog = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(widget), "finc_dialog"));
    field = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(widget), "finc_field"));

    if (finc_dialog_fields[dialog][field+1] == NULL) {
        CtkWidget *dialog_widget;
        dialog_widget = ctk_widget_get_toplevel(widget);
        if (ctk_widget_is_toplevel(dialog_widget)) {
            ctk_dialog_response(CTK_DIALOG(dialog_widget),
                                CTK_RESPONSE_OK);
            return;
        }
    }
    else {
        CtkWidget *next_widget;
        next_widget = GET_WIDGET(buttons->priv->financial_ui, finc_dialog_fields[dialog][field+1]);
        ctk_widget_grab_focus(next_widget);
    }
}


void finc_response_cb(CtkWidget *widget, gint response_id, MathButtons *buttons);
G_MODULE_EXPORT
void
finc_response_cb(CtkWidget *widget, gint response_id, MathButtons *buttons)
{
    int dialog;
    int i;
    MPNumber arg[4];
    CtkWidget *entry;

    if (response_id != CTK_RESPONSE_OK)
        return;

    dialog = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(widget), "finc_dialog"));

    for (i = 0; i < 4; i++) {
        if (finc_dialog_fields[dialog][i] == NULL) {
            continue;
        }
        entry = GET_WIDGET(buttons->priv->financial_ui, finc_dialog_fields[dialog][i]);
        mp_set_from_string(ctk_entry_get_text(CTK_ENTRY(entry)), 10, &arg[i]);
        ctk_entry_set_text(CTK_ENTRY(entry), "0");
    }
    ctk_widget_grab_focus(GET_WIDGET(buttons->priv->financial_ui, finc_dialog_fields[dialog][0]));

    do_finc_expression(buttons->priv->equation, dialog, &arg[0], &arg[1], &arg[2], &arg[3]);
}


void character_code_dialog_response_cb(CtkWidget *dialog, gint response_id, MathButtons *buttons);
G_MODULE_EXPORT
void
character_code_dialog_response_cb(CtkWidget *dialog, gint response_id, MathButtons *buttons)
{
    const gchar *text;

    text = ctk_entry_get_text(CTK_ENTRY(buttons->priv->character_code_entry));

    if (response_id == CTK_RESPONSE_OK) {
        MPNumber x;
        int i = 0;

        mp_set_from_integer(0, &x);
        while (TRUE) {
            mp_add_integer(&x, text[i], &x);
            if (text[i+1]) {
                 mp_shift(&x, 8, &x);
                 i++;
            }
            else
                break;
        }

        math_equation_insert_number(buttons->priv->equation, &x);
    }

    ctk_widget_hide(dialog);
}


void character_code_dialog_activate_cb(CtkWidget *entry, MathButtons *buttons);
G_MODULE_EXPORT
void
character_code_dialog_activate_cb(CtkWidget *entry, MathButtons *buttons)
{
    character_code_dialog_response_cb(buttons->priv->character_code_dialog, CTK_RESPONSE_OK, buttons);
}


gboolean character_code_dialog_delete_cb(CtkWidget *dialog, CdkEvent *event, MathButtons *buttons);
G_MODULE_EXPORT
gboolean
character_code_dialog_delete_cb(CtkWidget *dialog, CdkEvent *event, MathButtons *buttons)
{
    character_code_dialog_response_cb(dialog, CTK_RESPONSE_CANCEL, buttons);
    return TRUE;
}


gboolean bit_toggle_cb(CtkWidget *event_box, CdkEventButton *event, MathButtons *buttons);
G_MODULE_EXPORT
gboolean
bit_toggle_cb(CtkWidget *event_box, CdkEventButton *event, MathButtons *buttons)
{
    math_equation_toggle_bit(buttons->priv->equation, GPOINTER_TO_INT(g_object_get_data(G_OBJECT(event_box), "bit_index")));
    return TRUE;
}


static void
remove_trailing_spaces(MathButtons *buttons)
{
    CtkTextMark *insert_mark;
    CtkTextIter start, end;
    insert_mark = ctk_text_buffer_get_insert (CTK_TEXT_BUFFER(buttons->priv->equation));
    ctk_text_buffer_get_iter_at_mark(CTK_TEXT_BUFFER(buttons->priv->equation), &end, insert_mark);
    start = end;
    while (ctk_text_iter_backward_char(&start)) {
        if (!g_unichar_isspace(ctk_text_iter_get_char(&start)))
            break;
        ctk_text_buffer_delete(CTK_TEXT_BUFFER(buttons->priv->equation), &start, &end);
    }
}


void set_superscript_cb(CtkWidget *widget, MathButtons *buttons);
G_MODULE_EXPORT
void
set_superscript_cb(CtkWidget *widget, MathButtons *buttons)
{
    if (ctk_toggle_button_get_active(CTK_TOGGLE_BUTTON(widget))) {
        math_equation_set_number_mode(buttons->priv->equation, SUPERSCRIPT);
        if (!ctk_text_buffer_get_has_selection(CTK_TEXT_BUFFER(buttons->priv->equation))) {
            remove_trailing_spaces(buttons);
        }
    }
    else if (math_equation_get_number_mode(buttons->priv->equation) == SUPERSCRIPT)
        math_equation_set_number_mode(buttons->priv->equation, NORMAL);
}


void set_subscript_cb(CtkWidget *widget, MathButtons *buttons);
G_MODULE_EXPORT
void
set_subscript_cb(CtkWidget *widget, MathButtons *buttons)
{
    if (ctk_toggle_button_get_active(CTK_TOGGLE_BUTTON(widget))) {
        math_equation_set_number_mode(buttons->priv->equation, SUBSCRIPT);
        if (!ctk_text_buffer_get_has_selection(CTK_TEXT_BUFFER(buttons->priv->equation))) {
            remove_trailing_spaces(buttons);
        }
    }
    else if (math_equation_get_number_mode(buttons->priv->equation) == SUBSCRIPT)
        math_equation_set_number_mode(buttons->priv->equation, NORMAL);
}


static void
number_mode_changed_cb(MathEquation *equation, GParamSpec *spec, MathButtons *buttons)
{
    GList *i;
    NumberMode mode;

    mode = math_equation_get_number_mode(equation);

    for (i = buttons->priv->superscript_toggles; i; i = i->next) {
        CtkWidget *widget = i->data;
        ctk_toggle_button_set_active(CTK_TOGGLE_BUTTON(widget), mode == SUPERSCRIPT);
    }
    for (i = buttons->priv->subscript_toggles; i; i = i->next) {
        CtkWidget *widget = i->data;
        ctk_toggle_button_set_active(CTK_TOGGLE_BUTTON(widget), mode == SUBSCRIPT);
    }
}


static void
math_buttons_set_property(GObject      *object,
                          guint         prop_id,
                          const GValue *value,
                          GParamSpec   *pspec)
{
    MathButtons *self;

    self = MATH_BUTTONS(object);

    switch (prop_id) {
    case PROP_EQUATION:
        self->priv->equation = g_value_get_object(value);
        math_buttons_set_mode(self, self->priv->mode);
        g_signal_connect(self->priv->equation, "notify::display", G_CALLBACK(display_changed_cb), self);
        g_signal_connect(self->priv->equation, "notify::number-mode", G_CALLBACK(number_mode_changed_cb), self);
        g_signal_connect(self->priv->equation, "notify::angle-units", G_CALLBACK(display_changed_cb), self);
        g_signal_connect(self->priv->equation, "notify::number-format", G_CALLBACK(display_changed_cb), self);
        number_mode_changed_cb(self->priv->equation, NULL, self);
        display_changed_cb(self->priv->equation, NULL, self);
        break;
    case PROP_MODE:
        math_buttons_set_mode(self, g_value_get_int(value));
        break;
    case PROP_PROGRAMMING_BASE:
        math_buttons_set_programming_base(self, g_value_get_int(value));
        break;
    default:
        G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec);
        break;
    }
}


static void
math_buttons_get_property(GObject    *object,
                          guint       prop_id,
                          GValue     *value,
                          GParamSpec *pspec)
{
    MathButtons *self;

    self = MATH_BUTTONS(object);

    switch (prop_id) {
    case PROP_EQUATION:
        g_value_set_object(value, self->priv->equation);
        break;
    case PROP_MODE:
        g_value_set_int(value, self->priv->mode);
        break;
    case PROP_PROGRAMMING_BASE:
        g_value_set_int(value, math_buttons_get_programming_base(self));
        break;
    default:
        G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec);
        break;
    }
}


static void
math_buttons_class_init(MathButtonsClass *klass)
{
    static GEnumValue button_mode_values[] =
    {
      {BASIC,       "basic",       "basic"},
      {ADVANCED,    "advanced",    "advanced"},
      {FINANCIAL,   "financial",   "financial"},
      {PROGRAMMING, "programming", "programming"},
      {0, NULL, NULL}
    };
    GObjectClass *object_class = G_OBJECT_CLASS(klass);

    object_class->get_property = math_buttons_get_property;
    object_class->set_property = math_buttons_set_property;

    button_mode_type = g_enum_register_static("ButtonMode", button_mode_values);

    g_object_class_install_property(object_class,
                                    PROP_EQUATION,
                                    g_param_spec_object("equation",
                                                        "equation",
                                                        "Equation being controlled",
                                                        math_equation_get_type(),
                                                        G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY));
    g_object_class_install_property(object_class,
                                    PROP_MODE,
                                    g_param_spec_enum("mode",
                                                      "mode",
                                                      "Button mode",
                                                      button_mode_type,
                                                      BASIC,
                                                      G_PARAM_READWRITE));
    g_object_class_install_property(object_class,
                                    PROP_PROGRAMMING_BASE,
                                    g_param_spec_int("programming-base",
                                                     "programming-base",
                                                     "Base to use in programming mode",
                                                     2, 16, 10,
                                                     G_PARAM_READWRITE));
}


static void
math_buttons_init(MathButtons *buttons)
{
    buttons->priv = math_buttons_get_instance_private (buttons);
    ctk_box_set_spacing(CTK_BOX(buttons), 6);
    ctk_orientable_set_orientation (CTK_ORIENTABLE (buttons),
                                    CTK_ORIENTATION_VERTICAL);
    buttons->priv->programming_base = 10;
    g_signal_connect(G_OBJECT(buttons), "show", G_CALLBACK(load_buttons), NULL);
}