summaryrefslogtreecommitdiff
path: root/SmartDeviceLink/private/SDLMenuManager.m
blob: e8d7ef8a40158ceaf2ce9289cd8705e750899bec (plain)
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
//
//  SDLMenuManager.m
//  SmartDeviceLink
//
//  Created by Joel Fischer on 4/9/18.
//  Copyright © 2018 smartdevicelink. All rights reserved.
//

#import "SDLMenuManager.h"

#import "SDLAddCommand.h"
#import "SDLAddSubMenu.h"
#import "SDLArtwork.h"
#import "SDLConnectionManagerType.h"
#import "SDLDeleteCommand.h"
#import "SDLDeleteSubMenu.h"
#import "SDLDisplayCapability.h"
#import "SDLDisplayType.h"
#import "SDLDynamicMenuUpdateRunScore.h"
#import "SDLDynamicMenuUpdateAlgorithm.h"
#import "SDLError.h"
#import "SDLFileManager.h"
#import "SDLGlobals.h"
#import "SDLImage.h"
#import "SDLLogMacros.h"
#import "SDLMenuCell.h"
#import "SDLMenuConfiguration.h"
#import "SDLMenuConfigurationUpdateOperation.h"
#import "SDLMenuManagerPrivateConstants.h"
#import "SDLMenuParams.h"
#import "SDLMenuReplaceOperation.h"
#import "SDLMenuShowOperation.h"
#import "SDLOnCommand.h"
#import "SDLOnHMIStatus.h"
#import "SDLPredefinedWindows.h"
#import "SDLRegisterAppInterfaceResponse.h"
#import "SDLRPCNotificationNotification.h"
#import "SDLRPCResponseNotification.h"
#import "SDLSetDisplayLayoutResponse.h"
#import "SDLSetGlobalProperties.h"
#import "SDLScreenManager.h"
#import "SDLShowAppMenu.h"
#import "SDLSystemCapabilityManager.h"
#import "SDLWindowCapability.h"
#import "SDLWindowCapability+ScreenManagerExtensions.h"
#import "SDLVersion.h"
#import "SDLVoiceCommand.h"

NS_ASSUME_NONNULL_BEGIN

@interface SDLMenuCell()

@property (assign, nonatomic) UInt32 parentCellId;
@property (assign, nonatomic) UInt32 cellId;
@property (strong, nonatomic, readwrite) NSString *uniqueTitle;

@property (copy, nonatomic, readwrite) NSString *title;
@property (strong, nonatomic, readwrite, nullable) SDLArtwork *icon;
@property (copy, nonatomic, readwrite, nullable) NSArray<NSString *> *voiceCommands;
@property (copy, nonatomic, readwrite, nullable) NSString *secondaryText;
@property (copy, nonatomic, readwrite, nullable) NSString *tertiaryText;
@property (strong, nonatomic, readwrite, nullable) SDLArtwork *secondaryArtwork;
@property (copy, nonatomic, readwrite, nullable) NSArray<SDLMenuCell *> *subCells;
@property (copy, nonatomic, readwrite, nullable) SDLMenuCellSelectionHandler handler;

@end

@interface SDLMenuManager()

// Dependencies
@property (weak, nonatomic) id<SDLConnectionManagerType> connectionManager;
@property (weak, nonatomic) SDLFileManager *fileManager;
@property (weak, nonatomic) SDLSystemCapabilityManager *systemCapabilityManager;

@property (strong, nonatomic) NSOperationQueue *transactionQueue;
@property (strong, nonatomic, nullable) SDLWindowCapability *windowCapability;

@property (copy, nonatomic, nullable) SDLHMILevel currentHMILevel;
@property (copy, nonatomic, nullable) SDLSystemContext currentSystemContext;
@property (copy, nonatomic) NSArray<SDLMenuCell *> *currentMenuCells;
@property (strong, nonatomic, nullable) SDLMenuConfiguration *currentMenuConfiguration;

@end

@implementation SDLMenuManager

- (instancetype)init {
    self = [super init];
    if (!self) { return nil; }

    _menuConfiguration = [[SDLMenuConfiguration alloc] init];
    _menuCells = @[];
    _currentMenuCells = @[];
    _dynamicMenuUpdatesMode = SDLDynamicMenuUpdatesModeOnWithCompatibility;
    _transactionQueue = [self sdl_newTransactionQueue];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sdl_hmiStatusNotification:) name:SDLDidChangeHMIStatusNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sdl_commandNotification:) name:SDLDidReceiveCommandNotification object:nil];

    return self;
}

