0
# AppKit Framework
1
2
The Cocoa user interface framework providing comprehensive APIs for building native macOS applications. AppKit includes windows, views, controls, event handling, graphics, and all the components needed for rich desktop application development.
3
4
## Capabilities
5
6
### Utility Functions
7
8
Helper functions for common AppKit development tasks and convenient access to application-wide functionality.
9
10
```python { .api }
11
def NSDictionaryOfVariableBindings(*names):
12
"""
13
Creates a dictionary mapping variable names to their values from the calling scope.
14
Commonly used with Auto Layout visual format language.
15
16
Args:
17
*names (str): Variable names to include in dictionary
18
19
Returns:
20
dict: Dictionary with names as keys and variable values as values
21
22
Example:
23
button1 = NSButton.alloc().init()
24
button2 = NSButton.alloc().init()
25
views = NSDictionaryOfVariableBindings("button1", "button2")
26
# Returns: {"button1": button1, "button2": button2}
27
"""
28
```
29
30
### Application Instance
31
32
Global access to the shared application instance for application-wide operations and event handling.
33
34
```python { .api }
35
NSApp: object # Singleton NSApplication instance, equivalent to NSApplication.sharedApplication()
36
```
37
38
### Character Constants
39
40
Special character constants for keyboard input handling, converted to Python strings for convenient use in event processing and key binding systems.
41
42
```python { .api }
43
# Basic input characters
44
NSEnterCharacter: str # Enter/Return key character
45
NSBackspaceCharacter: str # Backspace key character
46
NSTabCharacter: str # Tab key character
47
NSNewlineCharacter: str # Newline character
48
NSFormFeedCharacter: str # Form feed character
49
NSCarriageReturnCharacter: str # Carriage return character
50
NSBackTabCharacter: str # Back tab (Shift+Tab) character
51
NSDeleteCharacter: str # Delete key character
52
NSLineSeparatorCharacter: str # Line separator character
53
NSParagraphSeparatorCharacter: str # Paragraph separator character
54
55
# Function keys F1-F35
56
NSF1FunctionKey: str # F1 function key
57
NSF2FunctionKey: str # F2 function key
58
NSF3FunctionKey: str # F3 function key
59
NSF4FunctionKey: str # F4 function key
60
NSF5FunctionKey: str # F5 function key
61
NSF6FunctionKey: str # F6 function key
62
NSF7FunctionKey: str # F7 function key
63
NSF8FunctionKey: str # F8 function key
64
NSF9FunctionKey: str # F9 function key
65
NSF10FunctionKey: str # F10 function key
66
NSF11FunctionKey: str # F11 function key
67
NSF12FunctionKey: str # F12 function key
68
NSF13FunctionKey: str # F13 function key
69
NSF14FunctionKey: str # F14 function key
70
NSF15FunctionKey: str # F15 function key
71
NSF16FunctionKey: str # F16 function key
72
NSF17FunctionKey: str # F17 function key
73
NSF18FunctionKey: str # F18 function key
74
NSF19FunctionKey: str # F19 function key
75
NSF20FunctionKey: str # F20 function key
76
NSF21FunctionKey: str # F21 function key
77
NSF22FunctionKey: str # F22 function key
78
NSF23FunctionKey: str # F23 function key
79
NSF24FunctionKey: str # F24 function key
80
NSF25FunctionKey: str # F25 function key
81
NSF26FunctionKey: str # F26 function key
82
NSF27FunctionKey: str # F27 function key
83
NSF28FunctionKey: str # F28 function key
84
NSF29FunctionKey: str # F29 function key
85
NSF30FunctionKey: str # F30 function key
86
NSF31FunctionKey: str # F31 function key
87
NSF32FunctionKey: str # F32 function key
88
NSF33FunctionKey: str # F33 function key
89
NSF34FunctionKey: str # F34 function key
90
NSF35FunctionKey: str # F35 function key
91
92
# Arrow keys
93
NSUpArrowFunctionKey: str # Up arrow key
94
NSDownArrowFunctionKey: str # Down arrow key
95
NSLeftArrowFunctionKey: str # Left arrow key
96
NSRightArrowFunctionKey: str # Right arrow key
97
98
# Special function keys
99
NSInsertFunctionKey: str # Insert key
100
NSDeleteFunctionKey: str # Delete function key
101
NSHomeFunctionKey: str # Home key
102
NSBeginFunctionKey: str # Begin key
103
NSEndFunctionKey: str # End key
104
NSPageUpFunctionKey: str # Page Up key
105
NSPageDownFunctionKey: str # Page Down key
106
NSPrintScreenFunctionKey: str # Print Screen key
107
NSScrollLockFunctionKey: str # Scroll Lock key
108
NSPauseFunctionKey: str # Pause key
109
NSSysReqFunctionKey: str # System Request key
110
NSBreakFunctionKey: str # Break key
111
NSResetFunctionKey: str # Reset key
112
NSStopFunctionKey: str # Stop key
113
NSMenuFunctionKey: str # Menu key
114
NSUserFunctionKey: str # User function key
115
NSSystemFunctionKey: str # System function key
116
NSPrintFunctionKey: str # Print function key
117
NSClearLineFunctionKey: str # Clear Line key
118
NSClearDisplayFunctionKey: str # Clear Display key
119
NSInsertLineFunctionKey: str # Insert Line key
120
NSDeleteLineFunctionKey: str # Delete Line key
121
NSInsertCharFunctionKey: str # Insert Character key
122
NSDeleteCharFunctionKey: str # Delete Character key
123
NSPrevFunctionKey: str # Previous key
124
NSNextFunctionKey: str # Next key
125
NSSelectFunctionKey: str # Select key
126
NSExecuteFunctionKey: str # Execute key
127
NSUndoFunctionKey: str # Undo key
128
NSRedoFunctionKey: str # Redo key
129
NSFindFunctionKey: str # Find key
130
NSHelpFunctionKey: str # Help key
131
NSModeSwitchFunctionKey: str # Mode Switch key
132
```
133
134
### Enhanced Font Descriptor
135
136
Python-friendly enhancements to NSFontDescriptor providing dictionary-like access to font attributes.
137
138
```python { .api }
139
# NSFontDescriptor enhancements (automatically available on NSFontDescriptor instances)
140
def __getitem__(self, key):
141
"""
142
Gets font attribute value for key using dictionary-style access.
143
144
Args:
145
key: Font attribute key (NSFontAttributeName constants)
146
147
Returns:
148
Font attribute value
149
150
Raises:
151
KeyError: If attribute key not found
152
"""
153
154
def get(self, key, default=None):
155
"""
156
Gets font attribute value with optional default.
157
158
Args:
159
key: Font attribute key
160
default: Value to return if key not found
161
162
Returns:
163
Font attribute value or default
164
"""
165
```
166
167
## Usage Examples
168
169
### Variable Bindings for Auto Layout
170
171
```python
172
import AppKit
173
174
# Create views
175
button1 = AppKit.NSButton.alloc().init()
176
button2 = AppKit.NSButton.alloc().init()
177
text_field = AppKit.NSTextField.alloc().init()
178
179
# Create variable bindings dictionary for visual format language
180
views = AppKit.NSDictionaryOfVariableBindings("button1", "button2", "text_field")
181
182
# Use with Auto Layout visual format
183
constraints = AppKit.NSLayoutConstraint.constraintsWithVisualFormat_options_metrics_views_(
184
"H:|-[button1]-[button2]-|",
185
0,
186
None,
187
views
188
)
189
```
190
191
### Application Instance Access
192
193
```python
194
import AppKit
195
196
# Access shared application instance
197
app = AppKit.NSApp # Equivalent to NSApplication.sharedApplication()
198
199
# Terminate application
200
app.terminate_(None)
201
202
# Set application delegate
203
app.setDelegate_(my_app_delegate)
204
205
# Handle application activation
206
app.activateIgnoringOtherApps_(True)
207
```
208
209
### Character Constants for Event Handling
210
211
```python
212
import AppKit
213
214
def keyDown_(self, event):
215
"""Handle key down events in a custom view."""
216
key_char = event.characters()
217
218
if key_char == AppKit.NSEnterCharacter:
219
self.handleEnterKey()
220
elif key_char == AppKit.NSBackspaceCharacter:
221
self.handleBackspaceKey()
222
elif key_char == AppKit.NSTabCharacter:
223
self.handleTabKey()
224
elif key_char in [AppKit.NSUpArrowFunctionKey, AppKit.NSDownArrowFunctionKey]:
225
self.handleArrowKeys(key_char)
226
elif key_char in [AppKit.NSF1FunctionKey, AppKit.NSF2FunctionKey]:
227
self.handleFunctionKeys(key_char)
228
229
def handleSpecialKeys(self, event):
230
"""Handle special function keys."""
231
key_char = event.characters()
232
233
function_keys = {
234
AppKit.NSF1FunctionKey: self.showHelp,
235
AppKit.NSF2FunctionKey: self.renameItem,
236
AppKit.NSF5FunctionKey: self.refreshView,
237
AppKit.NSF11FunctionKey: self.toggleFullScreen,
238
}
239
240
if key_char in function_keys:
241
function_keys[key_char]()
242
```
243
244
### Font Descriptor Enhancements
245
246
```python
247
import AppKit
248
249
# Create font descriptor
250
font_descriptor = AppKit.NSFontDescriptor.fontDescriptorWithName_size_("Helvetica", 12)
251
252
# Use dictionary-like access to font attributes
253
family_name = font_descriptor[AppKit.NSFontFamilyAttribute]
254
font_size = font_descriptor.get(AppKit.NSFontSizeAttribute, 12.0)
255
256
# Get font traits
257
traits = font_descriptor.get(AppKit.NSFontTraitsAttribute, {})
258
if traits:
259
weight = traits.get(AppKit.NSFontWeightTrait, 0.0)
260
slant = traits.get(AppKit.NSFontSlantTrait, 0.0)
261
```
262
263
### Window and View Management
264
265
```python
266
import AppKit
267
import Foundation
268
269
# Create application window
270
window = AppKit.NSWindow.alloc().initWithContentRect_styleMask_backing_defer_(
271
Foundation.NSMakeRect(100, 100, 600, 400),
272
AppKit.NSWindowStyleMaskTitled | AppKit.NSWindowStyleMaskClosable | AppKit.NSWindowStyleMaskResizable,
273
AppKit.NSBackingStoreBuffered,
274
False
275
)
276
277
# Configure window
278
window.setTitle_("My Application")
279
window.center()
280
window.makeKeyAndOrderFront_(None)
281
282
# Access application instance
283
AppKit.NSApp.activateIgnoringOtherApps_(True)
284
```
285
286
### Control Creation and Configuration
287
288
```python
289
import AppKit
290
import Foundation
291
292
# Create button with character constant for key equivalent
293
button = AppKit.NSButton.alloc().initWithFrame_(Foundation.NSMakeRect(20, 20, 100, 30))
294
button.setTitle_("OK")
295
button.setKeyEquivalent_(AppKit.NSEnterCharacter) # Enter key activates button
296
button.setTarget_(self)
297
button.setAction_("okButtonPressed:")
298
299
# Create text field
300
text_field = AppKit.NSTextField.alloc().initWithFrame_(Foundation.NSMakeRect(20, 60, 200, 22))
301
text_field.setStringValue_("Enter text here")
302
303
# Add to window content view
304
content_view = window.contentView()
305
content_view.addSubview_(button)
306
content_view.addSubview_(text_field)
307
```
308
309
### Event Handling with Special Characters
310
311
```python
312
import AppKit
313
314
class CustomView(AppKit.NSView):
315
def acceptsFirstResponder(self):
316
return True
317
318
def keyDown_(self, event):
319
characters = event.characters()
320
321
# Handle different types of input
322
if characters == AppKit.NSDeleteCharacter:
323
self.deleteSelection()
324
elif characters == AppKit.NSBackspaceCharacter:
325
self.backspaceAction()
326
elif characters in [AppKit.NSUpArrowFunctionKey, AppKit.NSDownArrowFunctionKey,
327
AppKit.NSLeftArrowFunctionKey, AppKit.NSRightArrowFunctionKey]:
328
self.handleArrowKey(characters)
329
elif characters.startswith(AppKit.NSF1FunctionKey[:1]): # Function key range
330
self.handleFunctionKey(characters)
331
else:
332
super(CustomView, self).keyDown_(event)
333
334
def handleArrowKey(self, arrow_char):
335
direction_map = {
336
AppKit.NSUpArrowFunctionKey: "up",
337
AppKit.NSDownArrowFunctionKey: "down",
338
AppKit.NSLeftArrowFunctionKey: "left",
339
AppKit.NSRightArrowFunctionKey: "right"
340
}
341
self.moveSelection(direction_map[arrow_char])
342
```
343
344
## Framework Coverage
345
346
AppKit provides comprehensive GUI capabilities including:
347
348
- **Windows and Panels**: NSWindow, NSPanel, and specialized window types
349
- **Views and Controls**: NSView hierarchy, buttons, text fields, tables, outlines
350
- **Menus and Toolbars**: NSMenu, NSMenuItem, NSToolbar with full customization
351
- **Drawing and Graphics**: NSBezierPath, NSImage, NSColor, graphics contexts
352
- **Text System**: NSTextView, NSTextField, rich text editing and formatting
353
- **Event Handling**: Mouse, keyboard, and touch events with responder chain
354
- **Application Lifecycle**: NSApplication, delegates, and application states
355
- **Document Architecture**: NSDocument, NSDocumentController for document-based apps
356
- **Printing**: NSPrintOperation, NSPrintInfo for document printing
357
- **Accessibility**: Full accessibility support for assistive technologies
358
359
All AppKit classes and constants are available through dynamic attribute access:
360
361
```python
362
import AppKit
363
364
# Access any AppKit class
365
window_class = AppKit.NSWindow
366
button_class = AppKit.NSButton
367
color_class = AppKit.NSColor
368
369
# Access constants
370
red_color = AppKit.NSColor.redColor()
371
app_kit_version = AppKit.NSAppKitVersionNumber
372
```