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
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
extern crate objc;
extern crate objc_foundation;
extern crate objc_id;

use super::interface::*;

use std::fmt;
use std::rc::Rc;
use std::cell::Cell;
use std::sync::{Once, ONCE_INIT};
use std::collections::BTreeMap;

use objc::Message;
use objc::declare::ClassDecl;
use objc::runtime::{Class, Object, Sel};
use self::objc_foundation::{INSObject, NSObject};
use self::objc_id::Id;
use self::objc_id::Shared;

use super::wrapper::RRTouchBar;
use super::wrapper::RRCustomTouchBarItem;
use super::wrapper::RRScrubber;
use super::wrapper::RRPopoverTouchBarItem;
use super::wrapper::RRSliderTouchBarItem;

const IDENT_PREFIX: &'static str = "com.trevorbentley.";

/// Controller for creating and using Touch Bar UIs
///
/// The `Touchbar` type provides the interface between Rust and the Apple Touch
/// Bar system.  It handles communication with the Touch Bar service, delegation
/// of UI and touch events, and memory management of Objective-C objects.  All
/// creation and modification of Touch Bar UIs is done through it.
///
/// This implementation uses **private** Apple APIs to create an always-available
/// menu to the Control Strip region, which can be accessed regardless of which
/// application is in focus.  Apps using it are **not permitted in the App Store**.
///
/// There should typically be **one** `Touchbar` type alocated per application.
/// Rubrail does not enforce the singleton pattern automatically, so it is up to
/// the application to guarantee that there is only one.  Theoretically, one
/// application _can_ have multiple disjoint entries in the Touch Bar by creating
/// more than one `Touchbar`, and Rubrail allows this though it is not tested.
///
/// See the documentation of the [`TTouchbar`](trait.TTouchbar.html) trait for usage.
///
/// # Example
///
/// ```
/// extern crate rubrail;
/// use rubrail::TTouchbar;
/// fn main() {
///   let controller = rubrail::Touchbar::alloc("test");
/// }
/// ```
pub type Touchbar = Box<RustTouchbarDelegateWrapper>;


/////
///// Simulate 'cocoa' crate
/////
///// Originally used 'cocoa' crate for some AppKit stuff.  To minimize
///// dependencies, the things below are either copied from the cocoa
///// crate, or minimally reimplemented
/////
#[allow(non_upper_case_globals)]
const nil: *mut Object = 0 as *mut Object;
const YES: i8 = 1i8;
const NO: i8 = 0i8;


#[allow(non_snake_case)]
unsafe fn NSApp() -> *mut Object {
    let cls = Class::get("NSApplication").unwrap();
    msg_send![cls, sharedApplication]
}

//             let res = NSString::alloc(nil).init_str(name);
struct NSString(*mut Object);
impl NSString {
    unsafe fn alloc(_: *mut Object) -> NSString {
        let cls = Class::get("NSString").unwrap();
        NSString(msg_send![cls, alloc])
    }
    unsafe fn init_str(self, s: &str) -> *mut Object {
        msg_send![self.0, initWithBytes: s.as_ptr() length: s.len() encoding: 4]
    }
}

// let objc_image = NSImage::alloc(nil).initWithContentsOfFile_(filename);
struct NSImage(*mut Object);
impl NSImage {
    unsafe fn alloc(_: *mut Object) -> NSImage {
        let cls = Class::get("NSImage").unwrap();
        NSImage(msg_send![cls, alloc])
    }
    #[allow(non_snake_case)]
    unsafe fn initWithContentsOfFile_(self, filename: *mut Object) -> *mut Object {
        msg_send![self.0, initWithContentsOfFile: filename]
    }
}


#[repr(C)]
#[derive(Copy, Clone)]
pub struct NSPoint {
    pub x: f64,
    pub y: f64,
}

impl NSPoint {
    #[inline]
    pub fn new(x: f64, y: f64) -> NSPoint {
        NSPoint {
            x: x,
            y: y,
        }
    }
}
unsafe impl objc::Encode for NSPoint {
    fn encode() -> objc::Encoding {
        let encoding = format!("{{CGPoint={}{}}}",
                               f64::encode().as_str(),
                               f64::encode().as_str());
        unsafe { objc::Encoding::from_str(&encoding) }
    }
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct NSSize {
    pub width: f64,
    pub height: f64,
}

impl NSSize {
    #[inline]
    pub fn new(width: f64, height: f64) -> NSSize {
        NSSize {
            width: width,
            height: height,
        }
    }
}
unsafe impl objc::Encode for NSSize {
    fn encode() -> objc::Encoding {
        let encoding = format!("{{CGSize={}{}}}",
                               f64::encode().as_str(),
                               f64::encode().as_str());
        unsafe { objc::Encoding::from_str(&encoding) }
    }
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct NSRect {
    pub origin: NSPoint,
    pub size: NSSize,
}
impl NSRect {
    pub fn new(origin: NSPoint, size: NSSize) -> NSRect {
        NSRect {
            origin: origin,
            size: size
        }
    }
}

/////
///// End simulate 'cocoa' crate
/////


pub type Ident = u64;

#[link(name = "DFRFoundation", kind = "framework")]
extern {
    pub fn DFRSystemModalShowsCloseBoxWhenFrontMost(x: i8);
    pub fn DFRElementSetControlStripPresenceForIdentifier(n: *mut Object, x: i8);
}

#[link(name = "AppKit", kind = "framework")]
extern {
    pub static NSAppKitVersionNumber: f64;
}

#[derive(PartialEq)]
/// Represents the version number of the current AppKit
///
/// MacOS 10.12, for example, would be:
///   `AppKitVersion {major: 10, minor: 12 }`
///
/// Instances of this struct can be compared with comparison operators.
pub struct AppKitVersion {
    major: u8,
    minor: u8,
}

impl AppKitVersion {
    pub fn from_f64(v: f64) -> AppKitVersion {
        // From NSApplication.h
        let (maj,min) = match v.trunc() as u64 {
            1504 => (10,12), // Sierra
            1561 => (10,13), // High Sierra
            1671 => (10,14), // Mojave
            _ => (0,0),
        };
        AppKitVersion {
            major: maj,
            minor: min
        }
    }
    pub fn from_tuple(maj: u8, min: u8) -> AppKitVersion {
        AppKitVersion { major: maj, minor: min }
    }
}
impl PartialOrd for AppKitVersion {
    fn partial_cmp(&self, other: &AppKitVersion) -> Option<std::cmp::Ordering> {
        match self.major.partial_cmp(&other.major) {
            None => None,
            Some(std::cmp::Ordering::Equal) => {
                self.minor.partial_cmp(&other.minor)
            },
            rest => rest,
        }
        //Some(self.cmp(other))
    }
}

pub mod util {
    //! Utility functions for working with the Apple/TouchBar environment
    //!
    //! Contains convenience functions that help with some common actions in
    //! Mac environments.

    extern crate libc;
    use super::ItemId;
    use std::ptr;
    use std::ffi::CStr;
    use objc::runtime::Object;
    use objc::runtime::Class;
    use super::NSString;
    use super::nil;
    use super::AppKitVersion;

