VirtualBox

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

Last change on this file since 105915 was 105915, checked in by vboxsync, 3 months ago

Additions/VBoxTray: We need to call VbglR3Init() first before setting up our custom logging for VBoxTray, as VbglR3Init() sets up a default release logger [addendum].

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 47.1 KB
Line 
1/* $Id: VBoxTray.cpp 105915 2024-09-02 10:57:45Z 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_SvcDescClipboard, 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. Can be NULL if not needed.
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#ifdef DEBUG
518 static const char s_szEnvVarPfx[] = "VBOXTRAY_LOG";
519 static const char s_szGroupSettings[] = "all.e.l.f";
520#else
521 static const char s_szEnvVarPfx[] = "VBOXTRAY_RELEASE_LOG";
522 static const char s_szGroupSettings[] = "all";
523#endif
524 RTERRINFOSTATIC ErrInfo;
525 int rc = RTLogCreateEx(&g_pLoggerRelease, s_szEnvVarPfx,
526 RTLOGFLAGS_PREFIX_THREAD | RTLOGFLAGS_PREFIX_TIME_PROG | RTLOGFLAGS_USECRLF,
527 s_szGroupSettings, RT_ELEMENTS(s_apszGroups), s_apszGroups, UINT32_MAX,
528 0 /*cBufDescs*/, NULL /*paBufDescs*/, RTLOGDEST_STDOUT,
529 vboxTrayLogHeaderFooter, g_cHistory, g_uHistoryFileSize, g_uHistoryFileTime,
530 NULL /*pOutputIf*/, NULL /*pvOutputIfUser*/,
531 RTErrInfoInitStatic(&ErrInfo), "%s", pszLogFile ? pszLogFile : "");
532 if (RT_SUCCESS(rc))
533 {
534#ifdef DEBUG
535 /* Register this logger as the _debug_ logger. */
536 RTLogSetDefaultInstance(g_pLoggerRelease);
537#else
538 /* Register this logger as the release logger. */
539 RTLogRelSetDefaultInstance(g_pLoggerRelease);
540#endif
541 /* If verbosity is explicitly set, make sure to increase the logging levels for
542 * the logging groups we offer functionality for in VBoxTray. */
543 if (g_cVerbosity)
544 {
545 /* All groups we want to enable logging for VBoxTray. */
546#ifdef DEBUG
547 const char *apszGroups[] = { "guest_dnd", "shared_clipboard" };
548#else /* For release builds we always want all groups being logged in verbose mode. Don't change this! */
549 const char *apszGroups[] = { "all" };
550#endif
551 char szGroupSettings[_1K];
552
553 szGroupSettings[0] = '\0';
554
555 for (size_t i = 0; i < RT_ELEMENTS(apszGroups); i++)
556 {
557 if (i > 0)
558 rc = RTStrCat(szGroupSettings, sizeof(szGroupSettings), "+");
559 if (RT_SUCCESS(rc))
560 rc = RTStrCat(szGroupSettings, sizeof(szGroupSettings), apszGroups[i]);
561 if (RT_FAILURE(rc))
562 break;
563
564 switch (g_cVerbosity)
565 {
566 case 1:
567 rc = RTStrCat(szGroupSettings, sizeof(szGroupSettings), ".e.l.l2");
568 break;
569
570 case 2:
571 rc = RTStrCat(szGroupSettings, sizeof(szGroupSettings), ".e.l.l2.l3");
572 break;
573
574 case 3:
575 rc = RTStrCat(szGroupSettings, sizeof(szGroupSettings), ".e.l.l2.l3.l4");
576 break;
577
578 case 4:
579 RT_FALL_THROUGH();
580 default:
581 rc = RTStrCat(szGroupSettings, sizeof(szGroupSettings), ".e.l.l2.l3.l4.f");
582 break;
583 }
584
585 if (RT_FAILURE(rc))
586 break;
587 }
588
589 LogRel(("Verbose log settings are: %s\n", szGroupSettings));
590
591 if (RT_SUCCESS(rc))
592 rc = RTLogGroupSettings(g_pLoggerRelease, szGroupSettings);
593 if (RT_FAILURE(rc))
594 RTMsgError("Setting log group settings failed, rc=%Rrc\n", rc);
595 }
596
597 /* Explicitly flush the log in case of VBOXTRAY_RELEASE_LOG=buffered. */
598 RTLogFlush(g_pLoggerRelease);
599 }
600 else
601 VBoxTrayShowError(ErrInfo.szMsg);
602
603 return rc;
604}
605
606static void vboxTrayLogDestroy(void)
607{
608 /* Only want to destroy the release logger before calling exit(). The debug
609 logger can be useful after that point... */
610 RTLogDestroy(RTLogRelSetDefaultInstance(NULL));
611}
612
613/**
614 * Displays an error message.
615 *
616 * @returns RTEXITCODE_FAILURE.
617 * @param pszFormat The message text.
618 * @param ... Format arguments.
619 */
620RTEXITCODE VBoxTrayShowError(const char *pszFormat, ...)
621{
622 va_list args;
623 va_start(args, pszFormat);
624 char *psz = NULL;
625 RTStrAPrintfV(&psz, pszFormat, args);
626 va_end(args);
627
628 AssertPtr(psz);
629 LogRel(("Error: %s", psz));
630
631 MessageBox(GetDesktopWindow(), psz, "VBoxTray - Error", MB_OK | MB_ICONERROR);
632
633 RTStrFree(psz);
634
635 return RTEXITCODE_FAILURE;
636}
637
638static void vboxTrayDestroyToolWindow(void)
639{
640 if (g_hwndToolWindow)
641 {
642 Log(("Destroying tool window ...\n"));
643
644 /* Destroy the tool window. */
645 DestroyWindow(g_hwndToolWindow);
646 g_hwndToolWindow = NULL;
647
648 UnregisterClass("VBoxTrayToolWndClass", g_hInstance);
649 }
650}
651
652static int vboxTrayCreateToolWindow(void)
653{
654 DWORD dwErr = ERROR_SUCCESS;
655
656 /* Create a custom window class. */
657 WNDCLASSEX wc = { 0 };
658 wc.cbSize = sizeof(WNDCLASSEX);
659 wc.style = CS_NOCLOSE;
660 wc.lpfnWndProc = (WNDPROC)vboxToolWndProc;
661 wc.hInstance = g_hInstance;
662 wc.hCursor = LoadCursor(NULL, IDC_ARROW);
663 wc.lpszClassName = "VBoxTrayToolWndClass";
664
665 if (!RegisterClassEx(&wc))
666 {
667 dwErr = GetLastError();
668 Log(("Registering invisible tool window failed, error = %08X\n", dwErr));
669 }
670 else
671 {
672 /*
673 * Create our (invisible) tool window.
674 * Note: The window name ("VBoxTrayToolWnd") and class ("VBoxTrayToolWndClass") is
675 * needed for posting globally registered messages to VBoxTray and must not be
676 * changed! Otherwise things get broken!
677 *
678 */
679 g_hwndToolWindow = CreateWindowEx(WS_EX_TOOLWINDOW | WS_EX_TRANSPARENT | WS_EX_TOPMOST,
680 "VBoxTrayToolWndClass", "VBoxTrayToolWnd",
681 WS_POPUPWINDOW,
682 -200, -200, 100, 100, NULL, NULL, g_hInstance, NULL);
683 if (!g_hwndToolWindow)
684 {
685 dwErr = GetLastError();
686 Log(("Creating invisible tool window failed, error = %08X\n", dwErr));
687 }
688 else
689 {
690 /* Reload the cursor(s). */
691 hlpReloadCursor();
692
693 Log(("Invisible tool window handle = %p\n", g_hwndToolWindow));
694 }
695 }
696
697 if (dwErr != ERROR_SUCCESS)
698 vboxTrayDestroyToolWindow();
699 return RTErrConvertFromWin32(dwErr);
700}
701
702static int vboxTraySetupSeamless(void)
703{
704 /* We need to setup a security descriptor to allow other processes modify access to the seamless notification event semaphore. */
705 SECURITY_ATTRIBUTES SecAttr;
706 DWORD dwErr = ERROR_SUCCESS;
707 char secDesc[SECURITY_DESCRIPTOR_MIN_LENGTH];
708 BOOL fRC;
709
710 SecAttr.nLength = sizeof(SecAttr);
711 SecAttr.bInheritHandle = FALSE;
712 SecAttr.lpSecurityDescriptor = &secDesc;
713 InitializeSecurityDescriptor(SecAttr.lpSecurityDescriptor, SECURITY_DESCRIPTOR_REVISION);
714 fRC = SetSecurityDescriptorDacl(SecAttr.lpSecurityDescriptor, TRUE, 0, FALSE);
715 if (!fRC)
716 {
717 dwErr = GetLastError();
718 Log(("SetSecurityDescriptorDacl failed with last error = %08X\n", dwErr));
719 }
720 else
721 {
722 /* For Vista and up we need to change the integrity of the security descriptor, too. */
723 uint64_t const uNtVersion = RTSystemGetNtVersion();
724 if (uNtVersion >= RTSYSTEM_MAKE_NT_VERSION(6, 0, 0))
725 {
726 BOOL (WINAPI * pfnConvertStringSecurityDescriptorToSecurityDescriptorA)(LPCSTR StringSecurityDescriptor, DWORD StringSDRevision, PSECURITY_DESCRIPTOR *SecurityDescriptor, PULONG SecurityDescriptorSize);
727 *(void **)&pfnConvertStringSecurityDescriptorToSecurityDescriptorA =
728 RTLdrGetSystemSymbol("advapi32.dll", "ConvertStringSecurityDescriptorToSecurityDescriptorA");
729 Log(("pfnConvertStringSecurityDescriptorToSecurityDescriptorA = %p\n",
730 RT_CB_LOG_CAST(pfnConvertStringSecurityDescriptorToSecurityDescriptorA)));
731 if (pfnConvertStringSecurityDescriptorToSecurityDescriptorA)
732 {
733 PSECURITY_DESCRIPTOR pSD;
734 PACL pSacl = NULL;
735 BOOL fSaclPresent = FALSE;
736 BOOL fSaclDefaulted = FALSE;
737
738 fRC = pfnConvertStringSecurityDescriptorToSecurityDescriptorA("S:(ML;;NW;;;LW)", /* this means "low integrity" */
739 SDDL_REVISION_1, &pSD, NULL);
740 if (!fRC)
741 {
742 dwErr = GetLastError();
743 Log(("ConvertStringSecurityDescriptorToSecurityDescriptorA failed with last error = %08X\n", dwErr));
744 }
745 else
746 {
747 fRC = GetSecurityDescriptorSacl(pSD, &fSaclPresent, &pSacl, &fSaclDefaulted);
748 if (!fRC)
749 {
750 dwErr = GetLastError();
751 Log(("GetSecurityDescriptorSacl failed with last error = %08X\n", dwErr));
752 }
753 else
754 {
755 fRC = SetSecurityDescriptorSacl(SecAttr.lpSecurityDescriptor, TRUE, pSacl, FALSE);
756 if (!fRC)
757 {
758 dwErr = GetLastError();
759 Log(("SetSecurityDescriptorSacl failed with last error = %08X\n", dwErr));
760 }
761 }
762 }
763 }
764 }
765
766 if ( dwErr == ERROR_SUCCESS
767 && uNtVersion >= RTSYSTEM_MAKE_NT_VERSION(5, 0, 0)) /* Only for W2K and up ... */
768 {
769 g_hSeamlessWtNotifyEvent = CreateEvent(&SecAttr, FALSE, FALSE, VBOXHOOK_GLOBAL_WT_EVENT_NAME);
770 if (g_hSeamlessWtNotifyEvent == NULL)
771 {
772 dwErr = GetLastError();
773 Log(("CreateEvent for Seamless failed, last error = %08X\n", dwErr));
774 }
775
776 g_hSeamlessKmNotifyEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
777 if (g_hSeamlessKmNotifyEvent == NULL)
778 {
779 dwErr = GetLastError();
780 Log(("CreateEvent for Seamless failed, last error = %08X\n", dwErr));
781 }
782 }
783 }
784 return RTErrConvertFromWin32(dwErr);
785}
786
787static void vboxTrayShutdownSeamless(void)
788{
789 if (g_hSeamlessWtNotifyEvent)
790 {
791 CloseHandle(g_hSeamlessWtNotifyEvent);
792 g_hSeamlessWtNotifyEvent = NULL;
793 }
794
795 if (g_hSeamlessKmNotifyEvent)
796 {
797 CloseHandle(g_hSeamlessKmNotifyEvent);
798 g_hSeamlessKmNotifyEvent = NULL;
799 }
800}
801
802static int vboxTrayServiceMain(void)
803{
804 int rc = VINF_SUCCESS;
805 LogFunc(("Entering vboxTrayServiceMain\n"));
806
807 g_hStopSem = CreateEvent(NULL, TRUE, FALSE, NULL);
808 if (g_hStopSem == NULL)
809 {
810 rc = RTErrConvertFromWin32(GetLastError());
811 LogFunc(("CreateEvent for stopping VBoxTray failed, rc=%Rrc\n", rc));
812 }
813 else
814 {
815 /*
816 * Start services listed in the vboxServiceTable.
817 */
818 VBOXSERVICEENV svcEnv;
819 svcEnv.hInstance = g_hInstance;
820
821 /* Initializes disp-if to default (XPDM) mode. */
822 VBoxDispIfInit(&svcEnv.dispIf); /* Cannot fail atm. */
823 #ifdef VBOX_WITH_WDDM
824 /*
825 * For now the display mode will be adjusted to WDDM mode if needed
826 * on display service initialization when it detects the display driver type.
827 */
828 #endif
829
830 /* Finally start all the built-in services! */
831 rc = vboxTrayServicesStart(&svcEnv);
832 if (RT_FAILURE(rc))
833 {
834 /* Terminate service if something went wrong. */
835 vboxTrayServicesStop(&svcEnv);
836 }
837 else
838 {
839 uint64_t const uNtVersion = RTSystemGetNtVersion();
840 rc = vboxTrayCreateTrayIcon();
841 if ( RT_SUCCESS(rc)
842 && uNtVersion >= RTSYSTEM_MAKE_NT_VERSION(5, 0, 0)) /* Only for W2K and up ... */
843 {
844 /* We're ready to create the tooltip balloon.
845 Check in 10 seconds (@todo make seconds configurable) ... */
846 SetTimer(g_hwndToolWindow,
847 TIMERID_VBOXTRAY_CHECK_HOSTVERSION,
848 10 * 1000, /* 10 seconds */
849 NULL /* No timerproc */);
850 }
851
852 if (RT_SUCCESS(rc))
853 {
854 /* Report the host that we're up and running! */
855 hlpReportStatus(VBoxGuestFacilityStatus_Active);
856 }
857
858 if (RT_SUCCESS(rc))
859 {
860 /* Boost thread priority to make sure we wake up early for seamless window notifications
861 * (not sure if it actually makes any difference though). */
862 SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_HIGHEST);
863
864 /*
865 * Main execution loop
866 * Wait for the stop semaphore to be posted or a window event to arrive
867 */
868
869 HANDLE hWaitEvent[4] = {0};
870 DWORD dwEventCount = 0;
871
872 hWaitEvent[dwEventCount++] = g_hStopSem;
873
874 /* Check if seamless mode is not active and add seamless event to the list */
875 if (0 != g_hSeamlessWtNotifyEvent)
876 {
877 hWaitEvent[dwEventCount++] = g_hSeamlessWtNotifyEvent;
878 }
879
880 if (0 != g_hSeamlessKmNotifyEvent)
881 {
882 hWaitEvent[dwEventCount++] = g_hSeamlessKmNotifyEvent;
883 }
884
885 if (0 != vboxDtGetNotifyEvent())
886 {
887 hWaitEvent[dwEventCount++] = vboxDtGetNotifyEvent();
888 }
889
890 LogFlowFunc(("Number of events to wait in main loop: %ld\n", dwEventCount));
891 while (true)
892 {
893 DWORD waitResult = MsgWaitForMultipleObjectsEx(dwEventCount, hWaitEvent, 500, QS_ALLINPUT, 0);
894 waitResult = waitResult - WAIT_OBJECT_0;
895
896 /* Only enable for message debugging, lots of traffic! */
897 //Log(("Wait result = %ld\n", waitResult));
898
899 if (waitResult == 0)
900 {
901 LogFunc(("Event 'Exit' triggered\n"));
902 /* exit */
903 break;
904 }
905 else
906 {
907 BOOL fHandled = FALSE;
908 if (waitResult < RT_ELEMENTS(hWaitEvent))
909 {
910 if (hWaitEvent[waitResult])
911 {
912 if (hWaitEvent[waitResult] == g_hSeamlessWtNotifyEvent)
913 {
914 LogFunc(("Event 'Seamless' triggered\n"));
915
916 /* seamless window notification */
917 VBoxSeamlessCheckWindows(false);
918 fHandled = TRUE;
919 }
920 else if (hWaitEvent[waitResult] == g_hSeamlessKmNotifyEvent)
921 {
922 LogFunc(("Event 'Km Seamless' triggered\n"));
923
924 /* seamless window notification */
925 VBoxSeamlessCheckWindows(true);
926 fHandled = TRUE;
927 }
928 else if (hWaitEvent[waitResult] == vboxDtGetNotifyEvent())
929 {
930 LogFunc(("Event 'Dt' triggered\n"));
931 vboxDtDoCheck();
932 fHandled = TRUE;
933 }
934 }
935 }
936
937 if (!fHandled)
938 {
939 /* timeout or a window message, handle it */
940 MSG msg;
941 while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
942 {
943#ifdef DEBUG_andy
944 LogFlowFunc(("PeekMessage %u\n", msg.message));
945#endif
946 if (msg.message == WM_QUIT)
947 {
948 LogFunc(("Terminating ...\n"));
949 SetEvent(g_hStopSem);
950 }
951 TranslateMessage(&msg);
952 DispatchMessage(&msg);
953 }
954 }
955 }
956 }
957 LogFunc(("Returned from main loop, exiting ...\n"));
958 }
959 LogFunc(("Waiting for services to stop ...\n"));
960 vboxTrayServicesStop(&svcEnv);
961 } /* Services started */
962 CloseHandle(g_hStopSem);
963 } /* Stop event created */
964
965 vboxTrayRemoveTrayIcon();
966
967 LogFunc(("Leaving with rc=%Rrc\n", rc));
968 return rc;
969}
970
971/**
972 * Main function
973 */
974int main(int cArgs, char **papszArgs)
975{
976 int rc = RTR3InitExe(cArgs, &papszArgs, RTR3INIT_FLAGS_STANDALONE_APP);
977 if (RT_FAILURE(rc))
978 return RTMsgInitFailure(rc);
979
980 /*
981 * Parse the top level arguments until we find a command.
982 */
983 static const RTGETOPTDEF s_aOptions[] =
984 {
985 { "--help", 'h', RTGETOPT_REQ_NOTHING },
986 { "-help", 'h', RTGETOPT_REQ_NOTHING },
987 { "/help", 'h', RTGETOPT_REQ_NOTHING },
988 { "/?", 'h', RTGETOPT_REQ_NOTHING },
989 { "--logfile", 'l', RTGETOPT_REQ_STRING },
990 { "--verbose", 'v', RTGETOPT_REQ_NOTHING },
991 { "--version", 'V', RTGETOPT_REQ_NOTHING },
992 };
993
994 char szLogFile[RTPATH_MAX] = {0};
995
996 RTGETOPTSTATE GetState;
997 rc = RTGetOptInit(&GetState, cArgs, papszArgs, s_aOptions, RT_ELEMENTS(s_aOptions), 1, 0 /*fFlags*/);
998 if (RT_FAILURE(rc))
999 return RTMsgErrorExit(RTEXITCODE_FAILURE, "RTGetOptInit failed: %Rrc\n", rc);
1000
1001 int ch;
1002 RTGETOPTUNION ValueUnion;
1003 while ((ch = RTGetOpt(&GetState, &ValueUnion)) != 0)
1004 {
1005 switch (ch)
1006 {
1007 case 'h':
1008 hlpShowMessageBox(VBOX_PRODUCT " - " VBOX_VBOXTRAY_TITLE,
1009 MB_ICONINFORMATION,
1010 "-- " VBOX_PRODUCT " %s v%u.%u.%ur%u --\n\n"
1011 "Copyright (C) 2009-" VBOX_C_YEAR " " VBOX_VENDOR "\n\n"
1012 "Command Line Parameters:\n\n"
1013 "-l, --logfile <file>\n"
1014 " Enables logging to a file\n"
1015 "-v, --verbose\n"
1016 " Increases verbosity\n"
1017 "-V, --version\n"
1018 " Displays version number and exit\n"
1019 "-?, -h, --help\n"
1020 " Displays this help text and exit\n"
1021 "\n"
1022 "Examples:\n"
1023 " %s -vvv\n",
1024 VBOX_VBOXTRAY_TITLE, VBOX_VERSION_MAJOR, VBOX_VERSION_MINOR, VBOX_VERSION_BUILD, VBOX_SVN_REV,
1025 papszArgs[0], papszArgs[0]);
1026 return RTEXITCODE_SUCCESS;
1027
1028 case 'l':
1029 if (*ValueUnion.psz == '\0')
1030 szLogFile[0] = '\0';
1031 else
1032 {
1033 rc = RTPathAbs(ValueUnion.psz, szLogFile, sizeof(szLogFile));
1034 if (RT_FAILURE(rc))
1035 return RTMsgErrorExit(RTEXITCODE_FAILURE, "RTPathAbs failed on log file path: %Rrc (%s)",
1036 rc, ValueUnion.psz);
1037 }
1038 break;
1039
1040 case 'v':
1041 g_cVerbosity++;
1042 break;
1043
1044 case 'V':
1045 hlpShowMessageBox(VBOX_VBOXTRAY_TITLE, MB_ICONINFORMATION,
1046 "Version: %u.%u.%ur%u",
1047 VBOX_VERSION_MAJOR, VBOX_VERSION_MINOR, VBOX_VERSION_BUILD, VBOX_SVN_REV);
1048 return RTEXITCODE_SUCCESS;
1049
1050 default:
1051 rc = RTGetOptPrintError(ch, &ValueUnion);
1052 break;
1053 }
1054 }
1055
1056 /* Note: Do not use a global namespace ("Global\\") for mutex name here,
1057 * will blow up NT4 compatibility! */
1058 HANDLE hMutexAppRunning = CreateMutex(NULL, FALSE, VBOX_VBOXTRAY_TITLE);
1059 if ( hMutexAppRunning != NULL
1060 && GetLastError() == ERROR_ALREADY_EXISTS)
1061 {
1062 /* VBoxTray already running? Bail out. */
1063 CloseHandle (hMutexAppRunning);
1064 hMutexAppRunning = NULL;
1065 return RTEXITCODE_SUCCESS;
1066 }
1067
1068 rc = VbglR3Init();
1069 if (RT_SUCCESS(rc))
1070 {
1071 rc = vboxTrayLogCreate(szLogFile[0] ? szLogFile : NULL);
1072 if (RT_SUCCESS(rc))
1073 {
1074 LogRel(("Verbosity level: %d\n", g_cVerbosity));
1075
1076 /* Log the major windows NT version: */
1077 uint64_t const uNtVersion = RTSystemGetNtVersion();
1078 LogRel(("Windows version %u.%u build %u (uNtVersion=%#RX64)\n", RTSYSTEM_NT_VERSION_GET_MAJOR(uNtVersion),
1079 RTSYSTEM_NT_VERSION_GET_MINOR(uNtVersion), RTSYSTEM_NT_VERSION_GET_BUILD(uNtVersion), uNtVersion ));
1080
1081 /* Set the instance handle. */
1082#ifdef IPRT_NO_CRT
1083 Assert(g_hInstance == NULL); /* Make sure this isn't set before by WinMain(). */
1084 g_hInstance = GetModuleHandleW(NULL);
1085#endif
1086 hlpReportStatus(VBoxGuestFacilityStatus_Init);
1087 rc = vboxTrayCreateToolWindow();
1088 if (RT_SUCCESS(rc))
1089 {
1090 VBoxCapsInit();
1091
1092 rc = vboxStInit(g_hwndToolWindow);
1093 if (!RT_SUCCESS(rc))
1094 {
1095 LogFlowFunc(("vboxStInit failed, rc=%Rrc\n", rc));
1096 /* ignore the St Init failure. this can happen for < XP win that do not support WTS API
1097 * in that case the session is treated as active connected to the physical console
1098 * (i.e. fallback to the old behavior that was before introduction of VBoxSt) */
1099 Assert(vboxStIsActiveConsole());
1100 }
1101
1102 rc = vboxDtInit();
1103 if (!RT_SUCCESS(rc))
1104 {
1105 LogFlowFunc(("vboxDtInit failed, rc=%Rrc\n", rc));
1106 /* ignore the Dt Init failure. this can happen for < XP win that do not support WTS API
1107 * in that case the session is treated as active connected to the physical console
1108 * (i.e. fallback to the old behavior that was before introduction of VBoxSt) */
1109 Assert(vboxDtIsInputDesktop());
1110 }
1111
1112 rc = VBoxAcquireGuestCaps(VMMDEV_GUEST_SUPPORTS_SEAMLESS | VMMDEV_GUEST_SUPPORTS_GRAPHICS, 0, true);
1113 if (!RT_SUCCESS(rc))
1114 LogFlowFunc(("VBoxAcquireGuestCaps failed with rc=%Rrc, ignoring ...\n", rc));
1115
1116 rc = vboxTraySetupSeamless(); /** @todo r=andy Do we really want to be this critical for the whole application? */
1117 if (RT_SUCCESS(rc))
1118 {
1119 rc = vboxTrayServiceMain();
1120 if (RT_SUCCESS(rc))
1121 hlpReportStatus(VBoxGuestFacilityStatus_Terminating);
1122 vboxTrayShutdownSeamless();
1123 }
1124
1125 /* it should be safe to call vboxDtTerm even if vboxStInit above failed */
1126 vboxDtTerm();
1127
1128 /* it should be safe to call vboxStTerm even if vboxStInit above failed */
1129 vboxStTerm();
1130
1131 VBoxCapsTerm();
1132
1133 vboxTrayDestroyToolWindow();
1134 }
1135 if (RT_SUCCESS(rc))
1136 hlpReportStatus(VBoxGuestFacilityStatus_Terminated);
1137 else
1138 {
1139 LogRel(("Error while starting, rc=%Rrc\n", rc));
1140 hlpReportStatus(VBoxGuestFacilityStatus_Failed);
1141 }
1142
1143 LogRel(("Ended\n"));
1144
1145 vboxTrayLogDestroy();
1146 }
1147
1148 VbglR3Term();
1149 }
1150 else
1151 VBoxTrayShowError("VbglR3Init failed: %Rrc\n", rc);
1152
1153 /* Release instance mutex. */
1154 if (hMutexAppRunning != NULL)
1155 {
1156 CloseHandle(hMutexAppRunning);
1157 hMutexAppRunning = NULL;
1158 }
1159
1160 return RT_SUCCESS(rc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
1161}
1162
1163#ifndef IPRT_NO_CRT
1164int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
1165{
1166 RT_NOREF(hPrevInstance, lpCmdLine, nCmdShow);
1167
1168 g_hInstance = hInstance;
1169
1170 return main(__argc, __argv);
1171}
1172#endif /* IPRT_NO_CRT */
1173
1174/**
1175 * Window procedure for our main tool window.
1176 */
1177static LRESULT CALLBACK vboxToolWndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
1178{
1179 LogFlowFunc(("hWnd=%p, uMsg=%u\n", hWnd, uMsg));
1180
1181 switch (uMsg)
1182 {
1183 case WM_CREATE:
1184 {
1185 LogFunc(("Tool window created\n"));
1186
1187 int rc = vboxTrayRegisterGlobalMessages(&g_vboxGlobalMessageTable[0]);
1188 if (RT_FAILURE(rc))
1189 LogFunc(("Error registering global window messages, rc=%Rrc\n", rc));
1190 return 0;
1191 }
1192
1193 case WM_CLOSE:
1194 return 0;
1195
1196 case WM_DESTROY:
1197 {
1198 LogFunc(("Tool window destroyed\n"));
1199 KillTimer(g_hwndToolWindow, TIMERID_VBOXTRAY_CHECK_HOSTVERSION);
1200 return 0;
1201 }
1202
1203 case WM_TIMER:
1204 {
1205 if (VBoxCapsCheckTimer(wParam))
1206 return 0;
1207 if (vboxDtCheckTimer(wParam))
1208 return 0;
1209 if (vboxStCheckTimer(wParam))
1210 return 0;
1211
1212 switch (wParam)
1213 {
1214 case TIMERID_VBOXTRAY_CHECK_HOSTVERSION:
1215 if (RT_SUCCESS(VBoxCheckHostVersion()))
1216 {
1217 /* After successful run we don't need to check again. */
1218 KillTimer(g_hwndToolWindow, TIMERID_VBOXTRAY_CHECK_HOSTVERSION);
1219 }
1220 return 0;
1221
1222 default:
1223 break;
1224 }
1225
1226 break; /* Make sure other timers get processed the usual way! */
1227 }
1228
1229 case WM_VBOXTRAY_TRAY_ICON:
1230 {
1231 switch (LOWORD(lParam))
1232 {
1233 case WM_LBUTTONDBLCLK:
1234 break;
1235 case WM_RBUTTONDOWN:
1236 {
1237 if (!g_cVerbosity) /* Don't show menu when running in non-verbose mode. */
1238 break;
1239
1240 POINT lpCursor;
1241 if (GetCursorPos(&lpCursor))
1242 {
1243 HMENU hContextMenu = CreatePopupMenu();
1244 if (hContextMenu)
1245 {
1246 UINT_PTR uMenuItem = 9999;
1247 UINT fMenuItem = MF_BYPOSITION | MF_STRING;
1248 if (InsertMenuW(hContextMenu, UINT_MAX, fMenuItem, uMenuItem, L"Exit"))
1249 {
1250 SetForegroundWindow(hWnd);
1251
1252 const bool fBlockWhileTracking = true;
1253
1254 UINT fTrack = TPM_LEFTALIGN | TPM_LEFTBUTTON | TPM_BOTTOMALIGN;
1255
1256 if (fBlockWhileTracking)
1257 fTrack |= TPM_RETURNCMD | TPM_NONOTIFY;
1258
1259 uMsg = TrackPopupMenu(hContextMenu, fTrack, lpCursor.x, lpCursor.y, 0, hWnd, NULL);
1260 if ( uMsg
1261 && fBlockWhileTracking)
1262 {
1263 if (uMsg == uMenuItem)
1264 PostMessage(g_hwndToolWindow, WM_QUIT, 0, 0);
1265 }
1266 else if (!uMsg)
1267 LogFlowFunc(("Tracking popup menu failed with %ld\n", GetLastError()));
1268 }
1269
1270 DestroyMenu(hContextMenu);
1271 }
1272 }
1273 break;
1274 }
1275 }
1276 return 0;
1277 }
1278
1279 case WM_VBOX_SEAMLESS_ENABLE:
1280 {
1281 VBoxCapsEntryFuncStateSet(VBOXCAPS_ENTRY_IDX_SEAMLESS, VBOXCAPS_ENTRY_FUNCSTATE_STARTED);
1282 if (VBoxCapsEntryIsEnabled(VBOXCAPS_ENTRY_IDX_SEAMLESS))
1283 VBoxSeamlessCheckWindows(true);
1284 return 0;
1285 }
1286
1287 case WM_VBOX_SEAMLESS_DISABLE:
1288 {
1289 VBoxCapsEntryFuncStateSet(VBOXCAPS_ENTRY_IDX_SEAMLESS, VBOXCAPS_ENTRY_FUNCSTATE_SUPPORTED);
1290 return 0;
1291 }
1292
1293 case WM_DISPLAYCHANGE:
1294 ASMAtomicUoWriteU32(&g_fGuestDisplaysChanged, 1);
1295 // No break or return is intentional here.
1296 case WM_VBOX_SEAMLESS_UPDATE:
1297 {
1298 if (VBoxCapsEntryIsEnabled(VBOXCAPS_ENTRY_IDX_SEAMLESS))
1299 VBoxSeamlessCheckWindows(true);
1300 return 0;
1301 }
1302
1303 case WM_VBOX_GRAPHICS_SUPPORTED:
1304 {
1305 VBoxGrapicsSetSupported(TRUE);
1306 return 0;
1307 }
1308
1309 case WM_VBOX_GRAPHICS_UNSUPPORTED:
1310 {
1311 VBoxGrapicsSetSupported(FALSE);
1312 return 0;
1313 }
1314
1315 case WM_WTSSESSION_CHANGE:
1316 {
1317 BOOL fOldAllowedState = VBoxConsoleIsAllowed();
1318 if (vboxStHandleEvent(wParam))
1319 {
1320 if (!VBoxConsoleIsAllowed() != !fOldAllowedState)
1321 VBoxConsoleEnable(!fOldAllowedState);
1322 }
1323 return 0;
1324 }
1325
1326 default:
1327 {
1328 /* Handle all globally registered window messages. */
1329 if (vboxTrayHandleGlobalMessages(&g_vboxGlobalMessageTable[0], uMsg,
1330 wParam, lParam))
1331 {
1332 return 0; /* We handled the message. @todo Add return value!*/
1333 }
1334 break; /* We did not handle the message, dispatch to DefWndProc. */
1335 }
1336 }
1337
1338 /* Only if message was *not* handled by our switch above, dispatch to DefWindowProc. */
1339 return DefWindowProc(hWnd, uMsg, wParam, lParam);
1340}
1341
1342static void VBoxGrapicsSetSupported(BOOL fSupported)
1343{
1344 VBoxConsoleCapSetSupported(VBOXCAPS_ENTRY_IDX_GRAPHICS, fSupported);
1345}
1346
Note: See TracBrowser for help on using the repository browser.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette