//
//	MiscBundleLoader.m -- an object category to load .bundle files with
//			code for a specific ObjC class in them
//		Written by Mike Ferris (c) 1994 by Mike Ferris.
//		Unburied from original MOKit by Don Yacktman.
//				Version 1.0.  All rights reserved.
//
//		This notice may not be removed from this source code.
//
//	This object is included in the MiscKit by permission from the author
//	and its use is governed by the MiscKit license, found in the file
//	"LICENSE.rtf" in the MiscKit distribution.  Please refer to that file
//	for a list of all applicable permissions and restrictions.
//	


// Category to load bundle-ized objects into apps dynamically.  Just
// ask for the object by name...
// This was originally in Mike Ferris' MOKit code, where it was well hidden...

#import <misckit/MiscBundleLoader.h>
#import <appkit/nextstd.h>
#import <objc/NXBundle.h>
#import <objc/objc-runtime.h>
#import <sys/param.h>		// for MAXPATHLEN

#define BUNDLE_TYPE							"bundle"

@implementation Object(MiscBundleLoader)

+ (Class)loadClassBundle:(const char *)className
// Finds the bundle of the same name as className, grabs it and loads the
// class from it and returns the named class.
{
	char pathBuff[MAXPATHLEN + 1];
	id classBundle = nil;
	Class class = nil;
	
	// Load the bundle
	if ((class = objc_lookUpClass(className)) == nil)  {
		// class is not already loaded... load it.
		
		// Look for the bundle in the main bundle first, 
		// else try in this class's bundle.
		if (![[NXBundle mainBundle] getPath:pathBuff forResource:className 
					ofType:BUNDLE_TYPE]) {
			if (![[NXBundle bundleForClass:[self class]] getPath:pathBuff 
						forResource:className ofType:BUNDLE_TYPE]) {
				NXLogError("[%s loadClassBundle] failed to "
						"find %s class bundle.", [self name], className);
				return nil;
			}
		}
		classBundle = [[NXBundle allocFromZone:[self zone]] 
					initForDirectory:pathBuff];
		if (!classBundle) {
			NXLogError("[%s loadClassBundle] failed to "
						"create bundle for class %s.", [self name], className);
			return nil;
		}
		if ((class = [classBundle classNamed:className]) == nil) {
			NXLogError("[%s loadClassBundle] failed to "
						"load %s class from bundle.", [self name], className);
			return nil;
		}
	}
	return class;
}

@end
