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
/// This module contains COM object for accessing the Windows Virtual Desktop API
use super::interfaces::*;
use super::Result;
use std::convert::TryFrom;
use std::rc::Rc;
use std::{cell::RefCell, ffi::c_void};
use windows::core::ComInterface;
use windows::core::HRESULT;
use windows::Win32::Foundation::HWND;
use windows::Win32::System::Com::CoIncrementMTAUsage;
use windows::Win32::System::Com::CLSCTX_LOCAL_SERVER;
use windows::{
    core::{Interface, GUID, HSTRING},
    Win32::{System::Com::CoCreateInstance, UI::Shell::Common::IObjectArray},
};

#[cfg(debug_assertions)]
use crate::log::log_output;

type WCHAR = u16;
type APPIDPWSTR = *const WCHAR;

#[derive(Debug, PartialEq, Clone)]
pub enum Error {
    /// Window is not found
    WindowNotFound,

    /// Desktop with given ID is not found
    DesktopNotFound,

    /// Creationg of desktop failed
    CreateDesktopFailed,

    /// Remove desktop failed
    RemoveDesktopFailed,

    /// Unable to create service, ensure that explorer.exe is running
    ClassNotRegistered,

    /// Unable to connect to service
    RpcServerNotAvailable,

    /// Com is not initialized, call CoInitializeEx or CoIncrementMTAUsage
    ComNotInitialized,

    /// Com object not connected
    ComObjectNotConnected,

    /// Generic element not found
    ComElementNotFound,

    /// Some unhandled COM error
    ComError(HRESULT),

    /// This should not happen, this means that successful COM call allocated a
    /// null pointer, in this case it is an error in the COM service, or it's
    /// usage.
    ComAllocatedNullPtr,

    /// Borrow error
    InternalBorrowError,
}

trait HRESULTHelpers {
    fn as_error(&self) -> Error;
    fn as_result(&self) -> Result<()>;
}

impl HRESULTHelpers for ::windows::core::HRESULT {
    fn as_error(&self) -> Error {
        if self.0 == -2147221164 {
            // 0x80040154
            return Error::ClassNotRegistered;
        }
        if self.0 == -2147023174 {
            // 0x800706BA
            return Error::RpcServerNotAvailable;
        }
        if self.0 == -2147220995 {
            // 0x800401FD
            return Error::ComObjectNotConnected;
        }
        if self.0 == -2147319765 {
            // 0x8002802B
            return Error::ComElementNotFound;
        }
        if self.0 == -2147221008 {
            // 0x800401F0
            return Error::ComNotInitialized;
        }
        Error::ComError(self.clone())
    }

    fn as_result(&self) -> Result<()> {
        if self.is_ok() {
            return Ok(());
        }
        Err(self.as_error())
    }
}

impl From<::windows::core::Error> for Error {
    fn from(r: ::windows::core::Error) -> Self {
        r.code().as_error()
    }
}

#[derive(Copy, Clone, Debug)]
pub enum DesktopInternal {
    Index(u32),
    Guid(GUID),
    IndexGuid(u32, GUID),
}

// Impl from u32 to DesktopTest
impl From<u32> for DesktopInternal {
    fn from(index: u32) -> Self {
        DesktopInternal::Index(index)
    }
}

// Impl from i32 to DesktopTest
impl From<i32> for DesktopInternal {
    fn from(index: i32) -> Self {
        DesktopInternal::Index(index as u32)
    }
}

// Impl from GUID to DesktopTest
impl From<GUID> for DesktopInternal {
    fn from(guid: GUID) -> Self {
        DesktopInternal::Guid(guid)
    }
}

// Impl from &GUID to DesktopTest
impl From<&GUID> for DesktopInternal {
    fn from(guid: &GUID) -> Self {
        DesktopInternal::Guid(*guid)
    }
}

impl<'a> TryFrom<&'a IVirtualDesktop> for DesktopInternal {
    type Error = Error;

