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
use std::ptr;

use super::{ComInterface, HString, HStringReference, HStringArg, ComPtr, ComArray, ComIid, Guid};
use HRESULT;

use w::shared::ntdef::{VOID, ULONG};
use w::shared::winerror::{S_OK, S_FALSE, CO_E_NOTINITIALIZED, REGDB_E_CLASSNOTREG};
use w::shared::guiddef::IID;
use w::um::unknwnbase::IUnknownVtbl;
use w::winrt::hstring::HSTRING;
use w::winrt::roapi::{RO_INIT_MULTITHREADED, RO_INIT_SINGLETHREADED, RoInitialize, RoUninitialize, RoGetActivationFactory};
use w::um::combaseapi::CoIncrementMTAUsage;

use self::gen::windows::foundation::collections::{
    IIterable,
    IIterator,
    IVector,
    IVectorView,
    IObservableVector
};

/// Represents a single UTF-16 character. This is the standard character type in WinRT. 
#[derive(Clone, Copy)]
#[repr(transparent)]
pub struct Char(pub ::w::ctypes::wchar_t); // TODO: deref to u16

/// Marker trait for all Windows Runtime interfaces. They must inherit from `IInspectable`.
pub unsafe trait RtInterface: ComInterface {}

/// Marker trait for all interfaces that are not factories or statics.
pub unsafe trait RtClassInterface: RtInterface {}

/// Marker trait for all value types (primitive types, structs, enums) that can be used as
/// generic parameters in Windows Runtime.
pub unsafe trait RtValueType: Copy {}

unsafe impl RtValueType for bool {}
unsafe impl RtValueType for f32 {}
unsafe impl RtValueType for f64 {}
unsafe impl RtValueType for i8 {}
unsafe impl RtValueType for i16 {}
unsafe impl RtValueType for i32 {}
unsafe impl RtValueType for i64 {}
unsafe impl RtValueType for u8 {}
unsafe impl RtValueType for u16 {}
unsafe impl RtValueType for u32 {}
unsafe impl RtValueType for u64 {}
unsafe impl RtValueType for Char {}
unsafe impl RtValueType for Guid {}

/// This is a trait implemented by all types that can be used as generic parameters of parameterized interfaces.
/// `Abi` and `OutNonNull` must be binary compatible (i.e. `wrap` must basically be the same as `transmute`)
/// in order to work in `ComArray`.
pub trait RtType {
    type In;
    type Abi;
    type Out;
    type OutNonNull;

    unsafe fn unwrap(input: &Self::In) -> Self::Abi;
    unsafe fn uninitialized() -> Self::Abi;
    unsafe fn wrap(abi: Self::Abi) -> Self::Out;
}

impl<'a> RtType for HString {
    type In = HStringArg;
    type Abi = HSTRING;
    type Out = HString;
    type OutNonNull = Self::Out;

    #[doc(hidden)] #[inline]
    unsafe fn unwrap(v: &HStringArg) -> Self::Abi {
        v.get()
    }
    #[doc(hidden)] #[inline]
    unsafe fn uninitialized() -> Self::Abi {
        ::std::ptr::null_mut()
    }
    #[doc(hidden)] #[inline]
    unsafe fn wrap(v: Self::Abi) -> Self::Out {
        HString::wrap(v)
    }
}

impl<T> RtType for T where T: RtValueType
{
    type In = T;
    type Abi = T;
    type Out = T;
    type OutNonNull = Self::Out;

    #[doc(hidden)] #[inline]
    unsafe fn unwrap(v: &Self::In) -> Self::Abi {
        *v
    }
    #[doc(hidden)] #[inline]
    unsafe fn uninitialized() -> Self::Abi {
        ::std::mem::zeroed()
    }
    #[doc(hidden)] #[inline]
    unsafe fn wrap(v: Self::Abi) -> Self::Out {
        v
    }
}

/// This trait is implemented by all classes that have a name
/// associated with them which can be used at runtime.
pub trait RtNamedClass {
    /// Returns the name of the class encoded as a 16-bit wide string.
    fn name() -> &'static [u16];
}

