-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhdesktop.cpp
More file actions
8300 lines (6786 loc) · 367 KB
/
Copy pathhdesktop.cpp
File metadata and controls
8300 lines (6786 loc) · 367 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
/*
* Copyright 2026, Kris Beazley hDesktop@epluribusunix.net
* All rights reserved. Distributed under the terms of the MIT license.
*/
#include <Alert.h>
#include <algorithm>
#include <AppKit.h>
#include <AppServerLink.h>
#include <Bitmap.h>
#include <Button.h>
#include <CheckBox.h>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstdarg>
#include <cstring>
#include <ctime>
#include <curl/curl.h>
#include <Deskbar.h>
#include <Directory.h>
#include <Entry.h>
#include <File.h>
#include <FindDirectory.h>
#include <Font.h>
#include <fs_attr.h>
#include <GL/gl.h>
#include <GL/glu.h>
#include <IconUtils.h>
#include <InterfaceDefs.h>
#include <InterfaceKit.h>
#include <iostream>
#include <map>
#include <MediaNode.h>
#include <MediaRoster.h>
#include <MessageRunner.h>
#include <MenuItem.h>
#include <Message.h>
#include <Messenger.h>
#include <MenuField.h>
#include <Node.h>
#include <NodeInfo.h>
#include <NodeMonitor.h>
#include <Notification.h>
#include <OS.h>
#include <ParameterWeb.h>
#include <Path.h>
#include <PopUpMenu.h>
#include <Rect.h>
#include <Roster.h>
#include <Screen.h>
#include <ScrollView.h>
#include <SDL2/SDL.h>
#include <SDL2/SDL_opengl.h>
#include <SDL2/SDL_syswm.h>
#include <set>
#include <Shape.h>
#include <stdio.h>
#include <stdlib.h>
#include <StorageKit.h>
#include <String.h>
#include <string>
#include <SupportDefs.h>
#include <SupportKit.h>
#include <TranslationUtils.h>
#include <vector>
#include <View.h>
#include <Window.h>
#include <NavMenu.h>
#include <WindowInfo.h>
#define APP_LOCAL_VERSION "v1.0.47"
class HaikuGlDesktopEngine;
class HaikuAppDrawerWindow;
HaikuAppDrawerWindow* gActiveDrawerInstance = nullptr;
BWindow* gActiveConfigInstance = nullptr;
std::set<std::string> gFavoritePaths;
bool gDebugEnabled = false; // Set by -d / --debug on the command line
// Prints only when hdesktop was launched with -d / --debug; a no-op otherwise.
static void DebugLog(const char* fmt, ...) {
if (!gDebugEnabled) return;
va_list args;
va_start(args, fmt);
vfprintf(stderr, fmt, args);
va_end(args);
fflush(stderr);
}
bool autoHideEnabled;
bool showSystemTray;
bool dockAlwaysOnTop;
bool fShowTitleOverlays = true;
bool fShowWorkspaceSwitcher = false;
// Which screen edge the dock is pinned to. Left/Right are intentionally not
// offered in the settings UI yet -- the dock's layout, hit-testing, and
// drag/drop are all built around a horizontal strip, so supporting a
// vertical (left/right) dock needs a follow-up pass of its own.
enum DockLocation {
kDockLocationBottom = 0,
kDockLocationTop = 1
};
int32 gDockLocation = kDockLocationBottom;
bool fEffectBounceEnabled = false;
bool fEffectSpinEnabled = true;
bool fEffectIllusionEnabled = false;
bool fEffectWobbleEnabled = false;
bool fEffectExplodeEnabled = false;
bool fEffectCloseBounceEnabled = false;
bool fEffectCloseSpinEnabled = false;
bool fEffectCloseIllusionEnabled = false;
bool fEffectCloseWobbleEnabled = false;
bool fEffectCloseExplodeEnabled = false;
void SaveConfiguration();
float fBaseIconSize = 48.0f;
float maxDockHeight = 160.0f;
float fDockAlpha = 0.40f;
uint32 fSpinDurationMs = 750;
const char* const kSettingsIconSizeKey = "base_icon_size";
const char* const kSettingsAlphaKey = "dock_alpha";
const char* const kSettingsSpinDurationKey = "spin_duration";
rgb_color GetLiveSystemBackgroundColor() {
// Default fallback color (Standard Haiku Grey)
rgb_color color = { 216, 216, 216, 255 };
BFile file("/boot/home/config/settings/system/app_server/appearance", B_READ_ONLY);
if (file.InitCheck() != B_OK) return color;
BMessage settingsMsg;
if (settingsMsg.Unflatten(&file) != B_OK) return color;
int32 packedColorValue = 0;
if (settingsMsg.FindInt32("color2", &packedColorValue) == B_OK) {
// CORRECTED BYTE OFFSET SHIFTS FOR LITTLE-ENDIAN HAIKU MESSAGES:
color.red = (uint8)(packedColorValue & 0xFF);
color.green = (uint8)((packedColorValue >> 8) & 0xFF);
color.blue = (uint8)((packedColorValue >> 16) & 0xFF);
color.alpha = (uint8)((packedColorValue >> 24) & 0xFF);
// Safety fallback: if Alpha channel decodes to 0, force full opacity
if (color.alpha == 0) color.alpha = 255;
}
return color;
}
// The real, authoritative desktop background color for a workspace -- whatever
// Haiku is actually showing behind a missing/undersized wallpaper on it, whether
// that color came from the Backgrounds preflet's per-workspace picker or from
// Haiku's own default. We read this rather than pushing our own guess at it, so
// per-workspace customization in Backgrounds is never overwritten, and it works
// the same regardless of whether the user last changed colors via Backgrounds or
// via Appearance.
rgb_color GetHaikuWorkspaceDesktopColor(int32 workspace) {
BScreen screen(B_MAIN_SCREEN_ID);
return screen.DesktopColor(workspace);
}
enum {
SDL_EVENT_WALLPAPER_CHANGED = SDL_USEREVENT + 1,
MSG_AUTOHIDE_TOGGLED = 'ahtg',
MSG_SYSTEMTRAY_TOGGLED = 'sttg',
MSG_TEXTOVERLAYS_TOGGLED = 'totg',
MSG_WORKSPACESWITCHER_TOGGLED = 'wstg',
MSG_DOCKLOCATION_BOTTOM_TOGGLED = 'dlbt',
MSG_DOCKLOCATION_TOP_TOGGLED = 'dltp',
MSG_LAUNCH_CONFIG_WINDOW = 'lcfg',
MSG_AUTORAISE_TOGGLED = 'srdt',
MSG_EFFECT_SPEED_SLIDER_CHANGED = 'efsc',
MSG_ALPHA_SLIDER_CHANGED = 'alsc',
MSG_ICON_SIZE_CHANGED = 'isic',
MSG_EFFECT_OPEN_NONE_TOGGLED = 'efon',
MSG_EFFECT_BOUNCE_TOGGLED = 'efbn',
MSG_EFFECT_SPIN_TOGGLED = 'efsp',
MSG_EFFECT_ILLUSION_TOGGLED = 'efil',
MSG_EFFECT_WOBBLE_TOGGLED = 'efwb',
MSG_EFFECT_EXPLODE_TOGGLED = 'efex',
MSG_EFFECT_CLOSE_NONE_TOGGLED = 'efcn',
MSG_EFFECT_CLOSE_BOUNCE_TOGGLED = 'efcb',
MSG_EFFECT_CLOSE_SPIN_TOGGLED = 'efcs',
MSG_EFFECT_CLOSE_ILLUSION_TOGGLED = 'efci',
MSG_EFFECT_CLOSE_WOBBLE_TOGGLED = 'efcw',
MSG_EFFECT_CLOSE_EXPLODE_TOGGLED = 'efcx'
};
struct TrackedWindowInfo {
BString title;
int32 windowIndex;
BRect hitBox;
// Explicit constructor to fix brace-enclosed initialization failures
TrackedWindowInfo(BString t, int32 idx, BRect box)
: title(t), windowIndex(idx), hitBox(box) {}
};
struct LeafMenuArgs {
HaikuGlDesktopEngine* engine;
int32 winX;
int32 winY;
int32 mouseX;
float currentDockH;
};
struct TrayItem {
std::string name;
int32 internalId;
GLuint textureId;
float currentRenderX;
float currentRenderWidth;
};
std::vector<TrayItem> fLiveTrayItems;
bigtime_t fLastTrayUpdateTime = 0;
struct SystrayMenuArgs {
HaikuGlDesktopEngine* engine;
int32 winX;
int32 winY;
int32 mouseX;
int32 mouseY;
std::string itemName;
};
struct CpuMenuArgs {
HaikuGlDesktopEngine* engine;
int32 winX;
int32 winY;
int32 mouseX;
int32 mouseY;
float currentDockH;
};
struct HaikuRect {
float left, top, right, bottom;
bool Contains(float x, float y) const {
return (x >= left && x <= right && y >= top && y <= bottom);
}
float Width() const {
return right - left;
}
float Height() const {
return bottom - top;
}
};
struct HaikuPoint {
float x;
float y;
};
struct HaikuTexture {
GLuint id = 0;
int width = 0;
int height = 0;
};
// Mirrors BPrivate::BackgroundImage::Mode (tracker/BackgroundImage.h) -- the numeric
// values are what Tracker actually writes into the "be:bgndimginfomode" attribute.
enum HaikuWallpaperMode {
kWallpaperAtOffset = 0, // "Manual" placement in Backgrounds prefs
kWallpaperCentered = 1,
kWallpaperScaledToFit = 2,
kWallpaperTiled = 3
};
struct HaikuWallpaperInfo {
BString path;
int32 mode = kWallpaperScaledToFit;
BPoint offset = BPoint(0.0f, 0.0f);
};
struct BrowserFileItem {
std::string name;
HaikuTexture icon;
HaikuTexture textTex;
int textW = 0, textH = 0;
HaikuRect clickBounds;
bool isFolder;
std::string fullPath;
};
struct TaskbarItem {
std::string title;
std::string appName;
HaikuTexture icon;
bool isMinimized;
bool* openStateFlag;
bool* minimizeStateFlag;
team_id teamId;
int32 windowIndex;
float textAlpha = 0.0f;
};
struct DesktopIconItem {
std::string name;
HaikuTexture texture;
HaikuTexture textTexture;
HaikuRect bounds;
HaikuRect textBounds;
bool isFolder;
};
void GetTrackedWindowsFromTeam(team_id team, std::vector<TrackedWindowInfo>& outList) {
outList.clear();
app_info info;
bool hasAppInfo = (be_roster->GetRunningAppInfo(team, &info) == B_OK);
// 1. CRITICAL GUARD: Keep only the Rakarrack guard to prevent hard system freezes via FLTK
if (hasAppInfo) {
if (strcmp(info.signature, "application/x-vnd.rakarrack-haiku") == 0 ||
BString(info.ref.name).ICompare("rakarrack") == 0) {
outList.push_back(TrackedWindowInfo("Rakarrack", 0, BRect()));
return;
}
}
bool isTrackerApp = (hasAppInfo && (strcmp(info.signature, "application/x-vnd.Benjamin-TRAK") == 0 ||
strcmp(info.signature, "application/x-vnd.Be-TRAK") == 0));
// 2. Query raw App Server window order stack directly
int32 currentWorkspace = current_workspace();
int32* windowTokens = nullptr;
int32 totalWindows = 0;
BPrivate::get_window_order(currentWorkspace, &windowTokens, &totalWindows);
BString combinedPaths = "";
int32 trackerValidCount = 0;
if (windowTokens != nullptr && totalWindows > 0) {
// Track the relative 0-indexed position of windows for each specific application team
int32 appSpecificScriptIndex = 0;
for (int32 i = 0; i < totalWindows; ++i) {
client_window_info* wInfo = get_window_info(windowTokens[i]);
if (wInfo == nullptr) continue;
if (wInfo->team == team) {
BString subTitle(wInfo->name);
if (subTitle.Length() > 0) {
if (isTrackerApp) {
// FIX A: Detect and ignore the system background wallpaper layer
if ((subTitle == "Desktop" || subTitle.EndsWith("/Desktop")) && wInfo->feel == 1024) {
free(wInfo);
appSpecificScriptIndex++;
continue;
}
// FIX B: Detect and ignore the background progress file dialog window
if (subTitle == "Tracker status") {
free(wInfo);
appSpecificScriptIndex++;
continue; // Bypasses the status panel safely!
}
// Gather genuine folders into a combined layout horizontal line
if (trackerValidCount > 0) combinedPaths << " | ";
combinedPaths << subTitle;
trackerValidCount++;
} else {
// Standard apps: Keep your working multiline row entries completely untouched!
outList.push_back(TrackedWindowInfo(subTitle, appSpecificScriptIndex, BRect()));
}
}
// Always increment relative to the team's scriptable object bounds stack
appSpecificScriptIndex++;
}
free(wInfo);
}
free(windowTokens);
}
// 3. Format final string output context
if (isTrackerApp && trackerValidCount > 0) {
BString finalDisplayString;
finalDisplayString << "Tracker (" << combinedPaths << ")";
// Target index 0 handles basic grouping for multi-window paths
outList.push_back(TrackedWindowInfo(finalDisplayString, 0, BRect()));
}
// Ultimate fallback if no window fields whatsoever were populated by the loop pass
if (outList.empty()) {
BString fallbackName = (hasAppInfo && info.ref.name) ? info.ref.name : "Application";
if (hasAppInfo) {
if (strcmp(info.signature, "application/x-vnd.Be-TRAK") == 0) fallbackName = "Tracker";
}
outList.push_back(TrackedWindowInfo(fallbackName, 0, BRect()));
}
}
void ActivateApplicationWindow(team_id team, int32 windowIndex) {
BMessenger appMessenger(NULL, team);
if (appMessenger.IsValid()) {
// Build the precise script message that worked beautifully earlier
BMessage activateMsg(B_SET_PROPERTY);
activateMsg.AddSpecifier("Active");
activateMsg.AddSpecifier("Window", windowIndex);
activateMsg.AddBool("data", true);
BMessage reply;
appMessenger.SendMessage(&activateMsg, &reply, 20000, 20000);
// --- NEW LINE: Unminimize the window if it's currently folded away ---
BMessage unminimizeMsg(B_SET_PROPERTY);
unminimizeMsg.AddSpecifier("Minimized");
unminimizeMsg.AddSpecifier("Window", windowIndex);
unminimizeMsg.AddBool("data", false); // Force Minimized to false
BMessage unminimizeReply;
appMessenger.SendMessage(&unminimizeMsg, &unminimizeReply, 20000, 20000);
}
// Globally lift the process context into the active foreground layer
be_roster->ActivateApp(team);
}
using BPrivate::BNavMenu;
// =========================================================================
// PRIVATE SYMBOL ACCESS LAYER: UNNESTED PUBLIC FLOATING NAVIGATOR SUBCLASS
// =========================================================================
class BPopupNavMenu : public BPrivate::BNavMenu {
public:
BPopupNavMenu(const char* title, uint32 message, const BMessenger& target)
: BPrivate::BNavMenu(title, message, target) {}
// Public bridge function to expose the protected base method to our click loop
BMenuItem* PublicTrack() {
return Track(true, nullptr);
}
};
// =========================================================================
// CUSTOM RENDERING LAYER: LIVE GEOMETRIC REAL-TIME MEMORY USAGE GRAPH BAR
// =========================================================================
class BMemoryBarMenuItem : public BMenuItem {
public:
BMemoryBarMenuItem(const char* label, double fillPercentage)
: BMenuItem(label, nullptr), fFillPercentage(fillPercentage) {}
void UpdateMetrics(double newPercentage, const char* newLabel) {
fFillPercentage = newPercentage;
SetLabel(newLabel);
}
protected:
virtual void GetContentSize(float* width, float* height) override {
BMenuItem::GetContentSize(width, height);
*width = 420.0f;
*height = 18.0f;
}
virtual void DrawContent() override {
BMenu* menu = Menu();
if (!menu) return;
BRect bounds = Frame();
float itemHeight = bounds.Height();
font_height fh;
menu->GetFontHeight(&fh);
float fontBaseline = bounds.top + (itemHeight - (fh.ascent + fh.descent)) / 2.0f + fh.ascent;
float nameColumnLeft = bounds.left + 5.0f;
float textColumnLeft = bounds.left + 280.0f;
float barColumnLeft = bounds.left + 330.0f;
float barWidth = 80.0f;
// Render the descriptive text label
menu->MovePenTo(nameColumnLeft, fontBaseline);
menu->DrawString(Label());
// Format and render the numeric consumption percentage string
char pctStr[16];
std::snprintf(pctStr, sizeof(pctStr), "%3.1f%%", fFillPercentage);
menu->MovePenTo(textColumnLeft, fontBaseline);
menu->DrawString(pctStr);
// Build and draw the visual progress track capsule
float barHeight = 10.0f;
float barTop = bounds.top + (itemHeight - barHeight) / 2.0f;
BRect barTrack(barColumnLeft, barTop, barColumnLeft + barWidth, barTop + barHeight);
double clampedPercent = (fFillPercentage < 0.0) ? 0.0 : (fFillPercentage > 100.0) ? 100.0 : fFillPercentage;
BRect fillCap(barColumnLeft, barTop, barColumnLeft + (barWidth * (clampedPercent / 100.0)), barTop + barHeight);
// Dark track background silhouette
menu->SetHighColor(45, 45, 45);
menu->FillRect(barTrack);
// Dynamic resource footprint styling thresholds
if (fFillPercentage > 85.0) {
menu->SetHighColor(50, 205, 50); // Neon Green
} else if (fFillPercentage > 60.0) {
menu->SetHighColor(220, 20, 60); // Crimson Red
} else {
menu->SetHighColor(255, 140, 0); // Dark Orange
}
if (fillCap.Width() > 0) {
menu->FillRect(fillCap);
}
// Apply a fine glass border overlay frame highlight
menu->SetHighColor(90, 90, 90);
menu->StrokeRect(barTrack);
// Restore brush configurations back to standard text properties
menu->SetHighColor(ui_color(B_MENU_ITEM_TEXT_COLOR));
}
private:
double fFillPercentage;
};
// =========================================================================
// CUSTOM RENDERING LAYER: LIVE COLORED CPU PERFORMANCE GRAPH BAR + ICONS
// =========================================================================
class BCpuBarMenuItem : public BMenuItem {
public:
BCpuBarMenuItem(const char* label, BMessage* message, double cpuPercent, BBitmap* icon = nullptr)
: BMenuItem(label, message), fCpuPercent(cpuPercent), fIcon(icon) {}
virtual ~BCpuBarMenuItem() override {
delete fIcon; // Safely release bitmap memory when item is removed
}
void UpdateMetrics(double newPercent, const char* newLabel) {
fCpuPercent = newPercent;
SetLabel(newLabel);
}
protected:
virtual void GetContentSize(float* width, float* height) override {
BMenuItem::GetContentSize(width, height);
*width = 340.0f; // Expand width parameter slightly to house the icon space cleanly
*height = 18.0f;
}
virtual void DrawContent() override {
BMenu* menu = Menu();
if (!menu) return;
BRect bounds = Frame();
float itemHeight = bounds.Height();
font_height fh;
menu->GetFontHeight(&fh);
float fontBaseline = bounds.top + (itemHeight - (fh.ascent + fh.descent)) / 2.0f + fh.ascent;
// 1. Define our absolute, left-aligned column grid positions (offset to accommodate the icon)
float iconColumnLeft = bounds.left + 5.0f;
float nameColumnLeft = bounds.left + 25.0f; // Shifted right by 20 pixels for clear layout padding
float textColumnLeft = bounds.left + 200.0f;
float barColumnLeft = bounds.left + 250.0f;
float barWidth = 80.0f;
// 2. Draw the application icon graphic if it was successfully resolved
if (fIcon) {
float graphicTop = bounds.top + (itemHeight - 16.0f) / 2.0f;
menu->SetDrawingMode(B_OP_ALPHA);
menu->DrawBitmap(fIcon, BPoint(iconColumnLeft, graphicTop));
menu->SetDrawingMode(B_OP_COPY);
}
// 3. Render the Process Name string
menu->MovePenTo(nameColumnLeft, fontBaseline);
menu->DrawString(Label());
// 4. Format and render the numeric percentage string
char pctStr[16];
std::snprintf(pctStr, sizeof(pctStr), "%3.1f%%", fCpuPercent);
menu->MovePenTo(textColumnLeft, fontBaseline);
menu->DrawString(pctStr);
// 5. Render the graphical performance loading bar container
float barHeight = 10.0f;
float barTop = bounds.top + (itemHeight - barHeight) / 2.0f;
BRect barTrack(barColumnLeft, barTop, barColumnLeft + barWidth, barTop + barHeight);
double clampedPercent = (fCpuPercent < 0.0) ? 0.0 : (fCpuPercent > 100.0) ? 100.0 : fCpuPercent;
BRect fillCap(barColumnLeft, barTop, barColumnLeft + (barWidth * (clampedPercent / 100.0)), barTop + barHeight);
menu->SetHighColor(45, 45, 45);
menu->FillRect(barTrack);
if (fCpuPercent > 75.0) {
menu->SetHighColor(50, 205, 50); // Neon Green
} else if (fCpuPercent > 35.0) {
menu->SetHighColor(255, 140, 0); // Dark Orange
} else {
menu->SetHighColor(50, 205, 50); // Neon Green
}
if (fillCap.Width() > 0) {
menu->FillRect(fillCap);
}
menu->SetHighColor(90, 90, 90);
menu->StrokeRect(barTrack);
menu->SetHighColor(ui_color(B_MENU_ITEM_TEXT_COLOR));
}
private:
double fCpuPercent;
BBitmap* fIcon;
};
// =========================================================================
// LIVE-PULSING SUBSYSTEM: DETAILED MEMORY AND RAM CACHE PROFILER CASCADE
// =========================================================================
class BLiveMemoryMenu : public BMenu {
public:
BLiveMemoryMenu(const char* title) : BMenu(title) {
SetFlags(Flags() | B_PULSE_NEEDED);
}
virtual void AttachedToWindow() override {
BMenu::AttachedToWindow();
Window()->SetPulseRate(500000); // Pulse metrics smoothly every half second
}
virtual void Pulse() override {
BMenu::Pulse();
system_info info;
if (get_system_info(&info) == B_OK) {
double pageSize = static_cast<double>(B_PAGE_SIZE);
double totalBytes = static_cast<double>(info.max_pages) * pageSize;
double usedBytes = static_cast<double>(info.used_pages) * pageSize;
int32 totalMB = static_cast<int32>(totalBytes / (1024.0 * 1024.0));
int32 usedMB = static_cast<int32>(usedBytes / (1024.0 * 1024.0));
int32 freeMB = totalMB - usedMB;
// Compute actual global RAM consumption utilization scaling
double overallMemoryUsagePercent = 0.0;
if (totalBytes > 0) {
overallMemoryUsagePercent = (usedBytes / totalBytes) * 100.0;
}
// Create clean text strings
char i1[64], i2[64], i3[64];
std::snprintf(i1, sizeof(i1), "Used Physical Memory: %d MB", usedMB);
std::snprintf(i2, sizeof(i2), "Free Available RAM: %d MB", freeMB);
std::snprintf(i3, sizeof(i3), "Total Installed Capacity: %d MB", totalMB);
// Update row item text metrics or inject custom green graph bar items seamlessly
UpdateOrAddMemoryBarItem(0, i1, overallMemoryUsagePercent);
UpdateOrAddMemoryBarItem(1, i2, 100.0 - overallMemoryUsagePercent); // Remaining percentage space
UpdateOrAddMemoryBarItem(2, i3, 100.0); // Total capacity sits solid filled
}
}
private:
void UpdateOrAddMemoryBarItem(int32 idx, const char* label, double percentage) {
BMemoryBarMenuItem* item = dynamic_cast<BMemoryBarMenuItem*>(ItemAt(idx));
if (item) {
item->UpdateMetrics(percentage, label);
} else {
// Instantiate our brand new memory bar object class
BMemoryBarMenuItem* newItem = new BMemoryBarMenuItem(label, percentage);
AddItem(newItem);
}
}
};
class BRealtimeCpuMenu : public BMenu {
public:
BRealtimeCpuMenu(const char* title) : BMenu(title) {
SetFlags(Flags() | B_PULSE_NEEDED);
system_info sysInfo;
fCpuCount = (get_system_info(&sysInfo) == B_OK) ? sysInfo.cpu_count : 1;
if (fCpuCount < 1) fCpuCount = 1;
// Initialize our rolling tracking anchor time
fLastUpdateTime = system_time();
// =========================================================================
// CRITICAL FIRST SWIPE FIX: POPULATE ALL TEAMS IMMEDIATELY ON CREATION!
// This ensures the Haiku Window Layout Server sizes the menu correctly at launch.
// =========================================================================
team_info tInfo;
int32 teamCookie = 0;
int32 index = 0;
while (get_next_team_info(&teamCookie, &tInfo) == B_OK) {
if (tInfo.team <= 0 || std::strlen(tInfo.name) == 0) continue;
char cleanName[B_OS_NAME_LENGTH];
const char* lastSlash = std::strrchr(tInfo.name, '/');
std::strncpy(cleanName, lastSlash ? lastSlash + 1 : tInfo.name, sizeof(cleanName));
// Extract the tracker icon asset for the layout size framework on launch
BBitmap* processIcon = nullptr;
image_info imgInfo;
int32 imgCookie = 0;
if (get_next_image_info(tInfo.team, &imgCookie, &imgInfo) == B_OK) {
BEntry appEntry(imgInfo.name);
if (appEntry.Exists()) {
entry_ref ref;
if (appEntry.GetRef(&ref) == B_OK) {
BRect iconBounds(0, 0, 15, 15);
BBitmap* tempIcon = new BBitmap(iconBounds, B_RGBA32);
if (BNodeInfo::GetTrackerIcon(&ref, tempIcon, B_MINI_ICON) == B_OK) {
processIcon = tempIcon;
} else {
delete tempIcon;
}
}
}
}
thread_info thInfo;
int32 thCookie = 0;
bigtime_t currentTeamTotalTime = 0;
while (get_next_thread_info(tInfo.team, &thCookie, &thInfo) == B_OK) {
currentTeamTotalTime += thInfo.user_time + thInfo.kernel_time;
}
fProcessHistoryMap[tInfo.team].mainThreadId = 0;
fProcessHistoryMap[tInfo.team].lastTimeSample = currentTeamTotalTime;
BMessage* killThMsg = new BMessage('kthr');
killThMsg->AddInt32("target_thread", tInfo.team);
killThMsg->AddString("target_name", cleanName);
// Pass the icon to initialize item sizes perfectly on swipe one
AddItem(new BCpuBarMenuItem(cleanName, killThMsg, 0.0, processIcon));
index++;
if (index >= 45) break;
}
}
virtual void AttachedToWindow() override {
BMenu::AttachedToWindow();
Window()->SetPulseRate(200000); // Pulse every 200ms
}
virtual void Pulse() override;
private:
int32 fCpuCount;
bigtime_t fLastUpdateTime;
// Persistent cache structure to measure metrics across separate pulses
struct CachedProcessState {
thread_id mainThreadId;
bigtime_t lastTimeSample;
};
std::map<team_id, CachedProcessState> fProcessHistoryMap;
};
void BRealtimeCpuMenu::Pulse() {
BMenu::Pulse();
// Compute global time differences since the absolute last frame slice
bigtime_t currentTime = system_time();
bigtime_t totalTimeDelta = (currentTime - fLastUpdateTime) * fCpuCount;
fLastUpdateTime = currentTime; // Roll anchor forward
// Local snapshot buffer for this specific layout pass
struct DisplayElement {
team_id teamId;
double calculatedCpu;
char name[B_OS_NAME_LENGTH];
};
std::vector<DisplayElement> currentPassList;
team_info tInfo;
int32 teamCookie = 0;
// 2. Iterate across the flat system team table directly to capture ALL running apps
while (get_next_team_info(&teamCookie, &tInfo) == B_OK) {
if (tInfo.team <= 0 || std::strlen(tInfo.name) == 0) continue;
DisplayElement element;
element.teamId = tInfo.team;
element.calculatedCpu = 0.0; // Default fallback for newly discovered processes
const char* lastSlash = std::strrchr(tInfo.name, '/');
std::strncpy(element.name, lastSlash ? lastSlash + 1 : tInfo.name, sizeof(element.name));
// Loop through ALL threads belonging to this team and sum their runtimes
thread_info thInfo;
int32 thCookie = 0;
bigtime_t currentTeamTotalTime = 0;
while (get_next_thread_info(tInfo.team, &thCookie, &thInfo) == B_OK) {
currentTeamTotalTime += thInfo.user_time + thInfo.kernel_time;
}
// Compute performance deltas against team histories
if (fProcessHistoryMap.find(tInfo.team) != fProcessHistoryMap.end()) {
bigtime_t oldTimeSample = fProcessHistoryMap[tInfo.team].lastTimeSample;
if (totalTimeDelta > 0 && currentTeamTotalTime >= oldTimeSample) {
element.calculatedCpu = (static_cast<double>(currentTeamTotalTime - oldTimeSample) /
static_cast<double>(totalTimeDelta)) * 100.0;
}
}
// Cache this team's total aggregated time for the next pulse calculation
fProcessHistoryMap[tInfo.team].mainThreadId = 0;
fProcessHistoryMap[tInfo.team].lastTimeSample = currentTeamTotalTime;
// FIXED: Always include the running process immediately so it never gets dropped!
currentPassList.push_back(element);
}
// 3. Purge history map records for applications that exited entirely
auto mapIter = fProcessHistoryMap.begin();
while (mapIter != fProcessHistoryMap.end()) {
bool stillExists = false;
for (const auto& live : currentPassList) {
if (live.teamId == mapIter->first) {
stillExists = true;
break;
}
}
if (!stillExists) {
mapIter = fProcessHistoryMap.erase(mapIter);
} else {
++mapIter;
}
}
// 4. Update existing graphical bars or create new ones complete with system icons!
int32 index = 0;
for (const auto& entry : currentPassList) {
char rowText[B_OS_NAME_LENGTH + 16];
std::snprintf(rowText, sizeof(rowText), "%s", entry.name);
BCpuBarMenuItem* item = dynamic_cast<BCpuBarMenuItem*>(ItemAt(index));
if (item) {
item->UpdateMetrics(entry.calculatedCpu, rowText);
if (item->Message()) {
item->Message()->ReplaceInt32("target_thread", entry.teamId);
}
} else {
// Locate and extract the dynamic system icon for this newly listed process team
BBitmap* processIcon = nullptr;
image_info imgInfo;
int32 imgCookie = 0;
if (get_next_image_info(entry.teamId, &imgCookie, &imgInfo) == B_OK) {
BEntry appEntry(imgInfo.name);
if (appEntry.Exists()) {
entry_ref ref;
if (appEntry.GetRef(&ref) == B_OK) {
BRect iconBounds(0, 0, 15, 15);
BBitmap* tempIcon = new BBitmap(iconBounds, B_RGBA32);
if (BNodeInfo::GetTrackerIcon(&ref, tempIcon, B_MINI_ICON) == B_OK) {
processIcon = tempIcon; // Successfully grabbed the icon asset!
} else {
delete tempIcon;
}
}
}
}
// Configure the message tracking hooks
BMessage* killThMsg = new BMessage('kthr');
killThMsg->AddInt32("target_thread", entry.teamId);
killThMsg->AddString("target_name", entry.name);
AddItem(new BCpuBarMenuItem(rowText, killThMsg, entry.calculatedCpu, processIcon));
}
index++;
if (index >= 45) break;
}
// Trim trailing elements smoothly
while (CountItems() > index) {
delete RemoveItem(index);
}
Invalidate();
}
// =========================================================================
// CUSTOM RENDERING LAYER: QUIT APPLICATION SUBMENU ITEMS (ICON ALIGNED)
// =========================================================================
class BIconMenuItem : public BMenuItem {
public:
// Overload 1: For Cascading Submenus (Teams)
BIconMenuItem(BMenu* submenu, BBitmap* icon = nullptr)
: BMenuItem(submenu), fIcon(icon) {}
// Overload 2: For Standard Action Items (Quit Processes)
BIconMenuItem(const char* label, BMessage* message, BBitmap* icon = nullptr)
: BMenuItem(label, message), fIcon(icon) {}
virtual ~BIconMenuItem() override {
delete fIcon; // Safely release bitmap memory upon closure
}
protected:
virtual void GetContentSize(float* width, float* height) override {
BMenuItem::GetContentSize(width, height);
// Force uniform structural row boundaries matching our design standards
*width = 240.0f;
*height = 18.0f;
}
virtual void DrawContent() override {
BMenu* menu = Menu();
if (!menu) return;
BRect bounds = Frame();
float itemHeight = bounds.Height();
// 1. Calculate font metrics for perfect vertical centering inside the row box
font_height fh;
menu->GetFontHeight(&fh);
float fontBaseline = bounds.top + (itemHeight - (fh.ascent + fh.descent)) / 2.0f + fh.ascent;
// 2. Define clear absolute column grids for your elements
float iconColumnLeft = bounds.left + 5.0f;
float nameColumnLeft = bounds.left + 25.0f; // Left padding gap to separate text from icons
// 3. Render the application binary icon graphic (perfectly centered vertically)
if (fIcon) {
float graphicTop = bounds.top + (itemHeight - 16.0f) / 2.0f;
menu->SetDrawingMode(B_OP_ALPHA);
menu->DrawBitmap(fIcon, BPoint(iconColumnLeft, graphicTop));
menu->SetDrawingMode(B_OP_COPY);
}
// 4. FIXED: Render the process text label manually.
// Skipping BMenuItem::DrawContent completely prevents Haiku from shifting our text unaligned!
menu->SetHighColor(ui_color(B_MENU_ITEM_TEXT_COLOR));
menu->MovePenTo(nameColumnLeft, fontBaseline);
menu->DrawString(Label());
}
private:
BBitmap* fIcon;
};
// Streamlined structural definition block
class AsyncCpuMenuRunner : public BWindow {
public:
AsyncCpuMenuRunner(CpuMenuArgs* args)
: BWindow(BRect(-50, -50, -10, -10), "AsyncCpuMenuLooper", B_NO_BORDER_WINDOW_LOOK, B_FLOATING_ALL_WINDOW_FEEL, 0),
fArgs(args)
{
BView* dummyView = new BView(Bounds(), "dummy", B_FOLLOW_ALL, B_WILL_DRAW);
AddChild(dummyView);
Run();
PostMessage(MSG_LAUNCH_MENU);
}
virtual void MessageReceived(BMessage* message) override {
switch (message->what) {
case MSG_LAUNCH_MENU:
_DisplayCPUGraphMenu(); // Will be resolved downstream
Quit();
break;