    fn try_from(desktop: &'a IVirtualDesktop) -> Result<Self> {
        let mut guid = GUID::default();
        unsafe { desktop.get_id(&mut guid).as_result()? }
        Ok(DesktopInternal::Guid(guid))
    }
}
impl<'a> TryFrom<&'a ComIn<'a, IVirtualDesktop>> for DesktopInternal {
    type Error = Error;

    fn try_from(desktop: &'a ComIn<'a, IVirtualDesktop>) -> Result<Self> {
        let mut guid = GUID::default();
        unsafe { desktop.get_id(&mut guid).as_result()? }
        Ok(DesktopInternal::Guid(guid))
    }
}

pub struct ComObjects {
    provider: RefCell<Option<Rc<IServiceProvider>>>,
    manager: RefCell<Option<Rc<IVirtualDesktopManager>>>,
    manager_internal: RefCell<Option<Rc<IVirtualDesktopManagerInternal>>>,
    notification_service: RefCell<Option<Rc<IVirtualDesktopNotificationService>>>,
    pinned_apps: RefCell<Option<Rc<IVirtualDesktopPinnedApps>>>,
    view_collection: RefCell<Option<Rc<IApplicationViewCollection>>>,
}

fn retry_function<F, R>(com_objects: &ComObjects, f: F) -> Result<R>
where
    F: Fn() -> Result<R>,
{
    let mut value = f();
    for _ in 0..3 {
        match &value {
            Err(er)
                if er == &Error::ClassNotRegistered
                    || er == &Error::RpcServerNotAvailable
                    || er == &Error::ComObjectNotConnected
                    || er == &Error::ComAllocatedNullPtr
                    || er == &Error::ComNotInitialized =>
            {
                #[cfg(debug_assertions)]
                log_output(&format!("Retry the function after {:?}", er));

                if er == &Error::ComNotInitialized {
                    let _ = unsafe { CoIncrementMTAUsage() };
                }

                drop(value);

                // If private function is decorated, then this drop_services call
                // will cause borrow issues.
                com_objects.drop_services();

                value = f();
            }
            _ => {
                break;
            }
        }
    }

    #[cfg(debug_assertions)]
    if let Err(er) = &value {
        log_output(&format!("Com_objects function failed with {:?}", er));
    }

    value
}