pub trait RtActivatable<Interface> : RtNamedClass {
    /// Returns a factory object to create instances of this class or to call static methods.
    #[inline]
    fn get_activation_factory() -> ComPtr<Interface> where Interface: RtInterface + ComIid {
        let mut res = ptr::null_mut();
        let class_id = unsafe { HStringReference::from_utf16_unchecked(Self::name()) };
        let mut hr = unsafe { RoGetActivationFactory(class_id.get(), <Interface as ComIid>::iid().as_ref(), &mut res as *mut *mut _ as *mut *mut VOID) };
        if hr == CO_E_NOTINITIALIZED {
            let mut cookie = ptr::null_mut();
            unsafe { CoIncrementMTAUsage(&mut cookie); }
            hr = unsafe { RoGetActivationFactory(class_id.get(), <Interface as ComIid>::iid().as_ref(), &mut res as *mut *mut _ as *mut *mut VOID) };
        }
        if hr == S_OK {
            unsafe { ComPtr::wrap(res) }
        } else if hr == REGDB_E_CLASSNOTREG {
            let name = Self::name();
            panic!("WinRT class \"{}\" not registered", String::from_utf16_lossy(&name[0..name.len()-1]))
        } else {
            panic!("RoGetActivationFactory failed with error code 0x{:X}", hr as u32)
        }     
    }
}

/// Enables easy access to a default constructor, using `IActivationFactory` under the hood.
pub trait RtDefaultConstructible {
    /// Uses the default constructor to create an instance of this class.
    fn new() -> ComPtr<Self> where Self: Sized + RtActivatable<IActivationFactory> + ComInterface;
}

impl<T> RtDefaultConstructible for T where T: RtActivatable<IActivationFactory> {
    #[inline]
    fn new() -> ComPtr<Self> where Self: Sized + RtActivatable<IActivationFactory> + ComInterface {
        let factory: ComPtr<IActivationFactory> = Self::get_activation_factory();
        unsafe { factory.activate_instance().into_unchecked() }
    }
}

pub struct IteratorAdaptor<'a, T: RtType + 'a> {
    iter: ComPtr<IIterator<T>>,
    called_next: bool,
    phantom: ::std::marker::PhantomData<&'a IIterable<T>>
}

impl<'a, T: RtType + 'a> IteratorAdaptor<'a, T> {
    // careful: this creates an unbounded lifetime
    fn new(iter: ComPtr<IIterator<T>>) -> Self {
        IteratorAdaptor {
            iter: iter,
            called_next: false,
            phantom: ::std::marker::PhantomData
        }
    }
}

impl<'a, T> Iterator for IteratorAdaptor<'a, T> where T: RtType
{
    type Item = <T as RtType>::Out;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        if !self.called_next {
            self.called_next = true;
            match self.iter.get_has_current().expect("IIterator::get_has_current failed") {
                true => Some(self.iter.get_current().expect("IIterator::get_current failed")),
                false => None
            }
        } else {
            match self.iter.move_next() {
                Ok(true) => Some(self.iter.get_current().expect("IIterator::get_current failed")),
                Ok(false) => None,
                Err(::Error::ChangedState) => panic!("the iterator was invalidated by an operation that changed the state of the container"),
                Err(e) => panic!("IIterator::move_next failed: {:?}", e),
            }
        }
    }
}

// NOTE: We can't totally prevent iterator invalidation statically (because we cannot
//       prevent multiple ComPtr's pointing at the same object), but making the
//       mutating collection methods take `&mut self` already helps prevent many bugs.

impl<'a, T> IntoIterator for &'a IIterable<T> where T: RtType
{
    type Item = <T as RtType>::Out;
    type IntoIter = IteratorAdaptor<'a, T>;
    #[inline] fn into_iter(self) -> Self::IntoIter {
        IteratorAdaptor::new(self.first().unwrap().unwrap())
    }
}

impl<'a, T> IntoIterator for &'a IVector<T> where T: RtType, IIterable<T>: ComIid
{
    type Item = <T as RtType>::Out;
    type IntoIter = IteratorAdaptor<'a, T>;
    #[inline] fn into_iter(self) -> Self::IntoIter {
        IteratorAdaptor::new(::comptr::query_interface::<_, IIterable<T>>(self).unwrap().first().unwrap().unwrap())
    }
}

impl<'a, T> IntoIterator for &'a IVectorView<T> where T: RtType, IIterable<T>: ComIid
{
    type Item = <T as RtType>::Out;
    type IntoIter = IteratorAdaptor<'a, T>;
    #[inline] fn into_iter(self) -> Self::IntoIter {
        IteratorAdaptor::new(::comptr::query_interface::<_, IIterable<T>>(self).unwrap().first().unwrap().unwrap())
    }
}

impl<'a, T> IntoIterator for &'a IObservableVector<T> where T: RtType, IIterable<T>: ComIid
{
    type Item = <T as RtType>::Out;
    type IntoIter = IteratorAdaptor<'a, T>;
    #[inline] fn into_iter(self) -> Self::IntoIter {
        IteratorAdaptor::new(::comptr::query_interface::<_, IIterable<T>>(self).unwrap().first().unwrap().unwrap())
    }
}

