4a9c3fffaba6ccc82c42fde5cf827bbd10a65b00
[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 if (mergeInto) {
251 [mergeInto mergeEntriesFrom:mapping];
252 [self activateMapping:mergeInto];
253 [self mappingsChanged];
254 } else {
255 [_mappings addObject:mapping];
256 [self activateMapping:mapping];
257 [self mappingsChanged];
258 }
259 }
260
261 if (error) {
262 [window presentError:error
263 modalForWindow:window
264 delegate:nil
265 didPresentSelector:nil
266 contextInfo:nil];
267 }
268 }
269
270 - (void)importPressed:(id)sender {
271 NSOpenPanel *panel = [NSOpenPanel openPanel];
272 panel.allowedFileTypes = @[ @"enjoyable", @"json", @"txt" ];
273 NSWindow *window = NSApplication.sharedApplication.keyWindow;
274 [panel beginSheetModalForWindow:window
275 completionHandler:^(NSInteger result) {
276 if (result != NSFileHandlingPanelOKButton)
277 return;
278 [panel close];
279 [self addMappingWithContentsOfURL:panel.URL];
280 }];
281
282 }
283
284 - (void)exportPressed:(id)sender {
285 NSSavePanel *panel = [NSSavePanel savePanel];
286 panel.allowedFileTypes = @[ @"enjoyable" ];
287 NJMapping *mapping = _currentMapping;
288 panel.nameFieldStringValue = [mapping.name stringByFixingPathComponent];
289 NSWindow *window = NSApplication.sharedApplication.keyWindow;
290 [panel beginSheetModalForWindow:window
291 completionHandler:^(NSInteger result) {
292 if (result != NSFileHandlingPanelOKButton)
293 return;
294 [panel close];
295 NSError *error;
296 [mapping writeToURL:panel.URL error:&error];
297 if (error) {
298 [window presentError:error
299 modalForWindow:window
300 delegate:nil
301 didPresentSelector:nil
302 contextInfo:nil];
303 }
304 }];
305 }
306
307 - (IBAction)mappingPressed:(id)sender {
308 [popover showRelativeToRect:popoverActivate.bounds
309 ofView:popoverActivate
310 preferredEdge:NSMinXEdge];
311 }
312
313 - (void)popoverWillShow:(NSNotification *)notification {
314 popoverActivate.state = NSOnState;
315 }
316
317 - (void)popoverWillClose:(NSNotification *)notification {
318 popoverActivate.state = NSOffState;
319 }
320
321 - (IBAction)moveUpPressed:(id)sender {
322 if ([_mappings moveFirstwards:_currentMapping upTo:1])
323 [self mappingsChanged];
324 }
325
326 - (IBAction)moveDownPressed:(id)sender {
327 if ([_mappings moveLastwards:_currentMapping])
328 [self mappingsChanged];
329 }
330
331 - (BOOL)tableView:(NSTableView *)tableView_
332 acceptDrop:(id <NSDraggingInfo>)info
333 row:(NSInteger)row
334 dropOperation:(NSTableViewDropOperation)dropOperation {
335 NSPasteboard *pboard = [info draggingPasteboard];
336 if ([pboard.types containsObject:PB_ROW]) {
337 NSString *value = [pboard stringForType:PB_ROW];
338 NSUInteger srcRow = [value intValue];
339 [_mappings moveObjectAtIndex:srcRow toIndex:row];
340 [self mappingsChanged];
341 return YES;
342 } else if ([pboard.types containsObject:NSURLPboardType]) {
343 NSURL *url = [NSURL URLFromPasteboard:pboard];
344 NSError *error;
345 NJMapping *mapping = [NJMapping mappingWithContentsOfURL:url
346 mappings:_mappings
347 error:&error];
348 if (error) {
349 [tableView_ presentError:error];
350 return NO;
351 } else {
352 [_mappings insertObject:mapping atIndex:row];
353 [self mappingsChanged];
354 return YES;
355 }
356 } else {
357 return NO;
358 }
359 }
360
361 - (NSDragOperation)tableView:(NSTableView *)tableView_
362 validateDrop:(id <NSDraggingInfo>)info
363 proposedRow:(NSInteger)row
364 proposedDropOperation:(NSTableViewDropOperation)dropOperation {
365 NSPasteboard *pboard = [info draggingPasteboard];
366 if ([pboard.types containsObject:PB_ROW]) {
367 [tableView_ setDropRow:MAX(1, row) dropOperation:NSTableViewDropAbove];
368 return NSDragOperationMove;
369 } else if ([pboard.types containsObject:NSURLPboardType]) {
370 NSURL *url = [NSURL URLFromPasteboard:pboard];
371 if ([url.pathExtension isEqualToString:@"enjoyable"]) {
372 [tableView_ setDropRow:MAX(1, row) dropOperation:NSTableViewDropAbove];
373 return NSDragOperationCopy;
374 } else {
375 return NSDragOperationNone;
376 }
377 } else {
378 return NSDragOperationNone;
379 }
380 }
381
382 - (NSArray *)tableView:(NSTableView *)tableView_
383 namesOfPromisedFilesDroppedAtDestination:(NSURL *)dropDestination
384 forDraggedRowsWithIndexes:(NSIndexSet *)indexSet {
385 NJMapping *toSave = self[indexSet.firstIndex];
386 NSString *filename = [[toSave.name stringByFixingPathComponent]
387 stringByAppendingPathExtension:@"enjoyable"];
388 NSURL *dst = [dropDestination URLByAppendingPathComponent:filename];
389 dst = [NSFileManager.defaultManager generateUniqueURLWithBase:dst];
390 NSError *error;
391 if (![toSave writeToURL:dst error:&error]) {
392 [tableView_ presentError:error];
393 return @[];
394 } else {
395 return @[dst.lastPathComponent];
396 }
397 }
398
399 - (BOOL)tableView:(NSTableView *)tableView_
400 writeRowsWithIndexes:(NSIndexSet *)rowIndexes
401 toPasteboard:(NSPasteboard *)pboard {
402 if (rowIndexes.count == 1 && rowIndexes.firstIndex != 0) {
403 [pboard declareTypes:@[PB_ROW, NSFilesPromisePboardType] owner:nil];
404 [pboard setString:@(rowIndexes.firstIndex).stringValue forType:PB_ROW];
405 [pboard setPropertyList:@[@"enjoyable"] forType:NSFilesPromisePboardType];
406 return YES;
407 } else if (rowIndexes.count == 1 && rowIndexes.firstIndex == 0) {
408 [pboard declareTypes:@[NSFilesPromisePboardType] owner:nil];
409 [pboard setPropertyList:@[@"enjoyable"] forType:NSFilesPromisePboardType];
410 return YES;
411 } else {
412 return NO;
413 }
414 }
415
416 @end