File: juce_win32_SystemStats.cpp

package info (click to toggle)
juce 6.1.3~ds0-1~exp1
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 61,612 kB
  • sloc: cpp: 431,694; java: 2,592; ansic: 797; xml: 259; sh: 164; python: 126; makefile: 64
file content (590 lines) | stat: -rw-r--r-- 19,059 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
/*
  ==============================================================================

   This file is part of the JUCE library.
   Copyright (c) 2020 - Raw Material Software Limited

   JUCE is an open source library subject to commercial or open-source
   licensing.

   The code included in this file is provided under the terms of the ISC license
   http://www.isc.org/downloads/software-support-policy/isc-license. Permission
   To use, copy, modify, and/or distribute this software for any purpose with or
   without fee is hereby granted provided that the above copyright notice and
   this permission notice appear in all copies.

   JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
   EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
   DISCLAIMED.

  ==============================================================================
*/

namespace juce
{

#if JUCE_MSVC && ! defined (__INTEL_COMPILER)
 #pragma intrinsic (__cpuid)
 #pragma intrinsic (__rdtsc)
#endif

void Logger::outputDebugString (const String& text)
{
    OutputDebugString ((text + "\n").toWideCharPointer());
}

//==============================================================================
#ifdef JUCE_DLL_BUILD
 JUCE_API void* juceDLL_malloc (size_t sz)    { return std::malloc (sz); }
 JUCE_API void  juceDLL_free (void* block)    { std::free (block); }
#endif

//==============================================================================

#if JUCE_MINGW || JUCE_CLANG
static void callCPUID (int result[4], uint32 type)
{
  uint32 la = (uint32) result[0], lb = (uint32) result[1],
         lc = (uint32) result[2], ld = (uint32) result[3];

  asm ("mov %%ebx, %%esi \n\t"
       "cpuid \n\t"
       "xchg %%esi, %%ebx"
       : "=a" (la), "=S" (lb), "=c" (lc), "=d" (ld) : "a" (type)
        #if JUCE_64BIT
     , "b" (lb), "c" (lc), "d" (ld)
        #endif
       );

  result[0] = (int) la; result[1] = (int) lb;
  result[2] = (int) lc; result[3] = (int) ld;
}
#else
static void callCPUID (int result[4], int infoType)
{
    __cpuid (result, infoType);
}
#endif

String SystemStats::getCpuVendor()
{
    int info[4] = { 0 };
    callCPUID (info, 0);

    char v [12];
    memcpy (v, info + 1, 4);
    memcpy (v + 4, info + 3, 4);
    memcpy (v + 8, info + 2, 4);

    return String (v, 12);
}

String SystemStats::getCpuModel()
{
    char name[65] = { 0 };
    int info[4] = { 0 };

    callCPUID (info, 0x80000000);

    const int numExtIDs = info[0];

    if ((unsigned) numExtIDs < 0x80000004)  // if brand string is unsupported
        return {};

    callCPUID (info, 0x80000002);
    memcpy (name, info, sizeof (info));

    callCPUID (info, 0x80000003);
    memcpy (name + 16, info, sizeof (info));

    callCPUID (info, 0x80000004);
    memcpy (name + 32, info, sizeof (info));

    return String (name).trim();
}

static int findNumberOfPhysicalCores() noexcept
{
   #if JUCE_MINGW
    // Not implemented in MinGW
    jassertfalse;

    return 1;
   #else

    int numPhysicalCores = 0;
    DWORD bufferSize = 0;
    GetLogicalProcessorInformation (nullptr, &bufferSize);

    if (auto numBuffers = (size_t) (bufferSize / sizeof (SYSTEM_LOGICAL_PROCESSOR_INFORMATION)))
    {
        HeapBlock<SYSTEM_LOGICAL_PROCESSOR_INFORMATION> buffer (numBuffers);

        if (GetLogicalProcessorInformation (buffer, &bufferSize))
            for (size_t i = 0; i < numBuffers; ++i)
                if (buffer[i].Relationship == RelationProcessorCore)
                    ++numPhysicalCores;
    }

    return numPhysicalCores;
   #endif // JUCE_MINGW
}

//==============================================================================
void CPUInformation::initialise() noexcept
{
    int info[4] = { 0 };
    callCPUID (info, 1);

    // NB: IsProcessorFeaturePresent doesn't work on XP
    hasMMX   = (info[3] & (1 << 23)) != 0;
    hasSSE   = (info[3] & (1 << 25)) != 0;
    hasSSE2  = (info[3] & (1 << 26)) != 0;
    hasSSE3  = (info[2] & (1 <<  0)) != 0;
    hasAVX   = (info[2] & (1 << 28)) != 0;
    hasFMA3  = (info[2] & (1 << 12)) != 0;
    hasSSSE3 = (info[2] & (1 <<  9)) != 0;
    hasSSE41 = (info[2] & (1 << 19)) != 0;
    hasSSE42 = (info[2] & (1 << 20)) != 0;

    JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wshift-sign-overflow")
    has3DNow = (info[1] & (1 << 31)) != 0;
    JUCE_END_IGNORE_WARNINGS_GCC_LIKE

    callCPUID (info, 0x80000001);
    hasFMA4  = (info[2] & (1 << 16)) != 0;

    callCPUID (info, 7);

    hasAVX2            = ((unsigned int) info[1] & (1 << 5))   != 0;
    hasAVX512F         = ((unsigned int) info[1] & (1u << 16)) != 0;
    hasAVX512DQ        = ((unsigned int) info[1] & (1u << 17)) != 0;
    hasAVX512IFMA      = ((unsigned int) info[1] & (1u << 21)) != 0;
    hasAVX512PF        = ((unsigned int) info[1] & (1u << 26)) != 0;
    hasAVX512ER        = ((unsigned int) info[1] & (1u << 27)) != 0;
    hasAVX512CD        = ((unsigned int) info[1] & (1u << 28)) != 0;
    hasAVX512BW        = ((unsigned int) info[1] & (1u << 30)) != 0;
    hasAVX512VL        = ((unsigned int) info[1] & (1u << 31)) != 0;
    hasAVX512VBMI      = ((unsigned int) info[2] & (1u <<  1)) != 0;
    hasAVX512VPOPCNTDQ = ((unsigned int) info[2] & (1u << 14)) != 0;

    SYSTEM_INFO systemInfo;
    GetNativeSystemInfo (&systemInfo);
    numLogicalCPUs  = (int) systemInfo.dwNumberOfProcessors;
    numPhysicalCPUs = findNumberOfPhysicalCores();

    if (numPhysicalCPUs <= 0)
        numPhysicalCPUs = numLogicalCPUs;
}

#if JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
struct DebugFlagsInitialiser
{
    DebugFlagsInitialiser()
    {
        _CrtSetDbgFlag (_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
    }
};

static DebugFlagsInitialiser debugFlagsInitialiser;
#endif

//==============================================================================
#if JUCE_MINGW
 static uint32 getWindowsVersion()
 {
     auto filename = _T("kernel32.dll");
     DWORD handle = 0;

     if (auto size = GetFileVersionInfoSize (filename, &handle))
     {
         HeapBlock<char> data (size);

         if (GetFileVersionInfo (filename, handle, size, data))
         {
             VS_FIXEDFILEINFO* info = nullptr;
             UINT verSize = 0;

             if (VerQueryValue (data, (LPCTSTR) _T("\\"), (void**) &info, &verSize))
                 if (size > 0 && info != nullptr && info->dwSignature == 0xfeef04bd)
                     return (uint32) info->dwFileVersionMS;
         }
     }

     return 0;
 }
#else
 RTL_OSVERSIONINFOW getWindowsVersionInfo()
 {
     RTL_OSVERSIONINFOW versionInfo = {};

     if (auto* moduleHandle = ::GetModuleHandleW (L"ntdll.dll"))
     {
         using RtlGetVersion = LONG (WINAPI*) (PRTL_OSVERSIONINFOW);

         if (auto* rtlGetVersion = (RtlGetVersion) ::GetProcAddress (moduleHandle, "RtlGetVersion"))
         {
             versionInfo.dwOSVersionInfoSize = sizeof (versionInfo);
             LONG STATUS_SUCCESS = 0;

             if (rtlGetVersion (&versionInfo) != STATUS_SUCCESS)
                 versionInfo = {};
         }
     }

     return versionInfo;
 }
#endif

SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
{
   #if JUCE_MINGW
    auto v = getWindowsVersion();
    auto major = (v >> 16) & 0xff;
    auto minor = (v >> 0)  & 0xff;
   #else
    auto versionInfo = getWindowsVersionInfo();
    auto major = versionInfo.dwMajorVersion;
    auto minor = versionInfo.dwMinorVersion;
   #endif

    jassert (major <= 10); // need to add support for new version!

    if (major == 10)                 return Windows10;
    if (major == 6 && minor == 3)    return Windows8_1;
    if (major == 6 && minor == 2)    return Windows8_0;
    if (major == 6 && minor == 1)    return Windows7;
    if (major == 6 && minor == 0)    return WinVista;
    if (major == 5 && minor == 1)    return WinXP;
    if (major == 5 && minor == 0)    return Win2000;

    jassertfalse;
    return UnknownOS;
}

String SystemStats::getOperatingSystemName()
{
    const char* name = "Unknown OS";

    switch (getOperatingSystemType())
    {
        case Windows10:         name = "Windows 10";        break;
        case Windows8_1:        name = "Windows 8.1";       break;
        case Windows8_0:        name = "Windows 8.0";       break;
        case Windows7:          name = "Windows 7";         break;
        case WinVista:          name = "Windows Vista";     break;
        case WinXP:             name = "Windows XP";        break;
        case Win2000:           name = "Windows 2000";      break;

        case MacOSX:            JUCE_FALLTHROUGH
        case Windows:           JUCE_FALLTHROUGH
        case Linux:             JUCE_FALLTHROUGH
        case Android:           JUCE_FALLTHROUGH
        case iOS:               JUCE_FALLTHROUGH

        case MacOSX_10_7:       JUCE_FALLTHROUGH
        case MacOSX_10_8:       JUCE_FALLTHROUGH
        case MacOSX_10_9:       JUCE_FALLTHROUGH
        case MacOSX_10_10:      JUCE_FALLTHROUGH
        case MacOSX_10_11:      JUCE_FALLTHROUGH
        case MacOSX_10_12:      JUCE_FALLTHROUGH
        case MacOSX_10_13:      JUCE_FALLTHROUGH
        case MacOSX_10_14:      JUCE_FALLTHROUGH
        case MacOSX_10_15:      JUCE_FALLTHROUGH
        case MacOS_11:          JUCE_FALLTHROUGH
        case MacOS_12:          JUCE_FALLTHROUGH

        case UnknownOS:         JUCE_FALLTHROUGH
        case WASM:              JUCE_FALLTHROUGH
        default:                jassertfalse; break; // !! new type of OS?
    }

    return name;
}

String SystemStats::getDeviceDescription()
{
   #if WINAPI_FAMILY == WINAPI_FAMILY_DESKTOP_APP
    return "Windows (Desktop)";
   #elif WINAPI_FAMILY == WINAPI_FAMILY_PC_APP
    return "Windows (Store)";
   #elif WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP
    return "Windows (Phone)";
   #elif WINAPI_FAMILY == WINAPI_FAMILY_SYSTEM
    return "Windows (System)";
   #elif WINAPI_FAMILY == WINAPI_FAMILY_SERVER
    return "Windows (Server)";
   #else
    return "Windows";
   #endif
}

String SystemStats::getDeviceManufacturer()
{
    return {};
}

bool SystemStats::isOperatingSystem64Bit()
{
   #if JUCE_64BIT
    return true;
   #else
    typedef BOOL (WINAPI* LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);

    const auto moduleHandle = GetModuleHandleA ("kernel32");

    if (moduleHandle == nullptr)
    {
        jassertfalse;
        return false;
    }

    LPFN_ISWOW64PROCESS fnIsWow64Process
        = (LPFN_ISWOW64PROCESS) GetProcAddress (moduleHandle, "IsWow64Process");

    BOOL isWow64 = FALSE;

    return fnIsWow64Process != nullptr
            && fnIsWow64Process (GetCurrentProcess(), &isWow64)
            && isWow64 != FALSE;
   #endif
}

//==============================================================================
int SystemStats::getMemorySizeInMegabytes()
{
    MEMORYSTATUSEX mem;
    mem.dwLength = sizeof (mem);
    GlobalMemoryStatusEx (&mem);
    return (int) (mem.ullTotalPhys / (1024 * 1024)) + 1;
}

//==============================================================================
String SystemStats::getEnvironmentVariable (const String& name, const String& defaultValue)
{
    auto len = GetEnvironmentVariableW (name.toWideCharPointer(), nullptr, 0);

    if (len == 0)
        return String (defaultValue);

    HeapBlock<WCHAR> buffer (len);
    len = GetEnvironmentVariableW (name.toWideCharPointer(), buffer, len);

    return String (CharPointer_wchar_t (buffer),
                   CharPointer_wchar_t (buffer + len));
}

//==============================================================================
uint32 juce_millisecondsSinceStartup() noexcept
{
    return (uint32) timeGetTime();
}

//==============================================================================
class HiResCounterHandler
{
public:
    HiResCounterHandler()
        : hiResTicksOffset (0)
    {
        // This macro allows you to override the default timer-period
        // used on Windows. By default this is set to 1, because that has
        // always been the value used in JUCE apps, and changing it could
        // affect the behaviour of existing code, but you may wish to make
        // it larger (or set it to 0 to use the system default) to make your
        // app less demanding on the CPU.
        // For more info, see win32 documentation about the timeBeginPeriod
        // function.
       #ifndef JUCE_WIN32_TIMER_PERIOD
        #define JUCE_WIN32_TIMER_PERIOD 1
       #endif

       #if JUCE_WIN32_TIMER_PERIOD > 0
        auto res = timeBeginPeriod (JUCE_WIN32_TIMER_PERIOD);
        ignoreUnused (res);
        jassert (res == TIMERR_NOERROR);
       #endif

        LARGE_INTEGER f;
        QueryPerformanceFrequency (&f);
        hiResTicksPerSecond = f.QuadPart;
        hiResTicksScaleFactor = 1000.0 / (double) hiResTicksPerSecond;
    }

