Create new mappings from the menu.
[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 [self mappingPressed:sender];
120 NJMapping *newMapping = [[NJMapping alloc] init];
121 [_mappings addObject:newMapping];
122 [self activateMapping:newMapping];
123 [self mappingsChanged];
124 [tableView editColumn:0 row:_mappings.count - 1 withEvent:nil select:YES];
125 }
126
127 - (IBAction)removePressed:(id)sender {
128 if (tableView.selectedRow == 0)
129 return;
130
131 NSInteger selectedRow = tableView.selectedRow;
132 [_mappings removeObjectAtIndex:selectedRow];
133 [self activateMapping:_mappings[MIN(selectedRow, _mappings.count - 1)]];
134 [self mappingsChanged];
135 }
136
137 - (void)tableViewSelectionDidChange:(NSNotification *)notify {
138 [self activateMapping:self[tableView.selectedRow]];
139 }
140
141 - (id)tableView:(NSTableView *)view objectValueForTableColumn:(NSTableColumn *)column row:(NSInteger)index {
142 return self[index].name;
143 }
144
145 - (void)tableView:(NSTableView *)view
146 setObjectValue:(NSString *)obj
147 forTableColumn:(NSTableColumn *)col
148 row:(NSInteger)index {
149 self[index].name = obj;
150 [self mappingsChanged];
151 }
152
153 - (NSInteger)numberOfRowsInTableView:(NSTableView *)tableView {
154 return _mappings.count;
155 }
156
157 - (BOOL)tableView:(NSTableView *)view shouldEditTableColumn:(NSTableColumn *)column row:(NSInteger)index {
158 return YES;
159 }
160
161 - (void)save {
162 NSLog(@"Saving mappings to defaults.");
163 NSMutableArray *ary = [[NSMutableArray alloc] initWithCapacity:_mappings.count];
164 for (NJMapping *mapping in _mappings)
165 [ary addObject:[mapping serialize]];
166 [NSUserDefaults.standardUserDefaults setObject:ary forKey:@"mappings"];
167 }
168
169 - (void)load {
170 NSUInteger selected = [NSUserDefaults.standardUserDefaults integerForKey:@"selected"];
171 NSArray *mappings = [NSUserDefaults.standardUserDefaults arrayForKey:@"mappings"];
172 [self loadAllFrom:mappings andActivate:selected];
173 }
174
175 - (void)loadAllFrom:(NSArray *)storedMappings andActivate:(NSUInteger)selected {
176 NSMutableArray* newMappings = [[NSMutableArray alloc] initWithCapacity:storedMappings.count];
177
178 // Requires two passes to deal with inter-mapping references. First make
179 // an empty mapping for each serialized mapping. Then, deserialize the
180 // data pointing to the empty mappings. Then merge that data back into
181 // its equivalent empty one, which is the one we finally use.
182 for (NSDictionary *storedMapping in storedMappings) {
183 NJMapping *mapping = [[NJMapping alloc] initWithName:storedMapping[@"name"]];
184 [newMappings addObject:mapping];
185 }
186
187 for (unsigned i = 0; i < storedMappings.count; ++i) {
188 NJMapping *realMapping = [[NJMapping alloc] initWithSerialization:storedMappings[i]
189 mappings:newMappings];
190 [newMappings[i] mergeEntriesFrom:realMapping];
191 }
192
193 if (newMappings.count) {
194 _mappings = newMappings;
195 if (selected >= newMappings.count)
196 selected = 0;
197 [self activateMapping:_mappings[selected]];
198 [self mappingsChanged];
199 }
200 }
201
202 - (void)mappingConflictDidResolve:(NSAlert *)alert
203 returnCode:(NSInteger)returnCode
204 contextInfo:(void *)contextInfo {
205 NSDictionary *userInfo = CFBridgingRelease(contextInfo);
206 NJMapping *oldMapping = userInfo[@"old mapping"];
207 NJMapping *newMapping = userInfo[@"new mapping"];
208 switch (returnCode) {
209 case NSAlertFirstButtonReturn: // Merge
210 [oldMapping mergeEntriesFrom:newMapping];
211 [self activateMapping:oldMapping];
212 [self mappingsChanged];
213 break;
214 case NSAlertThirdButtonReturn: // New Mapping
215 [_mappings addObject:newMapping];
216 [self activateMapping:newMapping];
217 [self mappingsChanged];
218 [self mappingPressed:alert];
219 [tableView selectRowIndexes:[NSIndexSet indexSetWithIndex:_mappings.count - 1] byExtendingSelection:NO];
220 [tableView editColumn:0 row:_mappings.count - 1 withEvent:nil select:YES];
221 break;
222 default: // Cancel, other.
223 break;
224 }
225 }
226
227 - (void)addMappingWithContentsOfURL:(NSURL *)url {
228 NSWindow *window = popoverActivate.window;
229 NSError *error;
230 NJMapping *mapping = [NJMapping mappingWithContentsOfURL:url
231 mappings:_mappings
232 error:&error];
233
234 if (mapping && !error) {
235 NJMapping *mergeInto = self[mapping.name];
236 if ([mergeInto hasConflictWith:mapping]) {
237 NSAlert *conflictAlert = [[NSAlert alloc] init];
238 conflictAlert.messageText = NSLocalizedString(@"import conflict prompt", @"Title of import conflict alert");
239 conflictAlert.informativeText =
240 [NSString stringWithFormat:NSLocalizedString(@"import conflict in %@", @"Explanation of import conflict"),
241 mapping.name];
242 [conflictAlert addButtonWithTitle:NSLocalizedString(@"import and merge", @"button to merge imported mappings")];
243 [conflictAlert addButtonWithTitle:NSLocalizedString(@"cancel import", @"button to cancel import")];
244 [conflictAlert addButtonWithTitle:NSLocalizedString(@"import new mapping", @"button to import as new mapping")];
245 [conflictAlert beginSheetModalForWindow:popoverActivate.window
246 modalDelegate:self
247 didEndSelector:@selector(mappingConflictDidResolve:returnCode:contextInfo:)
248 contextInfo:(void *)CFBridgingRetain(@{ @"old mapping": mergeInto,
249 @"new mapping": mapping })];
250 } else {
251 [_mappings addObject:mapping];
252 [self activateMapping:mapping];
253 [self mappingsChanged];
254 }
255 }
256
257 if (error) {
258 [window presentError:error
259 modalForWindow:window
260 delegate:nil
261 didPresentSelector:nil
262 contextInfo:nil];
263 }
264 }
265
266 - (void)importPressed:(id)sender {
267 NSOpenPanel *panel = [NSOpenPanel openPanel];
268 panel.allowedFileTypes = @[ @"enjoyable", @"json", @"txt" ];
269 NSWindow *window = NSApplication.sharedApplication.keyWindow;
270 [panel beginSheetModalForWindow:window
271 completionHandler:^(NSInteger result) {
272 if (result != NSFileHandlingPanelOKButton)
273 return;
274 [panel close];
275 [self addMappingWithContentsOfURL:panel.URL];
276 }];
277
278 }
279
280 - (void)exportPressed:(id)sender {
281 NSSavePanel *panel = [NSSavePanel savePanel];
282 panel.allowedFileTypes = @[ @"enjoyable" ];
283 NJMapping *mapping = _currentMapping;
284 panel.nameFieldStringValue = [mapping.name stringByFixingPathComponent];
285 NSWindow *window = NSApplication.sharedApplication.keyWindow;
286 [panel beginSheetModalForWindow:window
287 completionHandler:^(NSInteger result) {
288 if (result != NSFileHandlingPanelOKButton)
289 return;
290 [panel close];
291 NSError *error;
292 [mapping writeToURL:panel.URL error:&error];
293 if (error) {
294 [window presentError:error
295 modalForWindow:window
296 delegate:nil
297 didPresentSelector:nil
298 contextInfo:nil];
299 }
300 }];
301 }
302
303 - (IBAction)mappingPressed:(id)sender {
304 [popover showRelativeToRect:popoverActivate.bounds
305 ofView:popoverActivate
306 preferredEdge:NSMinXEdge];
307 }
308
309 - (void)popoverWillShow:(NSNotification *)notification {
310 popoverActivate.state = NSOnState;
311 }
312
313 - (void)popoverWillClose:(NSNotification *)notification {
314 popoverActivate.state = NSOffState;
315 }
316
317 - (IBAction)moveUpPressed:(id)sender {
318 if ([_mappings moveFirstwards:_currentMapping upTo:1])
319 [self mappingsChanged];
320 }
321
322 - (IBAction)moveDownPressed:(id)sender {
323 if ([_mappings moveLastwards:_currentMapping])
324 [self mappingsChanged];
325 }
326
327 - (BOOL)tableView:(NSTableView *)tableView_
328 acceptDrop:(id <NSDraggingInfo>)info
329 row:(NSInteger)row
330 dropOperation:(NSTableViewDropOperation)dropOperation {
331 NSPasteboard *pboard = [info draggingPasteboard];
332 if ([pboard.types containsObject:PB_ROW]) {
333 NSString *value = [pboard stringForType:PB_ROW];
334 NSUInteger srcRow = [value intValue];
335 [_mappings moveObjectAtIndex:srcRow toIndex:row];
336 [self mappingsChanged];
337 return YES;
338 } else if ([pboard.types containsObject:NSURLPboardType]) {
339 NSURL *url = [NSURL URLFromPasteboard:pboard];
340 NSError *error;
341 NJMapping *mapping = [NJMapping mappingWithContentsOfURL:url
342 mappings:_mappings
343 error:&error];
344 if (error) {
345 [tableView_ presentError:error];
346 return NO;
347 } else {
348 [_mappings insertObject:mapping atIndex:row];
349 [self mappingsChanged];
350 return YES;
351 }
352 } else {
353 return NO;
354 }
355 }
356
357 - (NSDragOperation)tableView:(NSTableView *)tableView_
358 validateDrop:(id <NSDraggingInfo>)info
359 proposedRow:(NSInteger)row
360 proposedDropOperation:(NSTableViewDropOperation)dropOperation {
361 NSPasteboard *pboard = [info draggingPasteboard];
362 if ([pboard.types containsObject:PB_ROW]) {
363 [tableView_ setDropRow:MAX(1, row) dropOperation:NSTableViewDropAbove];
364 return NSDragOperationMove;
365 } else if ([pboard.types containsObject:NSURLPboardType]) {
366 NSURL *url = [NSURL URLFromPasteboard:pboard];
367 if ([url.pathExtension isEqualToString:@"enjoyable"]) {
368 [tableView_ setDropRow:MAX(1, row) dropOperation:NSTableViewDropAbove];
369 return NSDragOperationCopy;
370 } else {
371 return NSDragOperationNone;
372 }
373 } else {
374 return NSDragOperationNone;
375 }
376 }
377
378 - (NSArray *)tableView:(NSTableView *)tableView_
379 namesOfPromisedFilesDroppedAtDestination:(NSURL *)dropDestination
380 forDraggedRowsWithIndexes:(NSIndexSet *)indexSet {
381 NJMapping *toSave = self[indexSet.firstIndex];
382 NSString *filename = [[toSave.name stringByFixingPathComponent]
383 stringByAppendingPathExtension:@"enjoyable"];
384 NSURL *dst = [dropDestination URLByAppendingPathComponent:filename];
385 dst = [NSFileManager.defaultManager generateUniqueURLWithBase:dst];
386 NSError *error;
387 if (![toSave writeToURL:dst error:&error]) {
388 [tableView_ presentError:error];
389 return @[];
390 } else {
391 return @[dst.lastPathComponent];
392 }
393 }
394
395 - (BOOL)tableView:(NSTableView *)tableView_
396 writeRowsWithIndexes:(NSIndexSet *)rowIndexes
397 toPasteboard:(NSPasteboard *)pboard {
398 if (rowIndexes.count == 1 && rowIndexes.firstIndex != 0) {
399 [pboard declareTypes:@[PB_ROW, NSFilesPromisePboardType] owner:nil];
400 [pboard setString:@(rowIndexes.firstIndex).stringValue forType:PB_ROW];
401 [pboard setPropertyList:@[@"enjoyable"] forType:NSFilesPromisePboardType];
402 return YES;
403 } else if (rowIndexes.count == 1 && rowIndexes.firstIndex == 0) {
404 [pboard declareTypes:@[NSFilesPromisePboardType] owner:nil];
405 [pboard setPropertyList:@[@"enjoyable"] forType:NSFilesPromisePboardType];
406 return YES;
407 } else {
408 return NO;
409 }
410 }
411
412 @end