    #[allow(dead_code)]
    /// Print an NSString object to the global logger
    pub fn print_nsstring(str: *mut Object) {
        unsafe {
            let cstr: *const libc::c_char = msg_send![str, UTF8String];
            let rstr = CStr::from_ptr(cstr).to_string_lossy().into_owned();
            info!("{}", rstr);
        }
    }

    /// Convert an NSString object into a Rust String
    pub fn nsstring_decode(str: *mut Object) -> String {
        unsafe {
            let cstr: *const libc::c_char = msg_send![str, UTF8String];
            let rstr = CStr::from_ptr(cstr).to_string_lossy().into_owned();
            rstr
        }
    }

    /// Locate a resource in the executing Mac App bundle
    ///
    /// If the program is executing from an App bundle (.app), which it must be
    /// to use Rubrail correctly, this looks for a resource by name and
    /// extension in the bundled Resources directory.
    pub fn bundled_resource_path(name: &str, extension: &str) -> Option<String> {
        unsafe {
            let cls = Class::get("NSBundle").unwrap();
            let bundle: *mut Object = msg_send![cls, mainBundle];
            let res = NSString::alloc(nil).init_str(name);
            let ext = NSString::alloc(nil).init_str(extension);
            let ini: *mut Object = msg_send![bundle, pathForResource:res ofType:ext];
            let _:() = msg_send![res, release];
            let _:() = msg_send![ext, release];
            let cstr: *const libc::c_char = msg_send![ini, UTF8String];
            if cstr != ptr::null() {
                let rstr = CStr::from_ptr(cstr).to_string_lossy().into_owned();
                return Some(rstr);
            }
            None
        }
    }

    /// Sets the backgroundColor attribute on an item's view.
    ///
    /// This is an **unsafe** helper function to set the backgroundColor
    /// attribute on the view of an item.  It does *not* verify that the item
    /// actually has a view, nor that the view supports backgroundColor, hence
    /// **unsafe**.
    ///
    /// Known compatible items: labels
    ///
    /// # Arguments
    ///
    /// * `item` - The `ItemId` to color
    /// * `r` - Red value (0.0 - 1.0)
    /// * `g` - Green value (0.0 - 1.0)
    /// * `b` - Blue value (0.0 - 1.0)
    /// * `alpha` - Alpha value (0.0 - 1.0)
    pub unsafe fn set_bg_color(item: &ItemId, r: f64, g: f64, b: f64, alpha: f64) {
        let item = *item as *mut Object;
        let view: *mut Object = msg_send![item, view];
        let cls = Class::get("NSColor").unwrap();
        let color: *mut Object = msg_send![
            cls, colorWithRed: r green: g blue: b alpha: alpha];
        let _:() = msg_send![view, setBackgroundColor: color];
    }

    /// Sets the textColor attribute on an item's view.
    ///
    /// This is an **unsafe** helper function to set the textColor attribute on
    /// the view of an item.  It does *not* verify that the item actually has a
    /// view, nor that the view supports textColor, hence **unsafe**.
    ///
    /// Known compatible items: labels
    ///
    /// # Arguments
    ///
    /// * `item` - The `ItemId` to color
    /// * `r` - Red value (0.0 - 1.0)
    /// * `g` - Green value (0.0 - 1.0)
    /// * `b` - Blue value (0.0 - 1.0)
    /// * `alpha` - Alpha value (0.0 - 1.0)
    pub unsafe fn set_text_color(item: &ItemId, r: f64, g: f64, b: f64, alpha: f64) {
        let item = *item as *mut Object;
        let view: *mut Object = msg_send![item, view];
        let cls = Class::get("NSColor").unwrap();
        let color: *mut Object = msg_send![
            cls, colorWithRed: r green: g blue: b alpha: alpha];
        let _:() = msg_send![view, setTextColor: color];
    }

    /// Get version of linked Apple AppKit framework
    pub fn get_appkit_version() -> AppKitVersion {
        unsafe { AppKitVersion::from_f64(super::NSAppKitVersionNumber) }
    }
}

macro_rules! image_template {
    ( $var:ident, $($template:ident),* ) => {
        match $var {
            $(
                ImageTemplate::$template => format!("NSTouchBar{}", stringify!($template)),
            )*
        }
    }
}

impl ImageTemplate {
    fn objc(template: ImageTemplate) -> *mut Object {
        unsafe {
            let s = image_template!(
                template,
                AddDetailTemplate,
                AddTemplate,
                AlarmTemplate,
                AudioInputMuteTemplate,
                AudioInputTemplate,
                AudioOutputMuteTemplate,
                AudioOutputVolumeHighTemplate,
                AudioOutputVolumeLowTemplate,
                AudioOutputVolumeMediumTemplate,
                AudioOutputVolumeOffTemplate,
                BookmarksTemplate,
                ColorPickerFill,
                ColorPickerFont,
                ColorPickerStroke,
                CommunicationAudioTemplate,
                CommunicationVideoTemplate,
                ComposeTemplate,
                DeleteTemplate,
                DownloadTemplate,
                EnterFullScreenTemplate,
                ExitFullScreenTemplate,
                FastForwardTemplate,
                FolderCopyToTemplate,
                FolderMoveToTemplate,
                FolderTemplate,
                GetInfoTemplate,
                GoBackTemplate,
                GoDownTemplate,
                GoForwardTemplate,
                GoUpTemplate,
                HistoryTemplate,
                IconViewTemplate,
                ListViewTemplate,
                MailTemplate,
                NewFolderTemplate,
                NewMessageTemplate,
                OpenInBrowserTemplate,
                PauseTemplate,
                PlayheadTemplate,
                PlayPauseTemplate,
                PlayTemplate,
                QuickLookTemplate,
                RecordStartTemplate,
                RecordStopTemplate,
                RefreshTemplate,
                RewindTemplate,
                RotateLeftTemplate,
                RotateRightTemplate,
                SearchTemplate,
                ShareTemplate,
                SidebarTemplate,
                SkipAhead15SecondsTemplate,
                SkipAhead30SecondsTemplate,
                SkipAheadTemplate,
                SkipBack15SecondsTemplate,
                SkipBack30SecondsTemplate,
                SkipBackTemplate,
                SkipToEndTemplate,
                SkipToStartTemplate,
                SlideshowTemplate,
                TagIconTemplate,
                TextBoldTemplate,
                TextBoxTemplate,
                TextCenterAlignTemplate,
                TextItalicTemplate,
                TextJustifiedAlignTemplate,
                TextLeftAlignTemplate,
                TextListTemplate,
                TextRightAlignTemplate,
                TextStrikethroughTemplate,
                TextUnderlineTemplate,
                UserAddTemplate,
                UserGroupTemplate,
                UserTemplate
            );
            let name = NSString::alloc(nil).init_str(&s);
            let _:() = msg_send![name, autorelease];
            name
        }
    }
}

#[derive(PartialEq, Debug)]
enum ItemType {
    Button,
    Label,
    Slider,
    Scrubber,
    Popover,
    Spacer,
}

struct InternalBar {
    view: *mut Object,
    ident: Ident,
    items: Vec<ItemId>,
}

impl fmt::Display for InternalBar {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "Bar[{}] ({}) <{:x}>",
               self.items.len(),
               util::nsstring_decode(self.ident as *mut Object),
               self.view as u64)
    }
}

