-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathParticleWindow.cpp
More file actions
1562 lines (1365 loc) · 52.4 KB
/
Copy pathParticleWindow.cpp
File metadata and controls
1562 lines (1365 loc) · 52.4 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
/* ParticleWindow.cpp – Coffee Toolkit
*
* Particle Size Analyzer — three modes:
* 1. Photo Estimate (local contrast map)
* 2. Sieve Cascade (threshold + accumulate per sieve fraction)
* 3. Calibrated Sheet (flood-fill blobs + px/mm calibration)
*
* Author: David Masson
*/
#include "ParticleWindow.h"
#include "RoastColorWindow.h" // reuse ThumbView + MSG_SELECTION_CHANGED
#include "Constants.h"
#include "Settings.h"
#include <Application.h>
#include <Entry.h>
#include <InterfaceDefs.h>
#include <LayoutBuilder.h>
#include <Menu.h>
#include <MenuBar.h>
#include <MenuField.h>
#include <MenuItem.h>
#include <Message.h>
#include <Path.h>
#include <TranslationUtils.h>
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <algorithm>
#include <stack>
// ===================================================================
// ParticleGaugeView
// ===================================================================
// Score→colour: Extra-Fine = pale tan, Extra-Coarse = dark brown
static const float kScoreMin = 0.0f;
static const float kScoreMax = 1.0f;
struct GrindBand { float lo; float hi; const char* name; };
static const GrindBand kBands[] = {
{ 0.00f, 0.15f, "X-Fine" },
{ 0.15f, 0.28f, "Fine" },
{ 0.28f, 0.42f, "Med-Fine"},
{ 0.42f, 0.58f, "Medium" },
{ 0.58f, 0.72f, "Med-Crs" },
{ 0.72f, 0.86f, "Coarse" },
{ 0.86f, 1.00f, "X-Coarse"},
};
static const int kNBands = 7;
ParticleGaugeView::ParticleGaugeView(BRect frame)
: BView(frame, "particle_gauge", B_FOLLOW_H_CENTER | B_FOLLOW_TOP,
B_WILL_DRAW),
fScore(-1.0f)
{
SetViewColor(ui_color(B_PANEL_BACKGROUND_COLOR));
}
void ParticleGaugeView::SetScore(float score)
{
fScore = score;
Invalidate();
}
void ParticleGaugeView::Draw(BRect /*updateRect*/)
{
CoffeeSettings* s = CoffeeSettings::Get();
rgb_color bg = s->ThemePanelBg();
rgb_color dim = s->ThemeDimTextColor();
rgb_color outline = s->ThemeOutlineColor();
rgb_color text = s->ThemeTextColor();
BRect b = Bounds();
float barTop = 18.0f;
float barBottom = 44.0f;
float barH = barBottom - barTop;
float barLeft = b.left + 2.0f;
float barRight = b.right - 2.0f;
float barWidth = barRight - barLeft;
// Clear background
SetHighColor(bg);
FillRect(b);
auto scoreToX = [&](float s) -> float {
return barLeft + s * barWidth;
};
// Gradient: pale tan (fine) → dark brown (coarse)
struct Stop { float pos; uint8 r, g, b; };
Stop stops[] = {
{ 0.00f, 230, 210, 175 }, // very pale / fine powder
{ 0.20f, 190, 160, 105 },
{ 0.40f, 150, 110, 60 },
{ 0.60f, 110, 70, 28 },
{ 0.80f, 65, 35, 12 },
{ 1.00f, 25, 12, 4 }, // very dark / coarse chunks
};
const int nStops = 6;
for (int i = 0; i < nStops - 1; i++) {
float x0 = barLeft + stops[i].pos * barWidth;
float x1 = barLeft + stops[i+1].pos * barWidth;
int steps = (int)(x1 - x0);
if (steps < 1) steps = 1;
for (int s = 0; s < steps; s++) {
float t = (float)s / steps;
uint8 r = (uint8)(stops[i].r + t*(stops[i+1].r - stops[i].r));
uint8 g = (uint8)(stops[i].g + t*(stops[i+1].g - stops[i].g));
uint8 bv = (uint8)(stops[i].b + t*(stops[i+1].b - stops[i].b));
SetHighColor(r, g, bv);
float sx = x0 + s;
StrokeLine(BPoint(sx, barTop), BPoint(sx, barBottom));
}
}
// Outline
SetHighColor(outline);
StrokeRect(BRect(barLeft, barTop, barRight, barBottom));
// Band dividers and labels
BFont tiny; tiny.SetSize(8.0f); SetFont(&tiny);
for (int i = 0; i < kNBands; i++) {
float xL = scoreToX(kBands[i].lo);
float xR = scoreToX(kBands[i].hi);
if (i > 0) {
SetHighColor(outline);
StrokeLine(BPoint(xL, barTop), BPoint(xL, barBottom));
}
// label colour: light on dark right side, dark on light left side
if (kBands[i].lo >= 0.5f)
SetHighColor(220, 200, 160);
else
SetHighColor(40, 20, 8);
DrawString(kBands[i].name,
BPoint((xL+xR)/2.0f - 14, barTop + barH*0.65f));
}
// Scale ticks
BFont small; small.SetSize(9.0f); SetFont(&small);
SetHighColor(dim);
for (int i = 0; i <= kNBands; i++) {
float sc = (float)i / kNBands;
float x = scoreToX(sc);
StrokeLine(BPoint(x, barBottom), BPoint(x, barBottom+4));
}
// Pointer
if (fScore >= 0.0f && fScore <= 1.0f) {
float x = scoreToX(fScore);
SetHighColor(text);
FillTriangle(BPoint(x, barTop-1),
BPoint(x-5, barTop-9),
BPoint(x+5, barTop-9));
SetHighColor(outline);
StrokeTriangle(BPoint(x, barTop-1),
BPoint(x-5, barTop-9),
BPoint(x+5, barTop-9));
SetHighColor(text);
SetDrawingMode(B_OP_OVER);
StrokeLine(BPoint(x, barTop), BPoint(x, barBottom));
SetDrawingMode(B_OP_COPY);
}
}
// ===================================================================
// SieveDistView
// ===================================================================
SieveDistView::SieveDistView(BRect frame)
: BView(frame, "sieve_dist", B_FOLLOW_H_CENTER | B_FOLLOW_TOP,
B_WILL_DRAW)
{
SetViewColor(ui_color(B_PANEL_BACKGROUND_COLOR));
}
void SieveDistView::SetFractions(const std::vector<SieveFraction>& fracs)
{
fFractions = fracs;
// Sort by sieve size ascending for display
std::sort(fFractions.begin(), fFractions.end(),
[](const SieveFraction& a, const SieveFraction& b){
return a.sizeUm < b.sizeUm;
});
Invalidate();
}
void SieveDistView::Draw(BRect /*updateRect*/)
{
CoffeeSettings* s = CoffeeSettings::Get();
rgb_color bg = s->ThemePanelBg();
rgb_color text = s->ThemeTextColor();
rgb_color dim = s->ThemeDimTextColor();
BRect b = Bounds();
SetHighColor(bg);
FillRect(b);
if (fFractions.empty()) {
SetHighColor(dim);
BFont f; f.SetSize(11); SetFont(&f);
DrawString("No fractions loaded yet.",
BPoint(10, b.Height()/2));
return;
}
// Normalise relative areas to percentages
float total = 0.0f;
for (const auto& fr : fFractions) total += fr.relArea;
if (total <= 0.0f) return;
float margin = 30.0f;
float areaW = b.Width() - margin * 2.0f;
float areaH = b.Height() - 30.0f;
float barW = areaW / (float)fFractions.size();
BFont tiny; tiny.SetSize(8.5f); SetFont(&tiny);
for (int i = 0; i < (int)fFractions.size(); i++) {
float pct = fFractions[i].relArea / total;
float bh = pct * areaH;
float bx = margin + i * barW + 2.0f;
float bxe = bx + barW - 4.0f;
float by = b.Height() - 20.0f - bh;
float bye = b.Height() - 20.0f;
// Bar fill — coffee brown gradient tinted by size
uint8 r = 120, g = 70, bv = 25;
SetHighColor(r, g, bv);
FillRect(BRect(bx, by, bxe, bye));
SetHighColor(60, 35, 10);
StrokeRect(BRect(bx, by, bxe, bye));
// Percentage label above bar
char pctStr[8]; snprintf(pctStr, sizeof(pctStr), "%.0f%%", pct*100.0f);
SetHighColor(text);
DrawString(pctStr, BPoint(bx, by - 2));
// Sieve size label below bar
char szStr[16];
if (fFractions[i].sizeUm < 1000)
snprintf(szStr, sizeof(szStr), "%dµm", fFractions[i].sizeUm);
else
snprintf(szStr, sizeof(szStr), "%.1fmm",
fFractions[i].sizeUm / 1000.0f);
SetHighColor(dim);
DrawString(szStr, BPoint(bx, bye + 12));
}
}
// ===================================================================
// CalHistView
// ===================================================================
CalHistView::CalHistView(BRect frame)
: BView(frame, "cal_hist", B_FOLLOW_H_CENTER | B_FOLLOW_TOP,
B_WILL_DRAW)
{
SetViewColor(ui_color(B_PANEL_BACKGROUND_COLOR));
}
void CalHistView::SetDiameters(const std::vector<float>& diameters_mm)
{
fDiameters = diameters_mm;
Invalidate();
}
void CalHistView::Draw(BRect /*updateRect*/)
{
CoffeeSettings* s = CoffeeSettings::Get();
rgb_color bg = s->ThemePanelBg();
rgb_color dim = s->ThemeDimTextColor();
BRect b = Bounds();
SetHighColor(bg);
FillRect(b);
if (fDiameters.empty()) {
SetHighColor(dim);
BFont f; f.SetSize(11); SetFont(&f);
DrawString("No analysis run yet.", BPoint(10, b.Height()/2));
return;
}
// Build histogram with 0.1 mm bins, range 0..4 mm
const float binW = 0.1f;
const int nBins = 40; // 0.0 to 4.0 mm
int bins[nBins] = {};
int maxCount = 0;
for (float d : fDiameters) {
int bin = (int)(d / binW);
if (bin < 0) bin = 0;
if (bin >= nBins) bin = nBins - 1;
bins[bin]++;
if (bins[bin] > maxCount) maxCount = bins[bin];
}
if (maxCount == 0) return;
float margin = 30.0f;
float areaW = b.Width() - margin * 2.0f;
float areaH = b.Height() - 30.0f;
float bw = areaW / nBins;
BFont tiny; tiny.SetSize(8.0f); SetFont(&tiny);
for (int i = 0; i < nBins; i++) {
if (bins[i] == 0) continue;
float bh = ((float)bins[i] / maxCount) * areaH;
float bx = margin + i * bw;
float bxe = bx + bw - 1.0f;
float by = b.Height() - 20.0f - bh;
float bye = b.Height() - 20.0f;
SetHighColor(110, 68, 25);
FillRect(BRect(bx, by, bxe, bye));
SetHighColor(60, 35, 10);
StrokeRect(BRect(bx, by, bxe, bye));
}
// X-axis tick labels every 0.5 mm (or equivalent in inches)
bool metric = CoffeeSettings::Get()->UseMetric();
SetHighColor(dim);
for (int i = 0; i <= nBins; i += 5) {
float x = margin + i * bw;
StrokeLine(BPoint(x, b.Height()-20.0f),
BPoint(x, b.Height()-16.0f));
float val = metric ? (i * binW) : (i * binW / 25.4f);
char lbl[10];
snprintf(lbl, sizeof(lbl), metric ? "%.1f" : "%.3f", val);
DrawString(lbl, BPoint(x-8, b.Height()-6));
}
// Unit label
SetHighColor(dim);
DrawString(metric ? "mm" : "in", BPoint(b.Width()-22, b.Height()-6));
}
// ===================================================================
// Shared helpers
// ===================================================================
// sRGB linearisation (same as RoastColorWindow)
static inline float lin(float c)
{
return c <= 0.04045f ? c / 12.92f
: powf((c + 0.055f) / 1.055f, 2.4f);
}
static float pixelLuminance(const uint8* bits, int bpr,
color_space cs, int x, int y)
{
float rf = 0, gf = 0, bf = 0;
if (cs == B_RGB32 || cs == B_RGBA32) {
const uint8* p = bits + y*bpr + x*4;
bf = p[0]/255.0f; gf = p[1]/255.0f; rf = p[2]/255.0f;
} else if (cs == B_RGB24) {
const uint8* p = bits + y*bpr + x*3;
bf = p[0]/255.0f; gf = p[1]/255.0f; rf = p[2]/255.0f;
}
return 0.2126f*lin(rf) + 0.7152f*lin(gf) + 0.0722f*lin(bf);
}
// Scale a bitmap to tw×th using nearest-neighbour
BBitmap* ParticleWindow::ScaleBitmap(BBitmap* src, int tw, int th)
{
BRect sr = src->Bounds();
float sw = sr.Width() + 1.0f;
float sh = sr.Height() + 1.0f;
const uint8* sbits = (const uint8*)src->Bits();
int sbpr = src->BytesPerRow();
color_space cs = src->ColorSpace();
BBitmap* dst = new BBitmap(BRect(0, 0, tw-1, th-1), B_RGB32);
uint8* dbits = (uint8*)dst->Bits();
int dbpr = dst->BytesPerRow();
for (int dy = 0; dy < th; dy++) {
int sy = (int)(dy * sh / th);
for (int dx = 0; dx < tw; dx++) {
int sx = (int)(dx * sw / tw);
uint8 r = 128, g = 128, bv = 128;
if (cs == B_RGB32 || cs == B_RGBA32) {
const uint8* p = sbits + sy*sbpr + sx*4;
bv = p[0]; g = p[1]; r = p[2];
} else if (cs == B_RGB24) {
const uint8* p = sbits + sy*sbpr + sx*3;
bv = p[0]; g = p[1]; r = p[2];
}
uint8* d = dbits + dy*dbpr + dx*4;
d[0] = bv; d[1] = g; d[2] = r; d[3] = 255;
}
}
return dst;
}
// ===================================================================
// ParticleWindow — constructor
// ===================================================================
ParticleWindow::ParticleWindow()
: BWindow(BRect(160, 100, 700, 840), "Particle Analyzer",
B_TITLED_WINDOW,
B_NOT_RESIZABLE | B_AUTO_UPDATE_SIZE_LIMITS),
fMode(kModePhoto),
fPhotoFilePanel(nullptr),
fPhotoSource(nullptr),
fPhotoThumbBmp(nullptr),
fSieveFilePanel(nullptr),
fSieveSource(nullptr),
fSieveThumbBmp(nullptr),
fCalFilePanel(nullptr),
fCalSource(nullptr),
fCalThumbBmp(nullptr)
{
BMessenger me(this);
// ---- Menu bar ----
BMenuBar* menuBar = new BMenuBar("menubar");
BMenu* helpMenu = new BMenu("Help");
helpMenu->AddItem(new BMenuItem("About" B_UTF8_ELLIPSIS,
new BMessage(B_ABOUT_REQUESTED)));
menuBar->AddItem(helpMenu);
CoffeeSettings::BuildSettingsMenu(menuBar);
// ---- Mode selector (radio buttons in one BGroupView) ----
fPhotoRadio = new BRadioButton("mode_photo", "Photo Estimate",
new BMessage(MSG_PART_MODE_PHOTO));
fSieveRadio = new BRadioButton("mode_sieve", "Sieve Cascade",
new BMessage(MSG_PART_MODE_SIEVE));
fCalRadio = new BRadioButton("mode_cal", "Calibrated Sheet",
new BMessage(MSG_PART_MODE_CAL));
fPhotoRadio->SetValue(B_CONTROL_ON);
fModeBar = new BGroupView(B_HORIZONTAL, kPad*2);
fModeBar->AddChild(fPhotoRadio);
fModeBar->AddChild(fSieveRadio);
fModeBar->AddChild(fCalRadio);
// ===== PANEL 1: Photo Estimate =====
fPhotoOpenBtn = new BButton("ph_open", "Load Image...",
new BMessage(MSG_PART_OPEN));
fPhotoFileView = new BStringView("ph_file", "No image loaded.");
fPhotoFileView->SetExplicitAlignment(
BAlignment(B_ALIGN_LEFT, B_ALIGN_MIDDLE));
ThumbView* phThumb = new ThumbView(BRect(0, 0, 239, 179), me);
phThumb->SetExplicitMinSize(BSize(240, 180));
phThumb->SetExplicitMaxSize(BSize(240, 180));
fPhotoThumb = phThumb;
fPhotoHintView = new BStringView("ph_hint",
"Drag on the image to select a sample region.");
BFont hintFont(be_plain_font);
hintFont.SetFace(B_ITALIC_FACE);
fPhotoHintView->SetFont(&hintFont);
fPhotoClearBtn = new BButton("ph_clear", "Clear Selection",
new BMessage(MSG_CLEAR_SELECTION));
fPhotoClearBtn->SetEnabled(false);
fPhotoGauge = new ParticleGaugeView(BRect(0, 0, 460, 55));
fPhotoGauge->SetExplicitMinSize(BSize(460, 55));
fPhotoGauge->SetExplicitMaxSize(BSize(B_SIZE_UNLIMITED, 55));
fPhotoResultView = new BStringView("ph_result", "");
fPhotoResultView->SetFont(be_bold_font);
fPhotoResultView->SetExplicitAlignment(
BAlignment(B_ALIGN_CENTER, B_ALIGN_MIDDLE));
BRect tvFrame(0, 0, 440, 130);
fPhotoTipsView = new BTextView(tvFrame, "ph_tips",
tvFrame.OffsetToCopy(B_ORIGIN),
B_FOLLOW_ALL, B_WILL_DRAW);
fPhotoTipsView->SetViewColor(ui_color(B_PANEL_BACKGROUND_COLOR));
fPhotoTipsView->MakeEditable(false);
fPhotoTipsView->MakeSelectable(false);
fPhotoTipsView->SetWordWrap(true);
fPhotoTipsView->SetText(
"Load a photograph of your coffee grounds on a uniform background.\n\n"
"For best results:\n"
" * Spread grounds in a thin, even layer\n"
" * Use a neutral grey or white background\n"
" * Diffuse, even lighting — avoid direct sunlight\n"
" * Fill the frame with grounds\n\n"
"Drag a rectangle on the preview to sample a specific region.");
{
CoffeeSettings* s = CoffeeSettings::Get();
fPhotoTipsView->SetViewColor(s->ThemePanelBg());
rgb_color tc = s->ThemeTextColor();
fPhotoTipsView->SetFontAndColor(0, fPhotoTipsView->TextLength(),
be_plain_font, B_FONT_ALL, &tc);
}
fPhotoTipsScroll = new BScrollView("ph_tips_scroll", fPhotoTipsView,
B_FOLLOW_ALL, 0, false, true);
fPhotoTipsScroll->SetExplicitMinSize(BSize(460, 75));
fPhotoTipsScroll->SetExplicitMaxSize(BSize(B_SIZE_UNLIMITED, 130));
fPhotoPanel = new BGroupView(B_VERTICAL, kPad);
BLayoutBuilder::Group<>(fPhotoPanel, B_VERTICAL, kPad)
.AddGroup(B_HORIZONTAL, kPad)
.Add(fPhotoOpenBtn)
.Add(fPhotoFileView)
.End()
.Add(fPhotoThumb)
.AddGroup(B_HORIZONTAL, kPad)
.Add(fPhotoHintView)
.AddGlue()
.Add(fPhotoClearBtn)
.End()
.Add(new BStringView("ph_glbl", "Grind size estimate:"))
.Add(fPhotoGauge)
.Add(fPhotoResultView)
.Add(new BStringView("ph_tlbl", "Grind notes & guidance:"))
.Add(fPhotoTipsScroll);
// ===== PANEL 2: Sieve Cascade =====
fSieveSizeMenu = new BPopUpMenu("600 µm");
const int sieveSizes[] = { 212, 300, 425, 600, 850, 1200, 1700 };
for (int sz : sieveSizes) {
char lbl[32];
if (sz < 1000)
snprintf(lbl, sizeof(lbl), "%d µm", sz);
else
snprintf(lbl, sizeof(lbl), "%.1f mm", sz / 1000.0f);
BMessage* pickMsg = new BMessage('SVSZ');
pickMsg->AddInt32("size_um", sz);
fSieveSizeMenu->AddItem(new BMenuItem(lbl, pickMsg));
}
// Default to 600 µm
fSieveSizeMenu->ItemAt(3)->SetMarked(true);
fSieveSizeField = new BMenuField("sv_szfield", "Sieve size:", fSieveSizeMenu);
fSieveOpenBtn = new BButton("sv_open", "Load Fraction Image...",
new BMessage(MSG_SIEVE_OPEN));
fSieveFileView = new BStringView("sv_file", "No image loaded.");
fSieveFileView->SetExplicitAlignment(
BAlignment(B_ALIGN_LEFT, B_ALIGN_MIDDLE));
ThumbView* svThumb = new ThumbView(BRect(0, 0, 239, 179), me);
svThumb->SetExplicitMinSize(BSize(240, 180));
svThumb->SetExplicitMaxSize(BSize(240, 180));
fSieveThumb = svThumb;
fSieveHintView = new BStringView("sv_hint",
"Drag on the image to select the sieve fraction region.");
fSieveHintView->SetFont(&hintFont);
fSieveClearBtn = new BButton("sv_clear", "Clear Selection",
new BMessage(MSG_CLEAR_SELECTION));
fSieveClearBtn->SetEnabled(false);
fSieveAddBtn = new BButton("sv_add", "Add Fraction",
new BMessage(MSG_SIEVE_ADD));
fSieveAddBtn->SetEnabled(false);
fSieveResetBtn = new BButton("sv_reset", "Reset Distribution",
new BMessage(MSG_SIEVE_RESET));
fSieveDist = new SieveDistView(BRect(0, 0, 460, 100));
fSieveDist->SetExplicitMinSize(BSize(460, 100));
fSieveDist->SetExplicitMaxSize(BSize(B_SIZE_UNLIMITED, 150));
fSieveSummary = new BStringView("sv_summary", "Load fraction images and click \"Add Fraction\".");
fSieveSummary->SetExplicitAlignment(
BAlignment(B_ALIGN_CENTER, B_ALIGN_MIDDLE));
fSievePanel = new BGroupView(B_VERTICAL, kPad);
BLayoutBuilder::Group<>(fSievePanel, B_VERTICAL, kPad)
.AddGroup(B_HORIZONTAL, kPad)
.Add(fSieveSizeField)
.Add(fSieveOpenBtn)
.Add(fSieveFileView)
.End()
.Add(fSieveThumb)
.AddGroup(B_HORIZONTAL, kPad)
.Add(fSieveHintView)
.AddGlue()
.Add(fSieveClearBtn)
.End()
.AddGroup(B_HORIZONTAL, kPad)
.Add(fSieveAddBtn)
.AddGlue()
.Add(fSieveResetBtn)
.End()
.Add(new BStringView("sv_dlbl", "Particle size distribution:"))
.Add(fSieveDist)
.Add(fSieveSummary);
// ===== PANEL 3: Calibrated Sheet =====
fCalOpenBtn = new BButton("cal_open", "Load Image...",
new BMessage(MSG_CAL_OPEN));
fCalFileView = new BStringView("cal_file", "No image loaded.");
fCalFileView->SetExplicitAlignment(
BAlignment(B_ALIGN_LEFT, B_ALIGN_MIDDLE));
ThumbView* calThumb = new ThumbView(BRect(0, 0, 239, 179), me);
calThumb->SetExplicitMinSize(BSize(240, 180));
calThumb->SetExplicitMaxSize(BSize(240, 180));
fCalThumb = calThumb;
fCalHintView = new BStringView("cal_hint",
"Drag on the image to select the coffee region.");
fCalHintView->SetFont(&hintFont);
fCalClearBtn = new BButton("cal_clear", "Clear Selection",
new BMessage(MSG_CLEAR_SELECTION));
fCalClearBtn->SetEnabled(false);
fCalSubCircle = new BRadioButton("cal_circ", "Circle Reference",
new BMessage(MSG_CAL_SUB_CIRCLE));
fCalSubLines = new BRadioButton("cal_lns", "Notebook Lines",
new BMessage(MSG_CAL_SUB_LINES));
fCalSubCircle->SetValue(B_CONTROL_ON);
fCalSubRadioGrp = new BGroupView(B_HORIZONTAL, kPad);
fCalSubRadioGrp->AddChild(fCalSubCircle);
fCalSubRadioGrp->AddChild(fCalSubLines);
fCalRefSizeCtl = new BTextControl("cal_ref", "Circle diameter (mm):",
"50.0", nullptr);
fCalRefSizeCtl->SetModificationMessage(nullptr);
fCalCalibrateBtn = new BButton("cal_cal", "Calibrate from Selection",
new BMessage(MSG_CAL_CALIBRATE));
fCalCalibrateBtn->SetEnabled(false);
fCalPxMmLabel = new BStringView("cal_pxmm_lbl", "Calibration: not set");
fCalPxMmLabel->SetExplicitAlignment(BAlignment(B_ALIGN_LEFT, B_ALIGN_MIDDLE));
fDerivedPxPerMm = 0.0f;
fCalAnalyseBtn = new BButton("cal_analyse", "Analyse",
new BMessage(MSG_CAL_ANALYSE));
fCalAnalyseBtn->SetEnabled(false);
fCalHist = new CalHistView(BRect(0, 0, 460, 100));
fCalHist->SetExplicitMinSize(BSize(460, 100));
fCalHist->SetExplicitMaxSize(BSize(B_SIZE_UNLIMITED, 150));
fCalResultView = new BStringView("cal_result", "");
fCalResultView->SetFont(be_bold_font);
fCalResultView->SetExplicitAlignment(
BAlignment(B_ALIGN_CENTER, B_ALIGN_MIDDLE));
fCalPanel = new BGroupView(B_VERTICAL, kPad);
BLayoutBuilder::Group<>(fCalPanel, B_VERTICAL, kPad)
.AddGroup(B_HORIZONTAL, kPad)
.Add(fCalOpenBtn)
.Add(fCalFileView)
.End()
.Add(fCalThumb)
.AddGroup(B_HORIZONTAL, kPad)
.Add(fCalHintView)
.AddGlue()
.Add(fCalClearBtn)
.End()
.Add(fCalSubRadioGrp)
.AddGroup(B_HORIZONTAL, kPad)
.Add(fCalRefSizeCtl)
.AddGlue()
.Add(fCalCalibrateBtn)
.End()
.Add(fCalPxMmLabel)
.AddGroup(B_HORIZONTAL, kPad)
.AddGlue()
.Add(fCalAnalyseBtn)
.End()
.Add(new BStringView("cal_hlbl", "Particle diameter histogram (mm):"))
.Add(fCalHist)
.Add(fCalResultView);
// ===== Main layout =====
BLayoutBuilder::Group<>(this, B_VERTICAL, 0)
.Add(menuBar)
.AddGroup(B_VERTICAL, kPad)
.SetInsets(kPad*2, kPad, kPad*2, kPad)
.Add(fModeBar)
.Add(fPhotoPanel)
.Add(fSievePanel)
.Add(fCalPanel)
.End();
// Hide non-default panels
fSievePanel->Hide();
fCalPanel->Hide();
ResizeTo(GetLayout()->PreferredSize().width + 40,
GetLayout()->PreferredSize().height);
CenterOnScreen();
}
ParticleWindow::~ParticleWindow()
{
delete fPhotoSource;
delete fPhotoThumbBmp;
delete fPhotoFilePanel;
delete fSieveSource;
delete fSieveThumbBmp;
delete fSieveFilePanel;
delete fCalSource;
delete fCalThumbBmp;
delete fCalFilePanel;
}
// ===================================================================
// SwitchMode
// ===================================================================
void ParticleWindow::SwitchMode(int mode)
{
fMode = mode;
BGroupView* panels[] = { fPhotoPanel, fSievePanel, fCalPanel };
for (int i = 0; i < 3; i++) {
bool shouldShow = (i == mode);
if (shouldShow && panels[i]->IsHidden())
panels[i]->Show();
else if (!shouldShow && !panels[i]->IsHidden())
panels[i]->Hide();
}
}
// ===================================================================
// Mode 1: Photo Estimate
// ===================================================================
void ParticleWindow::LoadPhotoImage(const entry_ref& ref)
{
BBitmap* bmp = BTranslationUtils::GetBitmapFile(BPath(&ref).Path());
if (!bmp || !bmp->IsValid()) {
delete bmp;
fPhotoFileView->SetText("Error: could not load image.");
return;
}
delete fPhotoSource;
fPhotoSource = bmp;
BEntry entry(&ref);
char name[B_FILE_NAME_LENGTH];
entry.GetName(name);
fPhotoFileView->SetText(name);
BRect src = fPhotoSource->Bounds();
float sw = src.Width() + 1, sh = src.Height() + 1;
float scale = (sw/sh > 320.0f/240.0f) ? 320.0f/sw : 240.0f/sh;
int tw = (int)(sw * scale), th = (int)(sh * scale);
delete fPhotoThumbBmp;
fPhotoThumbBmp = ScaleBitmap(fPhotoSource, tw, th);
((ThumbView*)fPhotoThumb)->SetBitmap(fPhotoThumbBmp);
fPhotoClearBtn->SetEnabled(false);
AnalysePhoto();
}
float ParticleWindow::ComputeGrindScore(BBitmap* bmp, BRect normSel)
{
BRect bounds = bmp->Bounds();
int w = (int)(bounds.Width() + 1);
int h = (int)(bounds.Height() + 1);
int bpr = bmp->BytesPerRow();
color_space cs = bmp->ColorSpace();
const uint8* bits = (const uint8*)bmp->Bits();
int x0, y0, x1, y1;
if (normSel.IsValid() && normSel.Width() > 0 && normSel.Height() > 0) {
x0 = (int)(normSel.left * w);
y0 = (int)(normSel.top * h);
x1 = (int)(normSel.right * w);
y1 = (int)(normSel.bottom * h);
} else {
x0 = w/4; y0 = h/4;
x1 = w*3/4; y1 = h*3/4;
}
if (x0 < 0) x0 = 0;
if (x1 > w) x1 = w;
if (y0 < 0) y0 = 0;
if (y1 > h) y1 = h;
if (x0 >= x1 || y0 >= y1) return 0.5f;
// Local contrast map: 8×8 cells
const int cellSz = 8;
double sumVar = 0.0;
int nCells = 0;
for (int cy = y0; cy < y1; cy += cellSz) {
int cye = cy + cellSz; if (cye > y1) cye = y1;
for (int cx = x0; cx < x1; cx += cellSz) {
int cxe = cx + cellSz; if (cxe > x1) cxe = x1;
double sum = 0.0;
int cnt = 0;
for (int py = cy; py < cye; py++)
for (int px = cx; px < cxe; px++) {
sum += pixelLuminance(bits, bpr, cs, px, py);
cnt++;
}
if (cnt == 0) continue;
double mean = sum / cnt;
double var = 0.0;
for (int py = cy; py < cye; py++)
for (int px = cx; px < cxe; px++) {
double d = pixelLuminance(bits, bpr, cs, px, py) - mean;
var += d * d;
}
sumVar += var / cnt;
nCells++;
}
}
if (nCells == 0) return 0.5f;
float avgVar = (float)(sumVar / nCells);
// Calibrate: typical max local variance for a coarse grind ≈ 0.05
float score = avgVar / 0.05f;
if (score > 1.0f) score = 1.0f;
return score;
}
const char* ParticleWindow::GrindName(float score)
{
for (int i = 0; i < kNBands; i++)
if (score < kBands[i].hi)
return kBands[i].name;
return kBands[kNBands-1].name;
}
void ParticleWindow::BuildPhotoTips(float score, char* buf, size_t sz)
{
if (score < 0.15f) {
snprintf(buf, sz,
"Grind: Extra Fine (<250 µm)\n\n"
"Suitable for: Turkish coffee only.\n\n"
"Notes: Very fine powder almost like flour. Over-extraction is "
"likely in most brew methods.\n\n"
"Brew tips:\n"
" * Use immediately — moisture absorption degrades quickly.\n"
" * Turkish: bring to boil 3 times, do not filter.\n"
" * Not suitable for espresso — will clog baskets.");
} else if (score < 0.28f) {
snprintf(buf, sz,
"Grind: Fine (250–400 µm)\n\n"
"Suitable for: Espresso, stovetop moka pot.\n\n"
"Notes: Dense puck, high extraction rate. Ideal for short, "
"concentrated shots.\n\n"
"Brew tips:\n"
" * Espresso: target 9 bar, 25–30 s shot time.\n"
" * Adjust dose ±0.5 g to dial in shot.\n"
" * Moka pot: medium heat, remove before hissing.");
} else if (score < 0.42f) {
snprintf(buf, sz,
"Grind: Medium-Fine (400–600 µm)\n\n"
"Suitable for: AeroPress, moka pot, siphon.\n\n"
"Notes: Good balance of extraction speed and clarity.\n\n"
"Brew tips:\n"
" * AeroPress: 2–3 min brew, inverted or standard method.\n"
" * Water temperature 90–95 deg C.\n"
" * Siphon: stir once at start, once mid-brew.");
} else if (score < 0.58f) {
snprintf(buf, sz,
"Grind: Medium (600–800 µm)\n\n"
"Suitable for: Pour-over (V60, Kalita), drip machine.\n\n"
"Notes: Most versatile grind — the starting point for "
"filter brewing.\n\n"
"Brew tips:\n"
" * Pour-over: 3 min total brew, 30 s bloom.\n"
" * Water temperature 92–94 deg C.\n"
" * Aim for 60 g/litre ratio as a baseline.");
} else if (score < 0.72f) {
snprintf(buf, sz,
"Grind: Medium-Coarse (800–1000 µm)\n\n"
"Suitable for: Chemex, Café Solo, Clever Dripper.\n\n"
"Notes: Slower flow rate; cleaner cup with the right filter.\n\n"
"Brew tips:\n"
" * Chemex: pre-wet filter, 4 min total brew.\n"
" * Water temperature 93–96 deg C.\n"
" * Use the thick Chemex filter for best clarity.");
} else if (score < 0.86f) {
snprintf(buf, sz,
"Grind: Coarse (1000–1200 µm)\n\n"
"Suitable for: French press, percolator.\n\n"
"Notes: Large particles prevent sediment clogging the press "
"mesh. Under-extraction risk if too coarse.\n\n"
"Brew tips:\n"
" * French press: 4 min steep, plunge slowly.\n"
" * Water temperature 95 deg C.\n"
" * Let settle 1 min before pouring.");
} else {
snprintf(buf, sz,
"Grind: Extra Coarse (>1200 µm)\n\n"
"Suitable for: Cold brew, cowboy coffee.\n\n"
"Notes: Very long extraction needed. Minimal extraction in "
"standard hot brew methods.\n\n"
"Brew tips:\n"
" * Cold brew: steep 16–24 h in cold water.\n"
" * Use a high coffee:water ratio (1:5 to 1:7).\n"
" * Strain through fine filter to remove sediment.");
}
}
void ParticleWindow::AnalysePhoto()
{
if (!fPhotoSource || !fPhotoSource->IsValid()) return;
BRect normSel;
ThumbView* tv = (ThumbView*)fPhotoThumb;
if (tv->HasSelection())
normSel = tv->NormalisedSelection();
float score = ComputeGrindScore(fPhotoSource, normSel);
fPhotoGauge->SetScore(score);
// Find band size string
const char* sizeStr = "";
if (score < 0.15f) sizeStr = "<250 µm";
else if (score < 0.28f) sizeStr = "250–400 µm";
else if (score < 0.42f) sizeStr = "400–600 µm";
else if (score < 0.58f) sizeStr = "600–800 µm";
else if (score < 0.72f) sizeStr = "800–1000 µm";
else if (score < 0.86f) sizeStr = "1000–1200 µm";
else sizeStr = ">1200 µm";
char label[256];
snprintf(label, sizeof(label),
"%s (%s) [%s]",
GrindName(score), sizeStr,
tv->HasSelection() ? "custom selection" : "centre region");
fPhotoResultView->SetText(label);
char tips[2048];
BuildPhotoTips(score, tips, sizeof(tips));
fPhotoTipsView->SetText(tips);
}
// ===================================================================
// Mode 2: Sieve Cascade
// ===================================================================
void ParticleWindow::LoadSieveFraction(const entry_ref& ref)
{
BBitmap* bmp = BTranslationUtils::GetBitmapFile(BPath(&ref).Path());
if (!bmp || !bmp->IsValid()) {
delete bmp;
fSieveFileView->SetText("Error: could not load image.");
return;
}
delete fSieveSource;
fSieveSource = bmp;
BEntry entry(&ref);
char name[B_FILE_NAME_LENGTH];
entry.GetName(name);
fSieveFileView->SetText(name);
BRect src = fSieveSource->Bounds();
float sw = src.Width() + 1, sh = src.Height() + 1;
float scale = (sw/sh > 320.0f/240.0f) ? 320.0f/sw : 240.0f/sh;
int tw = (int)(sw * scale), th = (int)(sh * scale);
delete fSieveThumbBmp;
fSieveThumbBmp = ScaleBitmap(fSieveSource, tw, th);
((ThumbView*)fSieveThumb)->SetBitmap(fSieveThumbBmp);
fSieveClearBtn->SetEnabled(false);
fSieveAddBtn->SetEnabled(true);
}
float ParticleWindow::ComputeFractionArea(BBitmap* bmp, BRect normSel)
{
BRect bounds = bmp->Bounds();
int w = (int)(bounds.Width() + 1);
int h = (int)(bounds.Height() + 1);
int bpr = bmp->BytesPerRow();
color_space cs = bmp->ColorSpace();
const uint8* bits = (const uint8*)bmp->Bits();
int x0, y0, x1, y1;
if (normSel.IsValid() && normSel.Width() > 0 && normSel.Height() > 0) {
x0 = (int)(normSel.left * w); y0 = (int)(normSel.top * h);
x1 = (int)(normSel.right * w); y1 = (int)(normSel.bottom * h);
} else {
x0 = 0; y0 = 0; x1 = w; y1 = h;
}
if (x0 < 0) x0 = 0;
if (x1 > w) x1 = w;
if (y0 < 0) y0 = 0;
if (y1 > h) y1 = h;
if (x0 >= x1 || y0 >= y1) return 0.0f;
int dark = 0, total = 0;
for (int y = y0; y < y1; y++) {
for (int x = x0; x < x1; x++) {
float L = pixelLuminance(bits, bpr, cs, x, y);
if (L < 0.7f) dark++;
total++;
}