- (instancetype)initWithConnectionManager:(id<SDLConnectionManagerType>)connectionManager fileManager:(SDLFileManager *)fileManager systemCapabilityManager:(nonnull SDLSystemCapabilityManager *)systemCapabilityManager {
    self = [self init];
    if (!self) { return nil; }

    _connectionManager = connectionManager;
    _fileManager = fileManager;
    _systemCapabilityManager = systemCapabilityManager;

    return self;
}

- (void)start {
    [self.systemCapabilityManager subscribeToCapabilityType:SDLSystemCapabilityTypeDisplays withObserver:self selector:@selector(sdl_displayCapabilityDidUpdate)];
}

- (void)stop {
    _menuCells = @[];
    _currentMenuCells = @[];
    _transactionQueue = [self sdl_newTransactionQueue];

    _currentHMILevel = nil;
    _currentSystemContext = nil;
    _currentMenuConfiguration = nil;
    _windowCapability = nil;
}

#pragma mark Transaction Queue

- (NSOperationQueue *)sdl_newTransactionQueue {
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    queue.name = @"SDLMenuManager Transaction Queue";
    queue.maxConcurrentOperationCount = 1;
    queue.qualityOfService = NSQualityOfServiceUserInitiated;
    queue.underlyingQueue = [SDLGlobals sharedGlobals].sdlConcurrentQueue;
    queue.suspended = YES;

    return queue;
}

/// Suspend the queue if the HMI level is NONE since we want to delay sending RPCs until we're in non-NONE
- (void)sdl_updateTransactionQueueSuspended {
    if ([self.currentHMILevel isEqualToEnum:SDLHMILevelNone] || [self.currentSystemContext isEqualToEnum:SDLSystemContextMenu]) {
        SDLLogD(@"Suspending the transaction queue. Current HMI level is NONE: %@, current system context is MENU: %@", ([self.currentHMILevel isEqualToEnum:SDLHMILevelNone] ? @"YES" : @"NO"), ([self.currentSystemContext isEqualToEnum:SDLSystemContextMenu] ? @"YES" : @"NO"));
        self.transactionQueue.suspended = YES;
    } else {
        SDLLogD(@"Starting the transaction queue");
        self.transactionQueue.suspended = NO;
    }
}

#pragma mark - Setters

- (void)setMenuConfiguration:(SDLMenuConfiguration *)menuConfiguration {
    if ([menuConfiguration isEqual:self.menuConfiguration]) {
        SDLLogD(@"New menu configuration is equal to existing one, will not set new configuration");
        return;
    } else if ([[SDLGlobals sharedGlobals].rpcVersion isLessThanVersion:[SDLVersion versionWithMajor:6 minor:0 patch:0]]) {
        SDLLogE(@"Setting a menu configuration is not supported on this head unit. Only supported on RPC 6.0+, this version: %@", [SDLGlobals sharedGlobals].rpcVersion);
        return;
    }

    _menuConfiguration = menuConfiguration;

    // Create the operation
    __weak typeof(self) weakself = self;
    SDLMenuConfigurationUpdateOperation *configurationUpdateOp = [[SDLMenuConfigurationUpdateOperation alloc] initWithConnectionManager:self.connectionManager windowCapability:self.windowCapability newMenuConfiguration:menuConfiguration configurationUpdatedHandler:^(SDLMenuConfiguration *newMenuConfiguration, NSError *_Nullable error) {
        if (error != nil) {
            SDLLogE(@"Error updating menu configuration: %@", error);
            return;
        }
        weakself.currentMenuConfiguration = newMenuConfiguration;
        [weakself sdl_updateMenuReplaceOperationsWithNewMenuConfiguration];
    }];

    // Cancel previous menu configuration operations
    for (NSOperation *operation in self.transactionQueue.operations) {
        if ([operation isMemberOfClass:[SDLMenuConfigurationUpdateOperation class]]) {
            [operation cancel];
        }
    }

    // Add the new menu configuration operation to the queue
    [self.transactionQueue addOperation:configurationUpdateOp];
}

