summaryrefslogtreecommitdiff
path: root/platform/macos/app/AppDelegate.m
blob: 8a184b094d8fee1ff7ea7149bcdb17d10bf6c9c6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
#import "AppDelegate.h"

#import "MapDocument.h"

NSString * const MGLMapboxAccessTokenDefaultsKey = @"MGLMapboxAccessToken";
NSString * const MGLLastMapCameraDefaultsKey = @"MGLLastMapCamera";
NSString * const MGLLastMapStyleURLDefaultsKey = @"MGLLastMapStyleURL";
NSString * const MGLLastMapDebugMaskDefaultsKey = @"MGLLastMapDebugMask";

/**
 Some convenience methods to make offline pack properties easier to bind to.
 */
@implementation MGLOfflinePack (Additions)

+ (NSSet *)keyPathsForValuesAffectingStateImage {
    return [NSSet setWithObjects:@"state", nil];
}

- (NSImage *)stateImage {
    switch (self.state) {
        case MGLOfflinePackStateComplete:
            return [NSImage imageNamed:@"NSMenuOnStateTemplate"];

        case MGLOfflinePackStateActive:
            return [NSImage imageNamed:@"NSFollowLinkFreestandingTemplate"];

        default:
            return nil;
    }
}

+ (NSSet<NSString *> *)keyPathsForValuesAffectingCountOfResourcesCompleted {
    return [NSSet setWithObjects:@"progress", nil];
}

- (uint64_t)countOfResourcesCompleted {
    return self.progress.countOfResourcesCompleted;
}

+ (NSSet<NSString *> *)keyPathsForValuesAffectingCountOfResourcesExpected {
    return [NSSet setWithObjects:@"progress", nil];
}

- (uint64_t)countOfResourcesExpected {
    return self.progress.countOfResourcesExpected;
}

+ (NSSet<NSString *> *)keyPathsForValuesAffectingCountOfBytesCompleted {
    return [NSSet setWithObjects:@"progress", nil];
}

- (uint64_t)countOfBytesCompleted {
    return self.progress.countOfBytesCompleted;
}

+ (NSSet<NSString *> *)keyPathsForValuesAffectingCountOfTilesCompleted {
    return [NSSet setWithObjects:@"progress", nil];
}

- (uint64_t)countOfTilesCompleted {
    return self.progress.countOfTilesCompleted;
}

+ (NSSet<NSString *> *)keyPathsForValuesAffectingCountOfTileBytesCompleted {
    return [NSSet setWithObjects:@"progress", nil];
}

- (uint64_t)countOfTileBytesCompleted {
    return self.progress.countOfTileBytesCompleted;
}

@end

@interface AppDelegate () <NSWindowDelegate>

@property (weak) IBOutlet NSArrayController *offlinePacksArrayController;
@property (weak) IBOutlet NSPanel *offlinePacksPanel;

@end

@implementation AppDelegate

#pragma mark Lifecycle

+ (void)load {
    // Set access token, unless MGLAccountManager already read it in from Info.plist.
    if (![MGLAccountManager accessToken]) {
        NSString *accessToken = [NSProcessInfo processInfo].environment[@"MAPBOX_ACCESS_TOKEN"];
        if (accessToken) {
            // Store to preferences so that we can launch the app later on without having to specify
            // token.
            [[NSUserDefaults standardUserDefaults] setObject:accessToken forKey:MGLMapboxAccessTokenDefaultsKey];
        } else {
            // Try to retrieve from preferences, maybe we've stored them there previously and can reuse
            // the token.
            accessToken = [[NSUserDefaults standardUserDefaults] stringForKey:MGLMapboxAccessTokenDefaultsKey];
        }
        [MGLAccountManager setAccessToken:accessToken];
    }
}

