// Small demo of nibless menu creation in ObjP. The "2" refered to an even simpler
// version which didn't have any custom items and thus no menu controller class.
// By Ingemar Ragnemalm 2009

// This was a test program I write when figuring out how to build menus from code.
// I don't recommend this code for general use. Building menus in Cocoa is inexcusably
// messy, so either you build your menus in Interface Builder, or though TransSkel.

program MiniMenu2;
{$mode objfpc}
{$modeswitch objectivec1}
uses
	CocoaAll, ctypes, MacOSAll;

// Mini-mini class for collecting events
type
	TMenuController = objcclass(NSObject)
	public
		procedure selectMenuItem (sender: id); message 'selectMenuItem:';
	end;

procedure TMenuController.selectMenuItem (sender: id);
begin
	WriteLn('Menu selection detected');
end;

var
	NSApp: NSApplication;
	pool: NSAutoreleasePool;
	
var
	myController: TMenuController;
	mainMenu, theMiniMenu: NSMenu;
	menuItem1, menuItem2: NSMenuItem;
	dummyItem: NSMenuItem;
begin
	pool := NSAutoreleasePool.new;
	NSApp := NSApplication.sharedApplication;
	
	// Allocate controller
	myController := TMenuController.alloc; // Create();
	
	// Create main menu = menu bar
	mainMenu := NSMenu.alloc;
	mainMenu.initWithTitle(NSString(CFSTR('')));
	NSApp.setMainMenu(mainMenu);
	
	// Create the custom menu
	theMiniMenu := NSMenu.alloc;
	theMiniMenu.initWithTitle(NSString(CFSTR('The MiniMenu')));
	
	// Create a menu item
	menuItem1 := NSMenuItem.alloc;
	menuItem1.initWithTitle_action_keyEquivalent(NSString(CFSTR('Item Text')), nil, NSString(CFSTR('')));
	menuItem1.setTarget(myController); // Who will handle it?
	menuItem1.setAction(sel_registerName(PChar('selectMenuItem:'))); // What method will handle it?
	theMiniMenu.addItem(menuItem1);
	
	// Create another menu item with standard message
	menuItem2 := NSMenuItem.alloc;
	menuItem2.initWithTitle_action_keyEquivalent(NSString(CFSTR('Quit')), nil, NSString(CFSTR('q')));
	menuItem2.setKeyEquivalentModifierMask(NSCommandKeyMask);
	menuItem2.setAction(sel_registerName(PChar('terminate:')));
	theMiniMenu.addItem(menuItem2);
	
	// Adding a menu is done with a dummy item to connect the menu to its parent
	dummyItem := NSMenuItem.alloc;
	dummyItem.initWithTitle_action_keyEquivalent(NSString(CFSTR('')), nil, NSString(CFSTR('')));
	dummyItem.setSubmenu(theMiniMenu);
	mainMenu.addItem(dummyItem);
	
	NSApp.run;
	pool.dealloc;
end.