- (void)setMenuCells:(NSArray<SDLMenuCell *> *)menuCells {
    if (![self sdl_menuCellsAreUnique:menuCells allVoiceCommands:[NSMutableArray array]]) {
        SDLLogE(@"Not all set menu cells are unique, but that is required");
        return;
    }

    _menuCells = [[NSArray alloc] initWithArray:menuCells copyItems:YES];

    __weak typeof(self) weakself = self;
    SDLMenuReplaceOperation *menuReplaceOperation = [[SDLMenuReplaceOperation alloc] initWithConnectionManager:self.connectionManager fileManager:self.fileManager windowCapability:self.windowCapability menuConfiguration:self.currentMenuConfiguration currentMenu:self.currentMenuCells updatedMenu:self.menuCells compatibilityModeEnabled:(![self sdl_isDynamicMenuUpdateActive:self.dynamicMenuUpdatesMode]) currentMenuUpdatedHandler:^(NSArray<SDLMenuCell *> * _Nonnull currentMenuCells, NSError *error) {
        weakself.currentMenuCells = currentMenuCells;
        [weakself sdl_updateMenuReplaceOperationsWithNewCurrentMenu];
        SDLLogD(@"Finished updating menu");
    }];

    // Cancel previous replace menu operations
    for (NSOperation *operation in self.transactionQueue.operations) {
        if ([operation isMemberOfClass:[SDLMenuReplaceOperation class]]) {
            [operation cancel];
        }
    }

    [self.transactionQueue addOperation:menuReplaceOperation];
}

#pragma mark - Open Menu

- (BOOL)openMenu:(nullable SDLMenuCell *)cell {
    if (cell != nil && cell.subCells.count == 0) {
        SDLLogE(@"The cell %@ does not contain any sub cells, so no submenu can be opened", cell);
        return NO;
    } else if (cell != nil && ![self.menuCells containsObject:cell]) {
        SDLLogE(@"This cell has not been sent to the head unit, so no submenu can be opened. Make sure that the cell exists in the SDLManager.menu array");
        return NO;
    } else if ([SDLGlobals.sharedGlobals.rpcVersion isLessThanVersion:[[SDLVersion alloc] initWithMajor:6 minor:0 patch:0]]) {
        SDLLogE(@"The openMenu / openSubmenu is not supported on this head unit.");
        return NO;
    }

    // Create the operation
    SDLMenuShowOperation *showMenuOp = [[SDLMenuShowOperation alloc] initWithConnectionManager:self.connectionManager toMenuCell:cell completionHandler:^(NSError * _Nullable error) {
        if (error != nil) {
            SDLLogE(@"Opening menu with error: %@, info: %@. Failed subcell (if nil, attempted to open to main menu): %@", error, error.userInfo, cell);
        }
    }];

    // Cancel previous open menu operations
    for (NSOperation *operation in self.transactionQueue.operations) {
        if ([operation isMemberOfClass:[SDLMenuShowOperation class]]) {
            [operation cancel];
        }
    }

    // Add the new open menu operation to the queue
    [self.transactionQueue addOperation:showMenuOp];

    return YES;
}

#pragma mark - Updating System

- (void)sdl_updateMenuReplaceOperationsWithNewCurrentMenu {
    for (NSOperation *operation in self.transactionQueue.operations) {
        if ([operation isMemberOfClass:[SDLMenuReplaceOperation class]]) {
            SDLMenuReplaceOperation *op = (SDLMenuReplaceOperation *)operation;
            op.currentMenu = self.currentMenuCells;
        }
    }
}

- (void)sdl_updateMenuReplaceOperationsWithNewWindowCapability {
    for (NSOperation *operation in self.transactionQueue.operations) {
        if ([operation isMemberOfClass:[SDLMenuReplaceOperation class]]) {
            SDLMenuReplaceOperation *op = (SDLMenuReplaceOperation *)operation;
            op.windowCapability = self.windowCapability;
        }
    }
}

- (void)sdl_updateMenuReplaceOperationsWithNewMenuConfiguration {
    for (NSOperation *operation in self.transactionQueue.operations) {
        if ([operation isMemberOfClass:[SDLMenuReplaceOperation class]]) {
            SDLMenuReplaceOperation *op = (SDLMenuReplaceOperation *)operation;
            op.menuConfiguration = self.currentMenuConfiguration;
        }
    }
}

#pragma mark - Helpers