- (void)applicationWillFinishLaunching:(NSNotification *)notification {
    [[NSAppleEventManager sharedAppleEventManager] setEventHandler:self
                                                       andSelector:@selector(handleGetURLEvent:withReplyEvent:)
                                                     forEventClass:kInternetEventClass
                                                        andEventID:kAEGetURL];

    if (![[NSUserDefaults standardUserDefaults] boolForKey:@"NSQuitAlwaysKeepsWindows"]) {
        NSData *cameraData = [[NSUserDefaults standardUserDefaults] objectForKey:MGLLastMapCameraDefaultsKey];
        if (cameraData) {
            NSKeyedUnarchiver *coder = [[NSKeyedUnarchiver alloc] initForReadingWithData:cameraData];
            self.pendingZoomLevel = -1;
            self.pendingCamera = [[MGLMapCamera alloc] initWithCoder:coder];
        }
        NSString *styleURLString = [[NSUserDefaults standardUserDefaults] objectForKey:MGLLastMapStyleURLDefaultsKey];
        if (styleURLString) {
            self.pendingStyleURL = [NSURL URLWithString:styleURLString];
        }
        self.pendingDebugMask = [[NSUserDefaults standardUserDefaults] integerForKey:MGLLastMapDebugMaskDefaultsKey];
    }
}

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
    // Set access token, unless MGLAccountManager already read it in from Info.plist.
    if (![MGLAccountManager accessToken]) {
        NSAlert *alert = [[NSAlert alloc] init];
        alert.messageText = @"Access token required";
        alert.informativeText = @"To load Mapbox-hosted tiles and styles, enter your Mapbox access token in Preferences.";
        [alert addButtonWithTitle:@"Open Preferences"];
        [alert runModal];
        [self showPreferences:nil];
    }

    [self.offlinePacksArrayController bind:@"content" toObject:[MGLOfflineStorage sharedOfflineStorage] withKeyPath:@"packs" options:nil];
    
    NSInteger maximumAllowedMapboxTiles = [[NSUserDefaults standardUserDefaults] integerForKey:@"MBXMaximumAllowedMapboxTiles"];
    if (maximumAllowedMapboxTiles) {
        [[MGLOfflineStorage sharedOfflineStorage] setMaximumAllowedMapboxTiles:maximumAllowedMapboxTiles];
    }
}

- (void)applicationWillTerminate:(NSNotification *)notification {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:nil object:nil];

    if (![[NSUserDefaults standardUserDefaults] boolForKey:@"NSQuitAlwaysKeepsWindows"]) {
        NSDocument *currentDocument = [NSDocumentController sharedDocumentController].currentDocument;
        if ([currentDocument isKindOfClass:[MapDocument class]]) {
            MGLMapView *mapView = [(MapDocument *)currentDocument mapView];
            NSMutableData *cameraData = [NSMutableData data];
            NSKeyedArchiver *coder = [[NSKeyedArchiver alloc] initForWritingWithMutableData:cameraData];
            [mapView.camera encodeWithCoder:coder];
            [coder finishEncoding];
            [[NSUserDefaults standardUserDefaults] setObject:cameraData forKey:MGLLastMapCameraDefaultsKey];
            [[NSUserDefaults standardUserDefaults] setObject:mapView.styleURL.absoluteString forKey:MGLLastMapStyleURLDefaultsKey];
            [[NSUserDefaults standardUserDefaults] setInteger:mapView.debugMask forKey:MGLLastMapDebugMaskDefaultsKey];
        }
    }

    [self.offlinePacksArrayController unbind:@"content"];
}

#pragma mark Services

- (void)handleGetURLEvent:(NSAppleEventDescriptor *)event withReplyEvent:(NSAppleEventDescriptor *)replyEvent {
    // mapboxgl://?center=29.95,-90.066667&zoom=14&bearing=45&pitch=30
    NSURL *url = [NSURL URLWithString:[event paramDescriptorForKeyword:keyDirectObject].stringValue];
    NSMutableDictionary<NSString *, NSString *> *params = [[NSMutableDictionary alloc] init];
    for (NSString *param in [url.query componentsSeparatedByString:@"&"]) {
        NSArray *parts = [param componentsSeparatedByString:@"="];
        if (parts.count >= 2) {
            params[parts[0]] = [parts[1] stringByRemovingPercentEncoding];
        }
    }

    MGLMapCamera *camera = [MGLMapCamera camera];
    NSString *zoomLevelString = params[@"zoom"];
    self.pendingZoomLevel = zoomLevelString.length ? zoomLevelString.doubleValue : -1;

    NSString *directionString = params[@"bearing"];
    if (directionString.length) {
        camera.heading = directionString.doubleValue;
    }

    NSString *centerString = params[@"center"];
    if (centerString) {
        NSArray *coordinateValues = [centerString componentsSeparatedByString:@","];
        if (coordinateValues.count == 2) {
            camera.centerCoordinate = CLLocationCoordinate2DMake([coordinateValues[0] doubleValue],
                                                                 [coordinateValues[1] doubleValue]);
        }
    }

    NSString *pitchString = params[@"pitch"];
    if (pitchString.length) {
        camera.pitch = pitchString.doubleValue;
    }

    self.pendingCamera = camera;
    [[NSDocumentController sharedDocumentController] openUntitledDocumentAndDisplay:YES error:NULL];
}

#pragma mark Offline pack management

- (IBAction)showOfflinePacksPanel:(id)sender {
    [self.offlinePacksPanel makeKeyAndOrderFront:sender];

    for (MGLOfflinePack *pack in self.offlinePacksArrayController.arrangedObjects) {
        [pack requestProgress];
    }
}