struct InternalItem {
    _type: ItemType,
    view: *mut Object,
    ident: Ident,
    control: Option<*mut Object>,
    scrubber: Option<Rc<dyn TScrubberData>>,
    button_cb: Option<ButtonCb>,
    slider_cb: Option<SliderCb>,
    swipe_cb: Option<SwipeCb>,
    tap_cb: Option<ButtonCb>,
    child_bar: Option<ItemId>,
}

impl fmt::Display for InternalItem {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{:?} ({}) <{:x}>", self._type,
               util::nsstring_decode(self.ident as *mut Object),
               self.view as u64)
    }
}

impl InternalItem {
    fn free_objc_allocations(&mut self) {
        unsafe {
            if let Some(obj) = self.control {
                // Sliders don't allocate their control
                if self._type != ItemType::Slider {
                    let _:() = msg_send![obj, release];
                }
            }
            let _:() = msg_send![self.view, release];
            let ident = self.ident as *mut Object;
            let _:() = msg_send![ident, release];
            self.view = nil;
            self.ident = 0;
            self.control = None;
            self.scrubber = None;
            self.button_cb = None;
            self.swipe_cb = None;
            self.tap_cb = None;
            self.slider_cb = None;
        }
    }
}

pub struct RustTouchbarDelegateWrapper {
    objc: Id<ObjcAppDelegate, Shared>,
    next_item_id: Cell<u64>,
    bar_map: BTreeMap<ItemId, InternalBar>,
    item_map: BTreeMap<ItemId, InternalItem>,
}

impl RustTouchbarDelegateWrapper {
    fn generate_ident(&mut self) -> u64 {
        unsafe {
            // Create string identifier
            let next_item_id = self.next_item_id.get();
            self.next_item_id.set(next_item_id + 1);
            let ident = format!("{}{}", IDENT_PREFIX, next_item_id);
            let objc_ident = NSString::alloc(nil).init_str(&ident);
            objc_ident as u64
        }
    }
    fn alloc_button(&mut self, image: Option<&TouchbarImage>, text: Option<&str>,
                    target: *mut Object, sel: Sel) -> *mut Object {
        unsafe {
            let text = match text {
                Some(s) => NSString::alloc(nil).init_str(s),
                None => nil,
            };
            let image = match image {
                Some(i) => *i as *mut Object,
                None => nil,
            };
            let cls = Class::get("NSButton").unwrap();
            let btn: *mut Object;
            // Match on (image, text) as booleans.   false == null.
            match ((image as u64) != 0, (text as u64) != 0) {
                (false,true) => {
                    btn = msg_send![cls,
                                    buttonWithTitle: text
                                    target:target
                                    action:sel];
                }
                (true,false) => {
                    btn = msg_send![cls,
                                    buttonWithImage: image
                                    target:target
                                    action:sel];
                }
                (true,true) => {
                    btn = msg_send![cls,
                                    buttonWithTitle: text
                                    image:image
                                    target:target
                                    action:sel];
                }
                _ => { return nil }
            }
            if text != nil {
                let _:() = msg_send![text, release];
            }
            if image != nil {
                let _:() = msg_send![image, release];
            }
            // These are auto-released, so they need an explicit retain
            let _:() = msg_send![btn, retain];
            btn
        }
    }
    fn find_view(&self, ident: Ident) -> Option<*mut Object> {
        match self.item_map.values().into_iter().filter(|x| {
            unsafe {
                let id = ident as *mut Object;
                let equal: bool = msg_send![id, isEqualToString: x.ident];
                equal
            }
        }).next() {
            Some(item) => Some(item.view),
            None => None,
        }
    }
    fn find_view_from_control(&self, item: &ItemId) -> Option<*mut Object> {
        match self.item_map.values().into_iter().filter(|x| {
            x.control.is_some() && x.control.unwrap() as ItemId == *item
        }).next() {
            Some(item) => Some(item.view),
            None => None,
        }
    }
    fn find_bar_ident(&self, bar: &ItemId) -> Option<Ident> {
        match self.bar_map.values().into_iter().filter(|x| {
            x.view as ItemId == *bar
        }).next() {
            Some(item) => Some(item.ident),
            None => None,
        }
    }
    fn find_ident(&self, item: &ItemId) -> Option<Ident> {
        match self.item_map.values().into_iter().filter(|x| {
            x.view as ItemId == *item
        }).next() {
            Some(item) => Some(item.ident),
            None => None,
        }
    }
    fn find_ident_from_control(&self, item: &ItemId) -> Option<Ident> {
        match self.item_map.values().into_iter().filter(|x| {
            x.control.is_some() && x.control.unwrap() as ItemId == *item
        }).next() {
            Some(item) => Some(item.ident),
            None => None,
        }
    }
    fn find_button_cb(&self, btn: u64) -> Option<&ButtonCb> {
        match self.item_map.values().into_iter().filter(|x| {
            x._type == ItemType::Button && x.control.unwrap() as u64 == btn
        }).next() {
            Some(item) => item.button_cb.as_ref(),
            None => None,
        }
    }
    fn find_swipe_cb(&self, item: u64) -> Option<&SwipeCb> {
        match self.item_map.values().into_iter().filter(|x| {
            x.control.is_some() && x.control.unwrap() as u64 == item
        }).next() {
            Some(item) => item.swipe_cb.as_ref(),
            None => None,
        }
    }
    fn find_tap_cb(&self, item: u64) -> Option<&ButtonCb> {
        match self.item_map.values().into_iter().filter(|x| {
            x.control.is_some() && x.control.unwrap() as u64 == item
        }).next() {
            Some(item) => item.tap_cb.as_ref(),
            None => None,
        }
    }
    fn find_slider_cb(&self, sldr: u64) -> Option<&SliderCb> {
        match self.item_map.values().into_iter().filter(|x| {
            x._type == ItemType::Slider && x.view as u64 == sldr
        }).next() {
            Some(item) => item.slider_cb.as_ref(),
            None => None,
        }
    }
    fn find_scrubber(&self, scrubber: u64) -> Option<ItemId> {
        match self.item_map.values().into_iter().filter(|x| {
            x._type == ItemType::Scrubber && x.control.unwrap() as u64 == scrubber
        }).next() {
            Some(item) => Some(item.view as ItemId),
            None => None,
        }
    }
    fn find_scrubber_callbacks(&self, scrubber: u64) -> Option<&Rc<dyn TScrubberData>> {
        match self.item_map.values().into_iter().filter(|x| {
            x._type == ItemType::Scrubber && x.control.unwrap() as u64 == scrubber
        }).next() {
            Some(item) => item.scrubber.as_ref(),
            None => None,
        }
    }
    fn find_popover(&self, button: u64) -> Option<ItemId> {
        match self.item_map.values().into_iter().filter(|x| {
            x._type == ItemType::Popover && x.control.unwrap() as u64 == button
        }).next() {
            Some(item) => Some(item.view as ItemId),
            None => None,
        }
    }
    fn free_bar_allocations(&mut self, bar: *mut Object) {
        let bar_id = bar as u64;
        let mut subbars = Vec::<*mut Object>::new();
        let items = self.bar_map.get(&bar_id).unwrap().items.clone();
        for item in items.iter() {
            let mut internal_item = self.item_map.remove(&item).unwrap();
            if internal_item._type == ItemType::Popover {
                subbars.push(internal_item.child_bar.unwrap() as *mut Object);
            }
            internal_item.free_objc_allocations();
        }
        self.bar_map.get_mut(&bar_id).unwrap().items.clear();
        for subbar in subbars {
            self.free_bar_allocations(subbar);
        }
    }
    unsafe fn set_label_font_for_text(label: *mut Object, text: &str) {
        //let constraints: *mut Object = msg_send![label, constraints];
        //let height_constraint: *mut Object = msg_send![constraints, firstObject];
        //if height_constraint != nil {
        //    // TODO: if re-enabled, must use NSLayoutConstraint identifier to
        //    // make sure the correct constraint is removed
        //    msg_send![label, removeConstraint: height_constraint];
        //}
        if text.contains("\n") {
            // Shrink font for multi-line labels.  This makes for quite small text.
            let cls = Class::get("NSFont").unwrap();
            let default_size:f64 = msg_send![cls, systemFontSize];
            let custom_font: *mut Object = msg_send![cls, systemFontOfSize: default_size - 3.0];
            let _:() = msg_send![label, setFont: custom_font];

            //let anchor: *mut Object = msg_send![label, heightAnchor];
            //let constraint: *mut Object = msg_send![anchor, constraintEqualToConstant: 30. as f64];
            //let _:() = msg_send![constraint, setActive: YES];
        }
        else {
            // Enlarge the font for single lines.  For some reason it defaults
            // to smaller than other elements.
            let cls = Class::get("NSFont").unwrap();
            let default_size:f64 = msg_send![cls, systemFontSize];
            let custom_font: *mut Object = msg_send![cls, systemFontOfSize: default_size + 3.0];
            let _:() = msg_send![label, setFont: custom_font];
        }
    }
}

