1 /*
2  * Copyright (c) 2022 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 
16 #include "core/components_ng/pattern/grid/grid_utils.h"
17 
18 #include <cmath>
19 #include <iostream>
20 
21 namespace OHOS::Ace::NG {
22 namespace {
23 
24 const std::string UNIT_AUTO = "auto";
25 
26 } // namespace
27 
ParseArgs(const std::string & args)28 std::string GridUtils::ParseArgs(const std::string& args)
29 {
30     if (args.empty() || args.find(UNIT_AUTO) == std::string::npos) {
31         return args;
32     }
33     std::string rowsArgs;
34     std::vector<std::string> strs;
35     StringUtils::StringSplitter(args, ' ', strs);
36     std::string current;
37     size_t rowArgSize = strs.size();
38     for (size_t i = 0; i < rowArgSize; ++i) {
39         current = strs[i];
40         // "auto" means 1fr in grid
41         if (strs[i] == std::string(UNIT_AUTO)) {
42             current = "1fr";
43         }
44         rowsArgs += " " + current;
45     }
46     return rowsArgs;
47 }
48 
49 namespace {
GetRowGap(const RefPtr<GridLayoutProperty> & props,float frameHeight)50 inline float GetRowGap(const RefPtr<GridLayoutProperty>& props, float frameHeight)
51 {
52     auto scale = props->GetLayoutConstraint()->scaleProperty;
53     return ConvertToPx(props->GetRowsGap().value_or(0.0_vp), scale, frameHeight).value_or(0);
54 }
55 
GetColumnGap(const RefPtr<GridLayoutProperty> & props,float frameWidth)56 inline float GetColumnGap(const RefPtr<GridLayoutProperty>& props, float frameWidth)
57 {
58     auto scale = props->GetLayoutConstraint()->scaleProperty;
59     return ConvertToPx(props->GetColumnsGap().value_or(0.0_vp), scale, frameWidth).value_or(0);
60 }
61 } // namespace
62 
GetMainGap(const RefPtr<GridLayoutProperty> & props,const SizeF & frameSize,Axis axis)63 float GridUtils::GetMainGap(const RefPtr<GridLayoutProperty>& props, const SizeF& frameSize, Axis axis)
64 {
65     return axis == Axis::HORIZONTAL ? GetColumnGap(props, frameSize.Width()) : GetRowGap(props, frameSize.Height());
66 }
67 
GetCrossGap(const RefPtr<GridLayoutProperty> & props,const SizeF & frameSize,Axis axis)68 float GridUtils::GetCrossGap(const RefPtr<GridLayoutProperty>& props, const SizeF& frameSize, Axis axis)
69 {
70     return axis == Axis::HORIZONTAL ? GetRowGap(props, frameSize.Height()) : GetColumnGap(props, frameSize.Width());
71 }
72 
73 } // namespace OHOS::Ace::NG