Skip to content

Commit

Permalink
Merge pull request #20 from mrob95/com-init-mta
Browse files Browse the repository at this point in the history
Ignore errors in CoInitialize()
  • Loading branch information
mrob95 committed Dec 12, 2022
2 parents fbd45f8 + 6ab4b60 commit c782b25
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 5 deletions.
18 changes: 15 additions & 3 deletions pyvda/utils.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import logging
import threading
from ctypes import POINTER
from comtypes import (
CoInitialize,
CoInitializeEx,
CoCreateInstance,
CLSCTX_LOCAL_SERVER,
)
Expand All @@ -15,13 +16,13 @@
IServiceProvider,
CLSID_ImmersiveShell,
CLSID_VirtualDesktopManagerInternal,
BUILD_OVER_20231,
BUILD_OVER_21313,
)

logger = logging.getLogger(__name__)


def _get_object(cls, clsid = None):
CoInitialize()
pServiceProvider = CoCreateInstance(
CLSID_ImmersiveShell, IServiceProvider, CLSCTX_LOCAL_SERVER
)
Expand Down Expand Up @@ -50,10 +51,21 @@ def get_pinned_apps():

class Managers(threading.local):
def __init__(self):
self.try_init_com()
self.manager_internal = get_vd_manager_internal()
self.view_collection = get_view_collection()
self.pinned_apps = get_pinned_apps()

# Old interface only used for SetName
if not BUILD_OVER_21313:
self.manager_internal2 = get_vd_manager_internal2()

@staticmethod
def try_init_com():
try:
CoInitializeEx()
except OSError as e:
# This is likely because COM has already been initialised with
# COINIT_MULTITHREADED, whereas CoInitialize uses COINIT_APARTMENTTHREADED.
# This should not be a problem for us, so warn and keep going.
logger.warning("Failed to initialise COM: %s", str(e))
18 changes: 16 additions & 2 deletions tests/test_desktop_functions.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
from comtypes import CoInitializeEx, COINIT_MULTITHREADED
from typing import Optional
from pyvda import (
AppView,
VirtualDesktop,
get_virtual_desktops,
get_apps_by_z_order,
set_wallpaper_for_all_desktops
)
import time
import win32gui
Expand Down Expand Up @@ -101,7 +101,6 @@ def test_desktop_names():
current_desktop.rename(current_name)
assert current_desktop.name == current_name, f"Wanted '{current_name}', got '{current_desktop.name}'"


def test_move_and_go_threads():
error: Optional[Exception] = None
def f():
Expand All @@ -115,3 +114,18 @@ def f():
t.join()
if error is not None:
raise error

def test_initialisation_with_com_mta():
error: Optional[Exception] = None
def f():
nonlocal error
try:
CoInitializeEx(COINIT_MULTITHREADED)
test_move_and_go()
except Exception as e:
error = e
t = threading.Thread(target=f)
t.start()
t.join()
if error is not None:
raise error

0 comments on commit c782b25

Please sign in to comment.