Source

pyobjc / pyobjc / Scripts / CodeGenerators / cocoa_generator.py

Full commit
  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
# 
# This script generates part of the python-wrappers around Cocoa.
#
# This script is based on some (not to clever) regular expressions, and seems
# to work pretty well with the current version of the Cocoa headers.
#
# NOTES:
# - This script is probably MacOSX specific.
# - This script should be rewritten, it's getting unmaintainable.
#
import enum_generator
import strconst_generator
import var_generator
import func_collector
import func_builder
import os
import sys
from dupfile import dupfile

#
# This script contains some MacOS X version dependencies. Because uname
# doesn't tell anything usefull, we use sw_vers to find the actual OS version.
#
import os
import sys
VER=None

if sys.platform == "darwin":
    fd = os.popen('/usr/bin/sw_vers', 'r')
    for ln in fd.readlines():
            if ln.startswith('ProductVersion:'):
		VER=ln.split()[-1]
    fd.close()
    fd = None
    VER = 'MacOS X ' + '.'.join(VER.split('.')[:2])
else:
    # This is probably incorrect, and was added to help a future 
    # port to GNUstep
    x = os.uname()
    VER = x[0] + ' ' + x[2]

if not os.path.isdir('Modules'):
    print "Run me from the root of the PyObjC source tree"
    sys.exit(1)

if not os.path.exists('build'):
    os.mkdir('build')

if not os.path.exists('build/codegen'):
    os.mkdir('build/codegen')

FRAMEWORKS="/System/Library/Frameworks"
FOUNDATION=os.path.join(FRAMEWORKS, "Foundation.framework")
APPKIT=os.path.join(FRAMEWORKS, "AppKit.framework")
ADDRESSBOOK=os.path.join(FRAMEWORKS, "AddressBook.framework")
PREFPANES=os.path.join(FRAMEWORKS, "PreferencePanes.framework")
WEBKIT=os.path.join(FRAMEWORKS, "WebKit.framework")
IB=os.path.join(FRAMEWORKS, "InterfaceBuilder.framework")
FOUNDATION_HDRS=os.path.join(FOUNDATION, 'Headers')
ADDRESSBOOK_HDRS=os.path.join(ADDRESSBOOK, 'Headers')
APPKIT_HDRS=os.path.join(APPKIT, 'Headers')
PREFPANES_HDRS=os.path.join(PREFPANES, 'Headers')
IB_HDRS=os.path.join(IB, 'Headers')
WEBKIT_HDRS=os.path.join(WEBKIT, 'Headers')

def filterAddressBookHeaders(fn):
    if fn[-3:] == 'C.h':
        return 0

    if fn == 'ABPeoplePickerView.h':
        return 0

    return 1

enum_generator.generate(FOUNDATION_HDRS, 'build/codegen/_Fnd_Enum.inc')
enum_generator.generate(APPKIT_HDRS, 'build/codegen/_App_Enum.inc')
enum_generator.generate(ADDRESSBOOK_HDRS,
                        'build/codegen/_Addr_Enum.inc',
                        filter=filterAddressBookHeaders)
enum_generator.generate(PREFPANES_HDRS, 
                        'build/codegen/_PreferencePanes_Enum.inc')
enum_generator.generate(IB_HDRS, 
                        'build/codegen/_InterfaceBuilder_Enum.inc')
enum_generator.generate(WEBKIT_HDRS, 
                        'build/codegen/_WebKit_Enum.inc')

strconst_generator.generate(FOUNDATION_HDRS, 'build/codegen/_Fnd_Str.inc')
strconst_generator.generate(APPKIT_HDRS, 'build/codegen/_App_Str.inc')
strconst_generator.generate(ADDRESSBOOK_HDRS,
                            'build/codegen/_Addr_Str.inc',
                            filter=filterAddressBookHeaders)
strconst_generator.generate(PREFPANES_HDRS, 
                        'build/codegen/_PreferencePanes_Str.inc')
strconst_generator.generate(IB_HDRS, 'build/codegen/_InterfaceBuilder_Str.inc')

# The two items on the ignore-list cause link errors, to-be-investigated.
strconst_generator.generate(WEBKIT_HDRS,
                            'build/codegen/_WebKit_Str.inc',
                            ignore=('WebElementImageAltStringKey', 
                                    'WebPreferencesChangedNotification')
)

