-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathRXMDocklet.cpp
More file actions
2135 lines (1876 loc) · 71.1 KB
/
Copy pathRXMDocklet.cpp
File metadata and controls
2135 lines (1876 loc) · 71.1 KB
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
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
RXMDocklet.cpp - "X" Monitor Docklet [DLL] implementation(s)
Copyright(c) 2009-2025, Robert Roessler
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "stdafx.h"
#include <atomic>
#include <mutex>
#include <thread>
#include <string>
#include <string_view>
#include <fstream>
#include <memory>
#include <set>
#include <map>
#include <unordered_map>
#include <vector>
#include <regex>
#include <charconv>
#include <format>
#include <functional>
#include "hwisenssm2.h"
#include "sdk/DockletSDK.h"
#include "TlHelp32.h"
#include "resource.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
/*
Helper template functions to derive [c]begin/[c]end iterators for C++
"native" multidimensional arrays... ultimately to be used with the std
library, e.g. copy(...).
*/
// (make sure we are "noexcept" to the maximum extent possible)
#define NOEXCEPT_RETURN(...) noexcept(noexcept(__VA_ARGS__)) { return (__VA_ARGS__); }
template <typename T>
requires std::is_array_v<T>
constexpr decltype(auto) decayed_begin(T&& c)
NOEXCEPT_RETURN(std::begin(std::forward<T>(c)))
template <typename T>
requires std::is_array_v<T>
constexpr decltype(auto) decayed_end(T&& c)
NOEXCEPT_RETURN(std::end(std::forward<T>(c)))
template <typename T, size_t N>
requires std::is_array_v<T>
constexpr decltype(auto) decayed_begin(T(&c)[N])
NOEXCEPT_RETURN(reinterpret_cast<typename std::remove_all_extents_t<T>*>(c))
template <typename T, size_t N>
requires std::is_array_v<T>
constexpr decltype(auto) decayed_end(T(&c)[N])
NOEXCEPT_RETURN(reinterpret_cast<typename std::remove_all_extents_t<T>*>(c + N))
/*
Define "alias templates" so as to use c++14 "is_transparent" comparators.
*/
template<typename T, typename Cmp = std::less<>>
using set = std::set<T, Cmp>;
template<typename K, typename T, typename Cmp = std::less<>>
using map = std::map<K, T, Cmp>;
using std::vector;
using std::string;
using std::wstring;
using std::string_view;
using std::begin, std::end, std::cbegin, std::cend;
using std::make_unique, std::unique_ptr;
using namespace std::string_literals;
// (resolve ambiguity with D2D declaration)
using Graphics = Gdiplus::Graphics;
using RectF = Gdiplus::RectF;
using Color = Gdiplus::Color;
using PointF = Gdiplus::PointF;
// set default sensor polling period (in ms)
constexpr auto polling_period = 1000;
// (change the following line to true for tracing with ::OutputDebugStringA())
constexpr auto trace_enabled = false;
template<typename... ARGS>
static void trace(const ARGS&... args)
{
if constexpr (trace_enabled) {
string_view fmt{ "RxTRACE> {}{}{}{}{}{}", min(sizeof...(ARGS), 6) * 2 + 9 };
::OutputDebugStringA(std::vformat(fmt, std::make_format_args(args...)).c_str());
}
}
template<typename... ARGS>
static void trace_ex(string_view fmt, const ARGS&... args)
{
if constexpr (trace_enabled)
::OutputDebugStringA(std::vformat("RxTRACE> "s.append(fmt), std::make_format_args(args...)).c_str());
}
/*
The rxm namespace contains all primary and supporting logic for
accessing and displaying the provider-specific shared memory based
data representations of some common "hardware monitors"... the
expected and supported client is the RXMDocklet plugin, compatible
with the ObjectDock Docklet SDK v1.0 interface specification(*).
Currently supported apps include GPU-Z, HWiNFO, CPUID HWMonitor,
MSI Afterburner, Core Temp, and SpeedFan.
* - this has only been tested/used with the [final] 1.3.5 version
of RocketDock... and even though the RocketDock download page says
that it is "unsupported" on 64-bit versions of Windows, it works!
*/
namespace rxm {
/*
sizeOfUTF8CodeUnits returns the length in bytes of a UTF-8 code point, based
on being passed the [presumed] first byte.
N.B. - if the passed value does NOT represent [the start of] a well-formed
UTF-8 code point, the returned length is ZERO, which means this should most
likely be used at least initially in a "validation" capacity.
Conceptually, this is the logic:
return
isascii(c) ? 1 :
(c & 0b11100000) == 0b11000000 ? 2 :
(c & 0b11110000) == 0b11100000 ? 3 :
(c & 0b11111000) == 0b11110000 ? 4 :
0; // (caller(s) should NOTICE this)
*/
constexpr size_t sizeOfUTF8CodeUnits(int u) noexcept {
return
"\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1" // 00-0f 1-byte UTF-8/ASCII
"\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1" // 10-1f
"\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1" // 20-2f
"\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1" // 30-3f
"\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1" // 40-4f
"\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1" // 50-5f
"\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1" // 60-6f
"\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1" // 70-7f
"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" // 80-8f <illegal>
"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" // 90-9f
"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" // a0-af
"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" // b0-bf
"\2\2\2\2\2\2\2\2\2\2\2\2\2\2\2\2" // c0-cf 2-byte UTF-8
"\2\2\2\2\2\2\2\2\2\2\2\2\2\2\2\2" // d0-df
"\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3" // e0-ef 3-byte UTF-8
"\4\4\4\4\4\4\4\4" // f0-f7 4-byte UTF-8
"\0\0\0\0\0\0\0\0" // f8-ff <illegal>
[u & 0xff];
}
constexpr size_t sizeOfUTF16CodeUnits(int u) noexcept {
return
u < 0xd800 ? 1 :
// u < 0xdc00 ? 2 : // (no need to distinguish this range separately)
u < 0xe000 || u >= 0x10000 ? 2 :
1;
}
/*
codePointToUTF8 is a template function providing flexible output options for
the encoded UTF-8 chars representing the supplied Unicode code point.
It is a template function so you can choose to store the output UTF-8 stream
either like this
char buf[80], * s = buf;
codePointToUTF8(c, [&](char x) { *s++ = x; })
or this
std::string buf;
codePointToUTF8(c, [&](char x) { buf.push_back(x); })
... where c is a Unicode code point in a char32_t.
*/
template<class CharOutput>
constexpr void codePointToUTF8(char32_t c, CharOutput f) {
if (c < 0x80)
f((char)c);
else if (c < 0x800)
f((char)(0b11000000 | (c >> 6))),
f((char)((c & 0b111111) | 0b10000000));
else if (c < 0x10000)
f((char)(0b11100000 | (c >> 12))),
f((char)(((c >> 6) & 0b111111) | 0b10000000)),
f((char)((c & 0b111111) | 0b10000000));
else
f((char)(0b11110000 | (c >> 18))),
f((char)(((c >> 12) & 0b111111) | 0b10000000)),
f((char)(((c >> 6) & 0b111111) | 0b10000000)),
f((char)((c & 0b111111) | 0b10000000));
}
template<class WordOutput>
constexpr void codePointToUTF16(char32_t c, WordOutput g) {
if (c < 0xd800 || (c >= 0xe000 && c < 0x10000))
g((wchar_t)c);
else {
const unsigned int v = c - 0x10000;
g((wchar_t)(0xd800 | (v & 0x3ff))), g((wchar_t)(0xdc00 | (v >> 10)));
}
}
constexpr char32_t codePointFromUTF8(const char* u) {
switch (const char8_t c = u[0]; sizeOfUTF8CodeUnits(c)) {
case 1: return c;
case 2: return (c & 0b11111) << 6 | (u[1] & 0b111111);
case 3: return (c & 0b1111) << 12 | (u[1] & 0b111111) << 6 | (u[2] & 0b111111);
case 4: return (c & 0b111) << 18 | (u[1] & 0b111111) << 12 | (u[2] & 0b111111) << 6 | (u[3] & 0b111111);
default: return 0; // (SHOULDN'T happen)
}
return 0; // ("CAN'T happen")
}
constexpr char32_t codePointFromUTF16(const wchar_t* u) {
return
sizeOfUTF16CodeUnits(u[0]) == 1 ? u[0] :
((u[0] - 0xd800) << 10) + (u[1] - 0xdc00) + 0x10000;
}
constexpr string utf8StringFromUTF16(const wchar_t* u) {
string t;
while (*u)
codePointToUTF8(codePointFromUTF16(u), [&t](char c) { t.push_back(c); }),
u += sizeOfUTF16CodeUnits(*u);
return t;
}
constexpr wstring utf16StringFromUTF8(const char* u) {
wstring t;
while (*u)
codePointToUTF16(codePointFromUTF8(u), [&t](wchar_t c) { t.push_back(c); }),
u += sizeOfUTF8CodeUnits(*u);
return t;
}
/*
Definition and implementation of simple [threading-aware] spinlock
*/
class RSpinLock {
std::atomic_flag lock_{};
public:
bool test() const noexcept { return lock_.test(); }
void lock() noexcept {
// try simple lock...
while (lock_.test_and_set(std::memory_order_acquire))
// ... nope, release time slice and keep trying
std::this_thread::yield();
}
void unlock() noexcept { lock_.clear(std::memory_order_release); }
};
/*
Implementation of Windows-style shared memory mapping
*/
class Mapping {
HANDLE mH{}; // mapped obj handle
LPBYTE vB{}; // mapped obj view base
size_t vN{}; // mapped obj view size
public:
Mapping() {}
~Mapping ()
{
if (vN != 0)
::UnmapViewOfFile(vB), ::CloseHandle(mH);
}
auto Create(const char* sharedObjName)
{
if (vN != 0)
return
trace_ex("MAPPING of '{}' ALREADY PRESENT @{:p} with {:#x} bytes", sharedObjName, (void*)vB, vN),
true; // (mapping ALREADY here)
mH = ::OpenFileMapping(GENERIC_READ, FALSE, sharedObjName);
if (mH == nullptr)
return false; // we're outta here
vB = (LPBYTE)::MapViewOfFile(mH, FILE_MAP_READ, 0, 0, 0);
if (vB == nullptr) {
::CloseHandle(mH), mH = nullptr;
return false; // we're outta here
}
MEMORY_BASIC_INFORMATION mbI;
if (::VirtualQuery(vB, &mbI, sizeof mbI) != sizeof mbI) {
::UnmapViewOfFile(vB), vB = nullptr, ::CloseHandle(mH), mH = nullptr;
return false; // we're outta here
}
vN = mbI.RegionSize; // NOW it's a full mapping
trace_ex("MAPPED '{}' @{:p} with {:#x} bytes", sharedObjName, (void*)vB, vN);
return true;
}
constexpr auto Base() const { return vB; }
constexpr auto Size() const { return vN; }
};
/*
primary types for dealing with sensor paths and collections
*/
using sensor_t = string;
using sensor_enumeration_t = set<sensor_t>;
// (generic COMPILE-TIME "get integer value for typesafe enum" function)
template<class E>
requires std::is_enum_v<E>
constexpr auto as_int(E u) { return static_cast<std::underlying_type_t<E>>(u); }
enum class LayoutConf { Pages = 4, LayoutsPerPage = 8, BackgroundImages = 10 };
enum class RenderType { Normal = 0, Forced, StartFocus, EndFocus };
/*
"universal" units to which all Monitor-specific units are mapped
*/
enum class Unit {
None,
// "base" units understood across most providers
Volts, Degrees, RPM, Amps, Watts, MHz, UsagePerCent,
// "extended" units from "comprehensive" providers
MB, MBs, YorN, GTs, T, X, KBs,
// even MORE "extended" units
FPS, MS, GB, DB,
Unknown
};
/*
utility functions for accessing [sensor] path components
*/
static constexpr string_view head(string_view path)
{
const auto i = path.find_first_of('|');
return i != string::npos ? path.substr(0, i) : "";
}
static constexpr string_view tail(string_view path)
{
const auto i = path.find_last_of('|');
return i != string::npos ? path.substr(i + 1) : "";
}
static inline vector<string> split(string_view path, const std::regex& sep)
{
std::cregex_token_iterator first(path.data(), path.data() + path.size(), sep, -1), last;
return { first, last };
}
/*
primary INTERFACE for talking to [abstract] "Monitors"...
*/
class IMonitor {
public:
virtual ~IMonitor() {};
virtual constexpr string DisplayName() const = 0;
virtual bool Refresh() = 0;
virtual constexpr bool RefreshNeeded() const = 0;
virtual const sensor_enumeration_t& Sensors() const = 0;
virtual constexpr Unit SensorUnit(string_view path) const = 0;
virtual constexpr string SensorUnitString(string_view path, bool fahrenheit = false) const = 0;
virtual constexpr float SensorValue(string_view path, bool fahrenheit = false) const = 0;
virtual constexpr string SensorValueString(string_view path, bool fahrenheit = false) const = 0;
virtual constexpr string FormatSensorValue(string_view path, float value) const = 0;
};
/*
... common functions and data elements supporting IMonitor IMPLEMENTATIONS
*/
class MonitorCommonImpl : public IMonitor {
protected:
using enum Unit;
using Value = std::function<float(void)>;
Mapping mapping;
string root, displayName;
sensor_enumeration_t sensors;
map<string_view, Value> values;
map<string_view, Unit> units;
RSpinLock lock;
MonitorCommonImpl() = delete;
MonitorCommonImpl(string root, string displayName) : root(root), displayName(displayName) {}
template<class SynchronizedInit>
bool refreshImpl(SynchronizedInit f) {
std::lock_guard acquire(lock);
return f();
}
// N.B. - supplied sensor path "consumed" by std::move!
void use_sensor(sensor_t& p, Value v, Unit u) {
const auto r = sensors.emplace(std::move(p));
const string_view k{ *r.first };
values[k] = v, units[k] = u;
trace(k);
}
public:
constexpr string DisplayName() const override { return displayName; }
constexpr bool RefreshNeeded() const override { return false; }
const sensor_enumeration_t& Sensors() const override { return sensors; }
Unit SensorUnit(string_view path) const override {
const auto u = units.find(path);
return u != cend(units) ? u->second : None;
}
float SensorValue(string_view path, bool fahrenheit) const override {
float ret{};
std::lock_guard acquire(const_cast<RSpinLock&>(lock));
const auto v = values.find(path);
const auto u = units.find(path);
if (v == cend(values) || u == cend(units))
ret = std::numeric_limits<float>::infinity(); // sensor not present
else try {
auto c2f = [](auto f) noexcept { return floor((f * 9 / 5 + 32) + 0.5); };
ret = (u->second == Degrees && fahrenheit) ? (float)c2f(v->second()) : v->second();
} catch (...) {
ret = std::numeric_limits<float>::infinity(); // sensor not present
}
return ret;
}
string SensorUnitString(string_view path, bool fahrenheit) const override {
const auto& u = SensorUnit(path);
/*
display representation for above "universal" units
N.B. - Unit enums will be used as indices into this array, so
make SURE they are kept in sync!
*/
static const constinit char* unitString[]{
"None",
"V", (const char*)u8"°", "rpm", "A", "W", "MHz", "%",
"MB", "MB/s", "", "GT/s", "T", "x", "KB/s",
"F/s", "ms", "GB", "dB",
"???"
};
string s{ unitString[as_int(u)] };
if (u == Degrees)
s.push_back(fahrenheit ? 'F' : 'C');
return s;
}
constexpr string SensorValueString(string_view path, bool fahrenheit) const override {
return FormatSensorValue(path, SensorValue(path, fahrenheit));
}
// N.B. - expects to receive an ALREADY Fahrenheit-adjusted value
constexpr string FormatSensorValue(string_view path, float value) const noexcept override {
const auto& u = SensorUnit(path);
// check for early out on non-numeric
if (u == YorN)
return value != 0 ? "Yes" : "No";
/*
# of fractional digits to display for above "universal" units
N.B. - Unit enums will be used as indices into this array, so
make SURE they are kept in sync!
*/
auto w{
"\000"
"\003\000\000\003\003\001\001"
"\000\003\000\001\000\000\003"
"\000\000\000\000"
"\000"
[as_int(u)]};
/*
Use "dynamic precision reduction" to stay within ~4 digits...
"fractional digits" width value is a *hint*, not absolute!
*/
if (w == 1) {
// try dropping decimal on simple width check...
if (value >= 1000 ||
// ... or try "Fan" heuristic (aka "hack")
(u == UsagePerCent && path.find("Fan") != string::npos))
w = 0;
} else if (w == 3)
if (value >= 100)
w = 1;
else if (value >= 10)
w = 2;
char b[16];
const auto [p, e] = std::to_chars(b, b + std::size(b), value, std::chars_format::fixed, (int)w);
return { b, p };
}
};
/*
Implementation of IMonitor for MSI Afterburner
*/
class ABMonitor : public MonitorCommonImpl {
using enum Unit;
#pragma pack(push, 1)
struct MAHM_SHARED_MEMORY_HEADER {
DWORD dwSignature; // 'MAHM' or not currently valid
DWORD dwVersion; // version of structure 2.0 == 0x20000
DWORD dwHeaderSize; // our size
DWORD dwNumEntries; // # of MAHM_SHARED_MEMORY_ENTRYs
DWORD dwEntrySize; // size of MAHM_SHARED_MEMORY_ENTRY
// WARNING! Force 32-bit time_t usage with #define _USE_32BIT_TIME_T
// to provide compatibility with VC8.0 and newer compiler versions,
// OR force use of __time32_t directly!
__time32_t time; // last poll time
DWORD dwNumGpuEntries; // # of MAHM_SHARED_MEMORY_GPU_ENTRYs
DWORD dwGpuEntrySize; // size of MAHM_SHARED_MEMORY_GPU_ENTRY
};
enum ShowTarget { ShowInOSD = 1, ShowInLCD = 2, ShowInTray = 4 };
struct MAHM_SHARED_MEMORY_ENTRY {
char szSrcName[MAX_PATH]; // source name
char szSrcUnits[MAX_PATH]; // source units
char szLocSrcName[MAX_PATH]; // [localized] source name
char szLocSrcUnits[MAX_PATH]; // [localized] source units
char szFormat[MAX_PATH]; // preferred formatting string
float data; // last value or FLOAT_MAX
float minLimit;
float maxLimit;
DWORD dwFlags; // control flags (from ShowTarget enum)
DWORD dwGpu; // GPU # component of data src
DWORD dwSrcId; // [per-GPU] ID # component of data src
};
struct MAHM_SHARED_MEMORY_GPU_ENTRY {
char szGpuId[MAX_PATH]; // Device Manager -style path name
char szFamily[MAX_PATH]; // GPU "family"
char szDevice[MAX_PATH]; // device description
char szDriver[MAX_PATH]; // driver descriptive name
char szBIOS[MAX_PATH]; // BIOS descriptive name
DWORD dwMemAmount; // device memory in KB
};
#pragma pack(pop)
int enumerateSensors();
auto& ab() const { return *(const MAHM_SHARED_MEMORY_HEADER*)mapping.Base(); }
auto& rE(int i) const { return *(MAHM_SHARED_MEMORY_ENTRY*)(mapping.Base() + ab().dwHeaderSize + ab().dwEntrySize * i); }
auto& gE(int i) const { return *(MAHM_SHARED_MEMORY_GPU_ENTRY*)(mapping.Base() + ab().dwHeaderSize + ab().dwEntrySize * ab().dwNumEntries + ab().dwGpuEntrySize * i); }
auto unitFromRecord(const MAHM_SHARED_MEMORY_ENTRY& r) const;
public:
ABMonitor(string root, string displayName) : MonitorCommonImpl(root, displayName) {}
~ABMonitor() override {}
bool Refresh() override {
return refreshImpl([this]() { return mapping.Create("MAHMSharedMemory") && enumerateSensors() > 0; });
}
};
auto ABMonitor::unitFromRecord(const MAHM_SHARED_MEMORY_ENTRY& r) const
{
// N.B. - MSI Afterburner uses (at best) a narrow code-page value for <degrees>
static const map<string, Unit> types{
{ "V", Volts }, { "\xb0""C", Degrees }, { "RPM", RPM }, { "MHz", MHz },
{ "%", UsagePerCent }, { "MB", MB }, { "FPS", FPS }, { "ms", MS },
{"W", Watts}
};
const auto u = types.find(r.szSrcUnits);
return u != cend(types) ? u->second : Unknown;
}
int ABMonitor::enumerateSensors()
{
trace("ABMonitor::enumerateSensors...");
sensors.clear(), values.clear(), units.clear();
const auto& a = ab();
if (a.dwSignature != 'MAHM')
return 0; // nothing to see here...
for (decltype(a.dwNumEntries) i = 0; i < a.dwNumEntries; ++i) {
const auto& r = rE(i);
if (const auto u = unitFromRecord(r); u != None) {
auto path{ std::format("{}|", root) };
if (r.dwSrcId != 0xffffffff && r.dwSrcId < 0x80) {
std::format_to(std::back_inserter(path), "{}", gE(r.dwGpu).szDevice);
/*
append #2, #3 etc for any subsequent GPUs - a simplifying
assumption, since cases when they AREN'T in a "standard"
SLI/Crossfire configuration should be rare (we will see
how the case of discrete GPU + integrated GPU stabilizes)
*/
if (r.dwGpu > 0)
std::format_to(std::back_inserter(path), " #{}", r.dwGpu + 1);
} else
path += "pc";
std::format_to(std::back_inserter(path), "|{}", r.szSrcName);
use_sensor(path, [&r]() { return r.data; }, u);
}
}
trace("ABMonitor found ", sensors.size(), " sensors");
return sensors.size();
}
/*
Implementation of IMonitor for Core Temp
*/
class CTMonitor : public MonitorCommonImpl {
using enum Unit;
#pragma pack(push, 1)
typedef struct core_temp_shared_data_ex {
// Original structure (CoreTempSharedData)
unsigned int uiLoad[256];
unsigned int uiTjMax[128];
unsigned int uiCoreCnt;
unsigned int uiCPUCnt;
float fTemp[256];
float fVID;
float fCPUSpeed;
float fFSBSpeed;
float fMultiplier;
char sCPUName[100];
unsigned char ucFahrenheit;
unsigned char ucDeltaToTjMax;
// uiStructVersion = 2
unsigned char ucTdpSupported;
unsigned char ucPowerSupported;
unsigned int uiStructVersion;
unsigned int uiTdp[128];
float fPower[128];
float fMultipliers[256];
} CoreTempSharedDataEx, *LPCoreTempSharedDataEx, **PPCoreTempSharedDataEx;
#pragma pack(pop)
int enumerateSensors();
auto& ct() const { return *(const CoreTempSharedDataEx*)mapping.Base(); }
public:
CTMonitor(string root, string displayName) : MonitorCommonImpl(root, displayName) {}
~CTMonitor() override {}
bool Refresh() override {
return refreshImpl([this]() { return mapping.Create("CoreTempMappingObjectEx") && enumerateSensors() > 0; });
}
};
int CTMonitor::enumerateSensors()
{
trace("CTMonitor::enumerateSensors...");
sensors.clear(), values.clear(), units.clear();
const auto& c = ct();
for (decltype(c.uiCPUCnt) cpu = 0; cpu < c.uiCPUCnt; ++cpu) {
auto off = c.uiCoreCnt * cpu;
const auto cpuPath{ std::format("{}|CPU [#{}]: {}|", root, cpu, c.sCPUName) };
auto vidPath{ cpuPath + "VID" };
use_sensor(vidPath, [&c]() { return c.fVID; }, Volts);
if (c.uiStructVersion >= 2 && c.ucTdpSupported) {
auto tdpPath{ cpuPath + "TDP" };
use_sensor(tdpPath, [off, &c]() { return (float)c.uiTdp[off]; }, Watts);
}
if (c.uiStructVersion >= 2 && c.ucPowerSupported) {
auto powerPath{ cpuPath + "Power" };
use_sensor(powerPath, [off, &c]() { return c.fPower[off]; }, Watts);
}
for (decltype(c.uiCoreCnt) core = 0; core < c.uiCoreCnt; ++core, ++off) {
const auto corePath{ std::format("{}Core #{}", cpuPath, core) };
auto tempPath{ corePath + " Temperature" };
Value v;
if (c.ucDeltaToTjMax)
v = [off, &c]() { return c.uiTjMax[0] - c.fTemp[off]; };
else
v = [off, &c]() { return c.fTemp[off]; };
use_sensor(tempPath, v, Degrees);
auto loadPath{ corePath + " Load" };
use_sensor(loadPath, [off, &c]() { return (float)c.uiLoad[off]; }, UsagePerCent);
}
}
trace("CTMonitor found ", sensors.size(), " sensors");
return sensors.size();
}
/*
Implementation of IMonitor for GPU-Z
*/
class GPUZMonitor : public MonitorCommonImpl {
using enum Unit;
enum { MaxRecords = 128 };
#pragma pack(push, 1)
struct Record {
wchar_t key[256];
wchar_t val[256];
};
struct SensorRecord {
wchar_t name[256];
wchar_t unit[8];
DWORD digits;
double value;
};
struct GpuzSharedMem {
DWORD version; // version of structure
volatile LONG busy; // updatING
DWORD updated; // [last] updatED from ::GetTickCount()
Record data[MaxRecords];
SensorRecord sensors[MaxRecords];
};
#pragma pack(pop)
int enumerateSensors();
auto& gpuz() const { return *(const GpuzSharedMem*)mapping.Base(); }
auto unitFromRecord(const SensorRecord& r) const;
public:
GPUZMonitor(string root, string displayName) : MonitorCommonImpl(root, displayName) {}
~GPUZMonitor() override {}
bool Refresh() override {
return refreshImpl([this]() { return mapping.Create("GPUZShMem") && enumerateSensors() > 0; });
}
};
auto GPUZMonitor::unitFromRecord(const SensorRecord& r) const
{
static const map<wstring, Unit> types{
{L"V", Volts}, {L"°C", Degrees}, {L"RPM", RPM}, {L"MHz", MHz},
{L"%", UsagePerCent}, {L"%%", UsagePerCent}
};
const auto u = types.find(r.unit);
return u != cend(types) ? u->second : None;
}
int GPUZMonitor::enumerateSensors()
{
trace("GPUZMonitor::enumerateSensors...");
sensors.clear(), values.clear(), units.clear();
const auto& g = gpuz();
const auto& device = std::find_if(cbegin(g.data), cend(g.data), [](const auto& r) {
return strcmp(utf8StringFromUTF16(r.key).c_str(), "CardName") == 0;
});
string deviceName{ utf8StringFromUTF16(device != cend(g.data) ? device->val : L"<Graphics Card>") };
for (const auto& s : g.sensors) {
if (s.name[0] == L'\0')
break; // nothing more to examine
if (const auto u = unitFromRecord(s); u != None) {
auto path{ std::format("{}|{}|{}", root, deviceName, utf8StringFromUTF16(s.name)) };
use_sensor(path, [&s]() { return (float)s.value; }, u);
}
}
trace("GPUZMonitor found ", sensors.size(), " sensors");
return sensors.size();
}
/*
Implementation of IMonitor for HWiNFO
*/
class HWiMonitor : public MonitorCommonImpl {
using enum Unit;
int enumerateSensors();
auto& hwi() const { return *(const HWiNFO_SENSORS_SHARED_MEM2*)mapping.Base(); }
auto& sE(int i) const { return *(PHWiNFO_SENSORS_SENSOR_ELEMENT)(mapping.Base() + hwi().dwOffsetOfSensorSection + hwi().dwSizeOfSensorElement * i); }
auto& rE(int i) const { return *(PHWiNFO_SENSORS_READING_ELEMENT)(mapping.Base() + hwi().dwOffsetOfReadingSection + hwi().dwSizeOfReadingElement * i); }
auto unitFromReading(const HWiNFO_SENSORS_READING_ELEMENT& r) const;
DWORD origSensors = 0;
DWORD origReadings = 0;
public:
HWiMonitor(string root, string displayName) : MonitorCommonImpl(root, displayName) {}
~HWiMonitor() override {}
bool Refresh() override {
return refreshImpl([this]() { return mapping.Create(HWiNFO_SENSORS_MAP_FILE_NAME2) && enumerateSensors() > 0; });
}
bool RefreshNeeded() const override {
const auto& h = hwi();
return h.dwNumSensorElements != origSensors || h.dwNumReadingElements != origReadings;
}
};
auto HWiMonitor::unitFromReading(const HWiNFO_SENSORS_READING_ELEMENT& r) const
{
switch (r.tReading) {
case SENSOR_TYPE_NONE:
return None;
case SENSOR_TYPE_TEMP:
return Degrees;
case SENSOR_TYPE_VOLT:
return Volts;
case SENSOR_TYPE_FAN:
return RPM;
case SENSOR_TYPE_CURRENT:
return Amps;
case SENSOR_TYPE_POWER:
return Watts;
case SENSOR_TYPE_CLOCK:
return MHz;
case SENSOR_TYPE_USAGE:
return UsagePerCent;
case SENSOR_TYPE_OTHER: {
// try to deduce our Unit from the "units" string in the READING...
// [UsagePerCent], MB, MBs, YorN, GTs, T, X, KBs
static const map<string, Unit> extendedTypes{
{"%", UsagePerCent},
{"MB", MB}, {"MB/s", MBs}, {"Yes/No", YorN}, {"GT/s", GTs},
{"T", T}, {"x", X}, {"KB/s", KBs}, {"GB", GB}, {"dB", DB}
};
const auto u = extendedTypes.find(r.szUnit);
return u != cend(extendedTypes) ? u->second : Unknown; // we did our best
}
default:
return None; // "shouldn't happen"
}
}
int HWiMonitor::enumerateSensors()
{
trace("HWiMonitor::enumerateSensors...");
// create a "sensorNameFromInstanceNumber"
auto computedSensorName = [](auto s) {
string deviceName{ s.szSensorNameUser };
if (s.dwSensorInst > 0)
std::format_to(std::back_inserter(deviceName), " #{}", s.dwSensorInst + 1);
return deviceName;
};
sensors.clear(), values.clear(), units.clear();
const auto& h = hwi();
if (h.dwSignature != 'SiWH')
return 0; // nothing to see here...
origSensors = h.dwNumSensorElements, origReadings = h.dwNumReadingElements;
for (decltype(h.dwNumReadingElements) i = 0; i < h.dwNumReadingElements; ++i) {
const auto& r = rE(i);
if (const auto u = unitFromReading(r); u != None) {
const auto& s = sE(r.dwSensorIndex);
auto path{ std::format("{}|{}|{}", root, computedSensorName(s), r.szLabelUser) };
if (r.szUnit[0])
std::format_to(std::back_inserter(path), " {}", r.szUnit);
use_sensor(path, [&r]() { return (float)r.Value; }, u);
}
}
trace("HWiMonitor found ", sensors.size(), " sensors");
return sensors.size();
}
/*
Implementation of IMonitor for CPUID HWMonitor
N.B. - ONLY good for versions 1.14 - 1.16 of HWMonitor - after that, they
appear to have "locked down" the shared memory interface such that only
zeros are returned.
*/
class HWMonitor : public MonitorCommonImpl {
enum { MaxGroups = 10 }; // HW Monitor 1.14-1.16 (1.13 was 9)
typedef struct {
unsigned char pad1[80]; // unknown
DWORD deviceNum; // # of HWMDevice structs
// HWMDevice structs base
} HWMHdr;
typedef struct {
DWORD nodeNum; // # of HWMSensor structs
DWORD nodePtr; // HWMSensor structs addr
} HWMSensorMap;
typedef struct {
char description[64]; // full descriptive device name
DWORD type; // type bit mask???
DWORD layout; // type extension / groups layout???
HWMSensorMap map[MaxGroups]; // map of HWMSensor structs
} HWMDevice;
typedef struct {
unsigned char pad1[8]; // unknown
char name[32]; // terse sensor name
DWORD value0; // sensor val (raw?)
float value; // sensor val
} HWMSensor;
const auto& device(int d) const { return ((const HWMDevice*)(mapping.Base() + sizeof HWMHdr))[d]; }
int deviceCount() const { return mapping.Base() ? ((const HWMHdr*)mapping.Base())->deviceNum : 0; }
const char* deviceDescription(int d) const { return mapping.Base() && d < deviceCount() ? device(d).description : "" ; }
int enumerateSensors();
const char* groupType(int g) const {
static const constinit char* sensorGroupTypes[MaxGroups]{
"<voltages>",
"<temperatures>",
"<fans>",
"<PWM fans>",
"<currents>",
"<powers>",
"xxx", "xxx", "xxx", "xxx"
};
return g < MaxGroups ? sensorGroupTypes[g] : "";
}
const auto& node(int d, int g, int s) const { return ((const HWMSensor*)(mapping.Base() + device(d).map[g].nodePtr))[s]; }
int sensorCount(int d, int g) const { return mapping.Base() && d < deviceCount() && g < MaxGroups ? device(d).map[g].nodeNum : 0; }
const char* sensorLabel(int d, int g, int s) const { return mapping.Base() && d < deviceCount() && g < MaxGroups && s < sensorCount(d, g) ? node(d, g, s).name : ""; }
auto unitFromDGS(int d, int g, int s) const;
public:
HWMonitor(string root, string displayName) : MonitorCommonImpl(root, displayName) {}
~HWMonitor() override {}
bool Refresh() override {
return refreshImpl([this]() { return mapping.Create("$CPUID$HWM$") && enumerateSensors() > 0; });
}
};
auto HWMonitor::unitFromDGS(int d, int g, int s) const {
using enum Unit;
static constexpr Unit g2u[]{ Volts, Degrees, RPM, RPM, Amps, Watts, Unknown, Unknown, Unknown, Unknown };
return mapping.Base() && d < deviceCount() && g < MaxGroups && s < sensorCount(d, g) ? g2u[g] : None;
}
int HWMonitor::enumerateSensors()
{
auto dgs = [](auto d, auto g, auto s) {
return std::format("{},{},{}", d, g, s);
};
trace("HWMonitor::enumerateSensors...");
std::multiset<string> devices;
sensors.clear(), values.clear(), units.clear();
for (auto d = 0; d < deviceCount(); ++d) {
const string deviceName{ deviceDescription(d) };
devices.emplace(deviceName);
const auto dupes = devices.count(deviceName);
for (auto g = 0; g < MaxGroups; ++g)
for (auto s = 0; s < sensorCount(d, g); ++s) {
auto path{ std::format("{}|{}", root, deviceName) };
if (dupes > 1)
std::format_to(std::back_inserter(path), " #{}", dupes);
// N.B. - ONLY CPUID Hardware Monitor needs this "extra" level
std::format_to(std::back_inserter(path), "|{}|{}", groupType(g), sensorLabel(d, g, s));
const auto& r{ node(d, g, s) };
use_sensor(path, [&r]() { return r.value; }, unitFromDGS(d, g, s));
}
}
trace("HWMonitor found ", sensors.size(), " sensors");
return sensors.size();
}
/*
Implementation of IMonitor for SpeedFan
N.B. - a number of the IT8720F sensor readings for voltages appear to be
incorrect - as these show this way in the SpeedFan app itself, they are
of course passed on by RXMDocklet... YMMV, of course.
*/
class SFMonitor : public MonitorCommonImpl {
enum { Temps = 32, Fans = 32, Voltages = 32 };
enum ParseState {
WantVer, WantTag, WantDeviceName, WantTempName, WantFanName, WantVoltName, WantEnd
};