VirtualBox

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

Last change on this file since 105581 was 105581, checked in by vboxsync, 5 months ago

Additions/VBoxTray: Logger adjustments for debug / release builds. This basically reverts to the behavior before r152549 so that we have different environment variable prefixes (VBOXTRAY_LOG and VBOXTRAY_RELEASE_LOG). Increasing the verbosity via the command line switch (--verbose) will only increase the verbosity for functionality we offer within VBoxTray. Untested.

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