1 /*
2  * Copyright (c) 2023-2024 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 #include "core/components_ng/pattern/grid/grid_layout_info.h"
16 
17 #include <numeric>
18 
19 #include "base/utils/utils.h"
20 #include "core/components_ng/pattern/scrollable/scrollable_properties.h"
21 
22 namespace OHOS::Ace::NG {
GetItemIndexByPosition(int32_t position)23 int32_t GridLayoutInfo::GetItemIndexByPosition(int32_t position)
24 {
25     auto iter = positionItemIndexMap_.find(position);
26     if (iter != positionItemIndexMap_.end()) {
27         return iter->second;
28     }
29     return position;
30 }
31 
GetPositionByItemIndex(int32_t itemIndex)32 int32_t GridLayoutInfo::GetPositionByItemIndex(int32_t itemIndex)
33 {
34     auto position = itemIndex;
35     auto find = std::find_if(positionItemIndexMap_.begin(), positionItemIndexMap_.end(),
36         [itemIndex](const std::pair<int32_t, int32_t>& item) { return item.second == itemIndex; });
37     if (find != positionItemIndexMap_.end()) {
38         position = find->first;
39     }
40 
41     return position;
42 }
43 
GetOriginalIndex() const44 int32_t GridLayoutInfo::GetOriginalIndex() const
45 {
46     return currentMovingItemPosition_;
47 }
48 
ClearDragState()49 void GridLayoutInfo::ClearDragState()
50 {
51     positionItemIndexMap_.clear();
52     currentMovingItemPosition_ = -1;
53     currentRect_.Reset();
54 }
55 
MoveItemsBack(int32_t from,int32_t to,int32_t itemIndex)56 void GridLayoutInfo::MoveItemsBack(int32_t from, int32_t to, int32_t itemIndex)
57 {
58     auto lastItemIndex = itemIndex;
59     if (crossCount_ == 0) {
60         return;
61     }
62     for (int32_t i = from; i <= to; ++i) {
63         int32_t mainIndex = (i - startIndex_) / crossCount_ + startMainLineIndex_;
64         int32_t crossIndex = (i - startIndex_) % crossCount_;
65         if (i == from) {
66             gridMatrix_[mainIndex][crossIndex] = itemIndex;
67         } else {
68             auto index = GetItemIndexByPosition(i - 1);
69             gridMatrix_[mainIndex][crossIndex] = index;
70             positionItemIndexMap_[i - 1] = lastItemIndex;
71             lastItemIndex = index;
72         }
73     }
74     positionItemIndexMap_[from] = itemIndex;
75     positionItemIndexMap_[to] = lastItemIndex;
76     currentMovingItemPosition_ = from;
77 }
78 
MoveItemsForward(int32_t from,int32_t to,int32_t itemIndex)79 void GridLayoutInfo::MoveItemsForward(int32_t from, int32_t to, int32_t itemIndex)
80 {
81     if (crossCount_ == 0) {
82         return;
83     }
84     for (int32_t i = from; i <= to; ++i) {
85         int32_t mainIndex = (i - startIndex_) / crossCount_ + startMainLineIndex_;
86         int32_t crossIndex = (i - startIndex_) % crossCount_;
87         if (i == to) {
88             gridMatrix_[mainIndex][crossIndex] = itemIndex;
89         } else {
90             auto index = GetItemIndexByPosition(i + 1);
91             gridMatrix_[mainIndex][crossIndex] = index;
92             positionItemIndexMap_[i] = index;
93         }
94     }
95     positionItemIndexMap_[to] = itemIndex;
96     currentMovingItemPosition_ = to;
97 }
98 
SwapItems(int32_t itemIndex,int32_t insertIndex)99 void GridLayoutInfo::SwapItems(int32_t itemIndex, int32_t insertIndex)
100 {
101     currentMovingItemPosition_ = currentMovingItemPosition_ == -1 ? itemIndex : currentMovingItemPosition_;
102     auto insertPosition = insertIndex;
103     // drag from another grid
104     if (itemIndex == -1) {
105         if (currentMovingItemPosition_ == -1) {
106             MoveItemsBack(insertPosition, childrenCount_, itemIndex);
107             return;
108         }
109     } else {
110         insertPosition = GetPositionByItemIndex(insertIndex);
111     }
112 
113     if (currentMovingItemPosition_ > insertPosition) {
114         MoveItemsBack(insertPosition, currentMovingItemPosition_, itemIndex);
115         return;
116     }
117 
118     if (insertPosition > currentMovingItemPosition_) {
119         MoveItemsForward(currentMovingItemPosition_, insertPosition, itemIndex);
120     }
121 }
122 
UpdateEndLine(float mainSize,float mainGap)123 void GridLayoutInfo::UpdateEndLine(float mainSize, float mainGap)
124 {
125     if (mainSize >= lastMainSize_) {
126         return;
127     }
128     for (auto i = startMainLineIndex_; i < endMainLineIndex_; ++i) {
129         mainSize -= (lineHeightMap_[i] + mainGap);
130         if (LessOrEqual(mainSize + mainGap, 0)) {
131             endMainLineIndex_ = i;
132             break;
133         }
134     }
135 }
136 
UpdateEndIndex(float overScrollOffset,float mainSize,float mainGap)137 void GridLayoutInfo::UpdateEndIndex(float overScrollOffset, float mainSize, float mainGap)
138 {
139     auto remainSize = mainSize - overScrollOffset;
140     for (auto i = startMainLineIndex_; i < endMainLineIndex_; ++i) {
141         remainSize -= (lineHeightMap_[i] + mainGap);
142         if (LessOrEqual(remainSize + mainGap, 0)) {
143             auto endLine = gridMatrix_.find(i);
144             CHECK_NULL_VOID(endLine != gridMatrix_.end());
145             CHECK_NULL_VOID(!endLine->second.empty());
146             endIndex_ = endLine->second.rbegin()->second;
147             break;
148         }
149     }
150 }
151 
IsOutOfStart() const152 bool GridLayoutInfo::IsOutOfStart() const
153 {
154     return reachStart_ && Positive(currentOffset_);
155 }
156 
IsOutOfEnd(float mainGap,bool irregular) const157 bool GridLayoutInfo::IsOutOfEnd(float mainGap, bool irregular) const
158 {
159     const bool atOrOutOfStart = reachStart_ && NonNegative(currentOffset_);
160     if (irregular) {
161         return !atOrOutOfStart && Negative(GetDistanceToBottom(lastMainSize_, totalHeightOfItemsInView_, mainGap));
162     }
163     const float endPos = currentOffset_ + totalHeightOfItemsInView_;
164     return !atOrOutOfStart && (endIndex_ == childrenCount_ - 1) &&
165            LessNotEqual(endPos, lastMainSize_ - contentEndPadding_);
166 }
167 
GetCurrentOffsetOfRegularGrid(float mainGap) const168 float GridLayoutInfo::GetCurrentOffsetOfRegularGrid(float mainGap) const
169 {
170     if (lineHeightMap_.empty()) {
171         return 0.0f;
172     }
173     float defaultHeight = GetTotalLineHeight(0.0f) / static_cast<float>(lineHeightMap_.size());
174     if (crossCount_ == 0) {
175         return 0.0f;
176     }
177     auto lines = startIndex_ / crossCount_;
178     float res = 0.0f;
179     for (int i = 0; i < lines; ++i) {
180         auto it = lineHeightMap_.find(i);
181         res += (it != lineHeightMap_.end() ? it->second : defaultHeight) + mainGap;
182     }
183     return res - currentOffset_;
184 }
185 
GetContentOffset(float mainGap) const186 float GridLayoutInfo::GetContentOffset(float mainGap) const
187 {
188     if (lineHeightMap_.empty()) {
189         return 0.0f;
190     }
191     if (!hasBigItem_) {
192         return GetCurrentOffsetOfRegularGrid(mainGap);
193     }
194     // assume lineHeightMap is continuous in range [begin, rbegin].
195     int32_t itemCount = FindItemCount(lineHeightMap_.begin()->first, lineHeightMap_.rbegin()->first);
196     if (itemCount == 0) {
197         return 0.0f;
198     }
199     if (itemCount == childrenCount_ || (lineHeightMap_.begin()->first == 0 && itemCount >= startIndex_)) {
200         return GetStartLineOffset(mainGap);
201     }
202     // begin estimation
203     float heightSum = GetTotalLineHeight(mainGap, false);
204     if (itemCount == 0) {
205         return 0.0f;
206     }
207     auto averageHeight = heightSum / itemCount;
208     return startIndex_ * averageHeight - currentOffset_;
209 }
210 
FindItemCount(int32_t startLine,int32_t endLine) const211 int32_t GridLayoutInfo::FindItemCount(int32_t startLine, int32_t endLine) const
212 {
213     auto firstLine = gridMatrix_.find(startLine);
214     auto lastLine = gridMatrix_.find(endLine);
215     if (firstLine == gridMatrix_.end() || firstLine->second.empty()) {
216         for (auto i = startLine; i <= endLine; ++i) {
217             auto it = gridMatrix_.find(i);
218             if (it != gridMatrix_.end()) {
219                 firstLine = it;
220                 break;
221             }
222         }
223         if (firstLine == gridMatrix_.end() || firstLine->second.empty()) {
224             return 0;
225         }
226     }
227     if (lastLine == gridMatrix_.end() || lastLine->second.empty()) {
228         for (auto i = endLine; i >= startLine; --i) {
229             auto it = gridMatrix_.find(i);
230             if (it != gridMatrix_.end()) {
231                 lastLine = it;
232                 break;
233             }
234         }
235         if (lastLine == gridMatrix_.end() || lastLine->second.empty()) {
236             return 0;
237         }
238     }
239 
240     int32_t minIdx = firstLine->second.begin()->second;
241 
242     int32_t maxIdx = 0;
243     // maxIdx might not be in the last position if hasBigItem_
244     for (const auto& it : lastLine->second) {
245         maxIdx = std::max(maxIdx, it.second);
246     }
247     maxIdx = std::max(maxIdx, FindEndIdx(endLine).itemIdx);
248     return maxIdx - minIdx + 1;
249 }
250 
GetContentHeightOfRegularGrid(float mainGap) const251 float GridLayoutInfo::GetContentHeightOfRegularGrid(float mainGap) const
252 {
253     float res = 0.0f;
254     if (crossCount_ == 0 || lineHeightMap_.empty()) {
255         return res;
256     }
257     float lineHeight = GetTotalLineHeight(0.0f) / static_cast<float>(lineHeightMap_.size());
258     auto lines = (childrenCount_) / crossCount_;
259     for (int i = 0; i < lines; ++i) {
260         auto it = lineHeightMap_.find(i);
261         res += (it != lineHeightMap_.end() ? it->second : lineHeight) + mainGap;
262     }
263     if (childrenCount_ % crossCount_ == 0) {
264         return res - mainGap;
265     }
266     auto lastLine = lineHeightMap_.find(lines);
267     return res + (lastLine != lineHeightMap_.end() ? lastLine->second : lineHeight);
268 }
269 
GetContentHeight(float mainGap) const270 float GridLayoutInfo::GetContentHeight(float mainGap) const
271 {
272     if (!hasBigItem_) {
273         return GetContentHeightOfRegularGrid(mainGap);
274     }
275     if (lineHeightMap_.empty()) {
276         return 0.0f;
277     }
278     float heightSum = GetTotalLineHeight(mainGap, false);
279     // assume lineHeightMap is continuous in range [begin, rbegin]
280     int32_t itemCount = FindItemCount(lineHeightMap_.begin()->first, lineHeightMap_.rbegin()->first);
281     if (itemCount == 0) {
282         return 0.0f;
283     }
284     float averageHeight = heightSum / itemCount;
285 
286     if (itemCount == childrenCount_) {
287         return heightSum - mainGap;
288     }
289     return heightSum + (childrenCount_ - itemCount) * averageHeight;
290 }
291 
GetContentOffset(const GridLayoutOptions & options,float mainGap) const292 float GridLayoutInfo::GetContentOffset(const GridLayoutOptions& options, float mainGap) const
293 {
294     if (startIndex_ == 0) {
295         return -currentOffset_;
296     }
297     if (options.irregularIndexes.empty() || startIndex_ < *(options.irregularIndexes.begin())) {
298         return GetCurrentOffsetOfRegularGrid(mainGap);
299     }
300     if (options.getSizeByIndex) {
301         return GetContentOffset(mainGap);
302     }
303     float prevHeight = GetContentHeight(options, startIndex_, mainGap) + mainGap;
304     return prevHeight - currentOffset_;
305 }
306 
307 namespace {
308 // prevIdx and idx are indices of two irregular items that take up a whole line
AddLinesInBetween(int32_t prevIdx,int32_t idx,int32_t crossCount,float lineHeight)309 inline float AddLinesInBetween(int32_t prevIdx, int32_t idx, int32_t crossCount, float lineHeight)
310 {
311     if (crossCount == 0) {
312         return 0.0f;
313     }
314     return (idx - prevIdx) > 1 ? ((idx - 2 - prevIdx) / crossCount + 1) * lineHeight : 0.0f;
315 }
316 } // namespace
317 
GetLineHeights(const GridLayoutOptions & options,float mainGap,float & regularHeight,float & irregularHeight) const318 void GridLayoutInfo::GetLineHeights(
319     const GridLayoutOptions& options, float mainGap, float& regularHeight, float& irregularHeight) const
320 {
321     for (const auto& item : lineHeightMap_) {
322         auto line = gridMatrix_.find(item.first);
323         if (line == gridMatrix_.end()) {
324             continue;
325         }
326         if (line->second.empty() || LessOrEqual(item.second, 0.0f)) {
327             continue;
328         }
329         auto lineStart = line->second.begin()->second;
330         if (options.irregularIndexes.find(lineStart) != options.irregularIndexes.end()) {
331             irregularHeight = item.second + mainGap;
332         } else {
333             if (NonPositive(regularHeight)) {
334                 regularHeight = item.second + mainGap;
335             }
336         }
337         if (Positive(irregularHeight) && Positive(regularHeight)) {
338             break;
339         }
340     }
341 }
342 
GetContentHeight(const GridLayoutOptions & options,int32_t endIdx,float mainGap) const343 float GridLayoutInfo::GetContentHeight(const GridLayoutOptions& options, int32_t endIdx, float mainGap) const
344 {
345     if (options.irregularIndexes.empty()) {
346         return GetContentHeightOfRegularGrid(mainGap);
347     }
348     if (options.getSizeByIndex) {
349         return GetContentHeight(mainGap);
350     }
351 
352     float irregularHeight = -1.0f;
353     float regularHeight = -1.0f;
354     GetLineHeights(options, mainGap, regularHeight, irregularHeight);
355     if (Negative(irregularHeight) && Positive(lastIrregularMainSize_)) {
356         irregularHeight = lastIrregularMainSize_;
357     }
358     if (NearZero(regularHeight)) {
359         regularHeight = lastRegularMainSize_;
360     }
361     if (Negative(irregularHeight)) {
362         irregularHeight = regularHeight;
363     }
364     // get line count
365     float totalHeight = 0;
366     auto lastIndex = -1;
367     for (int32_t idx : options.irregularIndexes) {
368         if (idx >= endIdx) {
369             break;
370         }
371         totalHeight += irregularHeight;
372         totalHeight += AddLinesInBetween(lastIndex, idx, crossCount_, regularHeight);
373         lastIndex = idx;
374     }
375 
376     totalHeight += AddLinesInBetween(lastIndex, endIdx, crossCount_, regularHeight);
377     totalHeight -= mainGap;
378     return totalHeight;
379 }
380 
GetIrregularOffset(float mainGap) const381 float GridLayoutInfo::GetIrregularOffset(float mainGap) const
382 {
383     // need to calculate total line height before startMainLine_
384     // gridMatrix ready up to endLine, so lineCnt is known.
385     // get sum of existing lines
386     // use average to estimate unknown lines
387     if (lineHeightMap_.empty() || childrenCount_ == 0) {
388         return 0.0f;
389     }
390 
391     auto it = lineHeightMap_.lower_bound(startMainLineIndex_);
392     auto knownLineCnt = static_cast<float>(std::distance(lineHeightMap_.begin(), it));
393     float knownHeight = GetHeightInRange(lineHeightMap_.begin()->first, startMainLineIndex_, 0.0f);
394     float avgHeight = synced_ ? avgLineHeight_ : GetTotalLineHeight(0.0f) / static_cast<float>(lineHeightMap_.size());
395 
396     auto startLine = static_cast<float>(startMainLineIndex_);
397     float estTotal = knownHeight + avgHeight * (startLine - knownLineCnt);
398     return estTotal + startLine * mainGap - currentOffset_;
399 }
400 
GetIrregularHeight(float mainGap) const401 float GridLayoutInfo::GetIrregularHeight(float mainGap) const
402 {
403     // count current number of lines
404     // estimate total number of lines based on {known item / total item}
405     if (lineHeightMap_.empty() || childrenCount_ == 0) {
406         return 0.0f;
407     }
408     int32_t lastKnownLine = lineHeightMap_.rbegin()->first;
409     float itemRatio = static_cast<float>(FindEndIdx(lastKnownLine).itemIdx + 1) / static_cast<float>(childrenCount_);
410     float estTotalLines = std::round(static_cast<float>(lastKnownLine + 1) / itemRatio);
411 
412     auto knownLineCnt = static_cast<float>(lineHeightMap_.size());
413     float knownHeight = synced_ ? avgLineHeight_ * knownLineCnt : GetTotalLineHeight(0.0f);
414     float avgHeight = synced_ ? avgLineHeight_ : knownHeight / knownLineCnt;
415     return knownHeight + (estTotalLines - knownLineCnt) * avgHeight + (estTotalLines - 1) * mainGap;
416 }
417 
SkipStartIndexByOffset(const GridLayoutOptions & options,float mainGap)418 void GridLayoutInfo::SkipStartIndexByOffset(const GridLayoutOptions& options, float mainGap)
419 {
420     float targetContent = currentHeight_ - (currentOffset_ - prevOffset_);
421     if (LessOrEqual(targetContent, 0.0)) {
422         currentOffset_ = 0.0f;
423         startIndex_ = 0;
424         return;
425     }
426 
427     float irregularHeight = -1.0f;
428     float regularHeight = -1.0f;
429     GetLineHeights(options, mainGap, regularHeight, irregularHeight);
430     if (Negative(irregularHeight) && Positive(lastIrregularMainSize_)) {
431         irregularHeight = lastIrregularMainSize_;
432     } else {
433         lastIrregularMainSize_ = irregularHeight;
434     }
435     if (NearZero(regularHeight)) {
436         regularHeight = lastRegularMainSize_;
437     } else {
438         lastRegularMainSize_ = regularHeight;
439     }
440     if (Negative(irregularHeight)) {
441         irregularHeight = regularHeight;
442     }
443 
444     float totalHeight = 0;
445     int32_t lastIndex = -1;
446 
447     for (int32_t idx : options.irregularIndexes) {
448         if (GreatOrEqual(totalHeight, targetContent)) {
449             break;
450         }
451         float height = AddLinesInBetween(lastIndex, idx, crossCount_, regularHeight);
452         if (GreatOrEqual(totalHeight + height, targetContent)) {
453             break;
454         }
455         totalHeight += height;
456         totalHeight += irregularHeight;
457         lastIndex = idx;
458     }
459     int32_t lines = static_cast<int32_t>(std::floor((targetContent - totalHeight) / regularHeight));
460     currentOffset_ = totalHeight + lines * regularHeight - targetContent;
461     int32_t startIdx = lines * crossCount_ + lastIndex + 1;
462     startIndex_ = std::min(startIdx, childrenCount_ - 1);
463 }
464 
GetCurrentLineHeight() const465 float GridLayoutInfo::GetCurrentLineHeight() const
466 {
467     auto currentLineHeight = lineHeightMap_.find(startMainLineIndex_);
468     auto currentLineMatrix = gridMatrix_.find(startMainLineIndex_);
469     // if current line exist, find it
470     if (currentLineHeight != lineHeightMap_.end() && currentLineMatrix != gridMatrix_.end() &&
471         !currentLineMatrix->second.empty()) {
472         return currentLineHeight->second;
473     }
474 
475     // otherwise return the first line in cache
476     for (const auto& item : lineHeightMap_) {
477         auto line = gridMatrix_.find(item.first);
478         if (line == gridMatrix_.end()) {
479             continue;
480         }
481         if (line->second.empty()) {
482             continue;
483         }
484         return item.second;
485     }
486     return 0.0f;
487 }
488 
FindItemInRange(int32_t target) const489 std::pair<int32_t, int32_t> GridLayoutInfo::FindItemInRange(int32_t target) const
490 {
491     if (gridMatrix_.empty()) {
492         return { -1, -1 };
493     }
494     auto end = gridMatrix_.upper_bound(endMainLineIndex_);
495     for (auto row = gridMatrix_.lower_bound(startMainLineIndex_); row != end; ++row) {
496         for (const auto& cell : row->second) {
497             if (cell.second == target) {
498                 return { row->first, cell.first };
499             }
500         }
501     }
502     return { -1, -1 };
503 }
504 
505 // Use the index to get the line number where the item is located
GetLineIndexByIndex(int32_t targetIndex,int32_t & targetLineIndex) const506 bool GridLayoutInfo::GetLineIndexByIndex(int32_t targetIndex, int32_t& targetLineIndex) const
507 {
508     for (auto [lineIndex, lineMap] : gridMatrix_) {
509         for (auto [crossIndex, index] : lineMap) {
510             if (index == targetIndex) {
511                 targetLineIndex = lineIndex;
512                 return true;
513             }
514         }
515     }
516     return false;
517 }
518 
519 // get the total height of all rows from zero before the targetLineIndex
GetTotalHeightFromZeroIndex(int32_t targetLineIndex,float mainGap) const520 float GridLayoutInfo::GetTotalHeightFromZeroIndex(int32_t targetLineIndex, float mainGap) const
521 {
522     auto targetPos = 0.f;
523     for (auto [lineIndex, lineHeight] : lineHeightMap_) {
524         if (targetLineIndex > lineIndex) {
525             targetPos += lineHeight + mainGap;
526         } else {
527             break;
528         }
529     }
530     return targetPos;
531 }
532 
TransformAutoScrollAlign(int32_t itemIdx,int32_t height,float mainSize,float mainGap) const533 ScrollAlign GridLayoutInfo::TransformAutoScrollAlign(
534     int32_t itemIdx, int32_t height, float mainSize, float mainGap) const
535 {
536     if (itemIdx >= startIndex_ && itemIdx <= endIndex_) {
537         auto [line, _] = FindItemInRange(itemIdx);
538         float topPos = GetItemTopPos(line, mainGap);
539         float botPos = GetItemBottomPos(line, height, mainGap);
540         if (NonPositive(topPos) && GreatOrEqual(botPos, mainSize)) {
541             // item occupies the whole viewport
542             return ScrollAlign::NONE;
543         }
544         // scrollAlign start / end if the item is not fully in viewport
545         if (Negative(topPos)) {
546             return ScrollAlign::START;
547         }
548         if (GreatNotEqual(botPos, mainSize)) {
549             return ScrollAlign::END;
550         }
551         return ScrollAlign::NONE;
552     }
553     if (itemIdx > endIndex_) {
554         return ScrollAlign::END;
555     }
556     return ScrollAlign::START;
557 }
558 
GetAnimatePosIrregular(int32_t targetIdx,int32_t height,ScrollAlign align,float mainGap) const559 float GridLayoutInfo::GetAnimatePosIrregular(int32_t targetIdx, int32_t height, ScrollAlign align, float mainGap) const
560 {
561     if (targetIdx == LAST_ITEM) {
562         targetIdx = childrenCount_ - 1;
563     }
564     auto it = FindInMatrix(targetIdx);
565     if (it == gridMatrix_.end()) {
566         return -1.0f;
567     }
568     if (align == ScrollAlign::AUTO) {
569         align = TransformAutoScrollAlign(targetIdx, height, lastMainSize_, mainGap);
570     }
571     switch (align) {
572         case ScrollAlign::START:
573             return GetTotalHeightFromZeroIndex(it->first, mainGap);
574         case ScrollAlign::CENTER: {
575             auto [center, offset] = FindItemCenter(it->first, height, mainGap);
576             float res = GetTotalHeightFromZeroIndex(center, mainGap) + offset - lastMainSize_ / 2.0f;
577             return std::max(res, 0.0f);
578         }
579         case ScrollAlign::END: {
580             float res = GetTotalHeightFromZeroIndex(it->first + height, mainGap) - mainGap - lastMainSize_;
581             return std::max(res, 0.0f);
582         }
583         default:
584             return -1.0f;
585     }
586 }
587 
588 // Based on the index from zero and align, gets the position to scroll to
GetGridItemAnimatePos(const GridLayoutInfo & currentGridLayoutInfo,int32_t targetIndex,ScrollAlign align,float mainGap,float & targetPos)589 bool GridLayoutInfo::GetGridItemAnimatePos(const GridLayoutInfo& currentGridLayoutInfo, int32_t targetIndex,
590     ScrollAlign align, float mainGap, float& targetPos)
591 {
592     int32_t startMainLineIndex = currentGridLayoutInfo.startMainLineIndex_;
593     int32_t endMainLineIndex = currentGridLayoutInfo.endMainLineIndex_;
594     float lastMainSize = currentGridLayoutInfo.lastMainSize_;
595     int32_t targetLineIndex = -1;
596     // Pre-check
597     // Get the line number where the index is located. If targetIndex does not exist, it is returned.
598     CHECK_NULL_RETURN(GetLineIndexByIndex(targetIndex, targetLineIndex), false);
599 
600     // Get the total height of the targetPos from row 0 to targetLineIndex-1.
601     targetPos = GetTotalHeightFromZeroIndex(targetLineIndex, mainGap);
602 
603     // Find the target row and get the altitude information
604     auto targetItem = lineHeightMap_.find(targetLineIndex);
605 
606     // Make sure that the target line has height information
607     CHECK_NULL_RETURN(targetItem != lineHeightMap_.end(), false);
608     auto targetLineHeight = targetItem->second;
609 
610     // Depending on align, calculate where you need to scroll to
611     switch (align) {
612         case ScrollAlign::START:
613         case ScrollAlign::NONE:
614             break;
615         case ScrollAlign::CENTER: {
616             targetPos -= ((lastMainSize - targetLineHeight) * HALF);
617             break;
618         }
619         case ScrollAlign::END: {
620             targetPos -= (lastMainSize - targetLineHeight);
621             break;
622         }
623         case ScrollAlign::AUTO: {
624             GetLineIndexByIndex(currentGridLayoutInfo.startIndex_, startMainLineIndex);
625             GetLineIndexByIndex(currentGridLayoutInfo.endIndex_, endMainLineIndex);
626             auto targetPosBeforeStartIndex = GetTotalHeightFromZeroIndex(startMainLineIndex, mainGap);
627             // targetPos - targetPosBeforeStartIndex:The distance between the top of the startLine row and the top of
628             // the targetLine row
629             // The distance of the targetLine row from the top of the screen
630             auto height2Top = targetPos - targetPosBeforeStartIndex - std::abs(currentGridLayoutInfo.currentOffset_);
631             // The distance of the targetLine row from the bottom of the screen
632             auto height2Bottom = std::abs(currentGridLayoutInfo.currentOffset_) + lastMainSize - targetPos +
633                                  targetPosBeforeStartIndex - targetLineHeight;
634             // This is handled when the targetLine line is the same as the endLine line. As for the period between
635             // startLine and endLine, follow the following process
636             if (GreatOrEqual(height2Top, 0.f) && GreatOrEqual(height2Bottom, 0.f)) {
637                 return false;
638             }
639             // When the row height is greater than the screen height and occupies the entire screen height, do nothing
640             if ((startMainLineIndex == targetLineIndex) && (endMainLineIndex == targetLineIndex)) {
641                 if ((std::abs(currentGridLayoutInfo.currentOffset_) + lastMainSize - targetLineHeight) <= 0) {
642                     return false;
643                 }
644             }
645             if (startMainLineIndex >= targetLineIndex) {
646             } else if (targetLineIndex >= endMainLineIndex) {
647                 targetPos -= (lastMainSize - targetLineHeight);
648             } else {
649                 return false;
650             }
651             break;
652         }
653     }
654     return true;
655 }
656 
657 namespace {
CheckRow(int32_t & maxV,const std::map<int,int> & row,int32_t target)658 bool CheckRow(int32_t& maxV, const std::map<int, int>& row, int32_t target)
659 {
660     for (auto [_, item] : row) {
661         maxV = std::max(maxV, std::abs(item));
662         if (item == target) {
663             return true;
664         }
665     }
666     return false;
667 }
668 
669 using MatIter = decltype(GridLayoutInfo::gridMatrix_)::const_iterator;
670 
SearchInReverse(const decltype (GridLayoutInfo::gridMatrix_)& mat,int32_t target,int32_t crossCnt)671 MatIter SearchInReverse(const decltype(GridLayoutInfo::gridMatrix_)& mat, int32_t target, int32_t crossCnt)
672 {
673     for (auto it = mat.rbegin(); it != mat.rend(); ++it) {
674         int32_t maxV = -1;
675         if (CheckRow(maxV, it->second, target)) {
676             return (++it).base();
677         }
678         if (static_cast<int32_t>(it->second.size()) == crossCnt && maxV < target) {
679             break;
680         }
681     }
682     return mat.end();
683 }
684 } // namespace
685 
FindInMatrix(int32_t index) const686 MatIter GridLayoutInfo::FindInMatrix(int32_t index) const
687 {
688     if (crossCount_ == 0) {
689         return gridMatrix_.end();
690     }
691     if (index == 0) {
692         return gridMatrix_.begin();
693     }
694     size_t count = gridMatrix_.size();
695     size_t step = 0;
696     auto left = gridMatrix_.begin();
697     auto it = left;
698     while (count > 0) {
699         it = left;
700         step = count / 2;
701         std::advance(it, step);
702 
703         // with irregular items, only the max index on each row is guaranteed to be in order.
704         int32_t maxV = -1;
705         if (CheckRow(maxV, it->second, index)) {
706             return it;
707         }
708 
709         if (index <= maxV) {
710             count = step;
711         } else {
712             // index on the right side of current row
713             left = ++it;
714             count -= step + 1;
715         }
716     }
717     /*
718     Fallback to linear to handle this situation:
719         1 | 2 | 3
720         x | 2 | x
721         x | 2 | x
722         x | 2 | x
723     When iterator points to Line 1 ~ 3, Item 3 can never be found.
724     */
725     return SearchInReverse(gridMatrix_, index, crossCount_);
726 }
727 
GetItemPos(int32_t itemIdx) const728 std::pair<int32_t, int32_t> GridLayoutInfo::GetItemPos(int32_t itemIdx) const
729 {
730     auto it = FindInMatrix(itemIdx);
731     if (it == gridMatrix_.end()) {
732         return { -1, -1 };
733     }
734     for (auto col : it->second) {
735         if (col.second == itemIdx) {
736             return { col.first, it->first };
737         }
738     }
739     return { -1, -1 };
740 }
741 
FindEndIdx(int32_t endLine) const742 GridLayoutInfo::EndIndexInfo GridLayoutInfo::FindEndIdx(int32_t endLine) const
743 {
744     auto it = gridMatrix_.find(endLine);
745     if (it == gridMatrix_.end()) {
746         return {};
747     }
748 
749     // Create reverse iterator starting from endLine position
750     for (auto rIt = std::make_reverse_iterator(++it); rIt != gridMatrix_.rend(); ++rIt) {
751         const auto& row = rIt->second;
752         // Search backwards in the row for first positive index
753         for (auto cell = row.rbegin(); cell != row.rend(); ++cell) {
754             if (cell->second > 0) {
755                 return { .itemIdx = cell->second, .y = rIt->first, .x = cell->first };
756             }
757         }
758     }
759     return { .itemIdx = 0, .y = 0, .x = 0 };
760 }
761 
ClearMapsToEnd(int32_t idx)762 void GridLayoutInfo::ClearMapsToEnd(int32_t idx)
763 {
764     auto gridIt = gridMatrix_.lower_bound(idx);
765     gridMatrix_.erase(gridIt, gridMatrix_.end());
766     ClearHeightsToEnd(idx);
767 }
768 
ClearMapsFromStart(int32_t idx)769 void GridLayoutInfo::ClearMapsFromStart(int32_t idx)
770 {
771     auto gridIt = gridMatrix_.lower_bound(idx);
772     gridMatrix_.erase(gridMatrix_.begin(), gridIt);
773     auto lineIt = lineHeightMap_.lower_bound(idx);
774     lineHeightMap_.erase(lineHeightMap_.begin(), lineIt);
775 }
776 
ClearHeightsToEnd(int32_t idx)777 void GridLayoutInfo::ClearHeightsToEnd(int32_t idx)
778 {
779     auto lineIt = lineHeightMap_.lower_bound(idx);
780     lineHeightMap_.erase(lineIt, lineHeightMap_.end());
781 }
782 
ClearMatrixToEnd(int32_t idx,int32_t lineIdx)783 void GridLayoutInfo::ClearMatrixToEnd(int32_t idx, int32_t lineIdx)
784 {
785     auto it = gridMatrix_.find(lineIdx);
786     for (; it != gridMatrix_.end(); ++it) {
787         for (auto itemIt = it->second.begin(); itemIt != it->second.end();) {
788             if (std::abs(itemIt->second) < idx) {
789                 ++itemIt;
790                 continue;
791             }
792             itemIt = it->second.erase(itemIt);
793         }
794         if (it->second.empty()) {
795             break;
796         }
797     }
798     gridMatrix_.erase(it, gridMatrix_.end());
799 }
800 
GetTotalHeightOfItemsInView(float mainGap,bool regular) const801 float GridLayoutInfo::GetTotalHeightOfItemsInView(float mainGap, bool regular) const
802 {
803     float len = 0.0f;
804     auto it = lineHeightMap_.find(startMainLineIndex_);
805     if (!regular) {
806         it = SkipLinesAboveView(mainGap).first;
807     }
808     if (it == lineHeightMap_.end()) {
809         return -mainGap;
810     }
811     if (startMainLineIndex_ > endMainLineIndex_ || it->first > endMainLineIndex_) {
812         return -mainGap;
813     }
814     auto endIt = lineHeightMap_.find(endMainLineIndex_ + 1);
815     for (; it != endIt; ++it) {
816         len += it->second + mainGap;
817     }
818     return len - mainGap;
819 }
820 
SkipLinesAboveView(float mainGap) const821 std::pair<GridLayoutInfo::HeightMapIt, float> GridLayoutInfo::SkipLinesAboveView(float mainGap) const
822 {
823     auto it = lineHeightMap_.find(startMainLineIndex_);
824     float offset = currentOffset_;
825     while (it != lineHeightMap_.end() && Negative(it->second + offset + mainGap)) {
826         offset += it->second + mainGap;
827         ++it;
828     }
829     return { it, offset };
830 }
831 
UpdateStartIndexForExtralOffset(float mainGap,float mainSize)832 void GridLayoutInfo::UpdateStartIndexForExtralOffset(float mainGap, float mainSize)
833 {
834     if (Negative(currentOffset_)) {
835         auto startLineHeight = lineHeightMap_.find(startMainLineIndex_);
836         CHECK_NULL_VOID(startLineHeight != lineHeightMap_.end());
837         auto currentEndOffset = currentOffset_ + startLineHeight->second + mainGap;
838         while (!Positive(currentEndOffset)) {
839             startMainLineIndex_++;
840             startLineHeight = lineHeightMap_.find(startMainLineIndex_);
841             if (startLineHeight == lineHeightMap_.end()) {
842                 startMainLineIndex_--;
843                 break;
844             }
845             currentOffset_ = currentEndOffset;
846             currentEndOffset += (startLineHeight->second + mainGap);
847         }
848     } else if (Positive(currentOffset_)) {
849         auto preLineHeight = lineHeightMap_.find(startMainLineIndex_ - 1);
850         CHECK_NULL_VOID(preLineHeight != lineHeightMap_.end());
851         auto preItemCurrentOffset = currentOffset_ - preLineHeight->second - mainGap;
852         while (Positive(preItemCurrentOffset)) {
853             startMainLineIndex_--;
854             preLineHeight = lineHeightMap_.find(startMainLineIndex_);
855             if (preLineHeight == lineHeightMap_.end()) {
856                 startMainLineIndex_++;
857                 break;
858             }
859             preItemCurrentOffset -= (preLineHeight->second + mainGap);
860             currentOffset_ = preItemCurrentOffset;
861         }
862     }
863     auto startLine = gridMatrix_.find(startMainLineIndex_);
864     CHECK_NULL_VOID(startLine != gridMatrix_.end() && (!startLine->second.empty()));
865     startIndex_ = startLine->second.begin()->second;
866     auto endLineHeight = lineHeightMap_.find(startMainLineIndex_);
867     CHECK_NULL_VOID(endLineHeight != lineHeightMap_.end());
868     endMainLineIndex_ = startMainLineIndex_;
869     auto currentEndOffset = currentOffset_ + endLineHeight->second + mainGap;
870     while (LessNotEqual(currentEndOffset, mainSize)) {
871         endMainLineIndex_++;
872         endLineHeight = lineHeightMap_.find(endMainLineIndex_);
873         if (endLineHeight == lineHeightMap_.end()) {
874             endMainLineIndex_--;
875             break;
876         }
877         currentEndOffset += (endLineHeight->second + mainGap);
878     }
879     auto endLine = gridMatrix_.find(endMainLineIndex_);
880     CHECK_NULL_VOID(endLine != gridMatrix_.end() && (!endLine->second.empty()));
881     endIndex_ = endLine->second.rbegin()->second;
882 }
883 
GetDistanceToBottom(float mainSize,float heightInView,float mainGap) const884 float GridLayoutInfo::GetDistanceToBottom(float mainSize, float heightInView, float mainGap) const
885 {
886     if (lineHeightMap_.empty() || endIndex_ < childrenCount_ - 1 ||
887         endMainLineIndex_ < lineHeightMap_.rbegin()->first) {
888         return Infinity<float>();
889     }
890 
891     float offset = currentOffset_;
892     // currentOffset_ is relative to startMainLine, which might be entirely above viewport
893     auto it = lineHeightMap_.find(startMainLineIndex_);
894     while (it != lineHeightMap_.end() && Negative(offset + it->second + mainGap)) {
895         offset += it->second + mainGap;
896         ++it;
897     }
898     const float bottomPos = offset + heightInView;
899     return bottomPos - mainSize;
900 }
901 
ClearHeightsFromMatrix(int32_t lineIdx)902 void GridLayoutInfo::ClearHeightsFromMatrix(int32_t lineIdx)
903 {
904     auto lineIt = lineHeightMap_.find(lineIdx);
905     if (lineIt == lineHeightMap_.end()) {
906         return;
907     }
908     if (gridMatrix_.find(lineIdx) != gridMatrix_.end()) {
909         lineIt++;
910     }
911     lineHeightMap_.erase(lineIt, lineHeightMap_.end());
912 }
913 
FindStartLineInMatrix(MatIter iter,int32_t index) const914 MatIter GridLayoutInfo::FindStartLineInMatrix(MatIter iter, int32_t index) const
915 {
916     if (iter == gridMatrix_.end() || iter == gridMatrix_.begin()) {
917         return iter;
918     }
919 
920     --iter;
921     int32_t maxValue = 0;
922     while (CheckRow(maxValue, iter->second, index)) {
923         if (iter == gridMatrix_.begin()) {
924             return iter;
925         }
926         --iter;
927     }
928     return ++iter;
929 }
930 
GetHeightInRange(int32_t startLine,int32_t endLine,float mainGap) const931 float GridLayoutInfo::GetHeightInRange(int32_t startLine, int32_t endLine, float mainGap) const
932 {
933     if (endLine <= startLine) {
934         return 0.0f;
935     }
936     float totalHeight = 0.0f;
937     auto endIt = lineHeightMap_.lower_bound(endLine);
938     for (auto it = lineHeightMap_.lower_bound(startLine); it != endIt; ++it) {
939         totalHeight += it->second + mainGap;
940     }
941     return totalHeight;
942 }
943 
HeightSumSmaller(float other,float mainGap) const944 bool GridLayoutInfo::HeightSumSmaller(float other, float mainGap) const
945 {
946     other += mainGap;
947     for (const auto& it : lineHeightMap_) {
948         other -= it.second + mainGap;
949         if (NonPositive(other)) {
950             return false;
951         }
952     }
953     return true;
954 }
955 
FindItemCenter(int32_t startLine,int32_t lineCnt,float mainGap) const956 std::pair<int32_t, float> GridLayoutInfo::FindItemCenter(int32_t startLine, int32_t lineCnt, float mainGap) const
957 {
958     float halfLen = (GetHeightInRange(startLine, startLine + lineCnt, mainGap) - mainGap) / 2.0f;
959     auto it = lineHeightMap_.find(startLine);
960     float len = 0.0f;
961     while (it != lineHeightMap_.end() && LessNotEqual(len + it->second + mainGap, halfLen)) {
962         len += it->second + mainGap;
963         ++it;
964     }
965     return { it->first, halfLen - len };
966 }
967 
PrepareJumpToBottom()968 void GridLayoutInfo::PrepareJumpToBottom()
969 {
970     if (gridMatrix_.empty() || gridMatrix_.rbegin()->second.empty()) {
971         TAG_LOGW(ACE_GRID, "Matrix setup is incorrect");
972         jumpIndex_ = LAST_ITEM;
973     } else {
974         jumpIndex_ = std::abs(gridMatrix_.rbegin()->second.begin()->second);
975     }
976     scrollAlign_ = ScrollAlign::END;
977 }
978 
UpdateDefaultCachedCount()979 void GridLayoutInfo::UpdateDefaultCachedCount()
980 {
981     if (crossCount_ == 0) {
982         return;
983     }
984     static float pageCount = SystemProperties::GetPageCount();
985     if (pageCount <= 0.0f) {
986         return;
987     }
988     int32_t itemCount = (endIndex_ - startIndex_ + 1) / crossCount_;
989     if (itemCount <= 0) {
990         return;
991     }
992     constexpr int32_t MAX_DEFAULT_CACHED_COUNT = 16;
993     int32_t newCachedCount = static_cast<int32_t>(ceil(pageCount * itemCount));
994     if (newCachedCount > MAX_DEFAULT_CACHED_COUNT) {
995         TAG_LOGI(ACE_GRID, "Default cachedCount exceed 16");
996         defCachedCount_ = MAX_DEFAULT_CACHED_COUNT;
997     } else {
998         defCachedCount_ = std::max(newCachedCount, defCachedCount_);
999     }
1000 }
1001 } // namespace OHOS::Ace::NG
1002