aboutsummaryrefslogtreecommitdiff
path: root/AppKit/GTMWindowSheetController.m
blob: 59a866d31bc4596c047b2eaef2fb10dd69dddb52 (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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
//
//  GTMWindowSheetController.m
//
//  Copyright 2009 Google Inc.
//
//  Licensed under the Apache License, Version 2.0 (the "License"); you may not
//  use this file except in compliance with the License.  You may obtain a copy
//  of the License at
//
//  http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
//  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
//  License for the specific language governing permissions and limitations under
//  the License.
//

#import "GTMWindowSheetController.h"

#import "GTMDefines.h"
#import "GTMTypeCasting.h"

@interface GTMWSCSheetInfo : NSObject {
 @public
  __weak NSWindow* overlayWindow_;

  // delegate data
  __weak id modalDelegate_;
  SEL didEndSelector_;
  void* contextInfo_;

  // sheet info
  CGFloat sheetAlpha_;
  NSRect sheetFrame_; // relative to overlay window
  BOOL sheetAutoresizesSubviews_;
}
@end

@implementation GTMWSCSheetInfo
@end

// The information about how to call up various AppKit-implemented sheets

struct GTMWSCSystemSheetInfo {
  NSString* className_;
  NSString* methodSignature_;
  NSUInteger modalForWindowIndex_;
  NSUInteger modalDelegateIndex_;
  NSUInteger didEndSelectorIndex_;
  NSUInteger contextInfoIndex_;
  // Callbacks invariably take three parameters. The first is always an id, the
  // third always a void*, but the second can be a BOOL (8 bits), an int (32
  // bits), or an id or NSInteger (64 bits in 64 bit mode). This is the size of
  // the argument in 64-bit mode.
  NSUInteger arg1OfEndSelectorSize_;
};

@interface GTMWindowSheetController (PrivateMethods)
- (void)beginSystemSheet:(id)systemSheet
                withInfo:(const struct GTMWSCSystemSheetInfo*)info
            modalForView:(NSView*)view
          withParameters:(NSArray*)params;
- (const struct GTMWSCSystemSheetInfo*)infoForSheet:(id)systemSheet;
- (void)notificationHappened:(NSNotification*)notification;
- (void)viewDidChangeSize:(NSView*)view;
- (NSRect)screenFrameOfView:(NSView*)view;
- (void)sheetDidEnd:(id)sheet
        returnCode8:(char)returnCode
        contextInfo:(void*)contextInfo;
- (void)sheetDidEnd:(id)sheet
       returnCode32:(int)returnCode
        contextInfo:(void*)contextInfo;
- (void)sheetDidEnd:(id)sheet
       returnCode64:(NSInteger)returnCode
        contextInfo:(void*)contextInfo;
- (void)sheetDidEnd:(id)sheet
         returnCode:(NSInteger)returnCode
        contextInfo:(void*)contextInfo
           arg1Size:(int)size;
- (void)systemRequestsVisibilityForWindow:(NSWindow*)window;
- (NSRect)window:(NSWindow*)window
willPositionSheet:(NSWindow*)sheet
       usingRect:(NSRect)defaultSheetRect;
@end

@interface GTMWSCOverlayWindow : NSWindow {
  GTMWindowSheetController* sheetController_;
}

- (id)initWithContentRect:(NSRect)contentRect
          sheetController:(GTMWindowSheetController*)sheetController;
- (void)makeKeyAndOrderFront:(id)sender;

@end

@implementation GTMWSCOverlayWindow

- (id)initWithContentRect:(NSRect)contentRect
          sheetController:(GTMWindowSheetController*)sheetController {
  self = [super initWithContentRect:contentRect
                          styleMask:NSBorderlessWindowMask
                            backing:NSBackingStoreBuffered
                              defer:NO];
  if (self != nil) {
    sheetController_ = sheetController;
    [self setOpaque:NO];
    [self setBackgroundColor:[NSColor clearColor]];
    [self setIgnoresMouseEvents:NO];
  }
  return self;
}

- (void)makeKeyAndOrderFront:(id)sender {
  [sheetController_ systemRequestsVisibilityForWindow:self];
}

@end

@implementation GTMWindowSheetController

- (id)initWithWindow:(NSWindow*)window
            delegate:(id <GTMWindowSheetControllerDelegate>)delegate {
  self = [super init];
  if (self != nil) {
    window_ = window;
    delegate_ = delegate;
    sheets_ = [[NSMutableDictionary alloc] init];
  }
  return self;
}

- (void)finalize {
  _GTMDevAssert([sheets_ count] == 0,
                @"Finalizing a controller with sheets still active!");
  [[NSNotificationCenter defaultCenter] removeObserver:self];
  
  [super finalize];
}

- (void)dealloc {
  _GTMDevAssert([sheets_ count] == 0,
                @"Deallocing a controller with sheets still active!");
  [[NSNotificationCenter defaultCenter] removeObserver:self];

  [sheets_ release];

  [super dealloc];
}

- (void)beginSheet:(NSWindow*)sheet
      modalForView:(NSView*)view
     modalDelegate:(id)modalDelegate
    didEndSelector:(SEL)didEndSelector
       contextInfo:(void*)contextInfo {
  NSArray* params =
      [NSArray arrayWithObjects:sheet,
                                [NSNull null],
                                modalDelegate,
                                [NSValue valueWithPointer:didEndSelector],
                                [NSValue valueWithPointer:contextInfo],
                                nil];
  [self beginSystemSheet:[NSApplication sharedApplication]
            modalForView:view
          withParameters:params];
}

- (void)beginSystemSheet:(id)systemSheet
            modalForView:(NSView*)view
          withParameters:(NSArray*)params {
  const struct GTMWSCSystemSheetInfo* info = [self infoForSheet:systemSheet];
  if (info) {
    [self beginSystemSheet:systemSheet
                  withInfo:info
              modalForView:view
            withParameters:params];
  } // else already logged
}


- (BOOL)isSheetAttachedToView:(NSView*)view {
  NSValue* viewValue = [NSValue valueWithNonretainedObject:view];
  return [sheets_ objectForKey:viewValue] != nil;
}

- (NSArray*)viewsWithAttachedSheets {
  NSMutableArray* views = [NSMutableArray array];
  NSValue* key;
  GTM_FOREACH_KEY(key, sheets_) {
    [views addObject:[key nonretainedObjectValue]];
  }

  return views;
}

- (void)setActiveView:(NSView*)view {
  // Hide old sheet

  NSValue* oldViewValue = [NSValue valueWithNonretainedObject:activeView_];
  GTMWSCSheetInfo* oldSheetInfo = [sheets_ objectForKey:oldViewValue];
  if (oldSheetInfo) {
    NSWindow* overlayWindow = oldSheetInfo->overlayWindow_;
    _GTMDevAssert(overlayWindow, @"Old sheet info has no overlay window");
    NSWindow* sheetWindow = [overlayWindow attachedSheet];
    _GTMDevAssert(sheetWindow, @"Old sheet info has no active sheet");

    // Why do we hide things this way?
    // - Keeping it local but alpha 0 means we get good Expose behavior
    // - Resizing it to 0 means we get no blurring effect left over

    oldSheetInfo->sheetAlpha_ = [sheetWindow alphaValue];
    [sheetWindow setAlphaValue:(CGFloat)0.0];

    oldSheetInfo->sheetAutoresizesSubviews_ =
        [[sheetWindow contentView] autoresizesSubviews];
    [[sheetWindow contentView] setAutoresizesSubviews:NO];

    NSRect overlayFrame = [overlayWindow frame];
    oldSheetInfo->sheetFrame_ = [sheetWindow frame];
    oldSheetInfo->sheetFrame_.origin.x -= overlayFrame.origin.x;
    oldSheetInfo->sheetFrame_.origin.y -= overlayFrame.origin.y;
    [sheetWindow setFrame:NSZeroRect display:NO];

    [overlayWindow setIgnoresMouseEvents:YES];

    // Make sure the now invisible sheet doesn't keep keyboard focus
    [[overlayWindow parentWindow] makeKeyWindow];
  }

  activeView_ = view;

  // Show new sheet

  NSValue* newViewValue = [NSValue valueWithNonretainedObject:view];
  GTMWSCSheetInfo* newSheetInfo = [sheets_ objectForKey:newViewValue];
  if (newSheetInfo) {
    NSWindow* overlayWindow = newSheetInfo->overlayWindow_;
    _GTMDevAssert(overlayWindow, @"New sheet info has no overlay window");
    NSWindow* sheetWindow = [overlayWindow attachedSheet];
    _GTMDevAssert(sheetWindow, @"New sheet info has no active sheet");

    [overlayWindow setIgnoresMouseEvents:NO];

    NSRect overlayFrame = [overlayWindow frame];
    newSheetInfo->sheetFrame_.origin.x += overlayFrame.origin.x;
    newSheetInfo->sheetFrame_.origin.y += overlayFrame.origin.y;
    [sheetWindow setFrame:newSheetInfo->sheetFrame_ display:NO];

    [[sheetWindow contentView]
        setAutoresizesSubviews:newSheetInfo->sheetAutoresizesSubviews_];

    [sheetWindow setAlphaValue:newSheetInfo->sheetAlpha_];

    [self viewDidChangeSize:view];

    [overlayWindow makeKeyWindow];
  }
}

@end

@implementation GTMWindowSheetController (PrivateMethods)

- (void)beginSystemSheet:(id)systemSheet
                withInfo:(const struct GTMWSCSystemSheetInfo*)info
            modalForView:(NSView*)view
          withParameters:(NSArray*)params {
  _GTMDevAssert([view window] == window_,
                @"Cannot show a sheet for a window for which we are not "
                @"managing sheets");
  _GTMDevAssert(![self isSheetAttachedToView:view],
                @"Cannot show another sheet for a view while already managing "
                @"one");
  _GTMDevAssert(info, @"Missing info for the type of sheet");

  GTMWSCSheetInfo* sheetInfo = [[[GTMWSCSheetInfo alloc] init] autorelease];

  sheetInfo->modalDelegate_ = [params objectAtIndex:info->modalDelegateIndex_];
  sheetInfo->didEndSelector_ =
      [[params objectAtIndex:info->didEndSelectorIndex_] pointerValue];
  sheetInfo->contextInfo_ =
      [[params objectAtIndex:info->contextInfoIndex_] pointerValue];

  _GTMDevAssert([sheetInfo->modalDelegate_
                  respondsToSelector:sheetInfo->didEndSelector_],
                @"Delegate does not respond to the specified selector");

  [view setPostsFrameChangedNotifications:YES];
  [[NSNotificationCenter defaultCenter]
      addObserver:self
         selector:@selector(notificationHappened:)
             name:NSViewFrameDidChangeNotification
           object:view];

  sheetInfo->overlayWindow_ =
      [[GTMWSCOverlayWindow alloc]
       initWithContentRect:[self screenFrameOfView:view]
           sheetController:self];

  [sheets_ setObject:sheetInfo
              forKey:[NSValue valueWithNonretainedObject:view]];

  [window_ addChildWindow:sheetInfo->overlayWindow_
                  ordered:NSWindowAbove];

  SEL methodSelector = NSSelectorFromString((NSString*)info->methodSignature_);
  NSInvocation* invocation =
      [NSInvocation invocationWithMethodSignature:
       [systemSheet methodSignatureForSelector:methodSelector]];
  [invocation setSelector:methodSelector];
  for (NSUInteger i = 0; i < [params count]; ++i) {
    // Remember that args 0 and 1 are the target and selector, thus the |i+2|s
    if (i == info->modalForWindowIndex_) {
      [invocation setArgument:&sheetInfo->overlayWindow_ atIndex:i+2];
    } else if (i == info->modalDelegateIndex_) {
      [invocation setArgument:&self atIndex:i+2];
    } else if (i == info->didEndSelectorIndex_) {
      if (info->arg1OfEndSelectorSize_ == 64)
        [invocation setArgument:&@selector(sheetDidEnd:returnCode64:contextInfo:)
                        atIndex:i+2];
      else if (info->arg1OfEndSelectorSize_ == 32)
        [invocation setArgument:&@selector(sheetDidEnd:returnCode32:contextInfo:)
                        atIndex:i+2];
      else if (info->arg1OfEndSelectorSize_ == 8)
        [invocation setArgument:&@selector(sheetDidEnd:returnCode8:contextInfo:)
                        atIndex:i+2];
    } else if (i == info->contextInfoIndex_) {
      [invocation setArgument:&view atIndex:i+2];
    } else {
      id param = [params objectAtIndex:i];
      if ([param isKindOfClass:[NSValue class]]) {
        char buffer[16];
        [param getValue:buffer];
        [invocation setArgument:buffer atIndex:i+2];
      } else {
        [invocation setArgument:&param atIndex:i+2];
      }
    }
  }
  [invocation invokeWithTarget:systemSheet];

  activeView_ = view;
}

- (const struct GTMWSCSystemSheetInfo*)infoForSheet:(id)systemSheet {
  static const struct GTMWSCSystemSheetInfo kGTMWSCSystemSheetInfoData[] =
  {
    {
      @"ABIdentityPicker",
      @"beginSheetModalForWindow:modalDelegate:didEndSelector:contextInfo:",
      0, 1, 2, 3, 64,
    },
    {
      @"CBIdentityPicker",
      @"runModalForWindow:modalDelegate:didEndSelector:contextInfo:",
      0, 1, 2, 3, 64,
    },
    {
      @"DRSetupPanel",
      @"beginSetupSheetForWindow:modalDelegate:didEndSelector:contextInfo:",
      0, 1, 2, 3, 32,
    },
    {
      @"NSAlert",
      @"beginSheetModalForWindow:modalDelegate:didEndSelector:contextInfo:",
      0, 1, 2, 3, 32,
    },
    {
      @"NSApplication",
      @"beginSheet:modalForWindow:modalDelegate:didEndSelector:contextInfo:",
      1, 2, 3, 4, 64,
    },
    {
      @"IKFilterBrowserPanel",
      @"beginSheetWithOptions:modalForWindow:modalDelegate:didEndSelector:contextInfo:",
      1, 2, 3, 4, 32,
    },
    {
      @"IKPictureTaker",
      @"beginPictureTakerSheetForWindow:withDelegate:didEndSelector:contextInfo:",
      0, 1, 2, 3, 64,
    },
    {
      @"IOBluetoothDeviceSelectorController",
      @"beginSheetModalForWindow:modalDelegate:didEndSelector:contextInfo:",
      0, 1, 2, 3, 32,
    },
    {
      @"IOBluetoothObjectPushUIController",
      @"beginSheetModalForWindow:modalDelegate:didEndSelector:contextInfo:",
      0, 1, 2, 3, 32,
    },
    {
      @"IOBluetoothServiceBrowserController",
      @"beginSheetModalForWindow:modalDelegate:didEndSelector:contextInfo:",
      0, 1, 2, 3, 32,
    },
    {
      @"NSOpenPanel",
      @"beginSheetForDirectory:file:types:modalForWindow:modalDelegate:didEndSelector:contextInfo:",
      3, 4, 5, 6, 32,
    },
    {
      @"NSPageLayout",
      @"beginSheetWithPrintInfo:modalForWindow:delegate:didEndSelector:contextInfo:",
      1, 2, 3, 4, 32,
    },
    {
      @"NSPrintOperation",
      @"ru32perationModalForWindow:delegate:didRunSelector:contextInfo:",
      0, 1, 2, 3, 8,
    },
    {
      @"NSPrintPanel",
      @"beginSheetWithPrintInfo:modalForWindow:delegate:didEndSelector:contextInfo:",
      1, 2, 3, 4, 32,
    },
    {
      @"NSSavePanel",
      @"beginSheetForDirectory:file:modalForWindow:modalDelegate:didEndSelector:contextInfo:",
      2, 3, 4, 5, 32,
    },
    {
      @"SFCertificatePanel",
      @"beginSheetForWindow:modalDelegate:didEndSelector:contextInfo:certificates:showGroup:",
      0, 1, 2, 3, 32,
    },
    {
      @"SFCertificateTrustPanel",
      @"beginSheetForWindow:modalDelegate:didEndSelector:contextInfo:trust:message:",
      0, 1, 2, 3, 32,
    },
    {
      @"SFChooseIdentityPanel",
      @"beginSheetForWindow:modalDelegate:didEndSelector:contextInfo:identities:message:",
      0, 1, 2, 3, 32,
    },
    {
      @"SFKeychainSettingsPanel",
      @"beginSheetForWindow:modalDelegate:didEndSelector:contextInfo:settings:keychain:",
      0, 1, 2, 3, 32,
    },
    {
      @"SFKeychainSavePanel",
      @"beginSheetForDirectory:file:modalForWindow:modalDelegate:didEndSelector:contextInfo:",
      2, 3, 4, 5, 32,
    },
  };

  static const size_t kGTMWSCSystemSheetInfoDataSize =
      sizeof(kGTMWSCSystemSheetInfoData)/sizeof(kGTMWSCSystemSheetInfoData[0]);

  for (size_t i = 0; i < kGTMWSCSystemSheetInfoDataSize; ++i) {
    Class testClass =
      NSClassFromString(kGTMWSCSystemSheetInfoData[i].className_);
    if (testClass && [systemSheet isKindOfClass:testClass]) {
      return &kGTMWSCSystemSheetInfoData[i];
    }
  }
  
  _GTMDevLog(@"Failed to find info for sheet of type %@", [systemSheet class]);
  return nil;
}

- (void)notificationHappened:(NSNotification*)notification {
  NSView *view = GTM_STATIC_CAST(NSView, [notification object]);
  [self viewDidChangeSize:view];
}

- (void)viewDidChangeSize:(NSView*)view {
  GTMWSCSheetInfo* sheetInfo =
      [sheets_ objectForKey:[NSValue valueWithNonretainedObject:view]];
  if (!sheetInfo)
    return;

  if (view != activeView_)
    return;

  NSWindow* overlayWindow = sheetInfo->overlayWindow_;
  if (!overlayWindow)
    return;

  [overlayWindow setFrame:[self screenFrameOfView:view] display:YES];
  [[overlayWindow attachedSheet] makeKeyWindow];
}

- (NSRect)screenFrameOfView:(NSView*)view {
  NSRect viewFrame = [view frame];
  viewFrame = [[view superview] convertRect:viewFrame toView:nil];
  viewFrame.origin = [[view window] convertBaseToScreen:viewFrame.origin];
  return viewFrame;
}

- (void)sheetDidEnd:(id)sheet
        returnCode8:(char)returnCode
        contextInfo:(void*)contextInfo {
  [self sheetDidEnd:sheet
         returnCode:returnCode
        contextInfo:contextInfo
           arg1Size:8];
}

- (void)sheetDidEnd:(id)sheet
       returnCode32:(int)returnCode
        contextInfo:(void*)contextInfo {
  [self sheetDidEnd:sheet
         returnCode:returnCode
        contextInfo:contextInfo
           arg1Size:32];
}

- (void)sheetDidEnd:(id)sheet
       returnCode64:(NSInteger)returnCode
        contextInfo:(void*)contextInfo {
  [self sheetDidEnd:sheet
         returnCode:returnCode
        contextInfo:contextInfo
           arg1Size:64];
}

- (void)sheetDidEnd:(id)sheet
         returnCode:(NSInteger)returnCode
        contextInfo:(void*)contextInfo
           arg1Size:(int)size {
  NSValue* viewKey = [NSValue valueWithNonretainedObject:(NSView*)contextInfo];
  GTMWSCSheetInfo* sheetInfo = [sheets_ objectForKey:viewKey];
  _GTMDevAssert(sheetInfo, @"Could not find information about the sheet that "
                           @"just ended");
  _GTMDevAssert(size == 8 || size == 32 || size == 64,
                @"Incorrect size information in the sheet entry; don't know "
                @"how big the second parameter is");

  // Can't turn off view's frame notifications as we don't know if someone else
  // wants them.
  [[NSNotificationCenter defaultCenter]
      removeObserver:self
                name:NSViewFrameDidChangeNotification
              object:contextInfo];

  NSInvocation* invocation =
      [NSInvocation invocationWithMethodSignature:
       [sheetInfo->modalDelegate_
        methodSignatureForSelector:sheetInfo->didEndSelector_]];
  [invocation setSelector:sheetInfo->didEndSelector_];
  // Remember that args 0 and 1 are the target and selector
  [invocation setArgument:&sheet atIndex:2];
  if (size == 64) {
    [invocation setArgument:&returnCode atIndex:3];
  } else if (size == 32) {
    int shortReturnCode = (int)returnCode;
    [invocation setArgument:&shortReturnCode atIndex:3];
  } else if (size == 8) {
    char charReturnCode = returnCode;
    [invocation setArgument:&charReturnCode atIndex:3];
  }
  [invocation setArgument:&sheetInfo->contextInfo_ atIndex:4];
  [invocation invokeWithTarget:sheetInfo->modalDelegate_];

  [window_ removeChildWindow:sheetInfo->overlayWindow_];
  [sheetInfo->overlayWindow_ release];

  [sheets_ removeObjectForKey:viewKey];
}

- (void)systemRequestsVisibilityForWindow:(NSWindow*)window {
  NSValue* key;
  GTM_FOREACH_KEY(key, sheets_) {
    GTMWSCSheetInfo* sheetInfo = [sheets_ objectForKey:key];
    if (sheetInfo->overlayWindow_ == window) {
      NSView* view = [key nonretainedObjectValue];
      [delegate_ gtm_systemRequestsVisibilityForView:view];
    }
  }
}

- (NSRect)window:(NSWindow*)window
willPositionSheet:(NSWindow*)sheet
       usingRect:(NSRect)defaultSheetRect {
  // Ensure that the sheets come out of the very top of the overlay windows.
  NSRect windowFrame = [window frame];
  defaultSheetRect.origin.y = windowFrame.size.height;
  return defaultSheetRect;
}

@end