// TODO: Implement IntoIterator also for Map types

// Make the for loop desugaring work with references to `ComPtr`s directly
impl<'a, T> IntoIterator for &'a ComPtr<T> where &'a T: IntoIterator
{
    type Item = <&'a T as IntoIterator>::Item;
    type IntoIter = <&'a T as IntoIterator>::IntoIter;
    #[inline] fn into_iter(self) -> Self::IntoIter {
        use std::ops::Deref;
        self.deref().into_iter()
    }
}

// TODO: also implement IndexMove for IVectorView etc once that exists (Index or IndexMut won't work since we can't return a reference)

macro_rules! RT_INTERFACE {
    ($(#[$attr:meta])* interface $interface:ident<$t1:ident, $t2:ident> $($rest:tt)*) => {
        RT_INTERFACE!($(#[$attr])* basic $interface<$t1,$t2> $($rest)*);
        unsafe impl<$t1: RtType, $t2: RtType> ::RtInterface for $interface<$t1,$t2> {}
        unsafe impl<$t1: RtType, $t2: RtType> ::RtClassInterface for $interface<$t1,$t2> {}
    };

    ($(#[$attr:meta])* interface $interface:ident<$t1:ident> $($rest:tt)*) => {
        RT_INTERFACE!($(#[$attr])* basic $interface<$t1> $($rest)*);
        unsafe impl<$t1: RtType> ::RtInterface for $interface<$t1> {}
        unsafe impl<$t1: RtType> ::RtClassInterface for $interface<$t1> {}
    };

    ($(#[$attr:meta])* interface $interface:ident $($rest:tt)*) => {
        RT_INTERFACE!($(#[$attr])* basic $interface $($rest)*);
        unsafe impl ::RtInterface for $interface {}
        unsafe impl ::RtClassInterface for $interface {}
    };

    ($(#[$attr:meta])* static interface $interface:ident<$t1:ident, $t2:ident> $($rest:tt)*) => {
        RT_INTERFACE!($(#[$attr])* basic $interface<$t1,$t2> $($rest)*);
        unsafe impl<$t1: RtType, $t2: RtType> ::RtInterface for $interface<$t1,$t2> {}
    };

    ($(#[$attr:meta])* static interface $interface:ident<$t1:ident> $($rest:tt)*) => {
        RT_INTERFACE!($(#[$attr])* basic $interface<$t1> $($rest)*);
        unsafe impl<$t1: RtType> ::RtInterface for $interface<$t1> {}
    };

    ($(#[$attr:meta])* static interface $interface:ident $($rest:tt)*) => {
        RT_INTERFACE!($(#[$attr])* basic $interface $($rest)*);
        unsafe impl ::RtInterface for $interface {}
    };

    // version with no methods
    ($(#[$attr:meta])* basic $interface:ident ($vtbl:ident) : $pinterface:ident ($pvtbl:ty) [$iid:ident]
        {}
    ) => {
        #[repr(transparent)] #[allow(missing_copy_implementations)] #[doc(hidden)]
        pub struct $vtbl {
            pub parent: $pvtbl
        }
        $(#[$attr])* #[repr(transparent)] #[allow(missing_copy_implementations)]
        pub struct $interface {
            lpVtbl: *const $vtbl
        }
        impl ComIid for $interface {
            #[inline] fn iid() -> &'static ::Guid { &$iid }
        }
        impl ComInterface for $interface {
            type Vtbl = $vtbl;
        }
        impl ::RtType for $interface {
            type In = $interface;
            type Abi = *mut $interface;
            type Out = Option<Self::OutNonNull>;
            type OutNonNull = ComPtr<$interface>;

            #[doc(hidden)] #[inline] unsafe fn unwrap(v: &Self::In) -> Self::Abi { v as *const _ as *mut _ }
            #[doc(hidden)] #[inline] unsafe fn uninitialized() -> Self::Abi { ::std::ptr::null_mut() }
            #[doc(hidden)] #[inline] unsafe fn wrap(v: Self::Abi) -> Self::Out { ComPtr::wrap_optional(v) }
        }
        impl ::std::ops::Deref for $interface {
            type Target = $crate::$pinterface;
            #[inline]
            fn deref(&self) -> &$crate::$pinterface {
                unsafe { ::std::mem::transmute(self) }
            }
        }
        impl ::std::ops::DerefMut for $interface {
            #[inline]
            fn deref_mut(&mut self) -> &mut $crate::$pinterface {
                unsafe { ::std::mem::transmute(self) }
            }
        }
    };

    // version with methods, but without generic parameters
    ($(#[$attr:meta])* basic $interface:ident ($vtbl:ident) : $pinterface:ident ($pvtbl:ty) [$iid:ident]
        {$(
            $(#[cfg($cond_attr:meta)])* fn $method:ident(&self $(,$p:ident : $t:ty)*) -> $rtr:ty
        ),+}
    ) => {
        #[repr(C)] #[allow(missing_copy_implementations)] #[doc(hidden)]
        pub struct $vtbl {
            pub parent: $pvtbl
            $(, $(#[cfg($cond_attr)])* pub $method: unsafe extern "system" fn(
                This: *mut $interface
                $(,$p: $t)*
            ) -> $rtr)+
        }
        $(#[$attr])* #[repr(transparent)] #[allow(missing_copy_implementations)]
        pub struct $interface {
            lpVtbl: *const $vtbl
        }
        impl ComIid for $interface {
            #[inline] fn iid() -> &'static ::Guid { &$iid }
        }
        impl ComInterface for $interface {
            type Vtbl = $vtbl;
        }
        impl ::RtType for $interface {
            type In = $interface;
            type Abi = *mut $interface;
            type Out = Option<Self::OutNonNull>;
            type OutNonNull = ComPtr<$interface>;

            #[doc(hidden)] #[inline] unsafe fn unwrap(v: &Self::In) -> Self::Abi { v as *const _ as *mut _ }
            #[doc(hidden)] #[inline] unsafe fn uninitialized() -> Self::Abi { ::std::ptr::null_mut() }
            #[doc(hidden)] #[inline] unsafe fn wrap(v: Self::Abi) -> Self::Out { ComPtr::wrap_optional(v) }
        }
        impl ::std::ops::Deref for $interface {
            type Target = $crate::$pinterface;
            #[inline]
            fn deref(&self) -> &$crate::$pinterface {
                unsafe { ::std::mem::transmute(self) }
            }
        }
        impl ::std::ops::DerefMut for $interface {
            #[inline]
            fn deref_mut(&mut self) -> &mut $crate::$pinterface {
                unsafe { ::std::mem::transmute(self) }
            }
        }
    };
    // The $iid is actually not necessary, because it refers to the uninstantiated version of the interface,
    // which is irrelevant at runtime (it is used to generate the IIDs of the parameterized interfaces).
    ($(#[$attr:meta])* basic $interface:ident<$t1:ident> ($vtbl:ident) : $pinterface:ident ($pvtbl:ty) [$iid:ident]
        {$(
            $(#[cfg($cond_attr:meta)])* fn $method:ident(&self $(,$p:ident : $t:ty)*) -> $rtr:ty
        ),+}
    ) => {
        #[repr(C)] #[allow(missing_copy_implementations)] #[doc(hidden)]
        pub struct $vtbl<$t1> where $t1: RtType {
            pub parent: $pvtbl
            $(, $(#[cfg($cond_attr)])* pub $method: unsafe extern "system" fn(
                This: *mut $interface<$t1>
                $(,$p: $t)*
            ) -> $rtr)+
        }
        $(#[$attr])* #[repr(transparent)] #[allow(missing_copy_implementations)]
        pub struct $interface<$t1> where $t1: RtType {
            lpVtbl: *const $vtbl<$t1>,
        }
        impl<$t1> ComInterface for $interface<$t1> where $t1: RtType {
            type Vtbl = $vtbl<$t1>;
        }
        impl<$t1> ::RtType for $interface<$t1> where $t1: RtType{
            type In = $interface<$t1>;
            type Abi = *mut $interface<$t1>;
            type Out = Option<Self::OutNonNull>;
            type OutNonNull = ComPtr<$interface<$t1>>;

            #[doc(hidden)] #[inline] unsafe fn unwrap(v: &Self::In) -> Self::Abi { v as *const _ as *mut _ }
            #[doc(hidden)] #[inline] unsafe fn uninitialized() -> Self::Abi { ::std::ptr::null_mut() }
            #[doc(hidden)] #[inline] unsafe fn wrap(v: Self::Abi) -> Self::Out { ComPtr::wrap_optional(v) }
        }
        impl<$t1> ::std::ops::Deref for $interface<$t1> where $t1: RtType {
            type Target = $pinterface;
            #[inline]
            fn deref(&self) -> &$pinterface {
                unsafe { ::std::mem::transmute(self) }
            }
        }
        impl<$t1> ::std::ops::DerefMut for $interface<$t1> where $t1: RtType {
            #[inline]
            fn deref_mut(&mut self) -> &mut $pinterface {
                unsafe { ::std::mem::transmute(self) }
            }
        }
    };

    ($(#[$attr:meta])* basic $interface:ident<$t1:ident, $t2:ident> ($vtbl:ident) : $pinterface:ident ($pvtbl:ty) [$iid:ident]
        {$(
            $(#[cfg($cond_attr:meta)])* fn $method:ident(&self $(,$p:ident : $t:ty)*) -> $rtr:ty
        ),+}
    ) => {
        #[repr(C)] #[allow(missing_copy_implementations)] #[doc(hidden)]
        pub struct $vtbl<$t1, $t2> where $t1: RtType, $t2: RtType {
            pub parent: $pvtbl
            $(, $(#[cfg($cond_attr)])* pub $method: unsafe extern "system" fn(
                This: *mut $interface<$t1, $t2>
                $(,$p: $t)*
            ) -> $rtr)+
        }
        $(#[$attr])* #[repr(transparent)] #[allow(missing_copy_implementations)]
        pub struct $interface<$t1, $t2> where $t1: RtType, $t2: RtType {
            lpVtbl: *const $vtbl<$t1, $t2>,
        }
        impl<$t1, $t2> ComInterface for $interface<$t1, $t2> where $t1: RtType, $t2: RtType {
            type Vtbl = $vtbl<$t1, $t2>;
        }
        impl<$t1, $t2> ::RtType for $interface<$t1, $t2> where $t1: RtType, $t2: RtType {
            type In = $interface<$t1, $t2>;
            type Abi = *mut $interface<$t1, $t2>;
            type Out = Option<Self::OutNonNull>;
            type OutNonNull = ComPtr<$interface<$t1, $t2>>;

            #[doc(hidden)] #[inline] unsafe fn unwrap(v: &Self::In) -> Self::Abi { v as *const _ as *mut _ }
            #[doc(hidden)] #[inline] unsafe fn uninitialized() -> Self::Abi { ::std::ptr::null_mut() }
            #[doc(hidden)] #[inline] unsafe fn wrap(v: Self::Abi) -> Self::Out { ComPtr::wrap_optional(v) }
        }
        impl<$t1, $t2> ::std::ops::Deref for $interface<$t1, $t2> where $t1: RtType, $t2: RtType {
            type Target = $pinterface;
            #[inline]
            fn deref(&self) -> &$pinterface {
                unsafe { ::std::mem::transmute(self) }
            }
        }
        impl<$t1, $t2> ::std::ops::DerefMut for $interface<$t1, $t2> where $t1: RtType, $t2: RtType {
            #[inline]
            fn deref_mut(&mut self) -> &mut $pinterface {
                unsafe { ::std::mem::transmute(self) }
            }
        }
    };
}

macro_rules! RT_DELEGATE {
    // without generic parameters
    (delegate $interface:ident ($vtbl:ident, $imp:ident) [$iid:ident] {
        $(#[cfg($cond_attr:meta)])* fn Invoke(&self $(,$p:ident : $t:ty)*) -> HRESULT
    }) => {
        RT_INTERFACE!{basic $interface($vtbl) : IUnknown(IUnknownVtbl) [$iid] {
            $(#[cfg($cond_attr)])* fn Invoke(&self $(,$p : $t)*) -> HRESULT
        }}

        $(#[cfg($cond_attr)])*
        impl $interface {
            #[inline] pub fn new<_F_>(f: _F_) -> ComPtr<$interface>
                where _F_: 'static + Send + FnMut($($t),*) -> Result<()>, $interface: ComIid {
                $imp::new(f).into_interface()
            }
        }

        $(#[cfg($cond_attr)])*
        struct $imp<_F_> where _F_: 'static + Send + FnMut($($t),*) -> Result<()> {
            invoke: _F_
        }

        $(#[cfg($cond_attr)])*
        impl<_F_> $imp<_F_>
            where $interface: ComIid, _F_: 'static + Send + FnMut($($t),*) -> Result<()>
        {
            #[inline]
            pub fn new(f: _F_) -> $imp<_F_> {
                $imp {
                    invoke: f,
                }
            }
        }

        $(#[cfg($cond_attr)])*
        impl<_F_> ::rt::handler::ComClass<$interface> for $imp<_F_>
            where $interface: ComIid, _F_: 'static + Send + FnMut($($t),*) -> Result<()>
        {
            #[inline]
            fn get_vtbl() -> $vtbl {
                $vtbl {
                    parent: IUnknownVtbl {
                        QueryInterface: ::rt::handler::ComReprHandler_QueryInterface::<$imp<_F_>, _>,
                        AddRef: ::rt::handler::ComRepr_AddRef::<$imp<_F_>>,
                        Release: ::rt::handler::ComRepr_Release::<$imp<_F_>>,
                    },
                    Invoke: {
                        unsafe extern "system" fn Invoke<_F_>(this_: *mut $interface $(,$p : $t)*) -> HRESULT
                            where $interface: ComIid, _F_: 'static + Send + FnMut($($t),*) -> Result<()>
                        {
                            let this: &mut $imp<_F_> = ::rt::handler::ComClass::from_interface(this_);
                            match (this.invoke)($($p),*) {
                                Ok(()) => S_OK,
                                Err(err) => err.as_hresult()
                            }
                        }
                        Invoke::<_F_>
                    }
                }
            }
        }

        /*impl<_F_> Drop for $imp<_F_>
            where _F_: 'static + Send + FnMut($($t),*) -> HRESULT
        {
            fn drop(&mut self) {
                println!("DROPPED {}<...>!", stringify!($imp));
            }
        }*/
    };

    // with generic parameters
    (delegate $interface:ident<$($ht:ident),+> ($vtbl:ident, $imp:ident) [$iid:ident] {
        $(#[cfg($cond_attr:meta)])* fn Invoke(&self $(,$p:ident : $t:ty)*) -> HRESULT
    }) => {
        RT_INTERFACE!{basic $interface<$($ht),+>($vtbl) : IUnknown(IUnknownVtbl) [$iid] {
            $(#[cfg($cond_attr)])* fn Invoke(&self $(,$p : $t)*) -> HRESULT
        }}

        impl<$($ht: RtType + 'static),+> $interface<$($ht),+> {
            #[inline] pub fn new<_F_>(f: _F_) -> ComPtr<$interface<$($ht),+>>
                where _F_: 'static + Send + FnMut($($t),*) -> Result<()>, $interface<$($ht),+>: ComIid {
                $imp::new(f).into_interface()
            }
        }

        struct $imp<$($ht: RtType),+ , _F_> where _F_: 'static + Send + FnMut($($t),*) -> Result<()> {
            invoke: _F_,
            phantom: ::std::marker::PhantomData<($($ht),+)>
        }

        impl<$($ht: RtType + 'static),+ , _F_> $imp<$($ht),+ , _F_>
            where $interface<$($ht),+>: ComIid, _F_: 'static + Send + FnMut($($t),*) -> Result<()>
        {
            #[inline]
            pub fn new(f: _F_) -> $imp<$($ht),+ , _F_> {
                $imp {
                    invoke: f,
                    phantom: ::std::marker::PhantomData
                }
            }
        }

        impl<$($ht: RtType + 'static),+ , _F_> ::rt::handler::ComClass<$interface<$($ht),+>> for $imp<$($ht),+ , _F_>
            where $interface<$($ht),+>: ComIid, _F_: 'static + Send + FnMut($($t),*) -> Result<()>
        {
            #[inline]
            fn get_vtbl() -> $vtbl<$($ht),+> {
                $vtbl::<$($ht),+> {
                    parent: IUnknownVtbl {
                        QueryInterface: ::rt::handler::ComReprHandler_QueryInterface::<$imp<$($ht),+ , _F_>, _>,
                        AddRef: ::rt::handler::ComRepr_AddRef::<$imp<$($ht),+ , _F_>>,
                        Release: ::rt::handler::ComRepr_Release::<$imp<$($ht),+ , _F_>>,
                    },
                    Invoke: {
                        unsafe extern "system" fn Invoke<$($ht: RtType + 'static),+ , _F_>(this_: *mut $interface<$($ht),+> $(,$p : $t)*) -> HRESULT
                            where $interface<$($ht),+>: ComIid, _F_: 'static + Send + FnMut($($t),*) -> Result<()>
                        {
                            let this: &mut $imp<$($ht),+ , _F_> = ::rt::handler::ComClass::from_interface(this_);
                            match (this.invoke)($($p),*) {
                                Ok(()) => S_OK,
                                Err(err) => err.as_hresult()
                            }
                        }
                        Invoke::<$($ht),+ , _F_>
                    }
                }
            }
        }

        /*impl<$($ht: RtType),+ , _F_> Drop for $imp<$($ht),+ , _F_>
            where _F_: 'static + Send + FnMut($($t),*) -> HRESULT
        {
            fn drop(&mut self) {
                println!("DROPPED {}<...>!", stringify!($imp));
            }
        }*/
    };
}

macro_rules! RT_CLASS {
    {static class $cls:ident} => {
        pub struct $cls; // does not exist at runtime and has no ABI representation
    };

    {class $cls:ident : $interface:ty} => {
        pub struct $cls($interface);
        unsafe impl ::RtInterface for $cls {}
        unsafe impl ::RtClassInterface for $cls {}
        impl ComInterface for $cls {
            type Vtbl = <$interface as ComInterface>::Vtbl;
        }
        impl ComIid for $cls {
            #[inline] fn iid() -> &'static ::Guid { <$interface as ComIid>::iid() }
        }
        impl ::RtType for $cls {
            type In = $cls;
            type Abi = *mut $cls;
            type Out = Option<Self::OutNonNull>;
            type OutNonNull = ComPtr<$cls>;
            
            #[doc(hidden)] #[inline] unsafe fn unwrap(v: &Self::In) -> Self::Abi { v as *const _ as *mut _ }
            #[doc(hidden)] #[inline] unsafe fn uninitialized() -> Self::Abi { ::std::ptr::null_mut() }
            #[doc(hidden)] #[inline] unsafe fn wrap(v: Self::Abi) -> Self::Out { ComPtr::wrap_optional(v) }
        }
        impl ::std::ops::Deref for $cls {
            type Target = $interface;
            #[inline]
            fn deref(&self) -> &$interface {
                &self.0
            }
        }
        impl ::std::ops::DerefMut for $cls {
            #[inline]
            fn deref_mut(&mut self) -> &mut $interface {
                &mut self.0
            }
        }
    };
}

macro_rules! DEFINE_CLSID {
    ($clsname:ident($id:expr) [$idname:ident]) => {
        const $idname: &'static [u16] = $id; // Full name of the class as null-terminated UTF16 string
        impl ::RtNamedClass for $clsname {
            #[inline]
            fn name() -> &'static [u16] { $idname } 
        }
    }
}

macro_rules! RT_ENUM {
    {enum $name:ident : $t:ty { $($variant:ident = $value:expr,)+ }} => {
        #[repr(transparent)]
        #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
        #[allow(non_upper_case_globals)]
        pub struct $name(pub $t);

        impl $name {
            $(pub const $variant: $name = $name($value);)+
        }
        unsafe impl ::RtValueType for $name {}
    };
}

macro_rules! RT_STRUCT {
    { struct $name:ident { $($field:ident: $ftype:ty,)* }} => {
        #[repr(C)] #[derive(Debug,Copy,Clone)]
        pub struct $name {
            $(pub $field: $ftype,)*
        }
        unsafe impl ::RtValueType for $name {}
    };
}

macro_rules! RT_PINTERFACE {
    (
        for $t:ty => [$l:expr, $w1:expr, $w2:expr, $b1:expr, $b2:expr, $b3:expr, $b4:expr, $b5:expr,
        $b6:expr, $b7:expr, $b8:expr] as $iid:ident
    ) => {
        DEFINE_IID!($iid, $l,$w1,$w2,$b1,$b2,$b3,$b4,$b5,$b6,$b7,$b8);
        impl ComIid for $t {
            #[inline] fn iid() -> &'static ::Guid { &$iid }
        }
    };
}

pub mod handler;
pub mod async;
pub mod gen; // import auto-generated definitions (has to come after macro definitions)

// FIXME: maybe better reexport from winapi?
DEFINE_IID!(IID_IInspectable, 0xAF86E2E0, 0xB12D, 0x4c6a, 0x9C, 0x5A, 0xD7, 0xAA, 0x65, 0x10, 0x1E, 0x90);
RT_INTERFACE!{
/// The `IInspectable` interface is the base interface for all Windows Runtime classes.
interface IInspectable(IInspectableVtbl): IUnknown(IUnknownVtbl) [IID_IInspectable]  {
    fn GetIids(&self, iidCount: *mut ULONG, iids: *mut *mut IID) -> HRESULT,
    fn GetRuntimeClassName(&self, className: *mut HSTRING) -> HRESULT,
    fn GetTrustLevel(&self, trustLevel: *mut ::TrustLevel) -> HRESULT
}}
impl IInspectable {
    /// Returns the interfaces that are implemented by the current Windows Runtime object.
    #[inline]
    pub fn get_iids(&self) -> ComArray<Guid> {
        let mut result = ::std::ptr::null_mut();
        let mut count = 0;
        let hr = unsafe { ((*self.lpVtbl).GetIids)(self as *const _ as *mut _, &mut count, &mut result) };
        assert_eq!(hr, S_OK);
        let result = result as *mut Guid; // convert from ::w::GUID to (binary compatible) Guid
        unsafe { ComArray::from_raw(count, result) }
    }

    /// Returns the trust level of the current Windows Runtime object.
    #[inline]
    pub fn get_trust_level(&self) -> ::TrustLevel {
        let mut result = unsafe { ::std::mem::zeroed() };
        let hr = unsafe { ((*self.lpVtbl).GetTrustLevel)(self as *const _ as *mut _, &mut result) };
        assert_eq!(hr, S_OK);
        result
    }
}

impl ::comptr::HiddenGetRuntimeClassName for IInspectable {
    #[inline]
    fn get_runtime_class_name(&self) -> HString {
        let mut result = ::std::ptr::null_mut();
        let hr = unsafe { ((*self.lpVtbl).GetRuntimeClassName)(self as *const _ as *mut _, &mut result) };
        assert_eq!(hr, S_OK);
        unsafe { HString::wrap(result) }
    }
}

DEFINE_IID!(IID_IActivationFactory, 0x00000035, 0x0000, 0x0000, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46);
RT_INTERFACE!{
/// Enables classes to be activated using a default constructor.
/// This interface should not be used directly, but the `new()` method of
/// the `RtDefaultConstructible` trait should be used instead.
interface IActivationFactory(IActivationFactoryVtbl): IInspectable(IInspectableVtbl) [IID_IActivationFactory]  {
    fn ActivateInstance(&self, instance: *mut *mut IInspectable) -> HRESULT
}}

impl IActivationFactory {
    #[inline]
    pub fn activate_instance(&self) -> ComPtr<IInspectable> {
        let mut result = ::std::ptr::null_mut();
        let hr = unsafe { ((*self.lpVtbl).ActivateInstance)(self as *const _ as *mut _, &mut result) };
        assert_eq!(hr, S_OK);
        unsafe { ComPtr::wrap(result) }
    }
}

DEFINE_IID!(IID_IMemoryBufferByteAccess, 0x5b0d3235, 0x4dba, 0x4d44, 0x86, 0x5e, 0x8f, 0x1d, 0x0e, 0x4f, 0xd0, 0x4d);
RT_INTERFACE!{
/// Provides direct byte access to the memory buffer underlying an `IMemoryBuffer`.
interface IMemoryBufferByteAccess(IMemoryBufferByteAccessVtbl) : IUnknown(IUnknownVtbl) [IID_IMemoryBufferByteAccess]  {
    fn GetBuffer(&self, value: *mut *mut u8, capacity: *mut u32) -> HRESULT
}}

impl IMemoryBufferByteAccess {
    /// Provides direct byte access to the memory buffer underlying an `IMemoryBuffer`.
    /// To use `IMemoryBufferByteAccess`, you first need to obtain an `IMemoryBufferReference`, then
    /// call `query_interface::<IMemoryBufferByteAccess>()` on that.
    ///
    /// This method is marked `unsafe`, because the buffer might be invalidated during its lifetime.
    /// Due to the nature of COM objects, the buffer might be referenced and modified or closed
    /// by some other instance, which Rust's type system cannot know about. The `Close` event on
    /// `IMemoryBufferReference` can be used to be notified when the buffer is closed.
    ///
    /// An empty slice is returned if the underlying buffer has already been closed.
    #[inline]
    pub unsafe fn get_buffer(&self) -> &[u8] {
        let mut ptr = ::std::ptr::null_mut();
        let mut capacity: u32 = 0;
        let hr = ((*self.lpVtbl).GetBuffer)(self as *const _ as *mut _, &mut ptr, &mut capacity);
        assert_eq!(hr, S_OK);
        if capacity == 0 {
            ptr = 1 as *mut u8; // null pointer is not allowed
        }
        ::std::slice::from_raw_parts(ptr, capacity as usize)
    }
}

/// Determines the concurrency model used for incoming calls to the objects created by a thread
/// that was initialized with a given apartment type (see also `init_apartment`).
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
#[repr(u32)]
pub enum ApartmentType {
    /// Initializes the thread in the multi-threaded apartment (MTA).
    MTA = RO_INIT_MULTITHREADED,
    
    /// Initializes the thread as a single-threaded apartment (STA).
    STA = RO_INIT_SINGLETHREADED
}

/// Initializes the current thread for use with the Windows Runtime. This is usually not needed,
/// because winrt-rust ensures that threads are implicitly assigned to the multi-threaded apartment (MTA).
/// However, if you need your thread to be initialized as a single-threaded apartment (STA), you can
/// call `init_apartment(ApartmentType::STA)`. Only call this when you own the thread!
pub fn init_apartment(apartment_type: ApartmentType) {
    let hr = unsafe { RoInitialize(apartment_type as u32) };
    assert!(hr == S_OK || hr == S_FALSE, "failed to call RoInitialize: error {}", hr);
}

/// Uninitializes the Windows Runtime in the current thread. This is usually not
/// needed, because uninitialization happens automatically on process termination.
/// Make sure that you never call this from a thread that still has references to
/// Windows Runtime objects.
pub fn uninit_apartment() {
    unsafe { RoUninitialize() };
}