Support opening/adding a mapping file directly to import it.
[enjoyable.git] / 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 "NJOutputController.h"
14 #import "NJEvents.h"
15
16 #define PB_ROW @"com.yukkurigames.Enjoyable.MappingRow"
17
18 @implementation NJMappingsController {
19 NSMutableArray *_mappings;
20 NJMapping *manualMapping;
21 NSString *draggingName;
22 }
23
24 - (id)init {
25 if ((self = [super init])) {
26 _mappings = [[NSMutableArray alloc] init];
27 _currentMapping = [[NJMapping alloc] initWithName:@"(default)"];
28 manualMapping = _currentMapping;
29 [_mappings addObject:_currentMapping];
30 }
31 return self;
32 }
33
34 - (void)awakeFromNib {
35 [tableView registerForDraggedTypes:@[PB_ROW, NSURLPboardType]];
36 [tableView setDraggingSourceOperationMask:NSDragOperationCopy forLocal:NO];
37 }
38
39 - (NJMapping *)objectForKeyedSubscript:(NSString *)name {
40 for (NJMapping *mapping in _mappings)
41 if ([name isEqualToString:mapping.name])
42 return mapping;
43 return nil;
44 }
45
46 - (NJMapping *)objectAtIndexedSubscript:(NSUInteger)idx {
47 return idx < _mappings.count ? _mappings[idx] : nil;
48 }
49
50 - (void)mappingsChanged {
51 [self save];
52 [tableView reloadData];
53 popoverActivate.title = _currentMapping.name;
54 [self updateInterfaceForCurrentMapping];
55 [NSNotificationCenter.defaultCenter
56 postNotificationName:NJEventMappingListChanged
57 object:_mappings];
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:(NSString *)processName {
69 if ([manualMapping.name.lowercaseString isEqualToString:@"@application"]) {
70 manualMapping.name = processName;
71 [self mappingsChanged];
72 } else {
73 NJMapping *oldMapping = manualMapping;
74 NJMapping *newMapping = self[processName];
75 if (!newMapping)
76 newMapping = oldMapping;
77 if (newMapping != _currentMapping)
78 [self activateMapping:newMapping];
79 manualMapping = oldMapping;
80 }
81 }
82
83 - (void)updateInterfaceForCurrentMapping {
84 NSUInteger selected = [_mappings indexOfObject:_currentMapping];
85 [removeButton setEnabled:selected != 0];
86 [moveDown setEnabled:selected && selected != _mappings.count - 1];
87 [moveUp setEnabled:selected > 1];
88 popoverActivate.title = _currentMapping.name;
89 [tableView selectRowIndexes:[NSIndexSet indexSetWithIndex:selected] byExtendingSelection:NO];
90 [NSUserDefaults.standardUserDefaults setInteger:selected forKey:@"selected"];
91 }
92
93 - (void)activateMapping:(NJMapping *)mapping {
94 if (!mapping)
95 mapping = manualMapping;
96 if (mapping == _currentMapping)
97 return;
98 NSLog(@"Switching to mapping %@.", mapping.name);
99 manualMapping = mapping;
100 _currentMapping = mapping;
101 [self updateInterfaceForCurrentMapping];
102 [outputController loadCurrent];
103 [NSNotificationCenter.defaultCenter postNotificationName:NJEventMappingChanged
104 object:_currentMapping];
105 }
106
107 - (IBAction)addPressed:(id)sender {
108 NJMapping *newMapping = [[NJMapping alloc] initWithName:@"Untitled"];
109 [_mappings addObject:newMapping];
110 [self activateMapping:newMapping];
111 [self mappingsChanged];
112 [tableView editColumn:0 row:_mappings.count - 1 withEvent:nil select:YES];
113 }
114
115 - (IBAction)removePressed:(id)sender {
116 if (tableView.selectedRow == 0)
117 return;
118
119 [_mappings removeObjectAtIndex:tableView.selectedRow];
120 [self activateMapping:_mappings[0]];
121 [self mappingsChanged];
122 }
123
124 -(void)tableViewSelectionDidChange:(NSNotification *)notify {
125 [self activateMapping:self[tableView.selectedRow]];
126 }
127
128 - (id)tableView:(NSTableView *)view objectValueForTableColumn:(NSTableColumn *)column row:(NSInteger)index {
129 return self[index].name;
130 }
131
132 - (void)tableView:(NSTableView *)view
133 setObjectValue:(NSString *)obj
134 forTableColumn:(NSTableColumn *)col
135 row:(NSInteger)index {
136 self[index].name = obj;
137 [self mappingsChanged];
138 }
139
140 - (NSInteger)numberOfRowsInTableView:(NSTableView *)tableView {
141 return _mappings.count;
142 }
143
144 - (BOOL)tableView:(NSTableView *)view shouldEditTableColumn:(NSTableColumn *)column row:(NSInteger)index {
145 return YES;
146 }
147
148 - (void)save {
149 NSLog(@"Saving mappings to defaults.");
150 NSMutableArray *ary = [[NSMutableArray alloc] initWithCapacity:_mappings.count];
151 for (NJMapping *mapping in _mappings)
152 [ary addObject:[mapping serialize]];
153 [NSUserDefaults.standardUserDefaults setObject:ary forKey:@"mappings"];
154 }
155
156 - (void)load {
157 NSUInteger selected = [NSUserDefaults.standardUserDefaults integerForKey:@"selected"];
158 NSArray *mappings = [NSUserDefaults.standardUserDefaults arrayForKey:@"mappings"];
159 [self loadAllFrom:mappings andActivate:selected];
160 }
161
162 - (void)loadAllFrom:(NSArray *)storedMappings andActivate:(NSUInteger)selected {
163 NSMutableArray* newMappings = [[NSMutableArray alloc] initWithCapacity:storedMappings.count];
164
165 // have to do two passes in case mapping1 refers to mapping2 via a NJOutputMapping
166 for (NSDictionary *storedMapping in storedMappings) {
167 NJMapping *mapping = [[NJMapping alloc] initWithName:storedMapping[@"name"]];
168 [newMappings addObject:mapping];
169 }
170
171 for (unsigned i = 0; i < storedMappings.count; ++i) {
172 NSDictionary *entries = storedMappings[i][@"entries"];
173 NJMapping *mapping = newMappings[i];
174 for (id key in entries) {
175 NJOutput *output = [NJOutput outputDeserialize:entries[key]
176 withMappings:newMappings];
177 if (output)
178 mapping.entries[key] = output;
179 }
180 }
181
182 if (newMappings.count) {
183 _mappings = newMappings;
184 if (selected >= newMappings.count)
185 selected = 0;
186 [self activateMapping:_mappings[selected]];
187 [self mappingsChanged];
188 }
189 }
190
191 - (NJMapping *)mappingWithURL:(NSURL *)url error:(NSError **)error {
192 NSInputStream *stream = [NSInputStream inputStreamWithURL:url];
193 [stream open];
194 NSDictionary *serialization = !*error
195 ? [NSJSONSerialization JSONObjectWithStream:stream options:0 error:error]
196 : nil;
197 [stream close];
198
199 if (!([serialization isKindOfClass:NSDictionary.class]
200 && [serialization[@"name"] isKindOfClass:NSString.class]
201 && [serialization[@"entries"] isKindOfClass:NSDictionary.class])) {
202 *error = [NSError errorWithDomain:@"Enjoyable"
203 code:0
204 description:@"This isn't a valid mapping file."];
205 return nil;
206 }
207
208 NSDictionary *entries = serialization[@"entries"];
209 NJMapping *mapping = [[NJMapping alloc] initWithName:serialization[@"name"]];
210 for (id key in entries) {
211 NSDictionary *value = entries[key];
212 if ([key isKindOfClass:NSString.class]) {
213 NJOutput *output = [NJOutput outputDeserialize:value
214 withMappings:_mappings];
215 if (output)
216 mapping.entries[key] = output;
217 }
218 }
219 return mapping;
220 }
221
222 - (void)addMappingWithContentsOfURL:(NSURL *)url {
223 NSWindow *window = popoverActivate.window;
224 NSError *error;
225 NJMapping *mapping = [NJMapping mappingWithContentsOfURL:url
226 mappings:_mappings
227 error:&error];
228
229 if (mapping && !error) {
230 BOOL conflict = NO;
231 NJMapping *mergeInto = self[mapping.name];
232 for (id key in mapping.entries) {
233 if (mergeInto.entries[key]
234 && ![mergeInto.entries[key] isEqual:mapping.entries[key]]) {
235 conflict = YES;
236 break;
237 }
238 }
239
240 if (conflict) {
241 NSAlert *conflictAlert = [[NSAlert alloc] init];
242 conflictAlert.messageText = @"Replace existing mappings?";
243 conflictAlert.informativeText =
244 [NSString stringWithFormat:
245 @"This file contains inputs you've already mapped in \"%@\". Do you "
246 @"want to merge them and replace your existing mappings, or import this "
247 @"as a separate mapping?", mapping.name];
248 [conflictAlert addButtonWithTitle:@"Merge"];
249 [conflictAlert addButtonWithTitle:@"Cancel"];
250 [conflictAlert addButtonWithTitle:@"New Mapping"];
251 NSInteger res = [conflictAlert runModal];
252 if (res == NSAlertSecondButtonReturn)
253 return;
254 else if (res == NSAlertThirdButtonReturn)
255 mergeInto = nil;
256 }
257
258 if (mergeInto) {
259 [mergeInto.entries addEntriesFromDictionary:mapping.entries];
260 mapping = mergeInto;
261 } else {
262 [_mappings addObject:mapping];
263 }
264
265 [self activateMapping:mapping];
266 [self mappingsChanged];
267
268 if (conflict && !mergeInto) {
269 [tableView selectRowIndexes:[NSIndexSet indexSetWithIndex:_mappings.count - 1] byExtendingSelection:NO];
270 [tableView editColumn:0 row:_mappings.count - 1 withEvent:nil select:YES];
271 }
272 }
273
274 if (error) {
275 [window presentError:error
276 modalForWindow:window
277 delegate:nil
278 didPresentSelector:nil
279 contextInfo:nil];
280 }
281 }
282
283 - (void)importPressed:(id)sender {
284 NSOpenPanel *panel = [NSOpenPanel openPanel];
285 panel.allowedFileTypes = @[ @"enjoyable", @"json", @"txt" ];
286 NSWindow *window = NSApplication.sharedApplication.keyWindow;
287 [panel beginSheetModalForWindow:window
288 completionHandler:^(NSInteger result) {
289 if (result != NSFileHandlingPanelOKButton)
290 return;
291 [panel close];
292 [self addMappingWithContentsOfURL:panel.URL];
293 }];
294
295 }
296
297 - (void)exportPressed:(id)sender {
298 NSSavePanel *panel = [NSSavePanel savePanel];
299 panel.allowedFileTypes = @[ @"enjoyable" ];
300 NJMapping *mapping = _currentMapping;
301 panel.nameFieldStringValue = mapping.name;
302 NSWindow *window = NSApplication.sharedApplication.keyWindow;
303 [panel beginSheetModalForWindow:window
304 completionHandler:^(NSInteger result) {
305 if (result != NSFileHandlingPanelOKButton)
306 return;
307 [panel close];
308 NSError *error;
309 [mapping writeToURL:panel.URL error:&error];
310 if (error) {
311 [window presentError:error
312 modalForWindow:window
313 delegate:nil
314 didPresentSelector:nil
315 contextInfo:nil];
316 }
317 }];
318 }
319
320 - (IBAction)mappingPressed:(id)sender {
321 [popover showRelativeToRect:popoverActivate.bounds
322 ofView:popoverActivate
323 preferredEdge:NSMinXEdge];
324 }
325
326 - (void)popoverWillShow:(NSNotification *)notification {
327 popoverActivate.state = NSOnState;
328 }
329
330 - (void)popoverWillClose:(NSNotification *)notification {
331 popoverActivate.state = NSOffState;
332 }
333
334 - (IBAction)moveUpPressed:(id)sender {
335 NSUInteger idx = [_mappings indexOfObject:_currentMapping];
336 if (idx > 1 && idx != NSNotFound) {
337 [_mappings exchangeObjectAtIndex:idx withObjectAtIndex:idx - 1];
338 [self mappingsChanged];
339 }
340 }
341
342 - (IBAction)moveDownPressed:(id)sender {
343 NSUInteger idx = [_mappings indexOfObject:_currentMapping];
344 if (idx < _mappings.count - 1) {
345 [_mappings exchangeObjectAtIndex:idx withObjectAtIndex:idx + 1];
346 [self mappingsChanged];
347 }
348 }
349
350 - (BOOL)tableView:(NSTableView *)tableView_
351 acceptDrop:(id <NSDraggingInfo>)info
352 row:(NSInteger)row
353 dropOperation:(NSTableViewDropOperation)dropOperation {
354 NSPasteboard *pboard = [info draggingPasteboard];
355 if ([pboard.types containsObject:PB_ROW]) {
356 NSString *value = [pboard stringForType:PB_ROW];
357 NSUInteger srcRow = [value intValue];
358 [_mappings moveObjectAtIndex:srcRow toIndex:row];
359 [self mappingsChanged];
360 return YES;
361 } else if ([pboard.types containsObject:NSURLPboardType]) {
362 NSURL *url = [NSURL URLFromPasteboard:pboard];
363 NSError *error;
364 NJMapping *mapping = [NJMapping mappingWithContentsOfURL:url
365 mappings:_mappings
366 error:&error];
367 if (error) {
368 [tableView_ presentError:error];
369 return NO;
370 } else {
371 [_mappings insertObject:mapping atIndex:row];
372 [self mappingsChanged];
373 return YES;
374 }
375 } else {
376 return NO;
377 }
378 }
379
380 - (NSDragOperation)tableView:(NSTableView *)tableView_
381 validateDrop:(id <NSDraggingInfo>)info
382 proposedRow:(NSInteger)row
383 proposedDropOperation:(NSTableViewDropOperation)dropOperation {
384 NSPasteboard *pboard = [info draggingPasteboard];
385 if ([pboard.types containsObject:PB_ROW]) {
386 [tableView_ setDropRow:MAX(1, row) dropOperation:NSTableViewDropAbove];
387 return NSDragOperationMove;
388 } else if ([pboard.types containsObject:NSURLPboardType]) {
389 NSURL *url = [NSURL URLFromPasteboard:pboard];
390 if ([url.pathExtension isEqualToString:@"enjoyable"]) {
391 [tableView_ setDropRow:MAX(1, row) dropOperation:NSTableViewDropAbove];
392 return NSDragOperationCopy;
393 } else {
394 return NSDragOperationNone;
395 }
396 } else {
397 return NSDragOperationNone;
398 }
399 }
400
401 - (NSArray *)tableView:(NSTableView *)tableView_
402 namesOfPromisedFilesDroppedAtDestination:(NSURL *)dropDestination
403 forDraggedRowsWithIndexes:(NSIndexSet *)indexSet {
404 NJMapping *toSave = self[indexSet.firstIndex];
405 NSString *filename = [[toSave.name stringByFixingPathComponent]
406 stringByAppendingPathExtension:@"enjoyable"];
407 NSURL *dst = [dropDestination URLByAppendingPathComponent:filename];
408 dst = [NSFileManager.defaultManager generateUniqueURLWithBase:dst];
409 NSError *error;
410 if (![toSave writeToURL:dst error:&error]) {
411 [tableView_ presentError:error];
412 return @[];
413 } else {
414 return @[dst.lastPathComponent];
415 }
416 }
417
418 - (BOOL)tableView:(NSTableView *)tableView_
419 writeRowsWithIndexes:(NSIndexSet *)rowIndexes
420 toPasteboard:(NSPasteboard *)pboard {
421 if (rowIndexes.count == 1 && rowIndexes.firstIndex != 0) {
422 [pboard declareTypes:@[PB_ROW, NSFilesPromisePboardType] owner:nil];
423 [pboard setString:@(rowIndexes.firstIndex).stringValue forType:PB_ROW];
424 [pboard setPropertyList:@[@"enjoyable"] forType:NSFilesPromisePboardType];
425 return YES;
426 } else {
427 return NO;
428 }
429 }
430
431 @end