Improve size in a number of pathological cases.
[enjoyable.git] / ConfigsController.m
1 //
2 // ConfigsController.m
3 // Enjoy
4 //
5 // Created by Sam McCall on 4/05/09.
6 //
7
8 #import "ConfigsController.h"
9
10 #import "ApplicationController.h"
11 #import "Config.h"
12 #import "ConfigsController.h"
13 #import "Target.h"
14 #import "TargetController.h"
15
16 @implementation ConfigsController {
17 NSMutableArray *_configs;
18 Config *manualConfig;
19 }
20
21 - (id)init {
22 if ((self = [super init])) {
23 _configs = [[NSMutableArray alloc] init];
24 _currentConfig = [[Config alloc] initWithName:@"(default)"];
25 manualConfig = _currentConfig;
26 [_configs addObject:_currentConfig];
27 }
28 return self;
29 }
30
31 - (Config *)objectForKeyedSubscript:(NSString *)name {
32 for (Config *config in _configs)
33 if ([name isEqualToString:config.name])
34 return config;
35 return nil;
36 }
37
38 - (void)activateConfigForProcess:(NSString *)processName {
39 Config *oldConfig = manualConfig;
40 [self activateConfig:self[processName]];
41 manualConfig = oldConfig;
42 }
43
44 - (void)activateConfig:(Config *)config {
45 if (!config)
46 config = manualConfig;
47 if (_currentConfig == config)
48 return;
49 manualConfig = config;
50 _currentConfig = config;
51 [removeButton setEnabled:_configs[0] != config];
52 [targetController loadCurrent];
53 [(ApplicationController *)[[NSApplication sharedApplication] delegate] configChanged];
54 [tableView selectRowIndexes:[NSIndexSet indexSetWithIndex:[_configs indexOfObject:config]] byExtendingSelection:NO];
55 }
56
57 - (IBAction)addPressed:(id)sender {
58 Config *newConfig = [[Config alloc] initWithName:@"Untitled"];
59 [_configs addObject:newConfig];
60 [(ApplicationController *)[[NSApplication sharedApplication] delegate] configsChanged];
61 [tableView reloadData];
62 [tableView selectRowIndexes:[NSIndexSet indexSetWithIndex:_configs.count - 1] byExtendingSelection:NO];
63 [tableView editColumn:0 row:_configs.count - 1 withEvent:nil select:YES];
64 }
65
66 - (IBAction)removePressed:(id)sender {
67 if (tableView.selectedRow == 0)
68 return;
69
70 Config *toRemove = _configs[tableView.selectedRow];
71 [_configs removeObjectAtIndex:tableView.selectedRow];
72
73 if (toRemove == _currentConfig)
74 _currentConfig = _configs[0];
75 if (toRemove == manualConfig)
76 manualConfig = _configs[0];
77
78 [(ApplicationController *)[[NSApplication sharedApplication] delegate] configsChanged];
79 [tableView reloadData];
80 }
81
82 -(void)tableViewSelectionDidChange:(NSNotification *)notify {
83 if (tableView.selectedRow >= 0)
84 [self activateConfig:_configs[tableView.selectedRow]];
85 }
86
87 - (id)tableView:(NSTableView *)view objectValueForTableColumn:(NSTableColumn *)column row:(NSInteger)index {
88 return [_configs[index] name];
89 }
90
91 - (void)tableView:(NSTableView *)view setObjectValue:(NSString *)obj forTableColumn:(NSTableColumn *)col row:(NSInteger)index {
92 [(Config *)_configs[index] setName:obj];
93 [tableView reloadData];
94 [(ApplicationController *)[[NSApplication sharedApplication] delegate] configsChanged];
95 }
96
97 - (NSInteger)numberOfRowsInTableView:(NSTableView *)tableView {
98 return _configs.count;
99 }
100
101 - (BOOL)tableView:(NSTableView *)view shouldEditTableColumn:(NSTableColumn *)column row:(NSInteger)index {
102 return index > 0;
103 }
104
105 - (void)save {
106 NSLog(@"Saving defaults.");
107 [[NSUserDefaults standardUserDefaults] setObject:[self dumpAll] forKey:@"configurations"];
108 }
109
110 - (void)load {
111 [self loadAllFrom:[[NSUserDefaults standardUserDefaults] objectForKey:@"configurations"]];
112 }
113
114 - (NSDictionary *)dumpAll {
115 NSMutableArray *ary = [[NSMutableArray alloc] initWithCapacity:_configs.count];
116 for (Config *config in _configs)
117 [ary addObject:[config serialize]];
118 NSUInteger current = _currentConfig ? [_configs indexOfObject:_currentConfig] : 0;
119 return @{ @"configurations": ary, @"selected": @(current) };
120 }
121
122 - (void)loadAllFrom:(NSDictionary*) envelope{
123 NSArray *storedConfigs = envelope[@"configurations"];
124 NSMutableArray* newConfigs = [[NSMutableArray alloc] initWithCapacity:storedConfigs.count];
125
126 // have to do two passes in case config1 refers to config2 via a TargetConfig
127 for (NSDictionary *storedConfig in storedConfigs) {
128 Config *cfg = [[Config alloc] initWithName:storedConfig[@"name"]];
129 [newConfigs addObject:cfg];
130 }
131
132 for (unsigned i = 0; i < storedConfigs.count; ++i) {
133 NSDictionary *entries = storedConfigs[i][@"entries"];
134 Config *config = newConfigs[i];
135 for (id key in entries)
136 config.entries[key] = [Target targetDeserialize:entries[key]
137 withConfigs:newConfigs];
138 }
139
140 if (newConfigs.count) {
141 unsigned current = [envelope[@"selected"] unsignedIntValue];
142 if (current >= newConfigs.count)
143 current = 0;
144 _configs = newConfigs;
145 [tableView reloadData];
146 [(ApplicationController *)[[NSApplication sharedApplication] delegate] configsChanged];
147 [self activateConfig:_configs[current]];
148 }
149 }
150
151 - (void)importPressed:(id)sender {
152 NSOpenPanel *panel = [NSOpenPanel openPanel];
153 panel.allowedFileTypes = @[ @"enjoyable", @"json", @"txt" ];
154 if ([panel runModal] == NSFileHandlingPanelOKButton) {
155 NSError *error;
156 NSInputStream *stream = [NSInputStream inputStreamWithURL:panel.URL];
157 [stream open];
158 NSDictionary *serialization = !error
159 ? [NSJSONSerialization JSONObjectWithStream:stream options:0 error:&error]
160 : nil;
161 [stream close];
162
163 if (!([serialization isKindOfClass:[NSDictionary class]]
164 && serialization[@"entries"])) {
165 error = [NSError errorWithDomain:@"Enjoyable"
166 code:0
167 description:@"This isn't a valid mapping file."];
168 }
169
170
171 if (!error) {
172 NSDictionary *entries = serialization[@"entries"];
173 Config *cfg = [[Config alloc] initWithName:serialization[@"name"]];
174 Config *mergeInto = self[cfg.name];
175 BOOL conflict = NO;
176 for (id key in entries) {
177 cfg.entries[key] = [Target targetDeserialize:entries[key]
178 withConfigs:_configs];
179 if (mergeInto.entries[key])
180 conflict = YES;
181 }
182
183 if (conflict) {
184 NSAlert *conflictAlert = [[NSAlert alloc] init];
185 conflictAlert.messageText = @"Replace existing mappings?";
186 conflictAlert.informativeText =
187 [NSString stringWithFormat:
188 @"This file contains inputs you've already mapped in \"%@\". Do you "
189 @"want to merge them and replace your existing mappings, or import this "
190 @"as a separate mapping?", cfg.name];
191 [conflictAlert addButtonWithTitle:@"Merge"];
192 [conflictAlert addButtonWithTitle:@"Cancel"];
193 [conflictAlert addButtonWithTitle:@"New Mapping"];
194 NSInteger res = [conflictAlert runModal];
195 if (res == NSAlertSecondButtonReturn)
196 return;
197 else if (res == NSAlertThirdButtonReturn)
198 mergeInto = nil;
199 }
200
201 if (mergeInto) {
202 [mergeInto.entries addEntriesFromDictionary:cfg.entries];
203 cfg = mergeInto;
204 } else {
205 [_configs addObject:cfg];
206 [tableView reloadData];
207 }
208
209 [self save];
210 [(ApplicationController *)[[NSApplication sharedApplication] delegate] configsChanged];
211 [self activateConfig:cfg];
212 [targetController loadCurrent];
213
214 if (conflict && !mergeInto) {
215 [tableView selectRowIndexes:[NSIndexSet indexSetWithIndex:_configs.count - 1] byExtendingSelection:NO];
216 [tableView editColumn:0 row:_configs.count - 1 withEvent:nil select:YES];
217 }
218 }
219
220 if (error)
221 [[NSAlert alertWithError:error] runModal];
222 }
223 }
224
225 - (void)exportPressed:(id)sender {
226 NSSavePanel *panel = [NSSavePanel savePanel];
227 panel.allowedFileTypes = @[ @"enjoyable" ];
228 if ([panel runModal] == NSFileHandlingPanelOKButton) {
229 NSError *error;
230 NSDictionary *serialization = [_currentConfig serialize];
231 NSData *json = [NSJSONSerialization dataWithJSONObject:serialization
232 options:NSJSONWritingPrettyPrinted
233 error:&error];
234 if (!error)
235 [json writeToURL:panel.URL options:NSDataWritingAtomic error:&error];
236
237 if (error)
238 [[NSAlert alertWithError:error] runModal];
239 }
240 }
241
242 @end