/// Safely reruns the function if it returns one of the recoverable errors
///
/// This should be applied to only public functions in ComObjects struct, having
/// it in private functions is not necessary. Decorating private functions will
/// also cause borrowing issues.
macro_rules! retry_function {(
    $( #[$attr:meta] )*
    $pub:vis
    fn $fname:ident (
        &$self_:ident $(,)? $( $arg_name:ident : $ArgTy:ty ),* $(,)?
    ) -> $RetTy:ty
    $body:block
) => (
    $( #[$attr] )*
    #[allow(unused_parens)]
    $pub
    fn $fname (
        &$self_, $( $arg_name : $ArgTy ),*
    ) -> $RetTy
    {
        retry_function(&$self_, || -> $RetTy {
            $body
        })
    }
)}

impl ComObjects {
    pub fn new() -> Self {
        Self {
            provider: RefCell::new(None),
            manager: RefCell::new(None),
            manager_internal: RefCell::new(None),
            notification_service: RefCell::new(None),
            pinned_apps: RefCell::new(None),
            view_collection: RefCell::new(None),
        }
    }

    fn get_provider(&self) -> Result<Rc<IServiceProvider>> {
        let mut provider = self
            .provider
            .try_borrow_mut()
            .map_err(|_| Error::InternalBorrowError)?;
        if provider.is_none() {
            let new_provider = Rc::new(unsafe {
                CoCreateInstance(&CLSID_ImmersiveShell, None, CLSCTX_LOCAL_SERVER)?
            });
            *provider = Some(new_provider);
        }

        provider
            .as_ref()
            .map(|v| Rc::clone(&v))
            .ok_or(Error::ComAllocatedNullPtr)
    }

    fn get_manager(&self) -> Result<Rc<IVirtualDesktopManager>> {
        let mut manager = self
            .manager
            .try_borrow_mut()
            .map_err(|_| Error::InternalBorrowError)?;
        if manager.is_none() {
            let provider = self.get_provider()?;
            let mut obj = std::ptr::null_mut::<c_void>();
            unsafe {
                provider
                    .query_service(
                        &IVirtualDesktopManager::IID,
                        &IVirtualDesktopManager::IID,
                        &mut obj,
                    )
                    .as_result()?;
            }
            assert_eq!(obj.is_null(), false);
            *manager = Some(Rc::new(unsafe { IVirtualDesktopManager::from_raw(obj) }));
        }
        manager
            .as_ref()
            .map(|v| Rc::clone(&v))
            .ok_or(Error::ComAllocatedNullPtr)
    }

    fn get_manager_internal(&self) -> Result<Rc<IVirtualDesktopManagerInternal>> {
        let mut manager_internal = self
            .manager_internal
            .try_borrow_mut()
            .map_err(|_| Error::InternalBorrowError)?;
        if manager_internal.is_none() {
            let mut obj = std::ptr::null_mut::<c_void>();
            let provider = self.get_provider()?;
            unsafe {
                provider
                    .query_service(
                        &CLSID_VirtualDesktopManagerInternal,
                        &IVirtualDesktopManagerInternal::IID,
                        &mut obj,
                    )
                    .as_result()?;
            }
            assert_eq!(obj.is_null(), false);
            *manager_internal = Some(Rc::new(unsafe {
                IVirtualDesktopManagerInternal::from_raw(obj)
            }));
        }
        manager_internal
            .as_ref()
            .map(|v| Rc::clone(&v))
            .ok_or(Error::ComAllocatedNullPtr)
    }

    fn get_notification_service(&self) -> Result<Rc<IVirtualDesktopNotificationService>> {
        let mut notification_service = self
            .notification_service
            .try_borrow_mut()
            .map_err(|_| Error::InternalBorrowError)?;
        if notification_service.is_none() {
            let provider = self.get_provider()?;
            let mut obj = std::ptr::null_mut::<c_void>();
            unsafe {
                provider
                    .query_service(
                        &CLSID_IVirtualNotificationService,
                        &IVirtualDesktopNotificationService::IID,
                        &mut obj,
                    )
                    .as_result()?;
            }
            assert_eq!(obj.is_null(), false);
            *notification_service = Some(Rc::new(unsafe {
                IVirtualDesktopNotificationService::from_raw(obj)
            }));
        }
        notification_service
            .as_ref()
            .map(|v| Rc::clone(&v))
            .ok_or(Error::ComAllocatedNullPtr)
    }

    fn get_pinned_apps(&self) -> Result<Rc<IVirtualDesktopPinnedApps>> {
        let mut pinned_apps = self
            .pinned_apps
            .try_borrow_mut()
            .map_err(|_| Error::InternalBorrowError)?;
        if pinned_apps.is_none() {
            let provider = self.get_provider()?;
            let mut obj = std::ptr::null_mut::<c_void>();
            unsafe {
                provider
                    .query_service(
                        &CLSID_VirtualDesktopPinnedApps,
                        &IVirtualDesktopPinnedApps::IID,
                        &mut obj,
                    )
                    .as_result()?;
            }
            assert_eq!(obj.is_null(), false);
            *pinned_apps = Some(Rc::new(unsafe { IVirtualDesktopPinnedApps::from_raw(obj) }));
        }
        pinned_apps
            .as_ref()
            .ok_or(Error::ComAllocatedNullPtr)
            .map(|a| Rc::clone(a))
    }

    fn get_view_collection(&self) -> Result<Rc<IApplicationViewCollection>> {
        let mut view_collection = self
            .view_collection
            .try_borrow_mut()
            .map_err(|_| Error::InternalBorrowError)?;
        if view_collection.is_none() {
            let provider = self.get_provider()?;
            let mut obj = std::ptr::null_mut::<c_void>();
            unsafe {
                provider
                    .query_service(
                        &IApplicationViewCollection::IID,
                        &IApplicationViewCollection::IID,
                        &mut obj,
                    )
                    .as_result()?;
            }
            assert_eq!(obj.is_null(), false);
            *view_collection = Some(Rc::new(unsafe {
                IApplicationViewCollection::from_raw(obj)
            }));
        }
        view_collection
            .as_ref()
            .map(|v| Rc::clone(&v))
            .ok_or(Error::ComAllocatedNullPtr)
    }

    fn drop_services(&self) {
        // Current implementation would be safe drop like this, but in case I
        // ever refactor I don't use this:

        // drop(self.provider.take());
        // drop(self.manager.take());
        // drop(self.manager_internal.take());

        // Instead I use try_borrow_mut() and map() to drop services.
        let _ = self.provider.try_borrow_mut().map(|mut v| v.take());
        let _ = self.manager.try_borrow_mut().map(|mut v| v.take());
        let _ = self.manager_internal.try_borrow_mut().map(|mut v| v.take());
        let _ = self
            .notification_service
            .try_borrow_mut()
            .map(|mut v| v.take());
        let _ = self.pinned_apps.try_borrow_mut().map(|mut v| v.take());
        let _ = self.view_collection.try_borrow_mut().map(|mut v| v.take());
    }

    pub(crate) fn is_connected(&self) -> bool {
        // TODO: What is a best way to check if service is connected?

        // Calling any method yields an error if service is not connected.
        //
        // I call get_count method, if it's well implemented it should be just
        // like returning a value, not allocating anything.
        match self.get_manager_internal() {
            Ok(manager_internal) => {
                let mut out_count = 0;
                let res = unsafe {
                    manager_internal
                        .get_desktop_count(&mut out_count)
                        .as_result()
                };

                #[cfg(debug_assertions)]
                if let Err(er) = &res {
                    log_output(&format!("is connected error: {:?} {}", er, out_count));
                }

                if out_count == 0 || res.is_err() {
                    return false;
                }
                return true;
            }
            Err(_) => false,
        }
    }

    fn get_idesktops_array(&self) -> Result<IObjectArray> {
        let mut desktops = None;
        unsafe {
            self.get_manager_internal()?
                .get_desktops(&mut desktops)
                .as_result()?
        }
        desktops.ok_or(Error::ComAllocatedNullPtr)
    }

    fn get_desktop_index_by_guid(&self, id: &GUID) -> Result<u32> {
        let desktops = self.get_idesktops_array()?;
        let count = unsafe { desktops.GetCount()? };
        for i in 0..count {
            let desktop_id: GUID = get_idesktop_guid(&unsafe { desktops.GetAt(i)? })?;
            if desktop_id == *id {
                return Ok(i);
            }
        }
        Err(Error::DesktopNotFound)
    }

    fn get_desktop_guid_by_index(&self, id: u32) -> Result<GUID> {
        let desktops = self.get_idesktops_array()?;
        let count = unsafe { desktops.GetCount()? };
        if id >= count {
            return Err(Error::DesktopNotFound);
        }
        get_idesktop_guid(&unsafe { desktops.GetAt(id)? })
    }

    fn get_idesktop(&self, desktop: &DesktopInternal) -> Result<IVirtualDesktop> {
        match desktop {
            DesktopInternal::Index(id) => {
                let desktops = self.get_idesktops_array()?;
                let count = unsafe { desktops.GetCount()? };
                if *id >= count {
                    return Err(Error::DesktopNotFound);
                }
                Ok(unsafe { desktops.GetAt(*id)? })
            }
            DesktopInternal::Guid(id) => {
                let manager = self.get_manager_internal()?;
                let mut desktop = None;
                unsafe {
                    manager.find_desktop(id, &mut desktop).as_result()?;
                }
                desktop.ok_or(Error::DesktopNotFound)
            }
            DesktopInternal::IndexGuid(_, id) => {
                let manager = self.get_manager_internal()?;
                let mut desktop = None;
                unsafe {
                    manager.find_desktop(id, &mut desktop).as_result()?;
                }
                desktop.ok_or(Error::DesktopNotFound)
            }
        }
    }

    fn move_view_to_desktop(
        &self,
        view: ComIn<IApplicationView>,
        desktop: &DesktopInternal,
    ) -> Result<()> {
        let desktop = self.get_idesktop(desktop)?;
        unsafe {
            self.get_manager_internal()?
                .move_view_to_desktop(view, ComIn::new(&desktop))
                .as_result()
                .map_err(|e| {
                    if e == Error::ComElementNotFound {
                        Error::DesktopNotFound
                    } else {
                        e
                    }
                })?
        }
        Ok(())
    }

    fn get_iapplication_view_for_hwnd(&self, hwnd: &HWND) -> Result<IApplicationView> {
        let mut view = None;
        unsafe {
            self.get_view_collection()?
                .get_view_for_hwnd(hwnd.clone(), &mut view)
                .as_result()
                .map_err(|er| {
                    if er == Error::ComElementNotFound {
                        Error::WindowNotFound
                    } else {
                        er
                    }
                })?
        }
        view.ok_or(Error::WindowNotFound)
    }

    #[apply(retry_function)]
    pub fn get_desktop_index(&self, id: &DesktopInternal) -> Result<u32> {
        match id {
            DesktopInternal::Index(id) => Ok(*id),
            DesktopInternal::Guid(guid) => self.get_desktop_index_by_guid(guid),
            DesktopInternal::IndexGuid(id, _) => Ok(*id),
        }
    }

    #[apply(retry_function)]
    pub fn get_desktop_id(&self, desktop: &DesktopInternal) -> Result<GUID> {
        match desktop {
            DesktopInternal::Index(id) => self.get_desktop_guid_by_index(*id),
            DesktopInternal::Guid(guid) => Ok(*guid),
            DesktopInternal::IndexGuid(_, guid) => Ok(*guid),
        }
    }

    #[apply(retry_function)]
    pub fn get_desktops(&self) -> Result<Vec<DesktopInternal>> {
        let desktops = self.get_idesktops_array()?;
        let count = unsafe { desktops.GetCount()? };
        let mut result = Vec::with_capacity(count as usize);
        for i in 0..count {
            let desktop = unsafe { desktops.GetAt(i)? };
            let id = get_idesktop_guid(&desktop)?;
            result.push(DesktopInternal::IndexGuid(i, id));
        }
        Ok(result)
    }

    #[apply(retry_function)]
    pub fn register_for_notifications(
        &self,
        // notification: &IVirtualDesktopNotification,
        notification: *mut c_void, // IVirtualDesktopNotification raw pointer
    ) -> Result<u32> {
        let notification_service = self.get_notification_service()?;

        unsafe {
            let mut cookie = 0;
            notification_service
                .register(notification, &mut cookie)
                .as_result()
                .map(|_| cookie)
        }
    }

    #[apply(retry_function)]
    pub fn unregister_for_notifications(&self, cookie: u32) -> Result<()> {
        let notification_service = self.get_notification_service()?;
        unsafe { notification_service.unregister(cookie).as_result() }
    }

    #[apply(retry_function)]
    pub fn switch_desktop(&self, desktop: &DesktopInternal) -> Result<()> {
        let desktop = self.get_idesktop(desktop)?;
        unsafe {
            self.get_manager_internal()?
                .switch_desktop(ComIn::new(&desktop))
                .as_result()?
        }
        Ok(())
    }

    #[apply(retry_function)]
    pub fn create_desktop(&self) -> Result<DesktopInternal> {
        let mut desktop = None;
        unsafe {
            self.get_manager_internal()?
                .create_desktop(&mut desktop)
                .as_result()?
        }
        let desktop = desktop.ok_or(Error::ComAllocatedNullPtr)?;
        let id = get_idesktop_guid(&desktop)?;
        let index = self.get_desktop_index_by_guid(&id)?;
        Ok(DesktopInternal::IndexGuid(index, id))
    }

    #[apply(retry_function)]
    pub fn remove_desktop(
        &self,
        desktop: &DesktopInternal,
        fallback_desktop: &DesktopInternal,
    ) -> Result<()> {
        let desktop = self.get_idesktop(desktop)?;
        let fb_desktop = self.get_idesktop(fallback_desktop)?;
        unsafe {
            self.get_manager_internal()?
                .remove_desktop(ComIn::new(&desktop), ComIn::new(&fb_desktop))
                .as_result()?
        }
        Ok(())
    }

    #[apply(retry_function)]
    pub fn is_window_on_desktop(&self, window: &HWND, desktop: &DesktopInternal) -> Result<bool> {
        let desktop_win = self.get_desktop_by_window(window)?;
        Ok(self.get_desktop_id(&desktop_win)? == self.get_desktop_id(&*desktop)?)
    }

    #[apply(retry_function)]
    pub fn is_window_on_current_desktop(&self, window: &HWND) -> Result<bool> {
        unsafe {
            let mut value = false;
            self.get_manager()?
                .is_window_on_current_desktop(window.clone(), &mut value)
                .as_result()
                .map_err(|er| match er {
                    // Window does not exist
                    Error::ComElementNotFound => Error::WindowNotFound,
                    _ => er,
                })?;
            Ok(value)
        }
    }

    #[apply(retry_function)]
    pub fn move_window_to_desktop(&self, window: &HWND, desktop: &DesktopInternal) -> Result<()> {
        let view = self.get_iapplication_view_for_hwnd(window)?;
        self.move_view_to_desktop(ComIn::new(&view), desktop)
    }

    #[apply(retry_function)]
    pub fn get_desktop_count(&self) -> Result<u32> {
        let manager = self.get_manager_internal()?;
        let mut count = 0;
        unsafe {
            manager.get_desktop_count(&mut count).as_result()?;
        };
        Ok(count)
    }

    #[apply(retry_function)]
    pub fn get_desktop_by_window(&self, window: &HWND) -> Result<DesktopInternal> {
        let mut desktop = GUID::default();
        unsafe {
            self.get_manager()?
                .get_desktop_by_window(window.clone(), &mut desktop)
                .as_result()
                .map_err(|er| match er {
                    // Window does not exist
                    Error::ComElementNotFound => Error::WindowNotFound,
                    _ => er,
                })?
        };
        if desktop == GUID::default() {
            return Err(Error::WindowNotFound);
        }
        Ok(DesktopInternal::Guid(desktop))
    }

    #[apply(retry_function)]
    pub fn get_current_desktop(&self) -> Result<DesktopInternal> {
        let mut desktop = None;
        unsafe {
            self.get_manager_internal()?
                .get_current_desktop(&mut desktop)
                .as_result()?
        }
        let desktop = desktop.ok_or(Error::ComAllocatedNullPtr)?;
        let id = get_idesktop_guid(&desktop)?;
        Ok(DesktopInternal::Guid(id))
    }

    #[apply(retry_function)]
    pub fn is_pinned_window(&self, window: &HWND) -> Result<bool> {
        let view = self.get_iapplication_view_for_hwnd(window)?;
        unsafe {
            let mut value = false;
            self.get_pinned_apps()?
                .is_view_pinned(ComIn::new(&view), &mut value)
                .as_result()?;
            Ok(value)
        }
    }

    #[apply(retry_function)]
    pub fn pin_window(&self, window: &HWND) -> Result<()> {
        let view = self.get_iapplication_view_for_hwnd(window)?;
        unsafe {
            self.get_pinned_apps()?
                .pin_view(ComIn::new(&view))
                .as_result()?;
        }
        Ok(())
    }

    #[apply(retry_function)]
    pub fn unpin_window(&self, window: &HWND) -> Result<()> {
        let view = self.get_iapplication_view_for_hwnd(window)?;
        unsafe {
            self.get_pinned_apps()?
                .unpin_view(ComIn::new(&view))
                .as_result()?;
        }
        Ok(())
    }

    #[apply(retry_function)]
    fn get_iapplication_id_for_view(&self, view: &IApplicationView) -> Result<APPIDPWSTR> {
        let mut app_id: APPIDPWSTR = std::ptr::null_mut();
        unsafe {
            view.get_app_user_model_id(&mut app_id as *mut _ as *mut _)
                .as_result()?
        }
        Ok(app_id)
    }

    #[apply(retry_function)]
    pub fn is_pinned_app(&self, window: &HWND) -> Result<bool> {
        let view = self.get_iapplication_view_for_hwnd(window)?;
        let app_id = self.get_iapplication_id_for_view(&view)?;
        unsafe {
            let mut value = false;
            self.get_pinned_apps()?
                .is_app_pinned(app_id, &mut value)
                .as_result()?;
            Ok(value)
        }
    }

    #[apply(retry_function)]
    pub fn pin_app(&self, window: &HWND) -> Result<()> {
        let view = self.get_iapplication_view_for_hwnd(window)?;
        let app_id = self.get_iapplication_id_for_view(&view)?;
        unsafe {
            self.get_pinned_apps()?.pin_app(app_id).as_result()?;
        }
        Ok(())
    }

    #[apply(retry_function)]
    pub fn unpin_app(&self, window: &HWND) -> Result<()> {
        let view = self.get_iapplication_view_for_hwnd(window)?;
        let app_id = self.get_iapplication_id_for_view(&view)?;
        unsafe {
            self.get_pinned_apps()?.unpin_app(app_id).as_result()?;
        }
        Ok(())
    }

    #[apply(retry_function)]
    pub fn get_desktop_name(&self, desktop: &DesktopInternal) -> Result<String> {
        let desktop = self.get_idesktop(&desktop)?;
        let mut name = HSTRING::default();
        unsafe {
            desktop.get_name(&mut name).as_result()?;
        }
        Ok(name.to_string())
    }

    #[apply(retry_function)]
    pub fn set_desktop_name(&self, desktop: &DesktopInternal, name: &str) -> Result<()> {
        let desktop = self.get_idesktop(&desktop)?;
        let manager_internal = self.get_manager_internal()?;

        unsafe {
            manager_internal
                .set_name(ComIn::new(&desktop), HSTRING::from(name))
                .as_result()
        }
    }

    #[apply(retry_function)]
    pub fn get_desktop_wallpaper(&self, desktop: &DesktopInternal) -> Result<String> {
        let desktop = self.get_idesktop(&desktop)?;
        let mut path = HSTRING::default();
        unsafe {
            desktop.get_wallpaper(&mut path).as_result()?;
        }
        Ok(path.to_string())
    }

    #[apply(retry_function)]
    pub fn set_desktop_wallpaper(&self, desktop: &DesktopInternal, path: &str) -> Result<()> {
        let manager_internal = self.get_manager_internal()?;
        let desktop = self.get_idesktop(&desktop)?;
        unsafe {
            manager_internal
                .set_wallpaper(ComIn::new(&desktop), HSTRING::from(path))
                .as_result()
        }
    }
}

fn get_idesktop_guid(desktop: &IVirtualDesktop) -> Result<GUID> {
    let mut guid = GUID::default();
    unsafe { desktop.get_id(&mut guid).as_result()? }
    Ok(guid)
}

thread_local! {
    static COM_OBJECTS: ComObjects = ComObjects::new();
}

/// This is a helper function to initialize and run COM related functions in a
/// a single thread.
///
/// Virtual Desktop COM Objects don't like to being called from different
/// threads rapidly, something goes wrong. This function ensures that all COM
/// calls are done in a single thread.
pub fn with_com_objects<F, T>(f: F) -> Result<T>
where
    F: Fn(&ComObjects) -> Result<T> + 'static,
    T: 'static,
{
    // return std::thread::scope(|env| {
    //     let com2 = ComObjects::new();
    //     run_function_and_retry(&f, &com2)
    // });

    // return COM_OBJECTS.with(|c| run_function_and_retry(&f, &c));
    return COM_OBJECTS.with(|c| f(&c));
}