/// Determine if the dynamic mode is active based on the set value.
/// @param dynamicMenuUpdatesMode The set dynamic mode
/// @returns YES if dynamic mode is forced on, or is on with compatibility, which only turns it on for Ford's Sync Gen 3 8-inch display type
- (BOOL)sdl_isDynamicMenuUpdateActive:(SDLDynamicMenuUpdatesMode)dynamicMenuUpdatesMode {
    switch (dynamicMenuUpdatesMode) {
        case SDLDynamicMenuUpdatesModeForceOn:
            return YES;
        case SDLDynamicMenuUpdatesModeForceOff:
            return NO;
        case SDLDynamicMenuUpdatesModeOnWithCompatibility:
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
            return ![self.systemCapabilityManager.displays.firstObject.displayName isEqualToString:SDLDisplayTypeGen38Inch];
#pragma clang diagnostic pop
    }
}

/// Check for cell lists with completely duplicate information, or any duplicate voiceCommands
///
/// @param cells The cells you will be adding
/// @return Boolean that indicates whether menuCells are unique or not
- (BOOL)sdl_menuCellsAreUnique:(NSArray<SDLMenuCell *> *)cells allVoiceCommands:(NSMutableArray<NSString *> *)allVoiceCommands {
    ///Check all voice commands for identical items and check each list of cells for identical cells
    NSMutableSet<SDLMenuCell *> *identicalCellsCheckSet = [NSMutableSet set];
    for (SDLMenuCell *cell in cells) {
        [identicalCellsCheckSet addObject:cell];

        // Recursively check the subcell lists to see if they are all unique as well. If anything is not, this will chain back up the list to return false.
        if (cell.subCells.count > 0) {
            BOOL subcellsAreUnique = [self sdl_menuCellsAreUnique:cell.subCells allVoiceCommands:allVoiceCommands];
            if (!subcellsAreUnique) { return NO; }
        }

        // Voice commands have to be identical across all lists
        if (cell.voiceCommands == nil) { continue; }
        [allVoiceCommands addObjectsFromArray:cell.voiceCommands];
    }

    // Check for duplicate cells
    if (identicalCellsCheckSet.count != cells.count) {
        SDLLogE(@"Not all cells are unique. Cells in each list (such as main menu or subcell list) must have some differentiating property other than the subcells within a cell. The menu will not be set.");
        return NO;
    }

    // All the VR commands must be unique
    if (allVoiceCommands.count != [NSSet setWithArray:allVoiceCommands].count) {
        SDLLogE(@"Attempted to create a menu with duplicate voice commands, but voice commands must be unique across all menu items including main menu and subcell lists. The menu will not be set.");
        return NO;
    }

    return YES;
}

#pragma mark - Calling handlers

/// Call a handler for a currently displayed SDLMenuCell based on the incoming SDLOnCommand notification
/// @param cells The menu cells to check (including their subcells)
/// @param onCommand The notification retrieved
/// @returns True if the handler was found, false if it was not found
- (BOOL)sdl_callHandlerForCells:(NSArray<SDLMenuCell *> *)cells command:(SDLOnCommand *)onCommand {
    for (SDLMenuCell *cell in cells) {
        if (cell.cellId == onCommand.cmdID.unsignedIntegerValue && cell.handler != nil) {
            cell.handler(onCommand.triggerSource);
            return YES;
        }

        if (cell.subCells.count > 0) {
            BOOL succeeded = [self sdl_callHandlerForCells:cell.subCells command:onCommand];
            if (succeeded) { return YES; }
        }
    }

    return NO;
}

#pragma mark - Observers

- (void)sdl_commandNotification:(SDLRPCNotificationNotification *)notification {
    SDLOnCommand *onCommand = (SDLOnCommand *)notification.notification;
    [self sdl_callHandlerForCells:self.currentMenuCells command:onCommand];
}

- (void)sdl_displayCapabilityDidUpdate {
    self.windowCapability = self.systemCapabilityManager.defaultMainWindowCapability;
    [self sdl_updateMenuReplaceOperationsWithNewWindowCapability];
}

- (void)sdl_hmiStatusNotification:(SDLRPCNotificationNotification *)notification {
    SDLOnHMIStatus *hmiStatus = (SDLOnHMIStatus *)notification.notification;
    if ((hmiStatus.windowID != nil) && (hmiStatus.windowID.integerValue != SDLPredefinedWindowsDefaultWindow)) { return; }

    self.currentHMILevel = hmiStatus.hmiLevel;
    self.currentSystemContext = hmiStatus.systemContext;

    [self sdl_updateTransactionQueueSuspended];
}

@end

NS_ASSUME_NONNULL_END