impl TTouchbar for Touchbar {
    type T = Touchbar;
    fn alloc(title: &str) -> Touchbar {
        let objc = ObjcAppDelegate::new().share();
        let rust = Box::new(RustTouchbarDelegateWrapper {
            objc: objc.clone(),
            next_item_id: Cell::new(0),
            item_map: BTreeMap::<ItemId, InternalItem>::new(),
            bar_map: BTreeMap::<ItemId, InternalBar>::new(),
        });
        unsafe {
            let ptr: u64 = &*rust as *const RustTouchbarDelegateWrapper as u64;
            let _:() = msg_send![rust.objc, setRustWrapper: ptr];
            let objc_title = NSString::alloc(nil).init_str(title);
            let _:() = msg_send![rust.objc, setTitle: objc_title];
            let _:() = msg_send![objc_title, release];
        }
        return rust
    }
    fn set_icon(&self, image: &str) {
        unsafe {
            let filename = NSString::alloc(nil).init_str(image);
            let objc_image = NSImage::alloc(nil).initWithContentsOfFile_(filename);
            let _:() = msg_send![self.objc, setIcon: objc_image];
            let _:() = msg_send![filename, release];
        }
    }

    fn create_bar(&mut self) -> BarId {
        unsafe {
            let ident = self.generate_ident();
            // Create touchbar
            let cls = RRTouchBar::class();
            let bar: *mut Object = msg_send![cls, alloc];
            let bar: *mut objc::runtime::Object = msg_send![bar, init];
            let _ : () = msg_send![bar, setDelegate: self.objc.clone()];
            let internal = InternalBar {
                view: bar,
                ident: ident,
                items: Vec::<ItemId>::new(),
            };
            self.bar_map.insert(bar as u64, internal);
            bar as u64
        }
    }
    fn create_popover_item(&mut self, image: Option<&TouchbarImage>,
                           text: Option<&str>, bar_id: &BarId) -> ItemId {
        unsafe {
            let bar = *bar_id as *mut Object;
            let ident = self.generate_ident();
            let cls = RRPopoverTouchBarItem::class();
            let item: *mut Object = msg_send![cls, alloc];
            let item: *mut Object = msg_send![item, initWithIdentifier: ident];

            let target = (&*self.objc.clone()) as *const ObjcAppDelegate as *mut Object;
            let btn = self.alloc_button(image, text,
                                        target,
                                        sel!(popbar:));
            let _:() = msg_send![item, setShowsCloseButton: YES];
            let gesture: *mut Object = msg_send![item, makeStandardActivatePopoverGestureRecognizer];
            let _:() = msg_send![btn, addGestureRecognizer: gesture];
            let _:() = msg_send![item, setCollapsedRepresentation: btn];
            let _:() = msg_send![item, setPopoverTouchBar: bar];
            let _:() = msg_send![item, setPressAndHoldTouchBar: bar];

            let internal = InternalItem {
                _type: ItemType::Popover,
                view: item,
                ident: ident,
                control: Some(btn),
                scrubber: None,
                button_cb: None,
                slider_cb: None,
                swipe_cb: None,
                tap_cb: None,
                child_bar: Some(bar as ItemId),
            };
            self.item_map.insert(item as u64, internal);
            item as u64
        }
    }
    fn add_items_to_bar(&mut self, bar_id: &BarId, items: Vec<ItemId>) {
        unsafe {
            let cls = Class::get("NSMutableArray").unwrap();
            let idents: *mut Object = msg_send![cls, alloc];
            let idents: *mut Object = msg_send![idents, initWithCapacity: items.len()];
            for item in items {
                if let Some(ident) = self.find_ident(&item) {
                    let ident = ident as *mut Object;
                    let _ : () = msg_send![idents, addObject: ident];
                    self.bar_map.get_mut(&bar_id).unwrap().items.push(item);
                }
            }
            let bar = *bar_id as *mut Object;
            let _ : () = msg_send![bar, setDefaultItemIdentifiers: idents];
            let _:() = msg_send![idents, release];
        }
    }
    fn set_bar_as_root(&mut self, bar_id: BarId) {
        unsafe {
            let old_bar: *mut Object = msg_send![self.objc, groupTouchBar];
            if old_bar != nil {
                let cls = Class::get("NSTouchBar").unwrap();
                match util::get_appkit_version() >= AppKitVersion::from_tuple(10, 14) {
                    true => {
                        msg_send![cls, minimizeSystemModalTouchBar: old_bar];
                        msg_send![cls, dismissSystemModalTouchBar: old_bar];
                    },
                    false => {
                        msg_send![cls, minimizeSystemModalFunctionBar: old_bar];
                        msg_send![cls, dismissSystemModalFunctionBar: old_bar];
                    },
                }
                self.free_bar_allocations(old_bar);
                msg_send![old_bar, release];
            }
            let _ : () = msg_send![self.objc, setGroupTouchBar: bar_id];
            let ident = self.find_bar_ident(&bar_id).unwrap();
            let _ : () = msg_send![self.objc, setGroupIdent: ident];
            let _ : () = msg_send![self.objc, applicationDidFinishLaunching: 0];
        }
    }
    fn create_label(&mut self, text: &str) -> ItemId {
        unsafe {
            let frame = NSRect::new(NSPoint::new(0., 0.), NSSize::new(0., 40.));
            let cls = Class::get("NSTextField").unwrap();
            let label: *mut Object = msg_send![cls, alloc];
            let label: *mut Object = msg_send![label, initWithFrame: frame];
            RustTouchbarDelegateWrapper::set_label_font_for_text(label, text);
            let _:() = msg_send![label, setEditable: NO];
            let cell: *mut Object = msg_send![label, cell];
            let _:() = msg_send![cell, setWraps: NO];
            let text = NSString::alloc(nil).init_str(text);
            let _:() = msg_send![label, setStringValue: text];
            let _:() = msg_send![text, release];

            let ident = self.generate_ident();
            let cls = RRCustomTouchBarItem::class();
            let item: *mut Object = msg_send![cls, alloc];
            let item: *mut Object = msg_send![item, initWithIdentifier: ident];
            let _:() = msg_send![item, setView: label];

            let internal = InternalItem {
                _type: ItemType::Label,
                view: item,
                ident: ident,
                control: Some(label),
                scrubber: None,
                button_cb: None,
                slider_cb: None,
                swipe_cb: None,
                tap_cb: None,
                child_bar: None
            };
            self.item_map.insert(item as u64, internal);
            item as u64
        }
    }
    fn update_label(&mut self, label_id: &ItemId, text: &str) {
        unsafe {
            let item: *mut Object = *label_id as *mut Object;
            let label: *mut Object = msg_send![item, view];
            RustTouchbarDelegateWrapper::set_label_font_for_text(label, text);
            let text = NSString::alloc(nil).init_str(text);
            let _:() = msg_send![label, setStringValue: text];
            let _:() = msg_send![text, release];
        }
    }
    fn update_label_width(&mut self, label_id: &ItemId, width: u32) {
        unsafe {
            //let _:() = msg_send![label, setAutoresizingMask: 0];
            //let _:() = msg_send![label, setFrameSize: NSSize::new(600., 10.)];
            //let _:() = msg_send![label, setBoundsSize: NSSize::new(600., 10.)];
            //let _:() = msg_send![item, setFrameSize: NSSize::new(600., 30.)];
            //let _:() = msg_send![label, setPreferredMaxLayoutWidth: 500.];
            //let constraints: *mut Object = msg_send![label, constraints];
            //let count: u32 = msg_send![constraints, count];
            //info!("CONSTRAINTS: {}", count);
            let item: *mut Object = *label_id as *mut Object;
            let label: *mut Object = msg_send![item, view];
            let anchor: *mut Object = msg_send![label, widthAnchor];
            let constraint: *mut Object = msg_send![anchor, constraintEqualToConstant: width as f64];
            let _:() = msg_send![constraint, setActive: YES];
        }
    }

