-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
p44view.cpp
2008 lines (1732 loc) · 59.9 KB
/
p44view.cpp
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
// SPDX-License-Identifier: GPL-3.0-or-later
//
// Copyright (c) 2016-2024 plan44.ch / Lukas Zeller, Zurich, Switzerland
//
// Author: Lukas Zeller <[email protected]>
//
// This file is part of p44lrgraphics.
//
// p44lrgraphics is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// p44lrgraphics is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with p44lrgraphics. If not, see <http://www.gnu.org/licenses/>.
//
// File scope debugging options
// - Set ALWAYS_DEBUG to 1 to enable DBGLOG output even in non-DEBUG builds of this file
#define ALWAYS_DEBUG 0
// - set FOCUSLOGLEVEL to non-zero log level (usually, 5,6, or 7==LOG_DEBUG) to get focus (extensive logging) for this file
// Note: must be before including "logger.hpp" (or anything that includes "logger.hpp")
#define FOCUSLOGLEVEL 7
#include "p44view.hpp"
#include "viewfactory.hpp" // for registering views
#include <math.h>
using namespace p44;
// MARK: ===== ViewRegistrar
ViewRegistrar::ViewRegistrar(const char* aName, ViewConstructor aConstructor)
{
p44::registerView(aName, aConstructor);
}
// MARK: ===== View
static ViewRegistrar r(P44View::staticTypeName(), &P44View::newInstance);
P44View::P44View() :
mParentView(NULL),
mDirty(false),
mUpdateRequested(false),
mMinUpdateInterval(0),
mChangeTrackingLevel(0),
mChangedGeometry(false),
mChangedColoring(false),
mChangedTransform(false),
mSubsampling(true),
mSizeToContent(false)
{
resetTransforms();
mDirty = false; // reset again, because resetTransforms() sets it
setFrame(zeroRect);
// default to normal orientation
mContentOrientation = right;
// default to clip to frame, no content repeating
mFramingMode = clipXY;
// no automatic adjustment when parent's geometry changes
mAutoAdjust = noFraming;
// default content size is same as view's
setContent(zeroRect);
mBackgroundColor = { .r=0, .g=0, .b=0, .a=0 }; // transparent background,
mForegroundColor = { .r=255, .g=255, .b=255, .a=255 }; // fully white foreground...
mAlpha = 255; // but content pixels passed trough 1:1
mZOrder = 0; // none in particular
mContentIsMask = false; // content color will be used
mInvertAlpha = false; // inverted mask
mLocalTimingPriority = true;
mMaskChildDirtyUntil = Never;
}
P44View::~P44View()
{
announceChanges(true); // unbalanced, avoid any further dependency updates while finally deleting view
clear();
removeFromParent();
}
// MARK: ===== frame and content
bool P44View::isInContentSize(PixelPoint aPt)
{
return aPt.x>=0 && aPt.y>=0 && aPt.x<mContent.dx && aPt.y<mContent.dy;
}
PixelColor P44View::contentColorAt(PixelPoint aPt)
{
// for plain views, show content rect in foreground
if (isInContentSize(aPt))
return mForegroundColor;
else
return mBackgroundColor;
}
void P44View::ledRGBdata(string& aLedRGB, PixelRect aArea)
{
normalizeRect(aArea);
aLedRGB.reserve(aArea.dx*aArea.dy*6+1); // one extra for a message terminator
// pixel data row by row
for (int y=0; y<aArea.dy; ++y) {
for (int x=0; x<aArea.dx; ++x) {
PixelColor pix = colorAt({
aArea.x+x,
aArea.y+y
});
dimPixel(pix, pix.a);
string_format_append(aLedRGB, "%02X%02X%02X", pix.r, pix.g, pix.b);
}
}
}
void P44View::announceChanges(bool aStart)
{
if (aStart) {
if (mChangeTrackingLevel<=0) {
beginChanges();
}
mChangeTrackingLevel++;
}
else {
if (mChangeTrackingLevel>0) {
mChangeTrackingLevel--;
if (mChangeTrackingLevel==0) {
finalizeChanges();
}
}
}
}
void P44View::flagChange(bool &aChangeFlag)
{
if (mChangeTrackingLevel>0) {
// just set the flag
aChangeFlag = true;
return;
}
// No change tracking in progress -> this is a singular change
// Note: if the change flag is already set, this can only mean we are called
// from finalizeChanges(), so DO NOT RECURSE here
if (!aChangeFlag) {
aChangeFlag = true;
// no change bracket open - singular change that needs finalisation right now
finalizeChanges();
aChangeFlag = false; // just to make sure, finalizing should reset the flag
}
}
void P44View::beginChanges()
{
// start tracking changes
mChangedGeometry = false;
mChangedColoring = false;
mChangedTransform = false;
mPreviousFrame = mFrame;
mPreviousContent = mContent;
}
void P44View::finalizeChanges()
{
if (mChangedGeometry) {
FOCUSLOG("View '%s' changed geometry: frame=(%d,%d,%d,%d)->(%d,%d,%d,%d), content=(%d,%d,%d,%d)->(%d,%d,%d,%d)",
getLabel().c_str(),
mPreviousFrame.x, mPreviousFrame.y, mPreviousFrame.dx, mPreviousFrame.dy,
mFrame.x, mFrame.y, mFrame.dx, mFrame.dy,
mPreviousContent.x, mPreviousContent.y, mPreviousContent.dx, mPreviousContent.dy,
mContent.x, mContent.y, mContent.dx, mContent.dy
);
makeDirty();
geometryChanged(mPreviousFrame, mPreviousContent); // let subclasses know
if (mParentView) {
// Note: as we are passing in the frames, it is safe when the following calls recursively calls geometryChanged again
// except that it must not do so unconditionally to prevent endless recursion
mParentView->childGeometryChanged(this, mPreviousFrame, mPreviousContent);
}
mChangedGeometry = false;
}
if (mChangedColoring) {
FOCUSLOG("View '%s' changed coloring", getLabel().c_str());
makeColorDirty();
mChangedColoring = false;
}
if (mChangedTransform) {
if (mContentRotation!=0) {
// Calculate rotation multipliers
double rotPi = FP_DBL_VAL(mContentRotation)*M_PI/180;
mRotSin = FP_FROM_DBL(sin(rotPi));
mRotCos = FP_FROM_DBL(cos(rotPi));
}
else {
// no rotation
mRotCos = FP_FROM_INT(1);
mRotSin = FP_FROM_INT(0);
}
recalculateScrollDependencies();
mChangedTransform = false;
makeDirty();
}
}
void P44View::recalculateScrollDependencies()
{
// but non-integer scrolling or scaling might need fractional sampling
mNeedsFractionalSampling = mContentRotation!=0 || FP_HASFRAC(mScrollX) || FP_HASFRAC(mScrollY) || mShrinkX!=FP_FROM_INT(1) || mShrinkY!=FP_FROM_INT(1);
}
void P44View::orientateCoord(PixelPoint &aCoord)
{
if (mContentOrientation & xy_swap) {
swap(aCoord.x, aCoord.y);
}
}
void P44View::flipCoordInFrame(PixelPoint &aCoord)
{
// flip within frame if not zero sized
if ((mContentOrientation & x_flip) && mFrame.dx>0) {
aCoord.x = mFrame.dx-aCoord.x-1;
}
if ((mContentOrientation & y_flip) && mFrame.dy>0) {
aCoord.y = mFrame.dy-aCoord.y-1;
}
}
void P44View::inFrameToContentCoord(PixelPoint &aCoord)
{
flipCoordInFrame(aCoord);
orientateCoord(aCoord);
aCoord.x -= mContent.x;
aCoord.y -= mContent.y;
}
void P44View::contentToInFrameCoord(PixelPoint &aCoord)
{
aCoord.x += mContent.x;
aCoord.y += mContent.y;
orientateCoord(aCoord);
flipCoordInFrame(aCoord);
}
/// change rect and trigger geometry change when actually changed
void P44View::changeGeometryRect(PixelRect &aRect, PixelRect aNewRect)
{
normalizeRect(aNewRect);
if (aNewRect.x!=aRect.x) {
aRect.x = aNewRect.x;
flagGeometryChange();
}
if (aNewRect.y!=aRect.y) {
aRect.y = aNewRect.y;
flagGeometryChange();
}
if (aNewRect.dx!=aRect.dx) {
aRect.dx = aNewRect.dx;
flagGeometryChange();
}
if (aNewRect.dy!=aRect.dy) {
aRect.dy = aNewRect.dy;
flagGeometryChange();
}
}
void P44View::setFrame(PixelRect aFrame)
{
announceChanges(true);
changeGeometryRect(mFrame, aFrame);
announceChanges(false);
}
void P44View::setParent(P44ViewPtr aParentView)
{
mParentView = aParentView.get();
}
P44ViewPtr P44View::getParent()
{
return P44ViewPtr(mParentView);
}
bool P44View::isParentOrThis(P44ViewPtr aRefView)
{
if (aRefView==this) return true;
if (mParentView) return mParentView->isParentOrThis(aRefView);
return false;
}
void P44View::setContent(PixelRect aContent)
{
announceChanges(true);
changeGeometryRect(mContent, aContent);
if (mSizeToContent) {
moveFrameToContent(true);
}
announceChanges(false);
};
void P44View::setContentSize(PixelPoint aSize)
{
announceChanges(true);
changeGeometryRect(mContent, { mContent.x, mContent.y, aSize.x, aSize.y });
if (mChangedGeometry && mSizeToContent) moveFrameToContent(true);
announceChanges(false);
};
void P44View::setContentOrigin(PixelPoint aOrigin)
{
announceChanges(true);
changeGeometryRect(mContent, { aOrigin.x, aOrigin.y, mContent.dx, mContent.dy });
announceChanges(false);
};
void P44View::setRelativeContentOrigin(double aRelX, double aRelY, bool aCentered)
{
announceChanges(true);
setRelativeContentOriginX(aRelX, aCentered);
setRelativeContentOriginY(aRelY, aCentered);
announceChanges(false);
}
void P44View::setRelativeContentOriginX(double aRelX, bool aCentered)
{
// standard version, content origin is a corner of the relevant area
announceChanges(true);
changeGeometryRect(mContent, { (int)(aRelX*max(mContent.dx,mFrame.dx)+(aCentered ? mFrame.dx/2 : 0)), mContent.y, mContent.dx, mContent.dy });
announceChanges(false);
}
void P44View::setRelativeContentOriginY(double aRelY, bool aCentered)
{
// standard version, content origin is a corner of the relevant area
announceChanges(true);
changeGeometryRect(mContent, { mContent.x, (int)(aRelY*max(mContent.dy,mFrame.dy)+(aCentered ? mFrame.dy/2 : 0)), mContent.dx, mContent.dy });
announceChanges(false);
}
void P44View::setRelativeContentSize(double aRelDx, double aRelDy, bool aRelativeToLargerFrameDimension)
{
PixelPoint sz = getFrameSize();
orientateCoord(sz); // maybe flipped
if (aRelativeToLargerFrameDimension) {
sz.x = max(sz.x, sz.y);
sz.y = sz.x;
}
sz.x *= aRelDx*FP_DBL_VAL(mShrinkX); // if content is shrunken, size must be boosted to appear same size again
sz.y *= aRelDy*FP_DBL_VAL(mShrinkY); // if content is shrunken, size must be boosted to appear same size again
announceChanges(true);
// Note: not using setContentSize() because we do not want auto-reframing when we adjust relative to frame
setContentDx(sz.x);
setContentDy(sz.y);
announceChanges(false);
}
void P44View::setContentAppearanceSize(double aRelDx, double aRelDy)
{
// by default, just 1:1 relative to frame size
setRelativeContentSize(aRelDx, aRelDy, false);
}
void P44View::setRelativeContentSizeX(double aRelDx)
{
PixelPoint sz = getFrameSize();
orientateCoord(sz); // maybe flipped
sz.x *= aRelDx*FP_DBL_VAL(mShrinkX); // if content is shrunken, size must be boosted to appear same size again
// Note: not using setContentSize() because we do not want auto-reframing when we adjust relative to frame
setContentDx(sz.x);
}
void P44View::setRelativeContentSizeY(double aRelDy)
{
PixelPoint sz = getFrameSize();
orientateCoord(sz); // maybe flipped
sz.y *= aRelDy*FP_DBL_VAL(mShrinkY); // if content is shrunken, size must be boosted to appear same size again
// Note: not using setContentSize() because we do not want auto-reframing when we adjust relative to frame
setContentDy(sz.y);
}
void P44View::setFullFrameContent()
{
PixelPoint sz = getFrameSize();
orientateCoord(sz);
setContent({ 0, 0, sz.x, sz.y });
}
void P44View::contentRectAsViewCoord(PixelRect &aRect)
{
// get opposite content rect corners
PixelPoint c1 = { 0, 0 };
contentToInFrameCoord(c1);
PixelPoint inset = { mContent.dx>0 ? 1 : 0, mContent.dy>0 ? 1 : 0 };
PixelPoint c2 = { mContent.dx-inset.x, mContent.dy-inset.y };
// transform into coords relative to frame origin
contentToInFrameCoord(c2);
// make c2 the non-origin corner
if (c1.x>c2.x) swap(c1.x, c2.x);
if (c1.y>c2.y) swap(c1.y, c2.y);
// create view coord rectangle around current contents
aRect.x = c1.x + mFrame.x;
aRect.dx = c2.x-c1.x+inset.x;
aRect.y = c1.y + mFrame.y;
aRect.dy = c2.y-c1.y+inset.y;
FOCUSLOG("View '%s' frame=(%d,%d,%d,%d), content rect as view coords=(%d,%d,%d,%d)",
getLabel().c_str(),
mFrame.x, mFrame.y, mFrame.dx, mFrame.dy,
aRect.x, aRect.y, aRect.dx, aRect.dy
);
}
/// move frame such that its origin is at the actual content's origin
/// @note content does not move relative to view frame origin, but frame does
void P44View::moveFrameToContent(bool aResize)
{
announceChanges(true);
if (aResize) sizeFrameToContent();
PixelRect f;
contentRectAsViewCoord(f);
// move frame to the place where the content rectangle did appear so far...
changeGeometryRect(mFrame, f);
// ...which means that no content offset is needed any more (we've compensated it by moving the frame)
mContent.x = 0; mContent.y = 0;
announceChanges(false);
}
void P44View::sizeFrameToContent()
{
PixelPoint sz = { mContent.dx, mContent.dy };
orientateCoord(sz);
PixelRect f = mFrame;
f.dx = sz.x;
f.dy = sz.y;
changeGeometryRect(mFrame, f);
}
void P44View::autoAdjustTo(PixelRect aReferenceRect)
{
normalizeRect(aReferenceRect);
announceChanges(true);
if (mAutoAdjust & adjustmentMask) {
if ((mAutoAdjust & fillX)==fillX) {
mFrame.dx = aReferenceRect.dx;
}
if ((mAutoAdjust & fillY)==fillY) {
mFrame.dy = aReferenceRect.dy;
}
if ((mAutoAdjust & noAdjust)!=noAdjust) {
setFullFrameContent();
}
}
announceChanges(false);
}
void P44View::clear()
{
stopAnimations();
// as the only thing a P44View can display is the content rect in foreground color, reset it here
// Note: subclasses will not always call inherited::clear() as they might want to retain the content rectangle,
// and just remove the actual content data
setContentSize({0, 0});
}
void P44View::resetTransforms()
{
announceChanges(true);
mContentRotation = FP_FROM_INT(0);
mScrollX = FP_FROM_INT(0);
mScrollY = FP_FROM_INT(0);
mShrinkX = FP_FROM_INT(1);
mShrinkY = FP_FROM_INT(1);
mChangedTransform = true;
announceChanges(false);
}
// MARK: ===== updating
void P44View::makeDirtyAndUpdate()
{
// make dirty locally
makeDirty();
// request a step at the root view level
requestUpdate();
}
void P44View::requestUpdate()
{
FOCUSLOG("requestUpdate() called for view@%p", this);
P44View *p = this;
while (p->mParentView) {
if (p->mUpdateRequested) return; // already requested, no need to descend to root
p->mUpdateRequested = true; // mark having requested update all the way down to root, update() will be called on all views to clear it
p = p->mParentView;
}
// now p = root view
if (!p->mUpdateRequested && p->mNeedUpdateCB) {
p->mUpdateRequested = true; // only request once
FOCUSLOG("actually requesting update from root view@%p (from view@%p)", p, this);
// there is a needUpdate callback here
// DO NOT call it directly, but from mainloop, so receiver can safely call
// back into any view object method without causing recursions
MainLoop::currentMainLoop().executeNow(p->mNeedUpdateCB);
}
}
void P44View::requestUpdateIfNeeded()
{
if (!mUpdateRequested && isDirty()) {
requestUpdate();
}
}
void P44View::updated()
{
mDirty = false;
mUpdateRequested = false;
}
void P44View::setNeedUpdateCB(TimerCB aNeedUpdateCB)
{
mNeedUpdateCB = aNeedUpdateCB;
}
void P44View::setMinUpdateInterval(MLMicroSeconds aMinUpdateInterval)
{
mMinUpdateInterval = aMinUpdateInterval;
}
MLMicroSeconds P44View::getMinUpdateInterval()
{
P44View *p = this;
do {
if (p->mMinUpdateInterval>0) return p->mMinUpdateInterval;
p = p->mParentView;
} while (p);
return DEFAULT_MIN_UPDATE_INTERVAL;
}
bool P44View::removeFromParent()
{
if (mParentView) {
return mParentView->removeView(this); // should always return true...
}
return false;
}
void P44View::makeDirty()
{
mDirty = true;
}
void P44View::makeColorDirty()
{
recalculateColoring();
makeDirty();
}
bool P44View::reportDirtyChilds()
{
if (mMaskChildDirtyUntil) {
if (MainLoop::now()<mMaskChildDirtyUntil) {
return false;
}
mMaskChildDirtyUntil = 0;
}
return true;
}
void P44View::updateNextCall(MLMicroSeconds &aNextCall, MLMicroSeconds aCallCandidate, MLMicroSeconds aCandidatePriorityUntil, MLMicroSeconds aNow)
{
if (mLocalTimingPriority && aCandidatePriorityUntil>0 && aCallCandidate>=0 && aCallCandidate<aCandidatePriorityUntil) {
// children must not cause "dirty" before candidate time is over
if (aNow==Never) aNow = MainLoop::now();
mMaskChildDirtyUntil = (aCallCandidate-aNow)*2+aNow; // duplicate to make sure candidate execution has some time to happen BEFORE dirty is unblocked
}
if (aNextCall<=0 || (aCallCandidate>0 && aCallCandidate<aNextCall)) {
// candidate wins
aNextCall = aCallCandidate;
}
}
MLMicroSeconds P44View::step(MLMicroSeconds aPriorityUntil, MLMicroSeconds aNow)
{
mUpdateRequested = false; // no step request pending any more
// check animations
MLMicroSeconds nextCall = Infinite;
#if ENABLE_ANIMATION
AnimationsList::iterator pos = mAnimations.begin();
while (pos != mAnimations.end()) {
ValueAnimatorPtr animator = (*pos);
MLMicroSeconds nextStep = animator->step(aNow);
if (!animator->inProgress()) {
// this animation is done, remove it from the list
pos = mAnimations.erase(pos);
continue;
}
updateNextCall(nextCall, nextStep);
pos++;
}
#endif // ENABLE_ANIMATION
return nextCall;
}
void P44View::setAlpha(PixelColorComponent aAlpha)
{
if (mAlpha!=aAlpha) {
mAlpha = aAlpha;
makeDirty();
}
}
void P44View::setZOrder(int aZOrder)
{
announceChanges(true);
if (mZOrder!=aZOrder) {
mZOrder = aZOrder;
flagGeometryChange();
}
announceChanges(false);
}
#define SHOW_ORIGIN 0
PixelColor P44View::colorAt(PixelPoint aPt)
{
// default is background color
if (mAlpha==0) return transparent; // optimisation
// aPt is parent view coordinates
aPt.x -= mFrame.x;
aPt.y -= mFrame.y;
// aPt is relative to frame origin now
return colorInFrameAt(aPt);
}
PixelColor P44View::colorInFrameAt(PixelPoint aPt)
{
if (mAlpha==0 || mShrinkX==0 || mShrinkY==0) return transparent; // optimisation
PixelColor pc = mBackgroundColor;
// optionally clip content to frame
if (mFramingMode&clipXY && (
((mFramingMode&clipXmin) && aPt.x<0) ||
((mFramingMode&clipXmax) && aPt.x>=mFrame.dx) ||
((mFramingMode&clipYmin) && aPt.y<0) ||
((mFramingMode&clipYmax) && aPt.y>=mFrame.dy)
)) {
// aPt is clipped out
pc.a = 0; // invisible
}
else {
// aPt is not clipped out, we need to consult content to get the color
// - optionally repeat frame's contents in selected directions outside the frame
// (i.e. wrap outside input coordinates back into x..x+dx and y..y+dy)
if (mFrame.dx>0) {
while ((mFramingMode&repeatXmin) && aPt.x<0) aPt.x+=mFrame.dx;
while ((mFramingMode&repeatXmax) && aPt.x>=mFrame.dx) aPt.x-=mFrame.dx;
}
if (mFrame.dy>0) {
while ((mFramingMode&repeatYmin) && aPt.y<0) aPt.y+=mFrame.dy;
while ((mFramingMode&repeatYmax) && aPt.y>=mFrame.dy) aPt.y-=mFrame.dy;
}
// re-orient in frame and make relative to content origin
inFrameToContentCoord(aPt);
// Until here, we are still in the pixel grid of the frame
if (!mNeedsFractionalSampling) {
// just apply integer scroll
aPt.x += FP_INT_VAL(mScrollX);
aPt.y += FP_INT_VAL(mScrollY);
// get the pixel
pc = contentColorAt(aPt);
}
else {
// apply rotation first, then scroll so we can scroll and shrink in any direction
FracValue rX = FP_FACTOR_FROM_INT(aPt.x);
FracValue rY = FP_FACTOR_FROM_INT(aPt.y);
FracValue samplingX = rX*mRotCos-rY*mRotSin;
FracValue samplingY = rX*mRotSin+rY*mRotCos;
// apply shrink and scroll (Important: scroll is in content coordinates, after rotation
samplingX = FP_MUL_CORR(samplingX*mShrinkX) + mScrollX;
samplingY = FP_MUL_CORR(samplingY*mShrinkY) + mScrollY;
// Note: subsampling is not centered, but always right/up from the sample point
// samplingX/Y is now where we must sample from content
// mShrinkX/Y is the size of the area we need to sample from
PixelPoint firstPt;
if (mSubsampling) {
// - the integer coordinates to start sampling
firstPt.x = FP_INT_FLOOR(samplingX);
firstPt.y = FP_INT_FLOOR(samplingY);
// - the integer coordinates to end sampling
PixelPoint lastPt;
lastPt.x = FP_INT_CEIL(samplingX+mShrinkX)-1;
lastPt.y = FP_INT_CEIL(samplingY+mShrinkY)-1;
// - the possibly fractional weight at the start
FracValue firstPixelWeightX = FP_FROM_INT(firstPt.x+1)-samplingX;
FracValue firstPixelWeightY = FP_FROM_INT(firstPt.y+1)-samplingY;
// - the possibly fractional weight at the end
FracValue lastPixelWeightX = samplingX+mShrinkX - FP_FROM_INT(lastPt.x);
FracValue lastPixelWeightY = samplingY+mShrinkY - FP_FROM_INT(lastPt.y);
// averaging loop
// - accumulators
FracValue r, g, b, a, tw;
prepareAverage(r, g, b, a, tw);
FracValue weightY = firstPixelWeightY;
PixelPoint samplingPt; // sampling point coordinate in content
for (samplingPt.y = firstPt.y; samplingPt.y<=lastPt.y; samplingPt.y++) {
FracValue weightX = firstPixelWeightX;
for (samplingPt.x = firstPt.x; samplingPt.x<=lastPt.x; samplingPt.x++) {
// the color to sample
pc = contentColorAt(samplingPt);
averagePixelPower(r, g, b, a, tw, pc, FP_MUL_CORR(weightY*weightX));
// adjust the weight
weightX = samplingPt.x+1==lastPt.x ? lastPixelWeightX : FP_FROM_INT(1); // possibly fractional weight on last pixel
}
weightY = samplingPt.y+1==lastPt.y ? lastPixelWeightY : FP_FROM_INT(1); // possibly fractional weight on last pixel
}
pc = averagedPixelResult(r, g, b, a, tw);
}
else {
// just get color from integer point
firstPt.x = FP_INT_ROUND(samplingX);
firstPt.y = FP_INT_ROUND(samplingY);
pc = contentColorAt(firstPt);
}
}
// now pc is the color at specified frame coordinate point
if (mInvertAlpha) {
pc.a = 255-pc.a;
}
if (mContentIsMask) {
// use only (possibly inverted) alpha of content, color comes from foregroundColor
pc.r = mForegroundColor.r;
pc.g = mForegroundColor.g;
pc.b = mForegroundColor.b;
}
#if SHOW_ORIGIN
if (aPt.x==0 && aPt.y==0) {
return { .r=255, .g=0, .b=0, .a=255 };
}
else if (aPt.x==1 && aPt.y==0) {
return { .r=0, .g=255, .b=0, .a=255 };
}
else if (aPt.x==0 && aPt.y==1) {
return { .r=0, .g=0, .b=255, .a=255 };
}
#endif
if (pc.a==0) {
// background is where content is fully transparent
pc = mBackgroundColor;
// Note: view background does NOT shine through semi-transparent content pixels!
// Rather, non-fully-transparent content pixels directly are view pixels!
}
// factor in layer alpha
if (mAlpha!=255) {
pc.a = dimVal(pc.a, mAlpha);
}
}
return pc;
}
// MARK: ===== Utilities
bool p44::rectContainsRect(const PixelRect &aParentRect, const PixelRect &aChildRect)
{
return
aChildRect.x>=aParentRect.x &&
aChildRect.x+aChildRect.dx<=aParentRect.x+aParentRect.dx &&
aChildRect.y>=aParentRect.y &&
aChildRect.y+aChildRect.dy<=aParentRect.y+aParentRect.dy;
}
bool p44::rectIntersectsRect(const PixelRect &aRect1, const PixelRect &aRect2)
{
return
aRect1.x+aRect1.dx>aRect2.x &&
aRect1.x<aRect2.x+aRect2.dx &&
aRect1.y+aRect1.dy>aRect2.y &&
aRect1.y<aRect2.y+aRect2.dy;
}
void p44::normalizeRect(PixelRect &aRect)
{
if (aRect.dx<0) { aRect.x+=aRect.dx; aRect.dx = -aRect.dx; }
if (aRect.dy<0) { aRect.y+=aRect.dy; aRect.dy = -aRect.dy; }
}
#if ENABLE_VIEWCONFIG
// MARK: ===== config utilities
typedef struct {
P44View::Orientation orientation;
const char *name;
} OrientationDesc;
static const OrientationDesc orientationDescs[] = {
{ P44View::right, "right" }, // untransformed X goes left to right, Y goes up
// Note: rest of table should be ordered such that multi-bit combinations come first (for orientationToText)
{ P44View::up, "up" }, // X goes up, Y goes left
{ P44View::left, "left" }, // X goes left, Y goes down
{ P44View::down, "down" }, // X goes down, Y goes right
{ P44View::xy_swap, "swapXY" }, // swap x and y
{ P44View::x_flip, "flipX" }, // flip x
{ P44View::y_flip, "flipY" }, // flip y
{ 0, NULL }
};
P44View::Orientation P44View::textToOrientation(const char *aOrientationText)
{
Orientation o = P44View::right;
while (aOrientationText) {
size_t n = 0;
while (aOrientationText[n] && aOrientationText[n]!='|') n++;
for (const OrientationDesc *od = orientationDescs; od->name; od++) {
if (uequals(aOrientationText, od->name, n)) {
o |= od->orientation;
}
}
aOrientationText += n;
if (*aOrientationText==0) break;
aOrientationText++; // skip |
}
return o;
}
typedef struct {
P44View::FramingMode mode;
const char *name;
bool forPos;
} FramingModeDesc;
static const FramingModeDesc framingModeDescs[] = {
{ P44View::noFraming, "none", false }, // do not repeat or clip = content spills over frame
// Note: rest of table should be ordered such that multi-bit combinations come first (for framingModeToText)
{ P44View::repeatXY, "repeatXY", false }, // repeat frame in all directions
{ P44View::repeatX, "repeatX", false }, // repeat frame in both X directions
{ P44View::repeatY, "repeatY", false }, // repeat frame in both Y directions
{ P44View::repeatXmin, "repeatXmin", false }, // repeat frame in X direction for X<frame area
{ P44View::repeatXmax, "repeatXmax", false }, // repeat frame in X direction for X>=frame area
{ P44View::repeatYmin, "repeatYmin", false }, // repeat frame in Y direction for Y<frame area
{ P44View::repeatYmax, "repeatYmax", false }, // repeat frame in Y direction for Y>=frame area
{ P44View::clipXY, "clipXY", false }, // clip content to frame rectangle
{ P44View::clipY, "clipY", false }, // clip content vertically
{ P44View::clipX, "clipX", false }, // clip content horizontally
{ P44View::clipXmin, "clipXmin", false }, // clip content left of frame area
{ P44View::clipXmax, "clipXmax", false }, // clip content right of frame area
{ P44View::clipYmin, "clipYmin", false }, // clip content below frame area
{ P44View::clipYmax, "clipYmax", false }, // clip content above frame area
{ P44View::noAdjust, "noAdjust", true }, // for positioning: do not adjust content rectangle
{ P44View::fillXY, "fillXY", true }, // for positioning: set frame size fill parent frame
{ P44View::fillX, "fillX", true }, // for positioning: set frame size fill parent in X direction
{ P44View::fillY, "fillY", true }, // for positioning: set frame size fill parent in Y direction
{ P44View::appendLeft, "appendLeft", true }, // for positioning: extend to the left
{ P44View::appendRight, "appendRight", true }, // for positioning: extend to the right
{ P44View::appendBottom, "appendBottom", true }, // for positioning: extend towards bottom
{ P44View::appendTop, "appendTop", true }, // for positioning: extend towards top
{ 0, NULL }
};
P44View::FramingMode P44View::textToFramingMode(const char *aFramingModeText)
{
FramingMode m = P44View::noFraming;
while (aFramingModeText) {
size_t n = 0;
while (aFramingModeText[n] && aFramingModeText[n]!='|') n++;
for (const FramingModeDesc *wd = framingModeDescs; wd->name && n>0; wd++) {
if (uequals(aFramingModeText, wd->name, n)) {
m |= wd->mode;
}
}
aFramingModeText += n;
if (*aFramingModeText==0) break;
aFramingModeText++; // skip |
}
return m;
}
// MARK: ===== view configuration
#if ENABLE_P44SCRIPT
using namespace P44Script;
ErrorPtr P44View::configureView(JsonObjectPtr aViewConfig)
{
announceChanges(true);
string name;
JsonObjectPtr val;
ScriptObjPtr vo = newViewObj();
// these must be postponed to after reading other properties
bool fullFrameContent = false;
JsonObjectPtr animationCfg;
// now
aViewConfig->resetKeyIteration();
while (aViewConfig->nextKeyValue(name, val)) {
// catch special procedural cases
if (name=="clear" && val->boolValue()) {
clear();
}
else if (name=="fullframe" && val->boolValue()) {
fullFrameContent = true;
}
else if (name=="stopanimations" && val->boolValue()) {
stopAnimations();
}
else if (name=="animate") {
animationCfg = val;
}
// write-onlys for backward compatibility
else if (name=="rel_content_x") {
setRelativeContentOriginX(val->doubleValue(), false);
}
else if (name=="rel_content_y") {
setRelativeContentOriginY(val->doubleValue(), false);
}
else if (name=="rel_center_x") {
setRelativeContentOriginX(val->doubleValue(), true);
}
else if (name=="rel_center_y") {
setRelativeContentOriginY(val->doubleValue(), true);
}
else {
// normal member access
ScriptObjPtr lv = vo->memberByName(name, lvalue);
if (lv) lv->assignLValue(NoOP, ScriptObj::valueFromJSON(val));
}
}
// now apply postponed ones
if (fullFrameContent) setFullFrameContent();
if (animationCfg) configureAnimation(animationCfg);
if (mChangedGeometry && mSizeToContent) {
moveFrameToContent(true);