FOUNDATION_PREFIX="FOUNDATION_EXPORT"
FOUNDATION_IGNORE_LIST=(
    # All have types that are not (yet) mapped to python
    'NSZeroPoint',
    'NSZeroSize',
    'NSZeroRect',
    "NSNonOwnedPointerHashCallBacks",
    "NSNonRetainedObjectHashCallBacks",
    "NSObjectHashCallBacks",
    "NSOwnedObjectIdentityHashCallBacks",
    "NSOwnedPointerHashCallBacks",
    "NSPointerToStructHashCallBacks",
    "NSIntMapKeyCallBacks",
    "NSNonOwnedPointerMapKeyCallBacks",
    "NSNonOwnedPointerOrNullMapKeyCallBacks",
    "NSNonRetainedObjectMapKeyCallBacks",
    "NSObjectMapKeyCallBacks",
    "NSOwnedPointerMapKeyCallBacks",
    "NSIntMapValueCallBacks", 
    "NSNonOwnedPointerMapValueCallBacks",
    "NSObjectMapValueCallBacks",
    "NSNonRetainedObjectMapValueCallBacks",
    "NSOwnedPointerMapValueCallBacks",
    "NSIntHashCallBacks",
    "NSHangOnMallocError",
)

var_generator.generate(FOUNDATION_HDRS, 'build/codegen/_Fnd_Var.inc', FOUNDATION_PREFIX, FOUNDATION_IGNORE_LIST)

APPKIT_PREFIX="APPKIT_EXTERN"
APPKIT_IGNORE_LIST=(
    # First two have types that are not yet mapped
    'NSIconSize', 
    'NSTokenSize', 

    # NSApp is a 'real' variable, will probably add get/set functions
    'NSApp')

var_generator.generate(APPKIT_HDRS, 
            'build/codegen/_App_Var.inc', APPKIT_PREFIX, APPKIT_IGNORE_LIST)

FOUNDATION_IGNORE_LIST=(
    # Private functions 
    '_NSAddHandler2(',
    '_NSRemoveHandler2(',
    '_NSExceptionObjectFromHandler2(',
    '_NSAutoreleaseNoPool(',
    '_NSAutoreleaseFreedObject(',
    '_NSAutoreleaseHighWaterLog(',
    'NXReadNSObjectFromCoder(',


    # List of functions that are not usefull from Python:
    'NSFrameAddress(',
    'NSReturnAddress(',
    'NSRecordAllocationEvent(',
    'NSCreateHashTableWithZone(',
    'NSCreateHashTable(',
    'NSFreeHashTable(',
    'NSResetHashTable(',
    'NSCompareHashTables(',
    'NSCopyHashTableWithZone(',
    'NSHashGet(',
    'NSHashInsert(',
    'NSHashInsertKnownAbsent(',
    'NSHashInsertIfAbsent(',
    'NSHashRemove(',
    'NSEnumerateHashTable(',
    'NSNextHashEnumeratorItem(',
    'NSEndHashTableEnumeration(',
    'NSCountHashTable(',
    'NSStringFromHashTable(',
    'NSAllHashTableObjects(',
    'NSJavaClassesFromPath(',
    'NSJavaClassesForBundle(',
    'NSCreateMapTableWithZone(',
    'NSCreateMapTable(',
    'NSFreeMapTable(',
    'NSResetMapTable(',
    'NSCompareMapTables(',
    'NSCopyMapTableWithZone(',
    'NSMapMember(',
    'NSMapGet(',
    'NSMapInsert(',
    'NSMapInsertKnownAbsent(',
    'NSMapInsertIfAbsent(',
    'NSMapRemove(',
    'NSEnumerateMapTable(',
    'NSNextMapEnumeratorPair(',
    'NSEndMapTableEnumeration(',
    'NSCountMapTable(',
    'NSStringFromMapTable(',
    'NSAllMapTableKeys(',
    'NSAllMapTableValues(',
    'NSGetSizeAndAlignment(', # Hmm, shouldn't we use this in the bridge?
    'NSLogv(',
    'NSAllocateObject(',
    'NSCopyObject(',
    'NSShouldRetainWithZone(',
    'NSAllocateMemoryPages(',
    'NSDeallocateMemoryPages(',
    'NSCopyMemoryPages(',


    # List of manually wrapped functions:
    'NSFileTypeForHFSTypeCode(',
    'NSHFSTypeCodeFromFileType(',
    'NSStringFromPoint',
    'NSDivideRect(',

    # NSDecimal support, should wrap type
    'NSDecimalCopy(',
    'NSDecimalCompact(',
    'NSDecimalCompare(',
    'NSDecimalRound(',
    'NSDecimalNormalize(',
    'NSDecimalAdd(',
    'NSDecimalSubtract(',
    'NSDecimalMultiply(',
    'NSDecimalDivide(',
    'NSDecimalPower(',
    'NSDecimalMultiplyByPowerOf10(',
    'NSDecimalString(',

    # Zones might be usefull someday
    'NSCreateZone(',
    'NSRecycleZone(',
    'NSSetZoneName(',
    'NSZoneName(',
    'NSZoneFromPointer(',
    'NSZoneMalloc(',
    'NSZoneCalloc(',
    'NSZoneRealloc(',
    'NSZoneFree(',


    # TODO
    'NSUncaughtExceptionHandler(',
    'NSSetUncaughtExceptionHandler(',
    'NSGetUncaughtExceptionHandler(',
    'NSDefaultMallocZone(',
)