    inline int64 getHighResolutionTicks() noexcept
    {
        LARGE_INTEGER ticks;
        QueryPerformanceCounter (&ticks);
        return ticks.QuadPart + hiResTicksOffset;
    }

    inline double getMillisecondCounterHiRes() noexcept
    {
        return (double) getHighResolutionTicks() * hiResTicksScaleFactor;
    }

    int64 hiResTicksPerSecond, hiResTicksOffset;
    double hiResTicksScaleFactor;
};

static HiResCounterHandler hiResCounterHandler;

int64  Time::getHighResolutionTicksPerSecond() noexcept  { return hiResCounterHandler.hiResTicksPerSecond; }
int64  Time::getHighResolutionTicks() noexcept           { return hiResCounterHandler.getHighResolutionTicks(); }
double Time::getMillisecondCounterHiRes() noexcept       { return hiResCounterHandler.getMillisecondCounterHiRes(); }

//==============================================================================
static int64 juce_getClockCycleCounter() noexcept
{
   #if JUCE_MSVC
    // MS intrinsics version...
    return (int64) __rdtsc();

   #elif JUCE_GCC || JUCE_CLANG
    // GNU inline asm version...
    unsigned int hi = 0, lo = 0;

    __asm__ __volatile__ (
        "xor %%eax, %%eax               \n\
         xor %%edx, %%edx               \n\
         rdtsc                          \n\
         movl %%eax, %[lo]              \n\
         movl %%edx, %[hi]"
         :
         : [hi] "m" (hi),
           [lo] "m" (lo)
         : "cc", "eax", "ebx", "ecx", "edx", "memory");

    return (int64) ((((uint64) hi) << 32) | lo);
   #else
    #error "unknown compiler?"
   #endif
}

int SystemStats::getCpuSpeedInMegahertz()
{
    auto cycles = juce_getClockCycleCounter();
    auto millis = Time::getMillisecondCounter();
    int lastResult = 0;

    for (;;)
    {
        int n = 1000000;
        while (--n > 0) {}

        auto millisElapsed = Time::getMillisecondCounter() - millis;
        auto cyclesNow = juce_getClockCycleCounter();

        if (millisElapsed > 80)
        {
            auto newResult = (int) (((cyclesNow - cycles) / millisElapsed) / 1000);

            if (millisElapsed > 500 || (lastResult == newResult && newResult > 100))
                return newResult;

            lastResult = newResult;
        }
    }
}


//==============================================================================
bool Time::setSystemTimeToThisTime() const
{
    SYSTEMTIME st;

    st.wDayOfWeek = 0;
    st.wYear           = (WORD) getYear();
    st.wMonth          = (WORD) (getMonth() + 1);
    st.wDay            = (WORD) getDayOfMonth();
    st.wHour           = (WORD) getHours();
    st.wMinute         = (WORD) getMinutes();
    st.wSecond         = (WORD) getSeconds();
    st.wMilliseconds   = (WORD) (millisSinceEpoch % 1000);

    // do this twice because of daylight saving conversion problems - the
    // first one sets it up, the second one kicks it in.
    // NB: the local variable is here to avoid analysers warning about having
    // two identical sub-expressions in the return statement
    auto firstCallToSetTimezone = SetLocalTime (&st) != 0;
    return firstCallToSetTimezone && SetLocalTime (&st) != 0;
}

int SystemStats::getPageSize()
{
    SYSTEM_INFO systemInfo;
    GetNativeSystemInfo (&systemInfo);

    return (int) systemInfo.dwPageSize;
}

//==============================================================================
String SystemStats::getLogonName()
{
    TCHAR text [256] = { 0 };
    auto len = (DWORD) numElementsInArray (text) - 1;
    GetUserName (text, &len);
    return String (text, len);
}

String SystemStats::getFullUserName()
{
    return getLogonName();
}

String SystemStats::getComputerName()
{
    TCHAR text[128] = { 0 };
    auto len = (DWORD) numElementsInArray (text) - 1;
    GetComputerNameEx (ComputerNamePhysicalDnsHostname, text, &len);
    return String (text, len);
}

static String getLocaleValue (LCID locale, LCTYPE key, const char* defaultValue)
{
    TCHAR buffer [256] = { 0 };
    if (GetLocaleInfo (locale, key, buffer, 255) > 0)
        return buffer;

    return defaultValue;
}

String SystemStats::getUserLanguage()     { return getLocaleValue (LOCALE_USER_DEFAULT, LOCALE_SISO639LANGNAME,  "en"); }
String SystemStats::getUserRegion()       { return getLocaleValue (LOCALE_USER_DEFAULT, LOCALE_SISO3166CTRYNAME, "US"); }

String SystemStats::getDisplayLanguage()
{
    DynamicLibrary dll ("kernel32.dll");
    JUCE_LOAD_WINAPI_FUNCTION (dll,
                               GetUserPreferredUILanguages,
                               getUserPreferredUILanguages,
                               BOOL,
                               (DWORD, PULONG, PZZWSTR, PULONG))

    constexpr auto defaultResult = "en";

    if (getUserPreferredUILanguages == nullptr)
        return defaultResult;

    ULONG numLanguages = 0;
    ULONG numCharsInLanguagesBuffer = 0;

    // Retrieving the necessary buffer size for storing the list of languages
    if (! getUserPreferredUILanguages (MUI_LANGUAGE_NAME, &numLanguages, nullptr, &numCharsInLanguagesBuffer))
        return defaultResult;

    std::vector<WCHAR> languagesBuffer (numCharsInLanguagesBuffer);
    const auto success = getUserPreferredUILanguages (MUI_LANGUAGE_NAME,
                                                      &numLanguages,
                                                      languagesBuffer.data(),
                                                      &numCharsInLanguagesBuffer);

    if (! success || numLanguages == 0)
        return defaultResult;

    // The buffer contains a zero delimited list of languages, the first being
    // the currently displayed language.
    return languagesBuffer.data();
}

} // namespace juce