VirtualBox

source: vbox/trunk/src/VBox/Additions/WINNT/VBoxTray/VBoxTray.cpp@ 99739

Last change on this file since 99739 was 99739, checked in by vboxsync, 12 months ago

*: doxygen corrections (mostly about removing @returns from functions returning void).

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 46.3 KB
Line 
1/* $Id: VBoxTray.cpp 99739 2023-05-11 01:01:08Z vboxsync $ */
2/** @file
3 * VBoxTray - Guest Additions Tray Application
4 */
5
6/*
7 * Copyright (C) 2006-2023 Oracle and/or its affiliates.
8 *
9 * This file is part of VirtualBox base platform packages, as
10 * available from https://www.virtualbox.org.
11 *
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation, in version 3 of the
15 * License.
16 *
17 * This program is distributed in the hope that it will be useful, but
18 * WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * General Public License for more details.
21 *
22 * You should have received a copy of the GNU General Public License
23 * along with this program; if not, see <https://www.gnu.org/licenses>.
24 *
25 * SPDX-License-Identifier: GPL-3.0-only
26 */
27
28
29/*********************************************************************************************************************************
30* Header Files *
31*********************************************************************************************************************************/
32#include <package-generated.h>
33#include "product-generated.h"
34
35#include "VBoxTray.h"
36#include "VBoxTrayInternal.h"
37#include "VBoxTrayMsg.h"
38#include "VBoxHelpers.h"
39#include "VBoxSeamless.h"
40#include "VBoxClipboard.h"
41#include "VBoxDisplay.h"
42#include "VBoxVRDP.h"
43#include "VBoxHostVersion.h"
44#ifdef VBOX_WITH_DRAG_AND_DROP
45# include "VBoxDnD.h"
46#endif
47#include "VBoxIPC.h"
48#include "VBoxLA.h"
49#include <VBoxHook.h>
50
51#include <sddl.h>
52
53#include <iprt/asm.h>
54#include <iprt/buildconfig.h>
55#include <iprt/getopt.h>
56#include <iprt/ldr.h>
57#include <iprt/message.h>
58#include <iprt/path.h>
59#include <iprt/process.h>
60#include <iprt/system.h>
61#include <iprt/time.h>
62#include <iprt/utf16.h>
63
64#include <VBox/log.h>
65#include <VBox/err.h>
66
67
68/*********************************************************************************************************************************
69* Internal Functions *
70*********************************************************************************************************************************/
71static void VBoxGrapicsSetSupported(BOOL fSupported);
72static int vboxTrayCreateTrayIcon(void);
73static LRESULT CALLBACK vboxToolWndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam);
74
75/* Global message handler prototypes. */
76static int vboxTrayGlMsgTaskbarCreated(WPARAM lParam, LPARAM wParam);
77
78
79/*********************************************************************************************************************************
80* Global Variables *
81*********************************************************************************************************************************/
82int g_cVerbosity = 0;
83HANDLE g_hStopSem;
84HANDLE g_hSeamlessWtNotifyEvent = 0;
85HANDLE g_hSeamlessKmNotifyEvent = 0;
86HINSTANCE g_hInstance = NULL;
87HWND g_hwndToolWindow;
88NOTIFYICONDATA g_NotifyIconData;
89
90uint32_t g_fGuestDisplaysChanged = 0;
91
92static PRTLOGGER g_pLoggerRelease = NULL; /**< This is actually the debug logger in DEBUG builds! */
93static uint32_t g_cHistory = 10; /**< Enable log rotation, 10 files. */
94static uint32_t g_uHistoryFileTime = RT_SEC_1DAY; /**< Max 1 day per file. */
95static uint64_t g_uHistoryFileSize = 100 * _1M; /**< Max 100MB per file. */
96
97#ifdef DEBUG_andy
98static VBOXSERVICEINFO g_aServices[] =
99{
100 {&g_SvcDescDnD, NIL_RTTHREAD, NULL, false, false, false, false, true }
101};
102#else
103/**
104 * The details of the services that has been compiled in.
105 */
106static VBOXSERVICEINFO g_aServices[] =
107{
108 { &g_SvcDescDisplay, NIL_RTTHREAD, NULL, false, false, false, false, true },
109#ifdef VBOX_WITH_SHARED_CLIPBOARD
110 { &g_SvcDescClipboard, NIL_RTTHREAD, NULL, false, false, false, false, true },
111#endif
112 { &g_SvcDescSeamless, NIL_RTTHREAD, NULL, false, false, false, false, true },
113 { &g_SvcDescVRDP, NIL_RTTHREAD, NULL, false, false, false, false, true },
114 { &g_SvcDescIPC, NIL_RTTHREAD, NULL, false, false, false, false, true },
115 { &g_SvcDescLA, NIL_RTTHREAD, NULL, false, false, false, false, true },
116#ifdef VBOX_WITH_DRAG_AND_DROP
117 { &g_SvcDescDnD, NIL_RTTHREAD, NULL, false, false, false, false, true }
118#endif
119};
120#endif
121
122/* The global message table. */
123static VBOXGLOBALMESSAGE g_vboxGlobalMessageTable[] =
124{
125 /* Windows specific stuff. */
126 {
127 "TaskbarCreated",
128 vboxTrayGlMsgTaskbarCreated
129 },
130
131 /* VBoxTray specific stuff. */
132 /** @todo Add new messages here! */
133
134 {
135 NULL
136 }
137};
138
139/**
140 * Gets called whenever the Windows main taskbar
141 * get (re-)created. Nice to install our tray icon.
142 *
143 * @return IPRT status code.
144 * @param wParam
145 * @param lParam
146 */
147static int vboxTrayGlMsgTaskbarCreated(WPARAM wParam, LPARAM lParam)
148{
149 RT_NOREF(wParam, lParam);
150 return vboxTrayCreateTrayIcon();
151}
152
153static int vboxTrayCreateTrayIcon(void)
154{
155 HICON hIcon = LoadIcon(g_hInstance, "IDI_ICON1"); /* see Artwork/win/TemplateR3.rc */
156 if (hIcon == NULL)
157 {
158 DWORD dwErr = GetLastError();
159 LogFunc(("Could not load tray icon, error %08X\n", dwErr));
160 return RTErrConvertFromWin32(dwErr);
161 }
162
163 /* Prepare the system tray icon. */
164 RT_ZERO(g_NotifyIconData);
165 g_NotifyIconData.cbSize = NOTIFYICONDATA_V1_SIZE; // sizeof(NOTIFYICONDATA);
166 g_NotifyIconData.hWnd = g_hwndToolWindow;
167 g_NotifyIconData.uID = ID_TRAYICON;
168 g_NotifyIconData.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
169 g_NotifyIconData.uCallbackMessage = WM_VBOXTRAY_TRAY_ICON;
170 g_NotifyIconData.hIcon = hIcon;
171
172 RTStrPrintf(g_NotifyIconData.szTip, sizeof(g_NotifyIconData.szTip), "%s Guest Additions %d.%d.%dr%d",
173 VBOX_PRODUCT, VBOX_VERSION_MAJOR, VBOX_VERSION_MINOR, VBOX_VERSION_BUILD, VBOX_SVN_REV);
174
175 int rc = VINF_SUCCESS;
176 if (!Shell_NotifyIcon(NIM_ADD, &g_NotifyIconData))
177 {
178 DWORD dwErr = GetLastError();
179 LogFunc(("Could not create tray icon, error=%ld\n", dwErr));
180 rc = RTErrConvertFromWin32(dwErr);
181 RT_ZERO(g_NotifyIconData);
182 }
183
184 if (hIcon)
185 DestroyIcon(hIcon);
186 return rc;
187}
188
189static void vboxTrayRemoveTrayIcon(void)
190{
191 if (g_NotifyIconData.cbSize > 0)
192 {
193 /* Remove the system tray icon and refresh system tray. */
194 Shell_NotifyIcon(NIM_DELETE, &g_NotifyIconData);
195 HWND hTrayWnd = FindWindow("Shell_TrayWnd", NULL); /* We assume we only have one tray atm. */
196 if (hTrayWnd)
197 {
198 HWND hTrayNotifyWnd = FindWindowEx(hTrayWnd, 0, "TrayNotifyWnd", NULL);
199 if (hTrayNotifyWnd)
200 SendMessage(hTrayNotifyWnd, WM_PAINT, 0, NULL);
201 }
202 RT_ZERO(g_NotifyIconData);
203 }
204}
205
206/**
207 * The service thread.
208 *
209 * @returns Whatever the worker function returns.
210 * @param ThreadSelf My thread handle.
211 * @param pvUser The service index.
212 */
213static DECLCALLBACK(int) vboxTrayServiceThread(RTTHREAD ThreadSelf, void *pvUser)
214{
215 PVBOXSERVICEINFO pSvc = (PVBOXSERVICEINFO)pvUser;
216 AssertPtr(pSvc);
217
218#ifndef RT_OS_WINDOWS
219 /*
220 * Block all signals for this thread. Only the main thread will handle signals.
221 */
222 sigset_t signalMask;
223 sigfillset(&signalMask);
224 pthread_sigmask(SIG_BLOCK, &signalMask, NULL);
225#endif
226
227 int rc = pSvc->pDesc->pfnWorker(pSvc->pInstance, &pSvc->fShutdown);
228 ASMAtomicXchgBool(&pSvc->fShutdown, true);
229 RTThreadUserSignal(ThreadSelf);
230
231 LogFunc(("Worker for '%s' ended with %Rrc\n", pSvc->pDesc->pszName, rc));
232 return rc;
233}
234
235static int vboxTrayServicesStart(PVBOXSERVICEENV pEnv)
236{
237 AssertPtrReturn(pEnv, VERR_INVALID_POINTER);
238
239 LogRel(("Starting services ...\n"));
240
241 int rc = VINF_SUCCESS;
242
243 for (unsigned i = 0; i < RT_ELEMENTS(g_aServices); i++)
244 {
245 PVBOXSERVICEINFO pSvc = &g_aServices[i];
246 LogRel(("Starting service '%s' ...\n", pSvc->pDesc->pszName));
247
248 pSvc->hThread = NIL_RTTHREAD;
249 pSvc->pInstance = NULL;
250 pSvc->fStarted = false;
251 pSvc->fShutdown = false;
252
253 int rc2 = VINF_SUCCESS;
254
255 if (pSvc->pDesc->pfnInit)
256 rc2 = pSvc->pDesc->pfnInit(pEnv, &pSvc->pInstance);
257
258 if (RT_FAILURE(rc2))
259 {
260 switch (rc2)
261 {
262 case VERR_NOT_SUPPORTED:
263 LogRel(("Service '%s' is not supported on this system\n", pSvc->pDesc->pszName));
264 rc2 = VINF_SUCCESS; /* Keep going. */
265 break;
266
267 case VERR_HGCM_SERVICE_NOT_FOUND:
268 LogRel(("Service '%s' is not available on the host\n", pSvc->pDesc->pszName));
269 rc2 = VINF_SUCCESS; /* Keep going. */
270 break;
271
272 default:
273 LogRel(("Failed to initialize service '%s', rc=%Rrc\n", pSvc->pDesc->pszName, rc2));
274 break;
275 }
276 }
277 else
278 {
279 if (pSvc->pDesc->pfnWorker)
280 {
281 rc2 = RTThreadCreate(&pSvc->hThread, vboxTrayServiceThread, pSvc /* pvUser */,
282 0 /* Default stack size */, RTTHREADTYPE_DEFAULT, RTTHREADFLAGS_WAITABLE, pSvc->pDesc->pszName);
283 if (RT_SUCCESS(rc2))
284 {
285 pSvc->fStarted = true;
286
287 RTThreadUserWait(pSvc->hThread, 30 * 1000 /* Timeout in ms */);
288 if (pSvc->fShutdown)
289 {
290 LogRel(("Service '%s' failed to start!\n", pSvc->pDesc->pszName));
291 rc = VERR_GENERAL_FAILURE;
292 }
293 else
294 LogRel(("Service '%s' started\n", pSvc->pDesc->pszName));
295 }
296 else
297 {
298 LogRel(("Failed to start thread for service '%s': %Rrc\n", rc2));
299 if (pSvc->pDesc->pfnDestroy)
300 pSvc->pDesc->pfnDestroy(pSvc->pInstance);
301 }
302 }
303 }
304
305 if (RT_SUCCESS(rc))
306 rc = rc2;
307 }
308
309 if (RT_SUCCESS(rc))
310 LogRel(("All services started\n"));
311 else
312 LogRel(("Services started, but some with errors\n"));
313
314 LogFlowFuncLeaveRC(rc);
315 return rc;
316}
317
318static int vboxTrayServicesStop(VBOXSERVICEENV *pEnv)
319{
320 AssertPtrReturn(pEnv, VERR_INVALID_POINTER);
321
322 LogRel2(("Stopping all services ...\n"));
323
324 /*
325 * Signal all the services.
326 */
327 for (unsigned i = 0; i < RT_ELEMENTS(g_aServices); i++)
328 ASMAtomicWriteBool(&g_aServices[i].fShutdown, true);
329
330 /*
331 * Do the pfnStop callback on all running services.
332 */
333 for (unsigned i = 0; i < RT_ELEMENTS(g_aServices); i++)
334 {
335 PVBOXSERVICEINFO pSvc = &g_aServices[i];
336 if ( pSvc->fStarted
337 && pSvc->pDesc->pfnStop)
338 {
339 LogRel2(("Calling stop function for service '%s' ...\n", pSvc->pDesc->pszName));
340 int rc2 = pSvc->pDesc->pfnStop(pSvc->pInstance);
341 if (RT_FAILURE(rc2))
342 LogRel(("Failed to stop service '%s': %Rrc\n", pSvc->pDesc->pszName, rc2));
343 }
344 }
345
346 LogRel2(("All stop functions for services called\n"));
347
348 int rc = VINF_SUCCESS;
349
350 /*
351 * Wait for all the service threads to complete.
352 */
353 for (unsigned i = 0; i < RT_ELEMENTS(g_aServices); i++)
354 {
355 PVBOXSERVICEINFO pSvc = &g_aServices[i];
356 if (!pSvc->fEnabled) /* Only stop services which were started before. */
357 continue;
358
359 if (pSvc->hThread != NIL_RTTHREAD)
360 {
361 LogRel2(("Waiting for service '%s' to stop ...\n", pSvc->pDesc->pszName));
362 int rc2 = VINF_SUCCESS;
363 for (int j = 0; j < 30; j++) /* Wait 30 seconds in total */
364 {
365 rc2 = RTThreadWait(pSvc->hThread, 1000 /* Wait 1 second */, NULL);
366 if (RT_SUCCESS(rc2))
367 break;
368 }
369 if (RT_FAILURE(rc2))
370 {
371 LogRel(("Service '%s' failed to stop (%Rrc)\n", pSvc->pDesc->pszName, rc2));
372 if (RT_SUCCESS(rc))
373 rc = rc2;
374 }
375 }
376
377 if ( pSvc->pDesc->pfnDestroy
378 && pSvc->pInstance) /* pInstance might be NULL if initialization of a service failed. */
379 {
380 LogRel2(("Terminating service '%s' ...\n", pSvc->pDesc->pszName));
381 pSvc->pDesc->pfnDestroy(pSvc->pInstance);
382 }
383 }
384
385 if (RT_SUCCESS(rc))
386 LogRel(("All services stopped\n"));
387
388 LogFlowFuncLeaveRC(rc);
389 return rc;
390}
391
392static int vboxTrayRegisterGlobalMessages(PVBOXGLOBALMESSAGE pTable)
393{
394 int rc = VINF_SUCCESS;
395 if (pTable == NULL) /* No table to register? Skip. */
396 return rc;
397 while ( pTable->pszName
398 && RT_SUCCESS(rc))
399 {
400 /* Register global accessible window messages. */
401 pTable->uMsgID = RegisterWindowMessage(TEXT(pTable->pszName));
402 if (!pTable->uMsgID)
403 {
404 DWORD dwErr = GetLastError();
405 Log(("Registering global message \"%s\" failed, error = %08X\n", dwErr));
406 rc = RTErrConvertFromWin32(dwErr);
407 }
408
409 /* Advance to next table element. */
410 pTable++;
411 }
412 return rc;
413}
414
415static bool vboxTrayHandleGlobalMessages(PVBOXGLOBALMESSAGE pTable, UINT uMsg,
416 WPARAM wParam, LPARAM lParam)
417{
418 if (pTable == NULL)
419 return false;
420 while (pTable && pTable->pszName)
421 {
422 if (pTable->uMsgID == uMsg)
423 {
424 if (pTable->pfnHandler)
425 pTable->pfnHandler(wParam, lParam);
426 return true;
427 }
428
429 /* Advance to next table element. */
430 pTable++;
431 }
432 return false;
433}
434
435/**
436 * Header/footer callback for the release logger.
437 *
438 * @param pLoggerRelease
439 * @param enmPhase
440 * @param pfnLog
441 */
442static DECLCALLBACK(void) vboxTrayLogHeaderFooter(PRTLOGGER pLoggerRelease, RTLOGPHASE enmPhase, PFNRTLOGPHASEMSG pfnLog)
443{
444 /* Some introductory information. */
445 static RTTIMESPEC s_TimeSpec;
446 char szTmp[256];
447 if (enmPhase == RTLOGPHASE_BEGIN)
448 RTTimeNow(&s_TimeSpec);
449 RTTimeSpecToString(&s_TimeSpec, szTmp, sizeof(szTmp));
450
451 switch (enmPhase)
452 {
453 case RTLOGPHASE_BEGIN:
454 {
455 pfnLog(pLoggerRelease,
456 "VBoxTray %s r%s %s (%s %s) release log\n"
457 "Log opened %s\n",
458 RTBldCfgVersion(), RTBldCfgRevisionStr(), VBOX_BUILD_TARGET,
459 __DATE__, __TIME__, szTmp);
460
461 int vrc = RTSystemQueryOSInfo(RTSYSOSINFO_PRODUCT, szTmp, sizeof(szTmp));
462 if (RT_SUCCESS(vrc) || vrc == VERR_BUFFER_OVERFLOW)
463 pfnLog(pLoggerRelease, "OS Product: %s\n", szTmp);
464 vrc = RTSystemQueryOSInfo(RTSYSOSINFO_RELEASE, szTmp, sizeof(szTmp));
465 if (RT_SUCCESS(vrc) || vrc == VERR_BUFFER_OVERFLOW)
466 pfnLog(pLoggerRelease, "OS Release: %s\n", szTmp);
467 vrc = RTSystemQueryOSInfo(RTSYSOSINFO_VERSION, szTmp, sizeof(szTmp));
468 if (RT_SUCCESS(vrc) || vrc == VERR_BUFFER_OVERFLOW)
469 pfnLog(pLoggerRelease, "OS Version: %s\n", szTmp);
470 if (RT_SUCCESS(vrc) || vrc == VERR_BUFFER_OVERFLOW)
471 pfnLog(pLoggerRelease, "OS Service Pack: %s\n", szTmp);
472
473 /* the package type is interesting for Linux distributions */
474 char szExecName[RTPATH_MAX];
475 char *pszExecName = RTProcGetExecutablePath(szExecName, sizeof(szExecName));
476 pfnLog(pLoggerRelease,
477 "Executable: %s\n"
478 "Process ID: %u\n"
479 "Package type: %s"
480#ifdef VBOX_OSE
481 " (OSE)"
482#endif
483 "\n",
484 pszExecName ? pszExecName : "unknown",
485 RTProcSelf(),
486 VBOX_PACKAGE_STRING);
487 break;
488 }
489
490 case RTLOGPHASE_PREROTATE:
491 pfnLog(pLoggerRelease, "Log rotated - Log started %s\n", szTmp);
492 break;
493
494 case RTLOGPHASE_POSTROTATE:
495 pfnLog(pLoggerRelease, "Log continuation - Log started %s\n", szTmp);
496 break;
497
498 case RTLOGPHASE_END:
499 pfnLog(pLoggerRelease, "End of log file - Log started %s\n", szTmp);
500 break;
501
502 default:
503 /* nothing */;
504 }
505}
506
507/**
508 * Creates the default release logger outputting to the specified file.
509 *
510 * @return IPRT status code.
511 * @param pszLogFile Path to log file to use.
512 */
513static int vboxTrayLogCreate(const char *pszLogFile)
514{
515 /* Create release (or debug) logger (stdout + file). */
516 static const char * const s_apszGroups[] = VBOX_LOGGROUP_NAMES;
517 static const char s_szEnvVarPfx[] = "VBOXTRAY_RELEASE_LOG";
518
519 RTERRINFOSTATIC ErrInfo;
520 int rc = RTLogCreateEx(&g_pLoggerRelease, s_szEnvVarPfx,
521 RTLOGFLAGS_PREFIX_THREAD | RTLOGFLAGS_PREFIX_TIME_PROG | RTLOGFLAGS_USECRLF,
522 "all.e", RT_ELEMENTS(s_apszGroups), s_apszGroups, UINT32_MAX,
523 0 /*cBufDescs*/, NULL /*paBufDescs*/, RTLOGDEST_STDOUT,
524 vboxTrayLogHeaderFooter, g_cHistory, g_uHistoryFileSize, g_uHistoryFileTime,
525 NULL /*pOutputIf*/, NULL /*pvOutputIfUser*/,
526 RTErrInfoInitStatic(&ErrInfo), "%s", pszLogFile ? pszLogFile : "");
527 if (RT_SUCCESS(rc))
528 {
529 /* Register this logger as the release logger. */
530 RTLogRelSetDefaultInstance(g_pLoggerRelease);
531
532 /* Register this logger as the _debug_ logger. */
533 RTLogSetDefaultInstance(g_pLoggerRelease);
534
535 const char *apszGroups[] = { "all", "guest_dnd" }; /* All groups we want to enable logging for VBoxTray. */
536 char szGroupSettings[_1K];
537
538 szGroupSettings[0] = '\0';
539
540 for (size_t i = 0; i < RT_ELEMENTS(apszGroups); i++)
541 {
542 if (i > 0)
543 rc = RTStrCat(szGroupSettings, sizeof(szGroupSettings), "+");
544 if (RT_SUCCESS(rc))
545 rc = RTStrCat(szGroupSettings, sizeof(szGroupSettings), apszGroups[i]);
546 if (RT_FAILURE(rc))
547 break;
548
549 switch (g_cVerbosity)
550 {
551 case 1:
552 rc = RTStrCat(szGroupSettings, sizeof(szGroupSettings), ".e.l");
553 break;
554
555 case 2:
556 rc = RTStrCat(szGroupSettings, sizeof(szGroupSettings), ".e.l.l2");
557 break;
558
559 case 3:
560 rc = RTStrCat(szGroupSettings, sizeof(szGroupSettings), ".e.l.l2.l3");
561 break;
562
563 case 4:
564 RT_FALL_THROUGH();
565 default:
566 rc = RTStrCat(szGroupSettings, sizeof(szGroupSettings), ".e.l.l2.l3.f");
567 break;
568 }
569
570 if (RT_FAILURE(rc))
571 break;
572 }
573
574 LogRel(("Verbose log settings are: %s\n", szGroupSettings));
575
576 if (RT_SUCCESS(rc))
577 rc = RTLogGroupSettings(g_pLoggerRelease, szGroupSettings);
578 if (RT_FAILURE(rc))
579 RTMsgError("Setting log group settings failed, rc=%Rrc\n", rc);
580
581 /* Explicitly flush the log in case of VBOXTRAY_RELEASE_LOG=buffered. */
582 RTLogFlush(g_pLoggerRelease);
583 }
584 else
585 VBoxTrayShowError(ErrInfo.szMsg);
586
587 return rc;
588}
589
590static void vboxTrayLogDestroy(void)
591{
592 /* Only want to destroy the release logger before calling exit(). The debug
593 logger can be useful after that point... */
594 RTLogDestroy(RTLogRelSetDefaultInstance(NULL));
595}
596
597/**
598 * Displays an error message.
599 *
600 * @returns RTEXITCODE_FAILURE.
601 * @param pszFormat The message text.
602 * @param ... Format arguments.
603 */
604RTEXITCODE VBoxTrayShowError(const char *pszFormat, ...)
605{
606 va_list args;
607 va_start(args, pszFormat);
608 char *psz = NULL;
609 RTStrAPrintfV(&psz, pszFormat, args);
610 va_end(args);
611
612 AssertPtr(psz);
613 LogRel(("Error: %s", psz));
614
615 MessageBox(GetDesktopWindow(), psz, "VBoxTray - Error", MB_OK | MB_ICONERROR);
616
617 RTStrFree(psz);
618
619 return RTEXITCODE_FAILURE;
620}
621
622static void vboxTrayDestroyToolWindow(void)
623{
624 if (g_hwndToolWindow)
625 {
626 Log(("Destroying tool window ...\n"));
627
628 /* Destroy the tool window. */
629 DestroyWindow(g_hwndToolWindow);
630 g_hwndToolWindow = NULL;
631
632 UnregisterClass("VBoxTrayToolWndClass", g_hInstance);
633 }
634}
635
636static int vboxTrayCreateToolWindow(void)
637{
638 DWORD dwErr = ERROR_SUCCESS;
639
640 /* Create a custom window class. */
641 WNDCLASSEX wc = { 0 };
642 wc.cbSize = sizeof(WNDCLASSEX);
643 wc.style = CS_NOCLOSE;
644 wc.lpfnWndProc = (WNDPROC)vboxToolWndProc;
645 wc.hInstance = g_hInstance;
646 wc.hCursor = LoadCursor(NULL, IDC_ARROW);
647 wc.lpszClassName = "VBoxTrayToolWndClass";
648
649 if (!RegisterClassEx(&wc))
650 {
651 dwErr = GetLastError();
652 Log(("Registering invisible tool window failed, error = %08X\n", dwErr));
653 }
654 else
655 {
656 /*
657 * Create our (invisible) tool window.
658 * Note: The window name ("VBoxTrayToolWnd") and class ("VBoxTrayToolWndClass") is
659 * needed for posting globally registered messages to VBoxTray and must not be
660 * changed! Otherwise things get broken!
661 *
662 */
663 g_hwndToolWindow = CreateWindowEx(WS_EX_TOOLWINDOW | WS_EX_TRANSPARENT | WS_EX_TOPMOST,
664 "VBoxTrayToolWndClass", "VBoxTrayToolWnd",
665 WS_POPUPWINDOW,
666 -200, -200, 100, 100, NULL, NULL, g_hInstance, NULL);
667 if (!g_hwndToolWindow)
668 {
669 dwErr = GetLastError();
670 Log(("Creating invisible tool window failed, error = %08X\n", dwErr));
671 }
672 else
673 {
674 /* Reload the cursor(s). */
675 hlpReloadCursor();
676
677 Log(("Invisible tool window handle = %p\n", g_hwndToolWindow));
678 }
679 }
680
681 if (dwErr != ERROR_SUCCESS)
682 vboxTrayDestroyToolWindow();
683 return RTErrConvertFromWin32(dwErr);
684}
685
686static int vboxTraySetupSeamless(void)
687{
688 /* We need to setup a security descriptor to allow other processes modify access to the seamless notification event semaphore. */
689 SECURITY_ATTRIBUTES SecAttr;
690 DWORD dwErr = ERROR_SUCCESS;
691 char secDesc[SECURITY_DESCRIPTOR_MIN_LENGTH];
692 BOOL fRC;
693
694 SecAttr.nLength = sizeof(SecAttr);
695 SecAttr.bInheritHandle = FALSE;
696 SecAttr.lpSecurityDescriptor = &secDesc;
697 InitializeSecurityDescriptor(SecAttr.lpSecurityDescriptor, SECURITY_DESCRIPTOR_REVISION);
698 fRC = SetSecurityDescriptorDacl(SecAttr.lpSecurityDescriptor, TRUE, 0, FALSE);
699 if (!fRC)
700 {
701 dwErr = GetLastError();
702 Log(("SetSecurityDescriptorDacl failed with last error = %08X\n", dwErr));
703 }
704 else
705 {
706 /* For Vista and up we need to change the integrity of the security descriptor, too. */
707 uint64_t const uNtVersion = RTSystemGetNtVersion();
708 if (uNtVersion >= RTSYSTEM_MAKE_NT_VERSION(6, 0, 0))
709 {
710 BOOL (WINAPI * pfnConvertStringSecurityDescriptorToSecurityDescriptorA)(LPCSTR StringSecurityDescriptor, DWORD StringSDRevision, PSECURITY_DESCRIPTOR *SecurityDescriptor, PULONG SecurityDescriptorSize);
711 *(void **)&pfnConvertStringSecurityDescriptorToSecurityDescriptorA =
712 RTLdrGetSystemSymbol("advapi32.dll", "ConvertStringSecurityDescriptorToSecurityDescriptorA");
713 Log(("pfnConvertStringSecurityDescriptorToSecurityDescriptorA = %p\n",
714 RT_CB_LOG_CAST(pfnConvertStringSecurityDescriptorToSecurityDescriptorA)));
715 if (pfnConvertStringSecurityDescriptorToSecurityDescriptorA)
716 {
717 PSECURITY_DESCRIPTOR pSD;
718 PACL pSacl = NULL;
719 BOOL fSaclPresent = FALSE;
720 BOOL fSaclDefaulted = FALSE;
721
722 fRC = pfnConvertStringSecurityDescriptorToSecurityDescriptorA("S:(ML;;NW;;;LW)", /* this means "low integrity" */
723 SDDL_REVISION_1, &pSD, NULL);
724 if (!fRC)
725 {
726 dwErr = GetLastError();
727 Log(("ConvertStringSecurityDescriptorToSecurityDescriptorA failed with last error = %08X\n", dwErr));
728 }
729 else
730 {
731 fRC = GetSecurityDescriptorSacl(pSD, &fSaclPresent, &pSacl, &fSaclDefaulted);
732 if (!fRC)
733 {
734 dwErr = GetLastError();
735 Log(("GetSecurityDescriptorSacl failed with last error = %08X\n", dwErr));
736 }
737 else
738 {
739 fRC = SetSecurityDescriptorSacl(SecAttr.lpSecurityDescriptor, TRUE, pSacl, FALSE);
740 if (!fRC)
741 {
742 dwErr = GetLastError();
743 Log(("SetSecurityDescriptorSacl failed with last error = %08X\n", dwErr));
744 }
745 }
746 }
747 }
748 }
749
750 if ( dwErr == ERROR_SUCCESS
751 && uNtVersion >= RTSYSTEM_MAKE_NT_VERSION(5, 0, 0)) /* Only for W2K and up ... */
752 {
753 g_hSeamlessWtNotifyEvent = CreateEvent(&SecAttr, FALSE, FALSE, VBOXHOOK_GLOBAL_WT_EVENT_NAME);
754 if (g_hSeamlessWtNotifyEvent == NULL)
755 {
756 dwErr = GetLastError();
757 Log(("CreateEvent for Seamless failed, last error = %08X\n", dwErr));
758 }
759
760 g_hSeamlessKmNotifyEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
761 if (g_hSeamlessKmNotifyEvent == NULL)
762 {
763 dwErr = GetLastError();
764 Log(("CreateEvent for Seamless failed, last error = %08X\n", dwErr));
765 }
766 }
767 }
768 return RTErrConvertFromWin32(dwErr);
769}
770
771static void vboxTrayShutdownSeamless(void)
772{
773 if (g_hSeamlessWtNotifyEvent)
774 {
775 CloseHandle(g_hSeamlessWtNotifyEvent);
776 g_hSeamlessWtNotifyEvent = NULL;
777 }
778
779 if (g_hSeamlessKmNotifyEvent)
780 {
781 CloseHandle(g_hSeamlessKmNotifyEvent);
782 g_hSeamlessKmNotifyEvent = NULL;
783 }
784}
785
786static int vboxTrayServiceMain(void)
787{
788 int rc = VINF_SUCCESS;
789 LogFunc(("Entering vboxTrayServiceMain\n"));
790
791 g_hStopSem = CreateEvent(NULL, TRUE, FALSE, NULL);
792 if (g_hStopSem == NULL)
793 {
794 rc = RTErrConvertFromWin32(GetLastError());
795 LogFunc(("CreateEvent for stopping VBoxTray failed, rc=%Rrc\n", rc));
796 }
797 else
798 {
799 /*
800 * Start services listed in the vboxServiceTable.
801 */
802 VBOXSERVICEENV svcEnv;
803 svcEnv.hInstance = g_hInstance;
804
805 /* Initializes disp-if to default (XPDM) mode. */
806 VBoxDispIfInit(&svcEnv.dispIf); /* Cannot fail atm. */
807 #ifdef VBOX_WITH_WDDM
808 /*
809 * For now the display mode will be adjusted to WDDM mode if needed
810 * on display service initialization when it detects the display driver type.
811 */
812 #endif
813
814 /* Finally start all the built-in services! */
815 rc = vboxTrayServicesStart(&svcEnv);
816 if (RT_FAILURE(rc))
817 {
818 /* Terminate service if something went wrong. */
819 vboxTrayServicesStop(&svcEnv);
820 }
821 else
822 {
823 uint64_t const uNtVersion = RTSystemGetNtVersion();
824 rc = vboxTrayCreateTrayIcon();
825 if ( RT_SUCCESS(rc)
826 && uNtVersion >= RTSYSTEM_MAKE_NT_VERSION(5, 0, 0)) /* Only for W2K and up ... */
827 {
828 /* We're ready to create the tooltip balloon.
829 Check in 10 seconds (@todo make seconds configurable) ... */
830 SetTimer(g_hwndToolWindow,
831 TIMERID_VBOXTRAY_CHECK_HOSTVERSION,
832 10 * 1000, /* 10 seconds */
833 NULL /* No timerproc */);
834 }
835
836 if (RT_SUCCESS(rc))
837 {
838 /* Report the host that we're up and running! */
839 hlpReportStatus(VBoxGuestFacilityStatus_Active);
840 }
841
842 if (RT_SUCCESS(rc))
843 {
844 /* Boost thread priority to make sure we wake up early for seamless window notifications
845 * (not sure if it actually makes any difference though). */
846 SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_HIGHEST);
847
848 /*
849 * Main execution loop
850 * Wait for the stop semaphore to be posted or a window event to arrive
851 */
852
853 HANDLE hWaitEvent[4] = {0};
854 DWORD dwEventCount = 0;
855
856 hWaitEvent[dwEventCount++] = g_hStopSem;
857
858 /* Check if seamless mode is not active and add seamless event to the list */
859 if (0 != g_hSeamlessWtNotifyEvent)
860 {
861 hWaitEvent[dwEventCount++] = g_hSeamlessWtNotifyEvent;
862 }
863
864 if (0 != g_hSeamlessKmNotifyEvent)
865 {
866 hWaitEvent[dwEventCount++] = g_hSeamlessKmNotifyEvent;
867 }
868
869 if (0 != vboxDtGetNotifyEvent())
870 {
871 hWaitEvent[dwEventCount++] = vboxDtGetNotifyEvent();
872 }
873
874 LogFlowFunc(("Number of events to wait in main loop: %ld\n", dwEventCount));
875 while (true)
876 {
877 DWORD waitResult = MsgWaitForMultipleObjectsEx(dwEventCount, hWaitEvent, 500, QS_ALLINPUT, 0);
878 waitResult = waitResult - WAIT_OBJECT_0;
879
880 /* Only enable for message debugging, lots of traffic! */
881 //Log(("Wait result = %ld\n", waitResult));
882
883 if (waitResult == 0)
884 {
885 LogFunc(("Event 'Exit' triggered\n"));
886 /* exit */
887 break;
888 }
889 else
890 {
891 BOOL fHandled = FALSE;
892 if (waitResult < RT_ELEMENTS(hWaitEvent))
893 {
894 if (hWaitEvent[waitResult])
895 {
896 if (hWaitEvent[waitResult] == g_hSeamlessWtNotifyEvent)
897 {
898 LogFunc(("Event 'Seamless' triggered\n"));
899
900 /* seamless window notification */
901 VBoxSeamlessCheckWindows(false);
902 fHandled = TRUE;
903 }
904 else if (hWaitEvent[waitResult] == g_hSeamlessKmNotifyEvent)
905 {
906 LogFunc(("Event 'Km Seamless' triggered\n"));
907
908 /* seamless window notification */
909 VBoxSeamlessCheckWindows(true);
910 fHandled = TRUE;
911 }
912 else if (hWaitEvent[waitResult] == vboxDtGetNotifyEvent())
913 {
914 LogFunc(("Event 'Dt' triggered\n"));
915 vboxDtDoCheck();
916 fHandled = TRUE;
917 }
918 }
919 }
920
921 if (!fHandled)
922 {
923 /* timeout or a window message, handle it */
924 MSG msg;
925 while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
926 {
927#ifdef DEBUG_andy
928 LogFlowFunc(("PeekMessage %u\n", msg.message));
929#endif
930 if (msg.message == WM_QUIT)
931 {
932 LogFunc(("Terminating ...\n"));
933 SetEvent(g_hStopSem);
934 }
935 TranslateMessage(&msg);
936 DispatchMessage(&msg);
937 }
938 }
939 }
940 }
941 LogFunc(("Returned from main loop, exiting ...\n"));
942 }
943 LogFunc(("Waiting for services to stop ...\n"));
944 vboxTrayServicesStop(&svcEnv);
945 } /* Services started */
946 CloseHandle(g_hStopSem);
947 } /* Stop event created */
948
949 vboxTrayRemoveTrayIcon();
950
951 LogFunc(("Leaving with rc=%Rrc\n", rc));
952 return rc;
953}
954
955/**
956 * Main function
957 */
958int main(int cArgs, char **papszArgs)
959{
960 int rc = RTR3InitExe(cArgs, &papszArgs, RTR3INIT_FLAGS_STANDALONE_APP);
961 if (RT_FAILURE(rc))
962 return RTMsgInitFailure(rc);
963
964 /*
965 * Parse the top level arguments until we find a command.
966 */
967 static const RTGETOPTDEF s_aOptions[] =
968 {
969 { "--help", 'h', RTGETOPT_REQ_NOTHING },
970 { "-help", 'h', RTGETOPT_REQ_NOTHING },
971 { "/help", 'h', RTGETOPT_REQ_NOTHING },
972 { "/?", 'h', RTGETOPT_REQ_NOTHING },
973 { "--logfile", 'l', RTGETOPT_REQ_STRING },
974 { "--verbose", 'v', RTGETOPT_REQ_NOTHING },
975 { "--version", 'V', RTGETOPT_REQ_NOTHING },
976 };
977
978 char szLogFile[RTPATH_MAX] = {0};
979
980 RTGETOPTSTATE GetState;
981 rc = RTGetOptInit(&GetState, cArgs, papszArgs, s_aOptions, RT_ELEMENTS(s_aOptions), 1, 0 /*fFlags*/);
982 if (RT_FAILURE(rc))
983 return RTMsgErrorExit(RTEXITCODE_FAILURE, "RTGetOptInit failed: %Rrc\n", rc);
984
985 int ch;
986 RTGETOPTUNION ValueUnion;
987 while ((ch = RTGetOpt(&GetState, &ValueUnion)) != 0)
988 {
989 switch (ch)
990 {
991 case 'h':
992 hlpShowMessageBox(VBOX_PRODUCT " - " VBOX_VBOXTRAY_TITLE,
993 MB_ICONINFORMATION,
994 "-- " VBOX_PRODUCT " %s v%u.%u.%ur%u --\n\n"
995 "Copyright (C) 2009-" VBOX_C_YEAR " " VBOX_VENDOR "\n\n"
996 "Command Line Parameters:\n\n"
997 "-l, --logfile <file>\n"
998 " Enables logging to a file\n"
999 "-v, --verbose\n"
1000 " Increases verbosity\n"
1001 "-V, --version\n"
1002 " Displays version number and exit\n"
1003 "-?, -h, --help\n"
1004 " Displays this help text and exit\n"
1005 "\n"
1006 "Examples:\n"
1007 " %s -vvv\n",
1008 VBOX_VBOXTRAY_TITLE, VBOX_VERSION_MAJOR, VBOX_VERSION_MINOR, VBOX_VERSION_BUILD, VBOX_SVN_REV,
1009 papszArgs[0], papszArgs[0]);
1010 return RTEXITCODE_SUCCESS;
1011
1012 case 'l':
1013 if (*ValueUnion.psz == '\0')
1014 szLogFile[0] = '\0';
1015 else
1016 {
1017 rc = RTPathAbs(ValueUnion.psz, szLogFile, sizeof(szLogFile));
1018 if (RT_FAILURE(rc))
1019 return RTMsgErrorExit(RTEXITCODE_FAILURE, "RTPathAbs failed on log file path: %Rrc (%s)",
1020 rc, ValueUnion.psz);
1021 }
1022 break;
1023
1024 case 'v':
1025 g_cVerbosity++;
1026 break;
1027
1028 case 'V':
1029 hlpShowMessageBox(VBOX_VBOXTRAY_TITLE, MB_ICONINFORMATION,
1030 "Version: %u.%u.%ur%u",
1031 VBOX_VERSION_MAJOR, VBOX_VERSION_MINOR, VBOX_VERSION_BUILD, VBOX_SVN_REV);
1032 return RTEXITCODE_SUCCESS;
1033
1034 default:
1035 rc = RTGetOptPrintError(ch, &ValueUnion);
1036 break;
1037 }
1038 }
1039
1040 /* Note: Do not use a global namespace ("Global\\") for mutex name here,
1041 * will blow up NT4 compatibility! */
1042 HANDLE hMutexAppRunning = CreateMutex(NULL, FALSE, VBOX_VBOXTRAY_TITLE);
1043 if ( hMutexAppRunning != NULL
1044 && GetLastError() == ERROR_ALREADY_EXISTS)
1045 {
1046 /* VBoxTray already running? Bail out. */
1047 CloseHandle (hMutexAppRunning);
1048 hMutexAppRunning = NULL;
1049 return RTEXITCODE_SUCCESS;
1050 }
1051
1052 rc = vboxTrayLogCreate(szLogFile[0] ? szLogFile : NULL);
1053 if (RT_SUCCESS(rc))
1054 {
1055 LogRel(("Verbosity level: %d\n", g_cVerbosity));
1056
1057 rc = VbglR3Init();
1058 if (RT_SUCCESS(rc))
1059 {
1060 /* Log the major windows NT version: */
1061 uint64_t const uNtVersion = RTSystemGetNtVersion();
1062 LogRel(("Windows version %u.%u build %u (uNtVersion=%#RX64)\n", RTSYSTEM_NT_VERSION_GET_MAJOR(uNtVersion),
1063 RTSYSTEM_NT_VERSION_GET_MINOR(uNtVersion), RTSYSTEM_NT_VERSION_GET_BUILD(uNtVersion), uNtVersion ));
1064
1065 /* Set the instance handle. */
1066#ifdef IPRT_NO_CRT
1067 Assert(g_hInstance == NULL); /* Make sure this isn't set before by WinMain(). */
1068 g_hInstance = GetModuleHandleW(NULL);
1069#endif
1070 hlpReportStatus(VBoxGuestFacilityStatus_Init);
1071 rc = vboxTrayCreateToolWindow();
1072 if (RT_SUCCESS(rc))
1073 {
1074 VBoxCapsInit();
1075
1076 rc = vboxStInit(g_hwndToolWindow);
1077 if (!RT_SUCCESS(rc))
1078 {
1079 LogFlowFunc(("vboxStInit failed, rc=%Rrc\n", rc));
1080 /* ignore the St Init failure. this can happen for < XP win that do not support WTS API
1081 * in that case the session is treated as active connected to the physical console
1082 * (i.e. fallback to the old behavior that was before introduction of VBoxSt) */
1083 Assert(vboxStIsActiveConsole());
1084 }
1085
1086 rc = vboxDtInit();
1087 if (!RT_SUCCESS(rc))
1088 {
1089 LogFlowFunc(("vboxDtInit failed, rc=%Rrc\n", rc));
1090 /* ignore the Dt Init failure. this can happen for < XP win that do not support WTS API
1091 * in that case the session is treated as active connected to the physical console
1092 * (i.e. fallback to the old behavior that was before introduction of VBoxSt) */
1093 Assert(vboxDtIsInputDesktop());
1094 }
1095
1096 rc = VBoxAcquireGuestCaps(VMMDEV_GUEST_SUPPORTS_SEAMLESS | VMMDEV_GUEST_SUPPORTS_GRAPHICS, 0, true);
1097 if (!RT_SUCCESS(rc))
1098 LogFlowFunc(("VBoxAcquireGuestCaps failed with rc=%Rrc, ignoring ...\n", rc));
1099
1100 rc = vboxTraySetupSeamless(); /** @todo r=andy Do we really want to be this critical for the whole application? */
1101 if (RT_SUCCESS(rc))
1102 {
1103 rc = vboxTrayServiceMain();
1104 if (RT_SUCCESS(rc))
1105 hlpReportStatus(VBoxGuestFacilityStatus_Terminating);
1106 vboxTrayShutdownSeamless();
1107 }
1108
1109 /* it should be safe to call vboxDtTerm even if vboxStInit above failed */
1110 vboxDtTerm();
1111
1112 /* it should be safe to call vboxStTerm even if vboxStInit above failed */
1113 vboxStTerm();
1114
1115 VBoxCapsTerm();
1116
1117 vboxTrayDestroyToolWindow();
1118 }
1119 if (RT_SUCCESS(rc))
1120 hlpReportStatus(VBoxGuestFacilityStatus_Terminated);
1121 else
1122 {
1123 LogRel(("Error while starting, rc=%Rrc\n", rc));
1124 hlpReportStatus(VBoxGuestFacilityStatus_Failed);
1125 }
1126
1127 LogRel(("Ended\n"));
1128 VbglR3Term();
1129 }
1130 else
1131 LogRel(("VbglR3Init failed: %Rrc\n", rc));
1132 }
1133
1134 /* Release instance mutex. */
1135 if (hMutexAppRunning != NULL)
1136 {
1137 CloseHandle(hMutexAppRunning);
1138 hMutexAppRunning = NULL;
1139 }
1140
1141 vboxTrayLogDestroy();
1142
1143 return RT_SUCCESS(rc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
1144}
1145
1146#ifndef IPRT_NO_CRT
1147int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
1148{
1149 RT_NOREF(hPrevInstance, lpCmdLine, nCmdShow);
1150
1151 g_hInstance = hInstance;
1152
1153 return main(__argc, __argv);
1154}
1155#endif /* IPRT_NO_CRT */
1156
1157/**
1158 * Window procedure for our main tool window.
1159 */
1160static LRESULT CALLBACK vboxToolWndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
1161{
1162 LogFlowFunc(("hWnd=%p, uMsg=%u\n", hWnd, uMsg));
1163
1164 switch (uMsg)
1165 {
1166 case WM_CREATE:
1167 {
1168 LogFunc(("Tool window created\n"));
1169
1170 int rc = vboxTrayRegisterGlobalMessages(&g_vboxGlobalMessageTable[0]);
1171 if (RT_FAILURE(rc))
1172 LogFunc(("Error registering global window messages, rc=%Rrc\n", rc));
1173 return 0;
1174 }
1175
1176 case WM_CLOSE:
1177 return 0;
1178
1179 case WM_DESTROY:
1180 {
1181 LogFunc(("Tool window destroyed\n"));
1182 KillTimer(g_hwndToolWindow, TIMERID_VBOXTRAY_CHECK_HOSTVERSION);
1183 return 0;
1184 }
1185
1186 case WM_TIMER:
1187 {
1188 if (VBoxCapsCheckTimer(wParam))
1189 return 0;
1190 if (vboxDtCheckTimer(wParam))
1191 return 0;
1192 if (vboxStCheckTimer(wParam))
1193 return 0;
1194
1195 switch (wParam)
1196 {
1197 case TIMERID_VBOXTRAY_CHECK_HOSTVERSION:
1198 if (RT_SUCCESS(VBoxCheckHostVersion()))
1199 {
1200 /* After successful run we don't need to check again. */
1201 KillTimer(g_hwndToolWindow, TIMERID_VBOXTRAY_CHECK_HOSTVERSION);
1202 }
1203 return 0;
1204
1205 default:
1206 break;
1207 }
1208
1209 break; /* Make sure other timers get processed the usual way! */
1210 }
1211
1212 case WM_VBOXTRAY_TRAY_ICON:
1213 {
1214 switch (LOWORD(lParam))
1215 {
1216 case WM_LBUTTONDBLCLK:
1217 break;
1218 case WM_RBUTTONDOWN:
1219 {
1220 if (!g_cVerbosity) /* Don't show menu when running in non-verbose mode. */
1221 break;
1222
1223 POINT lpCursor;
1224 if (GetCursorPos(&lpCursor))
1225 {
1226 HMENU hContextMenu = CreatePopupMenu();
1227 if (hContextMenu)
1228 {
1229 UINT_PTR uMenuItem = 9999;
1230 UINT fMenuItem = MF_BYPOSITION | MF_STRING;
1231 if (InsertMenuW(hContextMenu, UINT_MAX, fMenuItem, uMenuItem, L"Exit"))
1232 {
1233 SetForegroundWindow(hWnd);
1234
1235 const bool fBlockWhileTracking = true;
1236
1237 UINT fTrack = TPM_LEFTALIGN | TPM_LEFTBUTTON | TPM_BOTTOMALIGN;
1238
1239 if (fBlockWhileTracking)
1240 fTrack |= TPM_RETURNCMD | TPM_NONOTIFY;
1241
1242 uMsg = TrackPopupMenu(hContextMenu, fTrack, lpCursor.x, lpCursor.y, 0, hWnd, NULL);
1243 if ( uMsg
1244 && fBlockWhileTracking)
1245 {
1246 if (uMsg == uMenuItem)
1247 PostMessage(g_hwndToolWindow, WM_QUIT, 0, 0);
1248 }
1249 else if (!uMsg)
1250 LogFlowFunc(("Tracking popup menu failed with %ld\n", GetLastError()));
1251 }
1252
1253 DestroyMenu(hContextMenu);
1254 }
1255 }
1256 break;
1257 }
1258 }
1259 return 0;
1260 }
1261
1262 case WM_VBOX_SEAMLESS_ENABLE:
1263 {
1264 VBoxCapsEntryFuncStateSet(VBOXCAPS_ENTRY_IDX_SEAMLESS, VBOXCAPS_ENTRY_FUNCSTATE_STARTED);
1265 if (VBoxCapsEntryIsEnabled(VBOXCAPS_ENTRY_IDX_SEAMLESS))
1266 VBoxSeamlessCheckWindows(true);
1267 return 0;
1268 }
1269
1270 case WM_VBOX_SEAMLESS_DISABLE:
1271 {
1272 VBoxCapsEntryFuncStateSet(VBOXCAPS_ENTRY_IDX_SEAMLESS, VBOXCAPS_ENTRY_FUNCSTATE_SUPPORTED);
1273 return 0;
1274 }
1275
1276 case WM_DISPLAYCHANGE:
1277 ASMAtomicUoWriteU32(&g_fGuestDisplaysChanged, 1);
1278 // No break or return is intentional here.
1279 case WM_VBOX_SEAMLESS_UPDATE:
1280 {
1281 if (VBoxCapsEntryIsEnabled(VBOXCAPS_ENTRY_IDX_SEAMLESS))
1282 VBoxSeamlessCheckWindows(true);
1283 return 0;
1284 }
1285
1286 case WM_VBOX_GRAPHICS_SUPPORTED:
1287 {
1288 VBoxGrapicsSetSupported(TRUE);
1289 return 0;
1290 }
1291
1292 case WM_VBOX_GRAPHICS_UNSUPPORTED:
1293 {
1294 VBoxGrapicsSetSupported(FALSE);
1295 return 0;
1296 }
1297
1298 case WM_WTSSESSION_CHANGE:
1299 {
1300 BOOL fOldAllowedState = VBoxConsoleIsAllowed();
1301 if (vboxStHandleEvent(wParam))
1302 {
1303 if (!VBoxConsoleIsAllowed() != !fOldAllowedState)
1304 VBoxConsoleEnable(!fOldAllowedState);
1305 }
1306 return 0;
1307 }
1308
1309 default:
1310 {
1311 /* Handle all globally registered window messages. */
1312 if (vboxTrayHandleGlobalMessages(&g_vboxGlobalMessageTable[0], uMsg,
1313 wParam, lParam))
1314 {
1315 return 0; /* We handled the message. @todo Add return value!*/
1316 }
1317 break; /* We did not handle the message, dispatch to DefWndProc. */
1318 }
1319 }
1320
1321 /* Only if message was *not* handled by our switch above, dispatch to DefWindowProc. */
1322 return DefWindowProc(hWnd, uMsg, wParam, lParam);
1323}
1324
1325static void VBoxGrapicsSetSupported(BOOL fSupported)
1326{
1327 VBoxConsoleCapSetSupported(VBOXCAPS_ENTRY_IDX_GRAPHICS, fSupported);
1328}
1329
Note: See TracBrowser for help on using the repository browser.

© 2023 Oracle
ContactPrivacy policyTerms of Use