Localization support. Change many names in NJKeyInputField to standard keyboard short...
[enjoyable.git] / Classes / NJMappingsController.m
1 //
2 // NJMappingsController.m
3 // Enjoy
4 //
5 // Created by Sam McCall on 4/05/09.
6 //
7
8 #import "NJMappingsController.h"
9
10 #import "NJMapping.h"
11 #import "NJMappingsController.h"
12 #import "NJOutput.h"
13 #import "NJEvents.h"
14
15 #define PB_ROW @"com.yukkurigames.Enjoyable.MappingRow"
16
17 @implementation NJMappingsController {
18 NSMutableArray *_mappings;
19 NJMapping *_manualMapping;
20 }
21
22 - (id)init {
23 if ((self = [super init])) {
24 _mappings = [[NSMutableArray alloc] init];
25 _currentMapping = [[NJMapping alloc] initWithName:
26 NSLocalizedString(@"(default)", @"default name for first the mapping")];
27 _manualMapping = _currentMapping;
28 [_mappings addObject:_currentMapping];
29 }
30 return self;
31 }
32
33 - (void)awakeFromNib {
34 [tableView registerForDraggedTypes:@[PB_ROW, NSURLPboardType]];
35 [tableView setDraggingSourceOperationMask:NSDragOperationCopy forLocal:NO];
36 }
37
38 - (NJMapping *)objectForKeyedSubscript:(NSString *)name {
39 for (NJMapping *mapping in _mappings)
40 if ([name isEqualToString:mapping.name])
41 return mapping;
42 return nil;
43 }
44
45 - (NJMapping *)objectAtIndexedSubscript:(NSUInteger)idx {
46 return idx < _mappings.count ? _mappings[idx] : nil;
47 }
48
49 - (void)mappingsChanged {
50 [self save];
51 [tableView reloadData];
52 [self updateInterfaceForCurrentMapping];
53 [NSNotificationCenter.defaultCenter
54 postNotificationName:NJEventMappingListChanged
55 object:self
56 userInfo:@{ NJMappingListKey: _mappings,
57 NJMappingKey: _currentMapping }];
58 }
59
60 - (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state
61 objects:(__unsafe_unretained id [])buffer
62 count:(NSUInteger)len {
63 return [_mappings countByEnumeratingWithState:state
64 objects:buffer
65 count:len];
66 }
67
68 - (void)activateMappingForProcess:(NSRunningApplication *)app {
69 NJMapping *oldMapping = _manualMapping;
70 NSArray *names = app.possibleMappingNames;
71 BOOL found = NO;
72 for (NSString *name in names) {
73 NJMapping *mapping = self[name];
74 if (mapping) {
75 [self activateMapping:mapping];
76 found = YES;
77 break;
78 }
79 }
80
81 if (!found) {
82 [self activateMapping:oldMapping];
83 if ([oldMapping.name.lowercaseString isEqualToString:@"@application"]
84 || [oldMapping.name.lowercaseString isEqualToString:
85 NSLocalizedString(@"@Application", nil).lowercaseString]) {
86 oldMapping.name = app.bestMappingName;
87 [self mappingsChanged];
88 }
89 }
90 _manualMapping = oldMapping;
91 }
92
93 - (void)updateInterfaceForCurrentMapping {
94 NSUInteger selected = [_mappings indexOfObject:_currentMapping];
95 removeButton.enabled = selected != 0;
96 moveUp.enabled = selected > 1;
97 moveDown.enabled = selected && selected != _mappings.count - 1;
98 popoverActivate.title = _currentMapping.name;
99 [tableView selectRowIndexes:[NSIndexSet indexSetWithIndex:selected] byExtendingSelection:NO];
100 [NSUserDefaults.standardUserDefaults setInteger:selected forKey:@"selected"];
101 }
102
103 - (void)activateMapping:(NJMapping *)mapping {
104 if (!mapping)
105 mapping = _manualMapping;
106 if (mapping == _currentMapping)
107 return;
108 NSLog(@"Switching to mapping %@.", mapping.name);
109 _manualMapping = mapping;
110 _currentMapping = mapping;
111 [self updateInterfaceForCurrentMapping];
112 [NSNotificationCenter.defaultCenter
113 postNotificationName:NJEventMappingChanged
114 object:self
115 userInfo:@{ NJMappingKey : _currentMapping }];
116 }
117
118 - (IBAction)addPressed:(id)sender {
119 NJMapping *newMapping = [[NJMapping alloc] init];
120 [_mappings addObject:newMapping];
121 [self activateMapping:newMapping];
122 [self mappingsChanged];
123 [tableView editColumn:0 row:_mappings.count - 1 withEvent:nil select:YES];
124 }
125
126 - (IBAction)removePressed:(id)sender {
127 if (tableView.selectedRow == 0)
128 return;
129
130 NSInteger selectedRow = tableView.selectedRow;
131 [_mappings removeObjectAtIndex:selectedRow];
132 [self activateMapping:_mappings[MIN(selectedRow, _mappings.count - 1)]];
133 [self mappingsChanged];
134 }
135
136 - (void)tableViewSelectionDidChange:(NSNotification *)notify {
137 [self activateMapping:self[tableView.selectedRow]];
138 }
139
140 - (id)tableView:(NSTableView *)view objectValueForTableColumn:(NSTableColumn *)column row:(NSInteger)index {
141 return self[index].name;
142 }
143
144 - (void)tableView:(NSTableView *)view
145 setObjectValue:(NSString *)obj
146 forTableColumn:(NSTableColumn *)col
147 row:(NSInteger)index {
148 self[index].name = obj;
149 [self mappingsChanged];
150 }
151
152 - (NSInteger)numberOfRowsInTableView:(NSTableView *)tableView {
153 return _mappings.count;
154 }
155
156 - (BOOL)tableView:(NSTableView *)view shouldEditTableColumn:(NSTableColumn *)column row:(NSInteger)index {
157 return YES;
158 }
159
160 - (void)save {
161 NSLog(@"Saving mappings to defaults.");
162 NSMutableArray *ary = [[NSMutableArray alloc] initWithCapacity:_mappings.count];
163 for (NJMapping *mapping in _mappings)
164 [ary addObject:[mapping serialize]];
165 [NSUserDefaults.standardUserDefaults setObject:ary forKey:@"mappings"];
166 }
167
168 - (void)load {
169 NSUInteger selected = [NSUserDefaults.standardUserDefaults integerForKey:@"selected"];
170 NSArray *mappings = [NSUserDefaults.standardUserDefaults arrayForKey:@"mappings"];
171 [self loadAllFrom:mappings andActivate:selected];
172 }
173
174 - (void)loadAllFrom:(NSArray *)storedMappings andActivate:(NSUInteger)selected {
175 NSMutableArray* newMappings = [[NSMutableArray alloc] initWithCapacity:storedMappings.count];
176
177 // Requires two passes to deal with inter-mapping references. First make
178 // an empty mapping for each serialized mapping. Then, deserialize the
179 // data pointing to the empty mappings. Then merge that data back into
180 // its equivalent empty one, which is the one we finally use.
181 for (NSDictionary *storedMapping in storedMappings) {
182 NJMapping *mapping = [[NJMapping alloc] initWithName:storedMapping[@"name"]];
183 [newMappings addObject:mapping];
184 }
185
186 for (unsigned i = 0; i < storedMappings.count; ++i) {
187 NJMapping *realMapping = [[NJMapping alloc] initWithSerialization:storedMappings[i]
188 mappings:newMappings];
189 [newMappings[i] mergeEntriesFrom:realMapping];
190 }
191
192 if (newMappings.count) {
193 _mappings = newMappings;
194 if (selected >= newMappings.count)
195 selected = 0;
196 [self activateMapping:_mappings[selected]];
197 [self mappingsChanged];
198 }
199 }
200
201 - (void)mappingConflictDidResolve:(NSAlert *)alert
202 returnCode:(NSInteger)returnCode
203 contextInfo:(void *)contextInfo {
204 NSDictionary *userInfo = CFBridgingRelease(contextInfo);
205 NJMapping *oldMapping = userInfo[@"old mapping"];
206 NJMapping *newMapping = userInfo[@"new mapping"];
207 switch (returnCode) {
208 case NSAlertFirstButtonReturn: // Merge
209 [oldMapping mergeEntriesFrom:newMapping];
210 [self activateMapping:oldMapping];
211 [self mappingsChanged];
212 break;
213 case NSAlertThirdButtonReturn: // New Mapping
214 [_mappings addObject:newMapping];
215 [self activateMapping:newMapping];
216 [self mappingsChanged];
217 [self mappingPressed:alert];
218 [tableView selectRowIndexes:[NSIndexSet indexSetWithIndex:_mappings.count - 1] byExtendingSelection:NO];
219 [tableView editColumn:0 row:_mappings.count - 1 withEvent:nil select:YES];
220 break;
221 default: // Cancel, other.
222 break;
223 }
224 }
225
226 - (void)addMappingWithContentsOfURL:(NSURL *)url {
227 NSWindow *window = popoverActivate.window;
228 NSError *error;
229 NJMapping *mapping = [NJMapping mappingWithContentsOfURL:url
230 mappings:_mappings
231 error:&error];
232
233 if (mapping && !error) {
234 NJMapping *mergeInto = self[mapping.name];
235 if ([mergeInto hasConflictWith:mapping]) {
236 NSAlert *conflictAlert = [[NSAlert alloc] init];
237 conflictAlert.messageText = NSLocalizedString(@"import conflict prompt", @"Title of import conflict alert");
238 conflictAlert.informativeText =
239 [NSString stringWithFormat:NSLocalizedString(@"import conflict in %@", @"Explanation of import conflict"),
240 mapping.name];
241 [conflictAlert addButtonWithTitle:NSLocalizedString(@"import and merge", @"button to merge imported mappings")];
242 [conflictAlert addButtonWithTitle:NSLocalizedString(@"cancel import", @"button to cancel import")];
243 [conflictAlert addButtonWithTitle:NSLocalizedString(@"import new mapping", @"button to import as new mapping")];
244 [conflictAlert beginSheetModalForWindow:popoverActivate.window
245 modalDelegate:self
246 didEndSelector:@selector(mappingConflictDidResolve:returnCode:contextInfo:)
247 contextInfo:(void *)CFBridgingRetain(@{ @"old mapping": mergeInto,
248 @"new mapping": mapping })];
249 } else {
250 [_mappings addObject:mapping];
251 [self activateMapping:mapping];
252 [self mappingsChanged];
253 }
254 }
255
256 if (error) {
257 [window presentError:error
258 modalForWindow:window
259 delegate:nil
260 didPresentSelector:nil
261 contextInfo:nil];
262 }
263 }
264
265 - (void)importPressed:(id)sender {
266 NSOpenPanel *panel = [NSOpenPanel openPanel];
267 panel.allowedFileTypes = @[ @"enjoyable", @"json", @"txt" ];
268 NSWindow *window = NSApplication.sharedApplication.keyWindow;
269 [panel beginSheetModalForWindow:window
270 completionHandler:^(NSInteger result) {
271 if (result != NSFileHandlingPanelOKButton)
272 return;
273 [panel close];
274 [self addMappingWithContentsOfURL:panel.URL];
275 }];
276
277 }
278
279 - (void)exportPressed:(id)sender {
280 NSSavePanel *panel = [NSSavePanel savePanel];
281 panel.allowedFileTypes = @[ @"enjoyable" ];
282 NJMapping *mapping = _currentMapping;
283 panel.nameFieldStringValue = [mapping.name stringByFixingPathComponent];
284 NSWindow *window = NSApplication.sharedApplication.keyWindow;
285 [panel beginSheetModalForWindow:window
286 completionHandler:^(NSInteger result) {
287 if (result != NSFileHandlingPanelOKButton)
288 return;
289 [panel close];
290 NSError *error;
291 [mapping writeToURL:panel.URL error:&error];
292 if (error) {
293 [window presentError:error
294 modalForWindow:window
295 delegate:nil
296 didPresentSelector:nil
297 contextInfo:nil];
298 }
299 }];
300 }
301
302 - (IBAction)mappingPressed:(id)sender {
303 [popover showRelativeToRect:popoverActivate.bounds
304 ofView:popoverActivate
305 preferredEdge:NSMinXEdge];
306 }
307
308 - (void)popoverWillShow:(NSNotification *)notification {
309 popoverActivate.state = NSOnState;
310 }
311
312 - (void)popoverWillClose:(NSNotification *)notification {
313 popoverActivate.state = NSOffState;
314 }
315
316 - (IBAction)moveUpPressed:(id)sender {
317 if ([_mappings moveFirstwards:_currentMapping upTo:1])
318 [self mappingsChanged];
319 }
320
321 - (IBAction)moveDownPressed:(id)sender {
322 if ([_mappings moveLastwards:_currentMapping])
323 [self mappingsChanged];
324 }
325
326 - (BOOL)tableView:(NSTableView *)tableView_
327 acceptDrop:(id <NSDraggingInfo>)info
328 row:(NSInteger)row
329 dropOperation:(NSTableViewDropOperation)dropOperation {
330 NSPasteboard *pboard = [info draggingPasteboard];
331 if ([pboard.types containsObject:PB_ROW]) {
332 NSString *value = [pboard stringForType:PB_ROW];
333 NSUInteger srcRow = [value intValue];
334 [_mappings moveObjectAtIndex:srcRow toIndex:row];
335 [self mappingsChanged];
336 return YES;
337 } else if ([pboard.types containsObject:NSURLPboardType]) {
338 NSURL *url = [NSURL URLFromPasteboard:pboard];
339 NSError *error;
340 NJMapping *mapping = [NJMapping mappingWithContentsOfURL:url
341 mappings:_mappings
342 error:&error];
343 if (error) {
344 [tableView_ presentError:error];
345 return NO;
346 } else {
347 [_mappings insertObject:mapping atIndex:row];
348 [self mappingsChanged];
349 return YES;
350 }
351 } else {
352 return NO;
353 }
354 }
355
356 - (NSDragOperation)tableView:(NSTableView *)tableView_
357 validateDrop:(id <NSDraggingInfo>)info
358 proposedRow:(NSInteger)row
359 proposedDropOperation:(NSTableViewDropOperation)dropOperation {
360 NSPasteboard *pboard = [info draggingPasteboard];
361 if ([pboard.types containsObject:PB_ROW]) {
362 [tableView_ setDropRow:MAX(1, row) dropOperation:NSTableViewDropAbove];
363 return NSDragOperationMove;
364 } else if ([pboard.types containsObject:NSURLPboardType]) {
365 NSURL *url = [NSURL URLFromPasteboard:pboard];
366 if ([url.pathExtension isEqualToString:@"enjoyable"]) {
367 [tableView_ setDropRow:MAX(1, row) dropOperation:NSTableViewDropAbove];
368 return NSDragOperationCopy;
369 } else {
370 return NSDragOperationNone;
371 }
372 } else {
373 return NSDragOperationNone;
374 }
375 }
376
377 - (NSArray *)tableView:(NSTableView *)tableView_
378 namesOfPromisedFilesDroppedAtDestination:(NSURL *)dropDestination
379 forDraggedRowsWithIndexes:(NSIndexSet *)indexSet {
380 NJMapping *toSave = self[indexSet.firstIndex];
381 NSString *filename = [[toSave.name stringByFixingPathComponent]
382 stringByAppendingPathExtension:@"enjoyable"];
383 NSURL *dst = [dropDestination URLByAppendingPathComponent:filename];
384 dst = [NSFileManager.defaultManager generateUniqueURLWithBase:dst];
385 NSError *error;
386 if (![toSave writeToURL:dst error:&error]) {
387 [tableView_ presentError:error];
388 return @[];
389 } else {
390 return @[dst.lastPathComponent];
391 }
392 }
393
394 - (BOOL)tableView:(NSTableView *)tableView_
395 writeRowsWithIndexes:(NSIndexSet *)rowIndexes
396 toPasteboard:(NSPasteboard *)pboard {
397 if (rowIndexes.count == 1 && rowIndexes.firstIndex != 0) {
398 [pboard declareTypes:@[PB_ROW, NSFilesPromisePboardType] owner:nil];
399 [pboard setString:@(rowIndexes.firstIndex).stringValue forType:PB_ROW];
400 [pboard setPropertyList:@[@"enjoyable"] forType:NSFilesPromisePboardType];
401 return YES;
402 } else if (rowIndexes.count == 1 && rowIndexes.firstIndex == 0) {
403 [pboard declareTypes:@[NSFilesPromisePboardType] owner:nil];
404 [pboard setPropertyList:@[@"enjoyable"] forType:NSFilesPromisePboardType];
405 return YES;
406 } else {
407 return NO;
408 }
409 }
410
411 @end