    fn create_text_scrubber(&mut self, data: Rc<dyn TScrubberData>) -> ItemId {
        unsafe {
            let ident = self.generate_ident();
            let cls = RRCustomTouchBarItem::class();
            let item: *mut Object = msg_send![cls, alloc];
            let item: *mut Object = msg_send![item, initWithIdentifier: ident];

            // note: frame is ignored, but must be provided.
            let frame = NSRect::new(NSPoint::new(0., 0.), NSSize::new(0., 30.));
            let cls = RRScrubber::class();
            let scrubber: *mut Object = msg_send![cls, alloc];
            let scrubber: *mut Object = msg_send![scrubber, initWithFrame: frame];

            let cls = Class::get("NSScrubberSelectionStyle").unwrap();
            let style: *mut Object = msg_send![cls, outlineOverlayStyle];

            let cls = Class::get("NSScrubberTextItemView").unwrap();
            let _:() = msg_send![scrubber, registerClass: cls forItemIdentifier: ident];
            let _:() = msg_send![scrubber, setDelegate: self.objc.clone()];
            let _:() = msg_send![scrubber, setDataSource: self.objc.clone()];
            let _:() = msg_send![scrubber, setSelectionOverlayStyle: style];
            let _:() = msg_send![scrubber, setMode: 1]; // NSScrubberModeFree
            let _:() = msg_send![item, setView: scrubber];

            let internal = InternalItem {
                _type: ItemType::Scrubber,
                view: item,
                ident: ident,
                control: Some(scrubber),
                scrubber: Some(data),
                button_cb: None,
                slider_cb: None,
                swipe_cb: None,
                tap_cb: None,
                child_bar: None,
            };
            self.item_map.insert(item as u64, internal);
            item as u64
        }
    }
    fn select_scrubber_item(&mut self, scrub_id: &ItemId, index: u32) {
        unsafe {
            let item = *scrub_id as *mut Object;
            let scrubber: *mut Object = msg_send![item, view];
            let _:() = msg_send![scrubber, setSelectedIndex: index];
        }
    }
    fn refresh_scrubber(&mut self, scrub_id: &ItemId) {
        unsafe {
            let item = *scrub_id as *mut Object;
            let scrubber: *mut Object = msg_send![item, view];
            let sel_idx: i32 = msg_send![scrubber, selectedIndex];
            let pre_count: i32 = msg_send![scrubber, numberOfItems];
            let _:() = msg_send![scrubber, reloadData];
            let post_count: i32 = msg_send![scrubber, numberOfItems];
            // reload clears the selected item.  re-select it.
            if sel_idx >= 0 && pre_count == post_count {
                let _:() = msg_send![scrubber, setSelectedIndex: sel_idx];
            }
        }
    }

    fn add_item_swipe_gesture(&mut self, item_id: &ItemId, cb: SwipeCb) {
        unsafe {
            let item = *item_id as *mut Object;
            let view: *mut Object = msg_send![item, view];
            if view == nil {
                return;
            }
            let _:() = msg_send![view, setAllowedTouchTypes: 1]; // NSTouchTypeMaskDirect
            let cls = Class::get("NSPanGestureRecognizer").unwrap();
            let gesture: *mut Object = msg_send![cls, alloc];
            let gesture: *mut Object = msg_send![gesture,
                                                 initWithTarget: self.objc.clone()
                                                 action: sel!(swipeGesture:)];
            let _:() = msg_send![gesture, setAllowedTouchTypes: 1]; // NSTouchTypeMaskDirect
            let _:() = msg_send![view, addGestureRecognizer: gesture];
            let _:() = msg_send![gesture, release];
            let mut internal_item = self.item_map.remove(item_id).unwrap();
            internal_item.swipe_cb = Some(cb);
            self.item_map.insert(*item_id, internal_item);
        }
    }

    fn add_item_tap_gesture(&mut self, item_id: &ItemId, taps: u32,
                            fingers: u32, cb: ButtonCb) {
        unsafe {
            let item = *item_id as *mut Object;
            let view: *mut Object = msg_send![item, view];
            if view == nil {
                return;
            }
            let _:() = msg_send![view, setAllowedTouchTypes: 1]; // NSTouchTypeMaskDirect
            let cls = Class::get("NSClickGestureRecognizer").unwrap();
            let gesture: *mut Object = msg_send![cls, alloc];
            let gesture: *mut Object = msg_send![gesture,
                                                 initWithTarget: self.objc.clone()
                                                 action: sel!(tapGesture:)];
            let _:() = msg_send![gesture, setAllowedTouchTypes: 1]; // NSTouchTypeMaskDirect
            let _:() = msg_send![gesture, setNumberOfTouchesRequired: fingers];
            let _:() = msg_send![gesture, setNumberOfClicksRequired: taps];
            let _:() = msg_send![view, addGestureRecognizer: gesture];
            let _:() = msg_send![gesture, release];
            let mut internal_item = self.item_map.remove(item_id).unwrap();
            internal_item.tap_cb = Some(cb);
            self.item_map.insert(*item_id, internal_item);
        }
    }