APPKIT_IGNORE_LIST=(
    # List of manually wrapped functions:
    'NSApplicationMain(',
    'NSCountWindows(',
    'NSCountWindowsForContext(',
    'NSAvailableWindowDepths(',
    'NSRectFillList(',
    'NSGetWindowServerMemory(',


    #TODO:
    'NSBestDepth (',
    'NSAvailableWindowDepths (',
    'NSRectFillListWithGrays(',
    'NSRectFillListWithColors(',
    'NSRectFillListUsingOperation(',
    'NSRectFillListWithColorsUsingOperation(',
    'NSRectClipList(',
    'NSDrawTiledRects(',
    'NSDrawBitmap(',
    'NSWindowList(',
    'NSWindowListForContext(',
    'NSDrawColorTiledRects(',
)

if VER == "MacOS X 10.1":
	APPKIT_IGNORE_LIST = APPKIT_IGNORE_LIST + ('NSCopyBitmapFromGState',)

func_collector.generate(FOUNDATION_HDRS, 'build/codegen/Foundation.prototypes', 
    FOUNDATION_PREFIX, FOUNDATION_IGNORE_LIST)
func_collector.generate(FOUNDATION_HDRS, 'build/codegen/Foundation.prototype2', 
    'FOUNDATION_STATIC_INLINE', FOUNDATION_IGNORE_LIST)
func_collector.generate(APPKIT_HDRS, 'build/codegen/AppKit.prototypes', 
    APPKIT_PREFIX, APPKIT_IGNORE_LIST)


func_builder.INT_ALIASES.extend([
    'NSSearchPathDomainMask', 'NSCalculationError',
    'NSComparisonResult', 'NSInsertionPosition',
    'NSNotificationCoalescing', 'NSNotificationCoalescing',
    'NSRectEdge', 'NSRelativePosition',
    'NSRoundingMode', 'NSSaveOptions', 'NSSearchPathDirectory',
    'NSSearchPathDomainMask', 'NSTestComparisonOperation',
    'NSURLHandleStatus', 'NSWhoseSubelementIdentifier']
)
func_builder.IGNORE_VARARGS.extend([
    # Some of these are Foundation some are AppKit
    'NSGetInformationalAlertPanel',
    'NSLog',
    'NSRunAlertPanel',
    'NSRunInformationalAlertPanel',
    'NSRunCriticalAlertPanel',
    'NSRunAlertPanelRelativeToWindow',
    'NSRunInformationalAlertPanelRelativeToWindow',
    'NSRunCriticalAlertPanelRelativeToWindow',
    'NSBeginAlertSheet',
    'NSBeginInformationalAlertSheet',
    'NSBeginCriticalAlertSheet',
    'NSGetAlertPanel',
    'NSGetCriticalAlertPanel',
])

def BeginSheetMapper(funcname, args):
    new_args = []
    for tp, name in args:
        if name == 'contextInfo':
            tp = 'PYOBJC_VOIDPTR'
        new_args.append((tp, name))
    return tuple(new_args)
func_builder.FUNC_MAP['NSBeginAlertSheet'] = BeginSheetMapper
func_builder.FUNC_MAP['NSBeginInformationalAlertSheet'] = BeginSheetMapper
func_builder.FUNC_MAP['NSBeginCriticalAlertSheet'] = BeginSheetMapper

