1 /*
2  * Copyright (C) 2023 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.android.car.carlauncher;
18 
19 import androidx.annotation.NonNull;
20 import androidx.annotation.Nullable;
21 
22 import com.android.car.carlauncher.LauncherItemProto.LauncherItemListMessage;
23 import com.android.car.carlauncher.LauncherItemProto.LauncherItemMessage;
24 
25 import java.util.ArrayList;
26 import java.util.Collections;
27 import java.util.Comparator;
28 import java.util.List;
29 
30 /**
31  * Helper class that provides method used by LauncherModel
32  */
33 public class LauncherItemMessageHelper {
34     /**
35      * Convert a List of {@link LauncherItemMessage} to a single {@link LauncherItemListMessage}.
36      */
37     @Nullable
convertToMessage(List<LauncherItemMessage> msgList)38     public LauncherItemListMessage convertToMessage(List<LauncherItemMessage> msgList) {
39         if (msgList == null) {
40             return null;
41         }
42         LauncherItemListMessage.Builder builder =
43                 LauncherItemListMessage.newBuilder().addAllLauncherItemMessage(msgList);
44         return builder.build();
45     }
46 
47     /**
48      * Converts {@link LauncherItemListMessage} to a List of {@link LauncherItemMessage},
49      * sorts the LauncherItemList based on their relative order in the file, then return the list.
50      */
51     @NonNull
getSortedList(@ullable LauncherItemListMessage protoLstMsg)52     public List<LauncherItemMessage> getSortedList(@Nullable LauncherItemListMessage protoLstMsg) {
53         if (protoLstMsg == null) {
54             return new ArrayList<>();
55         }
56         List<LauncherItemMessage> itemMsgList = protoLstMsg.getLauncherItemMessageList();
57         List<LauncherItemMessage> sortedItemMsgList = new ArrayList<>();
58         if (!itemMsgList.isEmpty() && itemMsgList.size() > 0) {
59             // need to create a new list for sorting purposes since ProtobufArrayList is not mutable
60             sortedItemMsgList.addAll(itemMsgList);
61             Collections.sort(sortedItemMsgList,
62                     Comparator.comparingInt(LauncherItemMessage::getRelativePosition));
63         }
64         return sortedItemMsgList;
65     }
66 }
67 
68