    fn create_spacer(&mut self, space: SpacerType) -> ItemId {
        unsafe {
            let s = match space {
                SpacerType::Small =>
                    NSString::alloc(nil).init_str("NSTouchBarItemIdentifierFixedSpaceSmall"),
                SpacerType::Large =>
                    NSString::alloc(nil).init_str("NSTouchBarItemIdentifierFixedSpaceLarge"),
                SpacerType::Flexible =>
                    NSString::alloc(nil).init_str("NSTouchBarItemIdentifierFlexibleSpace"),
            };
            // This is really stupid, since it's just a string, but to fit into the
            // rest of the system we go ahead and allocate a whole internal item for it.

            // And since it doesn't have an ident, just use it as its own ident.  Both
            // the view and ident will be sent a release at shutdown, so retain it an
            // extra time here to keep the references balanced.
            let _:() = msg_send![s, retain];

            let internal = InternalItem {
                _type: ItemType::Spacer,
                view: s,
                ident: s as u64,
                control: None,
                scrubber: None,
                button_cb: None,
                slider_cb: None,
                swipe_cb: None,
                tap_cb: None,
                child_bar: None,
            };
            self.item_map.insert(s as u64, internal);
            s as ItemId
        }
    }

    fn create_image_from_path(&mut self, path: &str) -> TouchbarImage {
        unsafe {
            let filename = NSString::alloc(nil).init_str(path);
            let objc_image = NSImage::alloc(nil).initWithContentsOfFile_(filename);
            let _:() = msg_send![filename, release];
            objc_image as TouchbarImage
        }
    }

    fn create_image_from_template(&mut self, template: ImageTemplate) -> TouchbarImage {
        unsafe {
            let cls = Class::get("NSImage").unwrap();
            let image: *mut Object = msg_send![cls, imageNamed: ImageTemplate::objc(template)];
            let _:() = msg_send![image, retain];
            image as TouchbarImage
        }
    }

    fn create_button(&mut self, image: Option<&TouchbarImage>, text: Option<&str>, cb: ButtonCb) -> ItemId {
        unsafe {
            let ident = self.generate_ident();
            let target = (&*self.objc.clone()) as *const ObjcAppDelegate as *mut Object;
            let btn = self.alloc_button(image, text,
                                        target,
                                        sel!(button:));
            let cls = RRCustomTouchBarItem::class();
            let item: *mut Object = msg_send![cls, alloc];
            let item: *mut Object = msg_send![item, initWithIdentifier: ident];
            let _:() = msg_send![item, setView: btn];

            let internal = InternalItem {
                _type: ItemType::Button,
                view: item,
                ident: ident,
                control: Some(btn),
                scrubber: None,
                button_cb: Some(cb),
                slider_cb: None,
                swipe_cb: None,
                tap_cb: None,
                child_bar: None,
            };
            self.item_map.insert(item as u64, internal);
            item as u64
        }
    }

    fn update_button(&mut self, item: &ItemId, image: Option<&TouchbarImage>, text: Option<&str>) {
        unsafe {
            let item = *item as *mut Object;
            let btn: *mut Object = msg_send![item, view];
            if let Some(image) = image {
                let image = *image as *mut Object;
                let _:() = msg_send![btn, setImage: image];
                let _:() = msg_send![image, release];
            }
            if let Some(text) = text {
                let objc_text = NSString::alloc(nil).init_str(text);
                let _:() = msg_send![btn, setTitle: objc_text];
                let _:() = msg_send![objc_text, release];
            }
        }
    }

    fn update_button_width(&mut self, button_id: &ItemId, width: u32) {
        unsafe {
            let item: *mut Object = *button_id as *mut Object;
            let control: *mut Object = msg_send![item, view];
            let anchor: *mut Object = msg_send![control, widthAnchor];
            let constraint: *mut Object = msg_send![anchor, constraintEqualToConstant: width as f64];
            let _:() = msg_send![constraint, setActive: YES];
        }
    }

    fn create_slider(&mut self, min: f64, max: f64,
                     label: Option<&str>,
                     continuous: bool, cb: SliderCb) -> ItemId {
        unsafe {
            let ident = self.generate_ident();
            let cls = RRSliderTouchBarItem::class();
            let item: *mut Object = msg_send![cls, alloc];
            let item: *mut Object = msg_send![item, initWithIdentifier: ident];
            let slider: *mut Object = msg_send![item, slider];
            if let Some(label) = label {
                let objc_text: *mut Object = NSString::alloc(nil).init_str(label);
                let _:() = msg_send![item, setLabel: objc_text];
                let _:() = msg_send![objc_text, release];
            }
            let _:() = msg_send![slider, setMinValue: min];
            let _:() = msg_send![slider, setMaxValue: max];
            let _:() = msg_send![slider, setContinuous: continuous];
            let _:() = msg_send![item, setTarget: self.objc.clone()];
            let _:() = msg_send![item, setAction: sel!(slider:)];

            let internal = InternalItem {
                _type: ItemType::Slider,
                view: item,
                ident: ident,
                control: Some(slider),
                scrubber: None,
                button_cb: None,
                slider_cb: Some(cb),
                swipe_cb: None,
                tap_cb: None,
                child_bar: None,
            };
            self.item_map.insert(item as u64, internal);
            item as u64
        }
    }
    fn update_slider(&mut self, id: &ItemId, value: f64) {
        unsafe {
            let item = *id as *mut Object;
            let slider: *mut Object = msg_send![item, slider];
            let _:() = msg_send![slider, setDoubleValue: value];
        }
    }
}

// Below here defines a new native Obj-C class.
//
// See rustc-objc-foundation project by SSheldon, examples/custom_class.rs
// https://github.com/SSheldon/rust-objc-foundation/blob/master/examples/custom_class.rs
pub enum ObjcAppDelegate {}
impl ObjcAppDelegate {}

unsafe impl Message for ObjcAppDelegate { }

static OBJC_SUBCLASS_REGISTER_CLASS: Once = ONCE_INIT;