- (IBAction)delete:(id)sender {
    for (MGLOfflinePack *pack in self.offlinePacksArrayController.selectedObjects) {
        [self unwatchOfflinePack:pack];
        [[MGLOfflineStorage sharedOfflineStorage] removePack:pack withCompletionHandler:^(NSError * _Nullable error) {
            if (error) {
                [[NSAlert alertWithError:error] runModal];
            }
        }];
    }
}

- (IBAction)chooseOfflinePack:(id)sender {
    for (MGLOfflinePack *pack in self.offlinePacksArrayController.selectedObjects) {
        switch (pack.state) {
            case MGLOfflinePackStateComplete:
            {
                if ([pack.region isKindOfClass:[MGLTilePyramidOfflineRegion class]]) {
                    MGLTilePyramidOfflineRegion *region = (MGLTilePyramidOfflineRegion *)pack.region;
                    self.pendingVisibleCoordinateBounds = region.bounds;
                    self.pendingMinimumZoomLevel = region.minimumZoomLevel;
                    self.pendingMaximumZoomLevel = region.maximumZoomLevel;
                    [[NSDocumentController sharedDocumentController] openUntitledDocumentAndDisplay:YES error:NULL];
                }
                break;
            }

            case MGLOfflinePackStateInactive:
                [self watchOfflinePack:pack];
                [pack resume];
                break;

            case MGLOfflinePackStateActive:
                [pack suspend];
                [self unwatchOfflinePack:pack];
                break;

            default:
                break;
        }
    }
}

- (void)watchOfflinePack:(MGLOfflinePack *)pack {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(offlinePackDidChangeProgress:) name:MGLOfflinePackProgressChangedNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(offlinePackDidReceiveError:) name:MGLOfflinePackErrorNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(offlinePackDidReceiveError:) name:MGLOfflinePackMaximumMapboxTilesReachedNotification object:nil];
}

- (void)unwatchOfflinePack:(MGLOfflinePack *)pack {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:nil object:pack];
}

- (void)offlinePackDidChangeProgress:(NSNotification *)notification {
    MGLOfflinePack *pack = notification.object;
    if (pack.state == MGLOfflinePackStateComplete) {
        [[NSSound soundNamed:@"Glass"] play];
    }
}

- (void)offlinePackDidReceiveError:(NSNotification *)notification {
    [[NSSound soundNamed:@"Basso"] play];
}

#pragma mark Help methods

- (IBAction)showShortcuts:(id)sender {
    NSAlert *alert = [[NSAlert alloc] init];
    alert.messageText = @"Mapbox GL Help";
    alert.informativeText = @"\
• To scroll, swipe with two fingers on a trackpad, or drag the cursor, or press the arrow keys.\n\
• To zoom in, pinch two fingers apart on a trackpad, or double-click, or hold down Shift while dragging the cursor down, or hold down Option while pressing the up key.\n\
• To zoom out, pinch two fingers together on a trackpad, or double-tap with two fingers on a trackpad, or double-tap on a mouse, or hold down Shift while dragging the cursor up, or hold down Option while pressing the down key.\n\
• To rotate, move two fingers opposite each other in a circle on a trackpad, or hold down Option while dragging the cursor left and right, or hold down Option while pressing the left and right arrow keys.\n\
• To tilt, hold down Option while dragging the cursor up and down.\n\
• To drop a pin, click and hold.\
";
    [alert runModal];
}

- (IBAction)showPreferences:(id)sender {
    [self.preferencesWindow makeKeyAndOrderFront:sender];
}

- (IBAction)print:(id)sender {
    NSDocument *currentDocument = [NSDocumentController sharedDocumentController].currentDocument;
    if ([currentDocument isKindOfClass:[MapDocument class]]) {
        MGLMapView *mapView = [(MapDocument *)currentDocument mapView];
        [mapView print:sender];
    }
}

- (IBAction)openAccessTokenManager:(id)sender {
    [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"https://www.mapbox.com/studio/account/tokens/"]];
}

#pragma mark User interface validation

- (BOOL)validateMenuItem:(NSMenuItem *)menuItem {
    if (menuItem.action == @selector(showShortcuts:)) {
        return YES;
    }
    if (menuItem.action == @selector(showPreferences:)) {
        return YES;
    }
    if (menuItem.action == @selector(showOfflinePacksPanel:)) {
        return YES;
    }
    if (menuItem.action == @selector(print:)) {
        return YES;
    }
    if (menuItem.action == @selector(delete:)) {
        return self.offlinePacksArrayController.selectedObjects.count;
    }
    return NO;
}

#pragma mark NSWindowDelegate methods

- (void)windowWillClose:(NSNotification *)notification {
    NSWindow *window = notification.object;
    if (window == self.preferencesWindow) {
        [window makeFirstResponder:nil];
    }
}

@end