fd = dupfile('build/codegen/_Fnd_Functions.inc', 'w')
structs = ['NSPoint', 'NSSize', 'NSRect', 'NSRange', 'NSSwappedDouble', 'NSSwappedFloat']
for s in structs:
    func_builder.SIMPLE_TYPES[s] = (
        '\tresult = PyObjC_ObjCToPython(@encode(%s), (void*)&%%(varname)s); \n\tif (result == NULL) return NULL;'%s,
        'O&',
        'convert_%s, &%%(varname)s'%s
    )
    fd.write('''\

static inline int convert_%(type)s(PyObject* object, void* pvar)
{
        int err;

        err = PyObjC_PythonToObjC(@encode(%(type)s), object, pvar);
        if (err == -1) {
                return 0;
        }
        return 1;
}
'''%{'type': s })

fd.write('typedef void* PYOBJC_VOIDPTR;\n')

funcs = func_builder.process_list(fd , file('build/codegen/Foundation.prototypes'))
funcs2 = func_builder.process_list(fd , file('build/codegen/Foundation.prototype2'))
func_builder.gen_method_table_entries(fd, funcs + funcs2)
fd = None
for s in structs:
    del func_builder.SIMPLE_TYPES[s]

fd = dupfile('build/codegen/_App_Functions.inc', 'w')
structs = ['NSAffineTransformStruct', 'NSRect', 'NSPoint']
for s in structs:
    func_builder.SIMPLE_TYPES[s] = (
        '\tresult = PyObjC_ObjCToPython(@encode(%s), (void*)&%%(varname)s); \n\tif (result == NULL) return NULL;'%s,
        'O&',
        'convert_%s, &%%(varname)s'%s
    )
    fd.write('''\
static inline int convert_%(type)s(PyObject* object, void* pvar)
{
        int err;

        err = PyObjC_PythonToObjC(@encode(%(type)s), object, pvar);
        if (err == -1) {
                return 0;
        }
        return 1;
}
'''%{'type': s })

func_builder.INT_ALIASES.extend([
    'NSApplicationTerminateReply', 'NSBackingStoreType',
    'NSBezelStyle', 'NSBezierPathElement',
    'NSBitmapImageFileType', 'NSBorderType', 'NSBoxType',
    'NSButtonType', 'NSCellAttribute', 'NSCellImagePosition',
    'NSCellStateValue', 'NSCellType', 'NSCompositingOperation',
    'NSControlSize', 'NSControlTint', 'NSDocumentChangeType',
    'NSDragOperation', 'NSDrawerState', 'NSEventType',
    'NSFocusRingPlacement', 'NSFontAction', 'NSFontTraitMask',
    'NSGlyph', 'NSGlyphInscription', 'NSGlyphLayoutMode',
    'NSGlyphRelation', 'NSGradientType', 'NSImageAlignment',
    'NSImageFrameStyle', 'NSImageInterpolation', 'NSImageScaling',
    'NSInterfaceStyle', 'NSLayoutDirection', 'NSLayoutStatus',
    'NSLineBreakMode', 'NSLineCapStyle', 'NSLineJoinStyle',
    'NSLineMovementDirection', 'NSLineSweepDirection',
    'NSMatrixMode', 'NSMultibyteGlyphPacking', 'NSOpenGLContextParameter',
    'NSOpenGLGlobalOption', 'NSOpenGLPixelFormatAttribute',
    'NSPopUpArrowPosition', 'NSPrinterTableStatus',
    'NSPrintingOrientation', 'NSPrintingPageOrder', 
    'NSPrintingPaginationMode', 'NSProgressIndicatorThickness',
    'NSQTMovieLoopMode', 'NSRequestUserAttentionType',
    'NSRulerOrientation', 'NSSaveOperationType',
    'NSScrollArrowPosition', 'NSScrollerArrow',
    'NSScrollerPart', 'NSSelectionAffinity',
    'NSSelectionDirection', 'NSSelectionGranularity',
    'NSTabState', 'NSTabViewState', 'NSTableViewDropOperation',
    'NSTextAlignment', 'NSTextTabType', 'NSTickMarkPosition',
    'NSTIFFCompression', 'NSTitlePosition', 'NSToolbarDisplayMode',
    'NSToolTipTag', 'NSTrackingRectTag', 'NSUsableScrollerParts',
    'NSWindingRule', 'NSWindowDepth', 'NSWindowOrderingMode',
])


fd.write('typedef void* PYOBJC_VOIDPTR;\n')
funcs = func_builder.process_list(fd, file('build/codegen/AppKit.prototypes'))
func_builder.gen_method_table_entries(fd, funcs)
for s in structs:
    del func_builder.SIMPLE_TYPES[s]