impl INSObject for ObjcAppDelegate {
    fn class() -> &'static Class {
        OBJC_SUBCLASS_REGISTER_CLASS.call_once(|| {
            let superclass = NSObject::class();
            let mut decl = ClassDecl::new("ObjcAppDelegate", superclass).unwrap();
            decl.add_ivar::<u64>("_rust_wrapper");
            decl.add_ivar::<u64>("_group_bar");
            decl.add_ivar::<u64>("_group_id");
            decl.add_ivar::<u64>("_tray_item");
            decl.add_ivar::<u64>("_title");
            decl.add_ivar::<u64>("_icon");

            extern fn objc_set_title(this: &mut Object, _cmd: Sel, ptr: u64) {
                unsafe {this.set_ivar("_title", ptr);}
            }
            extern fn objc_set_rust_wrapper(this: &mut Object, _cmd: Sel, ptr: u64) {
                unsafe {this.set_ivar("_rust_wrapper", ptr);}
            }
            extern fn objc_group_touch_bar(this: &mut Object, _cmd: Sel) -> u64 {
                unsafe {*this.get_ivar("_group_bar")}
            }
            extern fn objc_set_group_touch_bar(this: &mut Object, _cmd: Sel, bar: u64) {
                unsafe {
                    this.set_ivar("_group_bar", bar);
                }
            }
            extern fn objc_set_group_ident(this: &mut Object, _cmd: Sel, bar: u64) {
                unsafe {this.set_ivar("_group_id", bar);}
            }
            extern fn objc_set_icon(this: &mut Object, _cmd: Sel, icon: u64) {
                unsafe {this.set_ivar("_icon", icon);}
            }
            extern fn objc_number_of_items_for_scrubber(this: &mut Object, _cmd: Sel,
                                                        scrub: u64) -> u32 {
                unsafe {
                    let ptr: u64 = *this.get_ivar("_rust_wrapper");
                    let wrapper = &mut *(ptr as *mut RustTouchbarDelegateWrapper);
                    if let Some(ref scrubber) = wrapper.find_scrubber(scrub) {
                        if let Some(ref cbs) = wrapper.find_scrubber_callbacks(scrub) {
                            let count = cbs.count(*scrubber);
                            return count;
                        }
                    }
                    0
                }
            }
            extern fn objc_scrubber_view_for_item_at_index(this: &mut Object, _cmd: Sel,
                                                           scrub: u64, idx: u32) -> u64 {
                unsafe {
                    let ptr: u64 = *this.get_ivar("_rust_wrapper");
                    let wrapper = &mut *(ptr as *mut RustTouchbarDelegateWrapper);
                    let scrubber = scrub as *mut Object;
                    if let Some(ref item) = wrapper.find_scrubber(scrub) {
                        if let Some(ref cbs) = wrapper.find_scrubber_callbacks(scrub) {
                            let ident = wrapper.find_ident_from_control(&scrub).unwrap() as
                                *mut Object;
                            let view: *mut Object = msg_send![scrubber,
                                                              makeItemWithIdentifier:ident
                                                              owner:nil];
                            let text = cbs.text(*item, idx);
                            let text_field: *mut Object = msg_send![view, textField];
                            let objc_text: *mut Object = NSString::alloc(nil).init_str(&text);
                            let _:() = msg_send![text_field, setStringValue: objc_text];
                            let _:() = msg_send![objc_text, release];
                            return view as u64;
                        }
                    }
                    0
                }
            }
            extern fn objc_scrubber_layout_size_for_item_at_index(this: &mut Object, _cmd: Sel,
                                                                  scrub: u64,
                                                                  _layout: u64, idx: u32) -> NSSize {
                unsafe {
                    let ptr: u64 = *this.get_ivar("_rust_wrapper");
                    let wrapper = &mut *(ptr as *mut RustTouchbarDelegateWrapper);
                    if let Some(ref item) = wrapper.find_scrubber(scrub) {
                        if let Some(ref cbs) = wrapper.find_scrubber_callbacks(scrub) {
                            let width = cbs.width(*item, idx);
                            return NSSize::new(width as f64, 30.);
                        }
                    }
                    NSSize::new(0., 30.)
                }
            }
            extern fn objc_scrubber_did_select_item_at_index(this: &mut Object, _cmd: Sel,
                                                             scrub: u64, idx: u32) {
                unsafe {
                    let ptr: u64 = *this.get_ivar("_rust_wrapper");
                    let wrapper = &mut *(ptr as *mut RustTouchbarDelegateWrapper);
                    if let Some(ref item) = wrapper.find_scrubber(scrub) {
                        if let Some(ref cbs) = wrapper.find_scrubber_callbacks(scrub) {
                            cbs.touch(*item, idx);
                        }
                    }
                }
            }
            extern fn objc_popbar(this: &mut Object, _cmd: Sel, sender: u64) {
                unsafe {
                    let ptr: u64 = *this.get_ivar("_rust_wrapper");
                    let wrapper = &mut *(ptr as *mut RustTouchbarDelegateWrapper);

                    let item = wrapper.find_popover(sender) .unwrap_or(0) as *mut Object;
                    let ident = wrapper.find_ident_from_control(&sender) .unwrap_or(0) as *mut Object;
                    if item == nil || ident == nil {
                        return;
                    }
                    let bar: *mut Object = msg_send![item, popoverTouchBar];

                    // Present the request popover.  This must be done instead of
                    // using the popover's built-in showPopover because that pops
                    // _under_ a system function bar.
                    let cls = Class::get("NSTouchBar").unwrap();
                    match util::get_appkit_version() >= AppKitVersion::from_tuple(10, 14) {
                        true => {
                            let _:() = msg_send![cls,
                                                 presentSystemModalTouchBar: bar
                                                 systemTrayItemIdentifier: ident];
                        },
                        false => {
                            let _:() = msg_send![cls,
                                                 presentSystemModalFunctionBar: bar
                                                 systemTrayItemIdentifier: ident];
                        },
                    }
                    let app = NSApp();
                    let _:() = msg_send![app, setTouchBar: nil];
                }
            }
            extern fn objc_button(this: &mut Object, _cmd: Sel, sender: u64) {
                unsafe {
                    let ptr: u64 = *this.get_ivar("_rust_wrapper");
                    let wrapper = &mut *(ptr as *mut RustTouchbarDelegateWrapper);
                    if let Some(ref cb) = wrapper.find_button_cb(sender) {
                        // Sender is the button.  Find the owning touchbar item:
                        let item = wrapper.find_view_from_control(&sender).unwrap();
                        cb(&(item as u64));
                    }
                }
            }
            extern fn objc_tap_gesture(this: &mut Object, _cmd: Sel, sender: u64) {
                unsafe {
                    let ptr: u64 = *this.get_ivar("_rust_wrapper");
                    let wrapper = &mut *(ptr as *mut RustTouchbarDelegateWrapper);
                    let gesture = sender as *mut Object;
                    let view: *mut Object = msg_send![gesture, view];
                    if let Some(ref cb) = wrapper.find_tap_cb(view as u64) {
                        // Sender is the view.  Find the owning touchbar item:
                        let item = wrapper.find_view_from_control(&(view as u64)).unwrap();
                        cb(&(item as u64));
                    }
                }
            }
            extern fn objc_swipe_gesture(this: &mut Object, _cmd: Sel, sender: u64) {
                unsafe {
                    let ptr: u64 = *this.get_ivar("_rust_wrapper");
                    let wrapper = &mut *(ptr as *mut RustTouchbarDelegateWrapper);
                    let gesture = sender as *mut Object;
                    let view: *mut Object = msg_send![gesture, view];
                    let translation: NSPoint = msg_send![gesture,
                                                         translationInView: view];
                    let gesture_state: u32 = msg_send![gesture, state];
                    let state = match gesture_state {
                        // NSGestureRecognizerStateBegan
                        1 => SwipeState::Began,
                        // NSGestureRecognizerStateChanged
                        2 => SwipeState::Changed,
                        // NSGestureRecognizerStateEnded
                        3 => SwipeState::Ended,
                        // NSGestureRecognizerStateCancelled,
                        4 => SwipeState::Cancelled,
                        // NSGestureRecognizerStateFailed
                        5 => SwipeState::Failed,
                        // NSGestureRecognizerStatePossible,
                        _ => SwipeState::Unknown,
                    };
                    if state != SwipeState::Unknown {
                        if let Some(ref cb) = wrapper.find_swipe_cb(view as u64) {
                            // Sender is the view.  Find the owning touchbar item:
                            let item = wrapper.find_view_from_control(&(view as u64)).unwrap();
                            cb(&(item as u64), state, translation.x);
                        }
                    }
                }
            }
            extern fn objc_slider(this: &mut Object, _cmd: Sel, sender: u64) {
                unsafe {
                    let ptr: u64 = *this.get_ivar("_rust_wrapper");
                    let wrapper = &mut *(ptr as *mut RustTouchbarDelegateWrapper);
                    if let Some(ref cb) = wrapper.find_slider_cb(sender) {
                        let item = sender as *mut Object;
                        let slider: *mut Object = msg_send![item, slider];
                        let value: f64 = msg_send![slider, doubleValue];
                        cb(&sender, value);
                    }
                }
            }
            extern fn objc_present(this: &mut Object, _cmd: Sel, _sender: u64) {
                unsafe {
                    let ident_int: u64 = *this.get_ivar("_group_id");
                    let bar_int: u64 = *this.get_ivar("_group_bar");
                    let ident = ident_int as *mut Object;
                    let bar = bar_int as *mut Object;
                    let cls = Class::get("NSTouchBar").unwrap();
                    match util::get_appkit_version() >= AppKitVersion::from_tuple(10, 14) {
                        true => {
                            let _:() = msg_send![cls,
                                                 presentSystemModalTouchBar: bar
                                                 systemTrayItemIdentifier: ident];
                        },
                        false => {
                            let _:() = msg_send![cls,
                                                 presentSystemModalFunctionBar: bar
                                                 systemTrayItemIdentifier: ident];
                        },
                    }
                }
            }
            extern fn objc_touch_bar_make_item_for_identifier(this: &mut Object, _cmd: Sel,
                                                              _bar: u64, id_ptr: u64) -> u64 {
                unsafe {
                    // Find the touchbar item matching this identifier in the
                    // Objective-C object map of the Rust wrapper class, and
                    // return it if found.
                    let ptr: u64 = *this.get_ivar("_rust_wrapper");
                    let wrapper = &mut *(ptr as *mut RustTouchbarDelegateWrapper);
                    if let Some(obj) = wrapper.find_view(id_ptr) {
                        return obj as u64;
                    }
                }
                0
            }
            extern fn objc_application_did_finish_launching(this: &mut Object, _cmd: Sel, _notification: u64) {
                unsafe {
                    DFRSystemModalShowsCloseBoxWhenFrontMost(YES);

                    let old_item_ptr: u64 = *this.get_ivar("_tray_item");
                    let old_item = old_item_ptr as *mut Object;
                    if old_item != nil {
                        let cls = Class::get("NSTouchBarItem").unwrap();
                        let _:() = msg_send![cls, removeSystemTrayItem: old_item];
                        let _:() = msg_send![old_item, release];
                    }

                    let app = NSApp();
                    let _:() = msg_send![app, setTouchBar: nil];

                    let ident_int: u64 = *this.get_ivar("_group_id");
                    let ident = ident_int as *mut Object;
                    let cls = Class::get("NSCustomTouchBarItem").unwrap();
                    let item: *mut Object = msg_send![cls, alloc];
                    let _:() = msg_send![item, initWithIdentifier:ident];
                    this.set_ivar("_tray_item", item as u64);

                    let cls = Class::get("NSButton").unwrap();
                    let icon_ptr: u64 = *this.get_ivar("_icon");
                    let title_ptr: u64 = *this.get_ivar("_title");
                    let btn: *mut Object;
                    if icon_ptr != (nil as u64) {
                        btn = msg_send![cls,
                                        buttonWithImage:icon_ptr
                                        target:this
                                        action:sel!(present:)];
                    }
                    else {
                        btn = msg_send![cls,
                                        buttonWithTitle:title_ptr
                                        target:this
                                        action:sel!(present:)];
                    }
                    let _:() = msg_send![item, setView:btn];

                    let cls = Class::get("NSTouchBarItem").unwrap();
                    let _:() = msg_send![cls, addSystemTrayItem: item];
                    DFRElementSetControlStripPresenceForIdentifier(ident, YES);
                }
            }

            unsafe {
                let f: extern fn(&mut Object, Sel, u64, u64) -> u64 = objc_touch_bar_make_item_for_identifier;
                decl.add_method(sel!(touchBar:makeItemForIdentifier:), f);

                let f: extern fn(&mut Object, Sel, u64) = objc_application_did_finish_launching;
                decl.add_method(sel!(applicationDidFinishLaunching:), f);

                let f: extern fn(&mut Object, Sel, u64) = objc_present;
                decl.add_method(sel!(present:), f);

                let f: extern fn(&mut Object, Sel, u64) = objc_button;
                decl.add_method(sel!(button:), f);

                let f: extern fn(&mut Object, Sel, u64) = objc_tap_gesture;
                decl.add_method(sel!(tapGesture:), f);

                let f: extern fn(&mut Object, Sel, u64) = objc_swipe_gesture;
                decl.add_method(sel!(swipeGesture:), f);

                let f: extern fn(&mut Object, Sel, u64) = objc_slider;
                decl.add_method(sel!(slider:), f);

                let f: extern fn(&mut Object, Sel, u64) = objc_popbar;
                decl.add_method(sel!(popbar:), f);

                let f: extern fn(&mut Object, Sel) -> u64 = objc_group_touch_bar;
                decl.add_method(sel!(groupTouchBar), f);

                let f: extern fn(&mut Object, Sel, u64) = objc_set_group_touch_bar;
                decl.add_method(sel!(setGroupTouchBar:), f);

                let f: extern fn(&mut Object, Sel, u64) = objc_set_group_ident;
                decl.add_method(sel!(setGroupIdent:), f);

                let f: extern fn(&mut Object, Sel, u64) = objc_set_icon;
                decl.add_method(sel!(setIcon:), f);

                let f: extern fn(&mut Object, Sel, u64) = objc_set_rust_wrapper;
                decl.add_method(sel!(setRustWrapper:), f);

                let f: extern fn(&mut Object, Sel, u64) = objc_set_title;
                decl.add_method(sel!(setTitle:), f);

                // Scrubber delegates
                let f: extern fn(&mut Object, Sel, u64) -> u32 = objc_number_of_items_for_scrubber;
                decl.add_method(sel!(numberOfItemsForScrubber:), f);
                let f: extern fn(&mut Object, Sel, u64, u32) -> u64 = objc_scrubber_view_for_item_at_index;
                decl.add_method(sel!(scrubber:viewForItemAtIndex:), f);
                let f: extern fn(&mut Object, Sel, u64, u64, u32) -> NSSize = objc_scrubber_layout_size_for_item_at_index;
                decl.add_method(sel!(scrubber:layout:sizeForItemAtIndex:), f);
                let f: extern fn(&mut Object, Sel, u64, u32) = objc_scrubber_did_select_item_at_index;
                decl.add_method(sel!(scrubber:didSelectItemAtIndex:), f);
            }

            decl.register();
        });

        Class::get("ObjcAppDelegate").unwrap()
    }
}