Fixed respondsToSelector() @selectors...
authorMark Sibly <blitzmunter@gmail.com>
Sun, 20 Sep 2015 06:49:17 +0000 (18:49 +1200)
committerMark Sibly <blitzmunter@gmail.com>
Sun, 20 Sep 2015 06:49:17 +0000 (18:49 +1200)
mod/maxgui.mod/cocoamaxgui.mod/cocoa.macos_tiger.m

index 440e131de9fb236abbafbcda54e72ccfde000229..452b9ddf853ff9207ecdd946c42b66ae7181a3b1 100644 (file)
-// cocoa.macos.m\r
-// blitzmax cocoa interface \r
-// by simonarmstrong@blitzbasic.com\r
-\r
-#include <AppKit/AppKit.h>\r
-#include <WebKit/WebView.h>\r
-#include <WebKit/WebFrame.h>a\r
-#include <WebKit/WebPolicyDelegate.h>\r
-#include <WebKit/WebFrameLoadDelegate.h>\r
-#include <WebKit/WebDataSource.h>\r
-#include <ApplicationServices/ApplicationServices.h>\r
-\r
-#include <brl.mod/blitz.mod/blitz.h>\r
-#include <maxgui.mod/maxgui.mod/maxgui.h>\r
-#include <pub.mod/macos.mod/macos.h>\r
-\r
-#define STATUSBARHEIGHT 18\r
-\r
-// Custom Cursor Stuff\r
-\r
-const int curNoEntry = 0;\r
-const int curHelp = 1;\r
-const int curSizeAll = 2;\r
-const int curNESW = 3;\r
-const int curNWSE = 4;\r
-\r
-typedef struct { short bits[16]; short mask[16]; short hitpoint[2]; } ArrayCursor;\r
-\r
-ArrayCursor arrCursors[5] =\r
-{{{0x0000, 0x07E0, 0x1FF0, 0x3838, 0x3C0C, 0x6E0E, 0x6706, 0x6386, 0x61C6, 0x60E6, 0x7076, 0x303C, 0x1C1C, 0x0FF8, 0x07E0, 0x0000},\r
-{0x0540, 0x0FF0, 0x3FF8, 0x3C3C, 0x7E0E, 0xFF0F, 0x6F86, 0xE7C7, 0x63E6, 0xE1F7, 0x70FE, 0x707E, 0x3C3C, 0x1FFC, 0x0FF0, 0x0540},\r
-{0x0007, 0x0007}},\r
-{{0x0000, 0x4078, 0x60FC, 0x71CE, 0x7986, 0x7C06, 0x7E0E, 0x7F1C, 0x7FB8, 0x7C30, 0x6C30, 0x4600, 0x0630, 0x0330, 0x0300, 0x0000},\r
-{0xC078, 0xE0FC, 0xF1FE, 0xFBFF, 0xFFCF, 0xFF8F, 0xFF1F, 0xFFBE, 0xFFFC, 0xFE78, 0xFF78, 0xEFF8, 0xCFF8, 0x87F8, 0x07F8, 0x0300},\r
-{0x0001, 0x0001}},\r
-{{0x0000, 0x0080, 0x01C0, 0x03E0, 0x0080, 0x0888, 0x188C, 0x3FFE, 0x188C, 0x0888, 0x0080, 0x03E0, 0x01C0, 0x0080, 0x0000, 0x0000},\r
-{0x0080, 0x01C0, 0x03E0, 0x07F0, 0x0BE8, 0x1DDC, 0x3FFE, 0x7FFF, 0x3FFE, 0x1DDC, 0x0BE8, 0x07F0, 0x03E0, 0x01C0, 0x0080, 0x0000},\r
-{0x0007, 0x0008}},\r
-{{0x0000, 0x001E, 0x000E, 0x060E, 0x0712, 0x03A0, 0x01C0, 0x00E0, 0x0170, 0x1238, 0x1C18, 0x1C00, 0x1E00, 0x0000, 0x0000, 0x0000},\r
-{0x007F, 0x003F, 0x0E1F, 0x0F0F, 0x0F97, 0x07E3, 0x03E1, 0x21F0, 0x31F8, 0x3A7C, 0x3C3C, 0x3E1C, 0x3F00, 0x3F80, 0x0000, 0x0000},\r
-{0x0006, 0x0009}},\r
-{{0x0000, 0x7800, 0x7000, 0x7060, 0x48E0, 0x05C0, 0x0380, 0x0700, 0x0E80, 0x1C48, 0x1838, 0x0038, 0x0078, 0x0000, 0x0000, 0x0000},\r
-{0xFE00, 0xFC00, 0xF870, 0xF0F0, 0xE9F0, 0xC7E0, 0x87C0, 0x0F84, 0x1F8C, 0x3E5C, 0x3C3C, 0x387C, 0x00FC, 0x01FC, 0x0000, 0x0000},\r
-{0x0006, 0x0006}}};\r
-\r
-// End of Cursor Stuff\r
-\r
-\r
-void brl_event_EmitEvent( BBObject *event );\r
-BBObject *maxgui_maxgui_HotKeyEvent( int key,int mods );\r
-void maxgui_maxgui_DispatchGuiEvents();\r
-void maxgui_cocoamaxgui_EmitCocoaOSEvent( NSEvent *event,void *handle,BBObject *gadget );\r
-int maxgui_cocoamaxgui_EmitCocoaMouseEvent( NSEvent *event,void *handle );\r
-int maxgui_cocoamaxgui_EmitCocoaKeyEvent( NSEvent *event,void *handle );\r
-void maxgui_cocoamaxgui_PostCocoaGuiEvent( int ev,void *handle,int data,int mods,int x,int y,BBObject *extra );\r
-\r
-int maxgui_cocoamaxgui_FilterChar( void *handle,int key,int mods );\r
-int maxgui_cocoamaxgui_FilterKeyDown( void *handle,int key,int mods );\r
-\r
-static void EmitOSEvent( NSEvent *event,void *handle ){\r
-       maxgui_cocoamaxgui_EmitCocoaOSEvent( event,handle,&bbNullObject );\r
-}\r
-\r
-int HaltMouseEvents;\r
-\r
-static int EmitMouseEvent( NSEvent *event,void *handle ){\r
-       if(([event type] == NSScrollWheel) && ([event deltaY] == 0)) return 0;\r
-       if(!HaltMouseEvents) return maxgui_cocoamaxgui_EmitCocoaMouseEvent( event,handle );\r
-}\r
-\r
-static int EmitKeyEvent( NSEvent *event,void *handle ){\r
-       return maxgui_cocoamaxgui_EmitCocoaKeyEvent( event,handle );\r
-}\r
-\r
-static void PostGuiEvent( int ev,void *handle,int data,int mods,int x,int y,BBObject *extra ){\r
-       if (extra==0) extra=&bbNullObject;\r
-       maxgui_cocoamaxgui_PostCocoaGuiEvent( ev,handle,data,mods,x,y,extra );\r
-}\r
-\r
-static int filterKeyDownEvent( NSEvent *event,id source ){\r
-       int i,sz,res,key,mods;\r
-       NSString *ch;\r
-       key=bbSystemTranslateKey( [event keyCode] );\r
-       mods=bbSystemTranslateMods( [event modifierFlags] );\r
-       res=maxgui_cocoamaxgui_FilterKeyDown( source,key,mods );\r
-       if (res==0) return 0;\r
-       ch=[event characters];\r
-       sz=[ch length];\r
-       for( i=0;i<sz;++i ){\r
-               key=[ch characterAtIndex:i];\r
-               switch( key ){\r
-                       case 3:key=13;break;    //Brucey's numberpad enter-key hack\r
-                       case 127:key=8;break;\r
-                       case 63272:key=127;break;\r
-               }\r
-               res=maxgui_cocoamaxgui_FilterChar( source,key,mods );\r
-               if (res==0) return 0;\r
-       }\r
-       return 1;\r
-}\r
-\r
-void NSRelease( NSObject *obj ){[obj release];}\r
-\r
-typedef struct nsgadget nsgadget;\r
-\r
-struct nsgadget{\r
-// BBObject\r
-       BBClass*        clas;\r
-       int                     refs;\r
-// gadget\r
-       BBObject        *target;        \r
-       nsgadget        *group;\r
-       BBObject        *kidlist;\r
-       int                     x,y,w,h;\r
-       BBString                *textarg;\r
-       void                    *extra;\r
-       int                     style, sensitivity;\r
-       int                     visible,total;\r
-       int                     lockl,lockr,lockt,lockb;\r
-       int                     lockx,locky,lockw,lockh,lockcw,lockch;\r
-       void                    *filter,*context;\r
-       void                    *items;\r
-       int                     *arrPrevSelection;\r
-       BBObject                *datasource;\r
-       void                    *datakeys;//$[]\r
-// nsGadget\r
-       int                     internalclass, origclass;\r
-       id                      handle;         \r
-       NSView          *view;\r
-       NSColor         *textcolor;\r
-       int                     intFontStyle;\r
-};\r
-\r
-// prototypes\r
-\r
-void NSClearItems(nsgadget *gadget);\r
-\r
-void NSSetSelection(nsgadget *gadget,int pos,int length,int units);\r
-\r
-@class CocoaApp;\r
-@class FlippedView;\r
-@class PanelView;\r
-@class CanvasView;\r
-@class ListView;\r
-@class TreeView;\r
-@class NodeItem;\r
-@class TextView;\r
-@class TabView;\r
-@class WindowView;\r
-@class ImageString;\r
-@class TableView;\r
-@class ToolView;\r
-@class Scroller;\r
-\r
-@interface CocoaApp:NSObject{\r
-       NSMutableDictionary     *toolbaritems;\r
-       NSMutableArray          *menuitems;\r
-}\r
--(id)init;\r
-+(void)delayedGadgetAction:(NSNotification*)n;\r
-+(void)dispatchGuiEvents;\r
--(BOOL)windowShouldClose:(id)sender;\r
--(void)windowDidResize:(NSNotification *)aNotification;\r
--(void)windowDidMove:(NSNotification *)aNotification;\r
--(BOOL)windowShouldZoom:(NSWindow *)sender toFrame:(NSRect)newFrame;\r
--(void)windowDidBecomeKey:(NSNotification *)aNotification;\r
--(void)menuSelect:(id)sender;\r
--(void)iconSelect:(id)sender;\r
--(void)sliderSelect:(id)sender;\r
--(void)scrollerSelect:(id)sender;\r
--(void)buttonPush:(id)sender;\r
--(void)textEdit:(id)sender;\r
--(void)comboBoxSelectionDidChange:(NSNotification *)notification;\r
--(void)addToolbarItem:(NSToolbarItem *)item;\r
--(NSToolbarItem *)toolbar:(NSToolbar *)toolbar itemForItemIdentifier:(NSString *)itemIdentifier willBeInsertedIntoToolbar:(BOOL)flag;\r
--(NSArray *)toolbarAllowedItemIdentifiers:(NSToolbar *)toolbar;\r
--(NSArray *)toolbarDefaultItemIdentifiers:(NSToolbar *)toolbar;\r
--(BOOL)validateToolbarItem:(NSToolbarItem *)theItem;\r
--(void)addMenuItem:(NSMenuItem *)item;\r
--(void)removeMenuItem:(NSMenuItem *)item;\r
-@end\r
-\r
-void ScheduleEventDispatch(){\r
-       [CocoaApp performSelector:@selector(dispatchGuiEvents) withObject:nil afterDelay:0.0];\r
-}\r
-\r
-@interface Scroller:NSScroller{\r
-}\r
--(id)init;\r
-//-(id)initWithFrame:(NSRect)rect;\r
-//-(void)drawParts;\r
-//-(void)drawKnob;\r
-//-(void)drawKnobSlotInRect:(NSRect)slotRect highlight:(BOOL)flag;\r
-//-(void)drawArrow:(NSScrollerArrow)arrow highlight:(BOOL)flag;\r
-//-(void)highlight:(BOOL)flag;\r
-@end\r
-\r
-@interface FlippedView:NSView{\r
-}\r
--(BOOL)isFlipped;\r
--(BOOL)mouseDownCanMoveWindow;\r
-@end\r
-\r
-@interface PanelView:NSBox{\r
-       int                     style;\r
-       int                     enabled;\r
-       nsgadget                *gadget;\r
-}\r
--(BOOL)isFlipped;\r
--(BOOL)mouseDownCanMoveWindow;\r
--(void)setColor:(NSColor*)rgb;\r
--(void)setAlpha:(float)alpha;\r
--(void)setGadget:(nsgadget*)_gadget;\r
--(void)setStyle:(int)s;\r
--(void)setImage:(NSImage *)image withFlags:(int)flags;\r
--(BOOL)acceptsFirstResponder;\r
--(BOOL)becomeFirstResponder;\r
-\r
--(void)setEnabled:(BOOL)flag;\r
--(BOOL)isEnabled;\r
-@end\r
-\r
-@interface PanelViewContent:NSView{\r
-       NSColor         *color;\r
-       NSImage         *image;\r
-       int                     imageflags;\r
-       float           alpha;\r
-}\r
--(BOOL)isFlipped;\r
--(BOOL)mouseDownCanMoveWindow;\r
--(void)setColor:(NSColor*)rgb;\r
--(void)setAlpha:(float)alpha;\r
--(void)setImage:(NSImage *)image withFlags:(int)flags;\r
--(void)drawRect:(NSRect)rect;\r
-@end\r
-\r
-@interface CanvasView:PanelView{\r
-}\r
--(void)drawRect:(NSRect)rect;\r
--(BOOL)acceptsFirstResponder;\r
--(BOOL)becomeFirstResponder;\r
-@end\r
-\r
-@interface ListView:NSScrollView{\r
-       TableView *table;\r
-       NSTableColumn *column;\r
-       NSBrowserCell *cell;\r
-       NSMutableArray *items;\r
-       NSDictionary    *textstyle;\r
-}\r
--(id)initWithFrame:(NSRect)rect;\r
--(id)table;\r
--(id)items;\r
--(void)removeItemAtIndex:(int)index;\r
--(void)setColor:(NSColor*)color;\r
--(void)setTextColor:(NSColor*)color;\r
--(int)numberOfRowsInTableView:(NSTableView *)aTableView;\r
--(id)tableView:(NSTableView *)aTableView objectValueForTableColumn:(NSTableColumn *)aTableColumn row:(int)rowIndex;\r
--(BOOL)tableView:(NSTableView *)tableView shouldEditTableColumn:(NSTableColumn *)tableColumn row:(int)rowIndex;\r
--(void)clear;\r
--(void)addItem:(NSString*)text atIndex:(unsigned)index withImage:(NSImage*)image withTip:(NSString*)tip withExtra:(BBObject*)extra;\r
--(void)setItem:(NSString*)text atIndex:(unsigned)index withImage:(NSImage*)image withTip:(NSString*)tip withExtra:(BBObject*)extra;\r
--(void)selectItem:(unsigned)index;\r
--(void)deselectItem:(unsigned)index;\r
--(void)tableViewSelectionDidChange:(NSNotification *)aNotification;\r
--(void)tableView:(NSTableView *)aTableView willDisplayCell:(id)aCell forTableColumn:(NSTableColumn *)aTableColumn row:(int)rowIndex;\r
--(void)setEnabled:(BOOL)flag;\r
--(BOOL)isEnabled;\r
--(void)updateWidthForString:(ImageString *) string;\r
--(void)updateWidth;\r
--(void)queueWidthUpdate;\r
--(void)dealloc;\r
--(void)setFont:(NSFont*)font;\r
--(NSString *)view:(NSView *)view stringForToolTip:(NSToolTipTag)tag point:(NSPoint)point userData:( void  *)data;\r
-@end\r
-\r
-@interface TableView:NSTableView{\r
-}\r
--(NSMenu*)menuForEvent:(NSEvent *)theEvent;\r
-@end\r
-\r
-@interface OutlineView:NSOutlineView{\r
-}\r
--(NSMenu*)menuForEvent:(NSEvent *)theEvent;\r
-@end\r
-\r
-@interface NodeItem:NSObject{\r
-       TreeView                *owner;\r
-       NodeItem                *parent;\r
-       NSMutableArray *kids;\r
-       NSString                *title;\r
-       NSImage         *icon;\r
-}\r
--(void)dealloc;\r
--(id)initWithTitle:(NSString*)text;\r
--(void)updateWidth;\r
--(void)setOwner:(TreeView*)treeview;\r
--(id)getOwner;\r
--(void)show;\r
--(void)attach:(NodeItem*)parent_ atIndex:(unsigned)index_;\r
--(void)remove;\r
--(BOOL)canExpand;\r
--(NSMutableArray*)kids;\r
--(NSString *)value;\r
--(NSImage *)icon;\r
--(void)setTitle:(NSString*)text;\r
--(void)setIcon:(NSImage*)image;\r
--(unsigned)count;\r
-@end\r
-\r
-@interface TreeView:NSScrollView{\r
-@public\r
-       NSOutlineView   *outline;\r
-       NSTableColumn   *column,*colin;\r
-       NSBrowserCell   *cell;\r
-       NodeItem                *rootNode;\r
-       NSDictionary    *textstyle;\r
-}\r
--(id)initWithFrame:(NSRect)rect;\r
--(void)reloadItem:(id)item;\r
--(void)refresh;\r
--(int)outlineView:(NSOutlineView*)outlineView numberOfChildrenOfItem:(id)item;\r
--(id)outlineView:(NSOutlineView*)outlineView child:(int)index ofItem:(id)item;\r
--(BOOL)outlineView:(NSOutlineView*)outlineView isItemExpandable:(id)item;\r
--(id)outlineView:(NSOutlineView*)outlineView objectValueForTableColumn:(NSTableColumn*)tableColumn byItem:(id)item;\r
--(unsigned)count;\r
--(id)rootNode;\r
--(id)selectedNode;\r
--(void)selectNode:(id)node;\r
--(void)expandNode:(id)node;\r
--(void)collapseNode:(id)node;\r
--(void)outlineViewItemDidExpand:(NSNotification *)notification;\r
--(void)outlineViewItemDidCollapse:(NSNotification *)notification;\r
--(void)outlineViewSelectionDidChange:(NSNotification *)notification;\r
--(BOOL)outlineView:(NSOutlineView *)outlineView shouldEditTableColumn:(NSTableColumn *)tableColumn item:(id)item;\r
--(void)outlineView:(NSOutlineView *)outlineView willDisplayCell:(id)dcell forTableColumn:(NSTableColumn *)tableColumn item:(id)item;\r
--(void)setColor:(NSColor*)color;\r
--(void)setTextColor:(NSColor*)color;\r
--(void)setFont:(NSFont*)font;\r
--(void)setEnabled:(BOOL)e;\r
--(BOOL)isEnabled;\r
--(void)dealloc;\r
-@end\r
-\r
-@interface TextView:NSTextView{\r
-@public\r
-       NSScrollView    *scroll;\r
-       NSMutableParagraphStyle *style;\r
-       NSMutableDictionary *styles;\r
-       NSTextStorage *storage;\r
-       int lockedNest;\r
-       NSRange lockedRange;\r
-}\r
--(NSSize)contentSize;\r
--(id)storage;\r
--(id)initWithFrame:(NSRect)rect;\r
--(id)getScroll;\r
--(void)setHidden:(BOOL)flag;\r
--(void)setWordWrap:(BOOL)flag;\r
--(void)setTabs:(int)tabs;\r
--(void)setMargins:(int)leftmargin;\r
--(void)setText:(NSString*)text;\r
--(void)addText:(NSString*)text;\r
--(void)setScrollFrame:(NSRect)rect;\r
--(void)setTextColor:(NSColor*)color;\r
--(void)setColor:(NSColor*)color;\r
--(void)setFont:(NSFont*)font;\r
--(NSMenu *)menuForEvent:(NSEvent*)theEvent;\r
--(void)textDidChange:(NSNotification*)aNotification;\r
--(void)textDidEndEditing:(NSNotification*)aNotification;\r
--(void)textViewDidChangeSelection:(NSNotification *)aNotification;\r
--(void)textStorageDidProcessEditing:(NSNotification *)aNotification;\r
--(void)textStorageWillProcessEditing:(NSNotification *)aNotification;\r
--(void)updateDragTypeRegistration;\r
--(NSArray *)acceptableDragTypes;\r
--(void)free;\r
-@end\r
-\r
-@interface TabView:NSTabView{\r
-       id              client;\r
-       int             user;\r
-}\r
--(id)initWithFrame:(NSRect)rect;\r
--(id)clientView;\r
--(void)setFrame:(NSRect)frameRect;\r
--(void)selectTabViewItemAtIndex:(int)index;\r
--(BOOL)tabView:(NSTabView *)tabView shouldSelectTabViewItem:(NSTabViewItem *)tabViewItem;\r
--(void)dealloc;\r
-@end\r
-\r
-@interface WindowView:NSWindow{\r
-       id      view;\r
-       id      label[3];\r
-       nsgadget *gadget;\r
-       int enabled;\r
-       int zooming;\r
-       NSView *dragging;\r
-}\r
--(id)textFirstResponder;\r
--(id)initWithContentRect:(NSRect)rect styleMask:(unsigned int)mask backing:(NSBackingStoreType)backing defer:(BOOL)flag withGadget:(nsgadget*)_gadget ;\r
--(id)clientView;\r
--(void)setStatus:(NSString*)text align:(int)pos;\r
--(void)sendEvent:(NSEvent*)event;\r
--(NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender;\r
--(BOOL)performDragOperation:(id <NSDraggingInfo>)sender;\r
--(void)didResize;\r
--(void)didMove;\r
--(void)zoom;\r
--(NSRect)localRect;\r
--(BOOL)canBecomeKeyWindow;\r
--(BOOL)canBecomeMainWindow;\r
--(BOOL)becomeFirstResponder;\r
--(void)setEnabled:(BOOL)flag;\r
--(BOOL)isEnabled;\r
--(void)dealloc;\r
-@end\r
-\r
-@interface ToolView:NSPanel{\r
-       id      view;\r
-       id      label[3];\r
-       nsgadget *gadget;\r
-       int enabled;\r
-       int zooming;\r
-       NSView *dragging;\r
-}\r
--(id)textFirstResponder;\r
--(id)initWithContentRect:(NSRect)rect styleMask:(unsigned int)mask backing:(NSBackingStoreType)backing defer:(BOOL)flag withGadget:(nsgadget*)_gadget ;\r
--(id)clientView;\r
--(void)setStatus:(NSString*)text align:(int)pos;\r
--(void)sendEvent:(NSEvent*)event;\r
--(NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender;\r
--(BOOL)performDragOperation:(id <NSDraggingInfo>)sender;\r
--(void)didResize;\r
--(void)didMove;\r
--(void)zoom;\r
--(NSRect)localRect;\r
--(BOOL)canBecomeKeyWindow;\r
--(BOOL)canBecomeMainWindow;\r
--(BOOL)becomeFirstResponder;\r
--(void)setEnabled:(BOOL)flag;\r
--(BOOL)isEnabled;\r
--(void)dealloc;\r
-@end\r
-\r
-static CocoaApp *GlobalApp;\r
-\r
-@class HTMLView;\r
-@interface HTMLView:WebView{\r
-       int             _state, _style;\r
-}\r
--(id)initWithFrame:(NSRect)rect;\r
--(int)loaded;\r
--(void)setStyle:(int)style;\r
--(void)setAddress:(NSString*)address;\r
--(NSString*)address;\r
-@end\r
-@implementation HTMLView\r
--(id)initWithFrame:(NSRect)rect{\r
-       self=[super initWithFrame:rect];\r
-       [self setAutoresizingMask:NSViewNotSizable];\r
-       [self setPolicyDelegate:self];\r
-       [self setFrameLoadDelegate:self];\r
-       [self setUIDelegate:self];\r
-       [self unregisterDraggedTypes];\r
-       _state=0;\r
-       return self;\r
-}\r
--(int)loaded{\r
-       return _state;\r
-}\r
--(void)setStyle:(int)style{\r
-       _style = style;\r
-}\r
--(NSString*)address{\r
-       WebDataSource           *datasource;\r
-       datasource = [[self mainFrame] provisionalDataSource];\r
-       if(datasource==nil) datasource = [[self mainFrame] dataSource];\r
-       if(datasource==nil) return [[NSString alloc] initWithString:@""];\r
-       return [[[datasource request] URL] absoluteString];\r
-}\r
--(void)setAddress:(NSString*)address{\r
-       NSURL                   *url;\r
-       NSURLRequest            *request;\r
-       WebFrame                        *frame;\r
-               \r
-       url=[NSURL URLWithString:address];\r
-       if (url==nil) url=[NSURL fileURLWithPath:address];\r
-       if (url==nil) return;\r
-       _state=1;\r
-       request=[NSURLRequest requestWithURL:url];\r
-       frame=[self mainFrame];\r
-       [frame loadRequest:request];\r
-}\r
-- (void)webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame{\r
-       int oldstate = _state;\r
-       NSURLRequest *url;\r
-       BBString*text;\r
-       \r
-       _state=0;\r
-       \r
-       url=[[frame dataSource]initialRequest];\r
-       text=bbStringFromCString((char*)[[[url URL] relativePath] cString]);\r
-       \r
-       if(oldstate)\r
-               PostGuiEvent( BBEVENT_GADGETDONE,sender,0,0,0,0,(BBObject*)text );\r
-}\r
-- (void)webView:(WebView *)sender didChangeLocationWithinPageForFrame:(WebFrame *)frame{\r
-       int oldstate = _state;\r
-       NSURLRequest *url;\r
-       BBString*text;\r
-       \r
-       _state=0;\r
-       \r
-       url=[[frame dataSource]initialRequest];\r
-       text=bbStringFromCString((char*)[[[url URL] relativePath] cString]);\r
-       \r
-       if(oldstate)\r
-               PostGuiEvent( BBEVENT_GADGETDONE,sender,0,0,0,0,(BBObject*)text );\r
-}\r
-- (void)webView:(WebView *)sender decidePolicyForNavigationAction:(NSDictionary *)actionInformation request:(NSURLRequest *)url frame:(WebFrame *)frame decisionListener:(id<WebPolicyDecisionListener>)listener{\r
-       BBString*text;\r
-       int     key;\r
-       key=(int)[[actionInformation objectForKey:WebActionNavigationTypeKey] intValue];\r
-       switch (key){\r
-       case WebNavigationTypeOther:\r
-       case WebNavigationTypeLinkClicked:\r
-               if ((_state==0) && (_style & HTMLVIEW_NONAVIGATE)) {\r
-                       [listener ignore];\r
-                       text=bbStringFromCString((char*)[[[url URL] absoluteString] cString]);\r
-                       PostGuiEvent( BBEVENT_GADGETACTION,sender,0,0,0,0,(BBObject*)text );\r
-               }else{\r
-                       [listener use];\r
-               }\r
-       default:\r
-               [listener use];\r
-       }\r
-}\r
-- (NSArray *)webView:(WebView *)sender contextMenuItemsForElement:(NSDictionary *)element defaultMenuItems:(NSArray *)defaultMenuItems{\r
-       if(_style&HTMLVIEW_NOCONTEXTMENU)\r
-               return [NSArray array];\r
-       else\r
-               return defaultMenuItems;\r
-}\r
-@end\r
-\r
-\r
-//Toolbar\r
-\r
-@class Toolbar;\r
-@interface Toolbar:NSToolbar{\r
-       NSMutableDictionary     *items;\r
-}\r
--(id)initWithIdentifier:(NSString *)string;\r
--(void)addToolbarItem:(NSToolbarItem *)item;\r
--(NSArray *)toolbarAllowedItemIdentifiers;\r
--(NSArray *)toolbarDefaultItemIdentifiers;\r
-@end\r
-@implementation Toolbar\r
--(id)initWithIdentifier:(NSString *)string{\r
-       self=[super initWithIdentifier:string];\r
-       items=[[NSMutableDictionary dictionaryWithCapacity:10] retain];\r
-       return self;\r
-}\r
--(void)addToolbarItem:(NSToolbarItem *)item{\r
-       [items setObject:item forKey:[item itemIdentifier]];\r
-}\r
--(NSArray *)toolbarAllowedItemIdentifiers{\r
-       return [items allValues];\r
-}\r
--(NSArray *)toolbarDefaultItemIdentifiers{\r
-       return [items allValues];\r
-}\r
-@end\r
-\r
-\r
-// CocoaApp\r
-@implementation CocoaApp\r
-+(void)dispatchGuiEvents{\r
-       maxgui_maxgui_DispatchGuiEvents();\r
-}\r
-+(void)delayedGadgetAction:(NSObject*)o{  // See controlTextDidChange\r
-       PostGuiEvent( BBEVENT_GADGETACTION, \r
-                     o, \r
-                     [o respondsToSelector:@selector(indexOfSelectedItem)] ? [o indexOfSelectedItem] : 0,\r
-                     0,0,0,0 );\r
-}\r
--(void)controlTextDidEndEditing:(NSNotification*)n{\r
-       PostGuiEvent( BBEVENT_GADGETLOSTFOCUS,[n object],0,0,0,0,0 );\r
-}\r
--(void)controlTextDidChange:(NSNotification*)n{\r
-       NSObject *o = [n object];\r
-       [CocoaApp performSelector:@selector(delayedGadgetAction:) withObject:o afterDelay:0.0];\r
-}\r
-\r
--(id)init{\r
-       toolbaritems=[[NSMutableDictionary dictionaryWithCapacity:10] retain];\r
-       menuitems=[[NSMutableArray arrayWithCapacity:10] retain];\r
-       return self;\r
-}\r
--(BOOL)windowShouldClose:(id)sender{\r
-       PostGuiEvent( BBEVENT_WINDOWCLOSE,sender,0,0,0,0,0 );\r
-       return NO;\r
-}\r
--(void)windowDidResize:(NSNotification *)aNotification{\r
-       WindowView *window;\r
-       ToolView * panel;\r
-       if ([[aNotification object] isKindOfClass:[WindowView class]]) {\r
-               window=(WindowView*)[aNotification object];\r
-               [window didResize];\r
-       } else {\r
-               panel =(ToolView*)[aNotification object];\r
-               [panel didResize];\r
-       }\r
-}\r
--(void)windowDidMove:(NSNotification *)aNotification{\r
-       WindowView *window;\r
-       ToolView * panel;\r
-       if ([[aNotification object] isKindOfClass:[WindowView class]]) {\r
-               window=(WindowView*)[aNotification object];\r
-               [window didMove];\r
-       } else {\r
-               panel =(ToolView*)[aNotification object];\r
-               [panel didMove];\r
-       }\r
-}\r
--(BOOL)windowShouldZoom:(NSWindow *)sender toFrame:(NSRect)newFrame{\r
-       [(WindowView*)sender zoom];\r
-       return YES;\r
-}\r
--(void)windowDidBecomeKey:(NSNotification *)aNotification{\r
-       NSWindow *window;\r
-       window=(NSWindow*)[aNotification object];\r
-       PostGuiEvent( BBEVENT_WINDOWACTIVATE,window,0,0,0,0,0 );\r
-}\r
--(void)menuSelect:(id)sender{\r
-       PostGuiEvent( BBEVENT_MENUACTION,sender,[sender tag],0,0,0,0 );\r
-}\r
--(void)iconSelect:(id)sender{\r
-       NSToolbar       *toolbar;\r
-       int                     index;\r
-       toolbar=[sender toolbar];\r
-       index=[[toolbar items] indexOfObject:sender];\r
-       PostGuiEvent( BBEVENT_GADGETACTION,toolbar,index,0,0,0,0 );\r
-}\r
--(void)sliderSelect:(id)sender{\r
-       PostGuiEvent( BBEVENT_GADGETACTION,sender,0,0,0,0,0 );\r
-}\r
--(void)scrollerSelect:(id)sender{\r
-       NSScroller *scroller;\r
-       int delta=0;\r
-       scroller=(NSScroller *)sender;\r
-       switch([scroller hitPart]){\r
-       case NSScrollerDecrementLine:\r
-               delta=-1;\r
-               break;\r
-       case NSScrollerDecrementPage:\r
-               delta=-2;\r
-               break;\r
-       case NSScrollerIncrementLine:\r
-               delta=1;\r
-               break;\r
-       case NSScrollerIncrementPage:\r
-               delta=2;\r
-               break;  \r
-       }\r
-       PostGuiEvent( BBEVENT_GADGETACTION,sender,delta,0,0,0,0 );\r
-}\r
--(void)buttonPush:(id)sender{\r
-       if([sender allowsMixedState]) [sender setAllowsMixedState:NO];\r
-       PostGuiEvent( BBEVENT_GADGETACTION,sender,0,0,0,0,0 );\r
-}\r
--(void)textEdit:(id)sender{\r
-       PostGuiEvent( BBEVENT_GADGETACTION,sender,0,0,0,0,0 );\r
-}\r
--(void)comboBoxSelectionDidChange:(NSNotification *)notification{\r
-       NSControl *o=(NSComboBox*)[notification object];\r
-       [CocoaApp performSelector:@selector(delayedGadgetAction:) withObject:o afterDelay:0.0];\r
-}\r
--(void)comboBoxSelectionIsChanging:(NSNotification *)notification{\r
-       \r
-}\r
--(void)comboBoxWillPopUp:(NSNotification *)notification{\r
-       HaltMouseEvents = 1;\r
-}\r
--(void)comboBoxWillDismiss:(NSNotification *)notification{\r
-       HaltMouseEvents = 0;\r
-}\r
--(void)addToolbarItem:(NSToolbarItem *)item{\r
-       [toolbaritems setObject:item forKey:[item itemIdentifier]];\r
-}\r
--(NSToolbarItem *)toolbar:(NSToolbar *)toolbar itemForItemIdentifier:(NSString *)itemIdentifier willBeInsertedIntoToolbar:(BOOL)flag{\r
-       return [toolbaritems objectForKey:itemIdentifier];\r
-}\r
--(NSArray *)toolbarAllowedItemIdentifiers:(NSToolbar *)toolbar{\r
-       Toolbar *mytoolbar=(Toolbar*)toolbar;\r
-       return [mytoolbar toolbarAllowedItemIdentifiers];\r
-}\r
--(NSArray *)toolbarDefaultItemIdentifiers:(NSToolbar *)toolbar{\r
-       Toolbar *mytoolbar=(Toolbar*)toolbar;\r
-       return [mytoolbar toolbarDefaultItemIdentifiers];\r
-}\r
--(BOOL)validateToolbarItem:(NSToolbarItem *)item{\r
-       return [item isEnabled];\r
-}\r
--(void)addMenuItem:(NSMenuItem *)item{\r
-       [menuitems addObject:item];\r
-}\r
--(void)removeMenuItem:(NSMenuItem *)item{\r
-       [menuitems removeObject:item];\r
-}\r
-\r
-@end\r
-\r
-// Scroller\r
-\r
-@implementation Scroller\r
--(id)init{\r
-       [super init];\r
-       [self setAlphaValue:.5f];               \r
-       return self;\r
-}\r
-//-(void)drawKnob{}\r
-//-(void)drawParts{}\r
-//-(void)drawKnobSlotInRect:(NSRect)slotRect highlight:(BOOL)flag{}\r
-//-(void)drawArrow:(NSScrollerArrow)arrow highlight:(BOOL)flag{}\r
-//-(void)highlight:(BOOL)flag{}\r
-@end\r
-\r
-// FlippedView\r
-\r
-@implementation FlippedView\r
--(BOOL)isFlipped{\r
-       return YES;\r
-}\r
--(BOOL)mouseDownCanMoveWindow{\r
-       return YES;\r
-}\r
-@end\r
-\r
-// PanelView\r
-\r
-@implementation PanelView\r
-- (BOOL)acceptsFirstResponder{\r
-       return YES;\r
-}\r
--(BOOL)becomeFirstResponder{\r
-       return [self isEnabled];\r
-}\r
--(void)setColor:(NSColor *)rgb{\r
-       [[self contentView] setColor:rgb];\r
-}\r
--(void)setAlpha:(float)al{\r
-       [[self contentView] setAlpha:al];\r
-}\r
--(void)setImage:(NSImage *)img withFlags:(int)flags{\r
-       [[self contentView] setImage:img withFlags:flags];\r
-}\r
--(void)setEnabled:(BOOL)e{\r
-       enabled=e;\r
-}\r
--(BOOL)isEnabled{\r
-       return (enabled)?YES:NO;\r
-}\r
--(void)setStyle:(int)s{\r
-       \r
-       gadget->sensitivity |= (s & PANEL_ACTIVE) ? (SENSITIZE_MOUSE|SENSITIZE_KEYS) : 0;\r
-       \r
-       switch ( s & (PANEL_SUNKEN|PANEL_RAISED|PANEL_GROUP) ){\r
-               case PANEL_GROUP:\r
-                       [self setContentViewMargins: NSMakeSize(4.0,4.0)];\r
-                       [self setBoxType:NSBoxPrimary];\r
-                       [self setBorderType: NSBezelBorder];\r
-                       [self setTitlePosition: NSAtTop];\r
-                       break;\r
-               case PANEL_RAISED:\r
-               case PANEL_SUNKEN:\r
-                       [self setContentViewMargins: NSMakeSize(0.0,0.0)];\r
-                       [self setBoxType: NSBoxOldStyle];\r
-                       [self setBorderType: NSLineBorder];\r
-                       [self setTitlePosition: NSNoTitle];\r
-                       break;\r
-               default:\r
-                       [self setContentViewMargins: NSMakeSize(0.0,0.0)];\r
-                       [self setBorderType: NSNoBorder];\r
-                       [self setTitlePosition: NSNoTitle];\r
-       }\r
-       \r
-       style=s;\r
-}\r
--(void)setGadget:(nsgadget*)_gadget{\r
-       gadget=_gadget;\r
-}\r
--(BOOL)mouseDownCanMoveWindow{\r
-       return NO;\r
-}\r
-@end\r
-\r
-//PanelViewContent\r
-@implementation PanelViewContent\r
--(BOOL)isFlipped{\r
-       return YES;\r
-}\r
--(BOOL)mouseDownCanMoveWindow{\r
-       return NO;\r
-}\r
--(void)setColor:(NSColor *)rgb{\r
-       if (color){\r
-               [color release];\r
-               color=0;\r
-       }\r
-       if(rgb){\r
-               color=[rgb colorWithAlphaComponent:1.0];\r
-               [color retain];\r
-       }\r
-       [self setNeedsDisplay:YES];\r
-}\r
--(void)setImage:(NSImage *)img withFlags:(int)flags{\r
-       if (img) [img retain];\r
-       if (image) [image release];\r
-       image=img;\r
-       imageflags=flags;\r
-       [self setNeedsDisplay:YES];\r
-}\r
--(void)setAlpha:(float)al{\r
-       alpha=al;\r
-       if (color){\r
-               [color release];\r
-               color=[color colorWithAlphaComponent:alpha];\r
-               [color retain];\r
-       }\r
-       [self setNeedsDisplay:YES];\r
-}\r
--(void)drawRect:(NSRect)rect{\r
-       \r
-       NSRect dest = NSUnionRect(rect,[self frame]);\r
-       \r
-       if (color){\r
-               [color set];\r
-               if (alpha<1.0)\r
-                       NSRectFillUsingOperation( dest,NSCompositeSourceOver );\r
-               else\r
-                       NSRectFill( dest );\r
-       }\r
-       \r
-       if (image){\r
-               int             op,x,y,w,h;\r
-               float   a;\r
-               float   m,mm;\r
-               NSRect  src,tile;\r
-\r
-               a=alpha;\r
-               op=NSCompositeSourceOver;\r
-               src.origin.x=0;\r
-               src.origin.y=0;\r
-               src.size=[image size];\r
-               [image setFlipped:YES];\r
-\r
-               switch (imageflags&(GADGETPIXMAP_ICON-1)){\r
-               case PANELPIXMAP_TILE:\r
-                       tile.size=[image size];\r
-                       for (y=0;y<dest.size.height;y+=src.size.height){\r
-                               tile.origin.y=y;\r
-                               for (x=0;x<dest.size.width;x+=src.size.width){\r
-                                       tile.origin.x=x;\r
-                                       [image drawInRect:tile fromRect:src operation:op fraction:a];\r
-                               }\r
-                       }                                       \r
-                       break;\r
-               case PANELPIXMAP_CENTER:\r
-                       dest.origin.x=(dest.size.width-src.size.width)/2;\r
-                       dest.origin.y=(dest.size.height-src.size.height)/2;\r
-                       dest.size=src.size;\r
-                       [image drawInRect:dest fromRect:src operation:op fraction:a];\r
-                       break;\r
-               case PANELPIXMAP_FIT:\r
-                       m=dest.size.width/src.size.width;\r
-                       mm=dest.size.height/src.size.height;\r
-                       if (m>mm) m=mm;\r
-                       dest.origin.x+=(dest.size.width-src.size.width*m)/2;\r
-                       dest.origin.y+=(dest.size.height-src.size.height*m)/2;\r
-                       dest.size.width=src.size.width*m;\r
-                       dest.size.height=src.size.height*m;\r
-                       [image drawInRect:dest fromRect:src operation:op fraction:a];\r
-                       break;\r
-               case PANELPIXMAP_STRETCH:\r
-                       [image drawInRect:dest fromRect:src operation:op fraction:a];\r
-                       break;\r
-               case PANELPIXMAP_FIT2:\r
-                       m = dest.size.width/dest.size.height;\r
-                       \r
-                       if ((dest.size.width/src.size.width)<(dest.size.height/src.size.height)){\r
-                               src.origin.x = (src.size.width-(src.size.height*m))/2;\r
-                               src.size.width = src.size.height*m;\r
-                       } else {\r
-                               src.origin.y = (src.size.height-(src.size.width/m))/2;\r
-                               src.size.height = src.size.width/m;\r
-                       }\r
-                       \r
-                       [image drawInRect:dest fromRect:src operation:op fraction:a];\r
-                       break;\r
-               }\r
-               [image setFlipped:NO];\r
-       }\r
-       \r
-       [super drawRect:rect];\r
-} \r
-@end\r
-\r
-// CanvasView\r
-@implementation CanvasView\r
--(void)drawRect:(NSRect)rect{\r
-       [super drawRect:rect];\r
-       PostGuiEvent( BBEVENT_GADGETPAINT,self,0,0,0,0,0 );\r
-} \r
-- (BOOL)acceptsFirstResponder{\r
-       return YES;\r
-}\r
--(BOOL)becomeFirstResponder{\r
-       return [self isEnabled];\r
-}\r
-@end\r
-\r
-// ImageString\r
-\r
-@class ImageString;\r
-@interface ImageString:NSObject{\r
-       NSString        *_string;\r
-       NSImage *_image;\r
-       NSString        *_tip;\r
-       BBObject        *_extra;\r
-}\r
--(id)initWithString:(NSString *)text image:(NSImage *)image tip:(NSString *)tip extra:(BBObject*)extra;\r
--(void)dealloc;\r
--(id)copyWithZone:(NSZone *)zone;\r
--(NSString*)string;\r
--(NSImage*)image;\r
--(NSString*)description;\r
--(BBObject*)extra;\r
-@end\r
-@implementation ImageString\r
--(id)initWithString:(NSString *)string image:(NSImage *)image tip:(NSString*)tip extra:(BBObject*)extra{\r
-       _string=string;\r
-       _image=image;\r
-       _tip=tip;\r
-       _extra=extra;\r
-       if (string) [string retain];\r
-       if (image) [image retain];\r
-       if (tip) [tip retain];\r
-       return self;\r
-}\r
--(void)dealloc{\r
-       if (_string) [_string release];\r
-       if (_image) [_image release];\r
-       if (_tip) [_tip release];\r
-       [super dealloc];\r
-}\r
--(id)copyWithZone:(NSZone *)zone{\r
-       ImageString *copy=[[[self class] allocWithZone:zone] initWithString:_string image:_image tip:_tip extra:_extra];\r
-       return copy;\r
-}\r
--(NSString*)string{return _string;}\r
--(NSImage*)image{return _image;}\r
--(NSString*)description{return _tip;}\r
--(BBObject*)extra{return _extra;}\r
-@end\r
-\r
-// ListView\r
-\r
-@implementation ListView\r
--(id)initWithFrame:(NSRect)rect{\r
-       [super initWithFrame:rect];\r
-       [self setBorderType:NSNoBorder];\r
-       [self setHasVerticalScroller:YES];\r
-       [self setHasHorizontalScroller:YES];\r
-       [self setAutohidesScrollers:YES];\r
-       column=[[NSTableColumn alloc] init];\r
-       cell=[[NSBrowserCell alloc] init];\r
-       [cell setLeaf:YES];\r
-       [column setDataCell:cell];\r
-       NSSize contentSize = [self contentSize];        \r
-       table=[[TableView alloc] initWithFrame:NSMakeRect(0, 0,contentSize.width, contentSize.height)];\r
-       [table setAutoresizingMask:(NSViewWidthSizable|NSViewHeightSizable)];\r
-       items=[[NSMutableArray alloc] initWithCapacity:10];\r
-       [table setHeaderView:nil];      \r
-       [table setDataSource:self];\r
-       [table setDelegate:self];\r
-       [self setDocumentView:table];\r
-       [table addTableColumn:column];\r
-       [table sizeLastColumnToFit];\r
-       return self;\r
-}\r
--(id)table{\r
-       return table;\r
-}\r
--(id)items{\r
-       return items;\r
-}\r
--(void)removeItemAtIndex:(int)index{\r
-       ImageString *item=(ImageString*)[items objectAtIndex:index];\r
-       [items removeObjectAtIndex:index];\r
-       [item release];\r
-       [table reloadData];\r
-       [self queueWidthUpdate];\r
-}\r
--(void)setColor:(NSColor*)color{\r
-       [table setBackgroundColor:color];\r
-}\r
--(void)setEnabled:(BOOL)e{\r
-       [table setEnabled:e];\r
-}\r
--(BOOL)isEnabled{\r
-       return [table isEnabled];\r
-}\r
--(void)setTextColor:(NSColor*)color{\r
-       if (textstyle) {[textstyle release];textstyle=nil;}\r
-       if (color){\r
-               textstyle=[NSDictionary dictionaryWithObjectsAndKeys:color,NSForegroundColorAttributeName,nil];\r
-               [textstyle retain];     \r
-       }\r
-}\r
--(int)numberOfRowsInTableView:(NSTableView *)aTableView{\r
-       return [items count];\r
-}\r
--(id)tableView:(NSTableView *)aTableView objectValueForTableColumn:(NSTableColumn *)aTableColumn row:(int)rowIndex{\r
-       return [items objectAtIndex:rowIndex];\r
-}\r
--(BOOL)tableView:(NSTableView *)tableView shouldEditTableColumn:(NSTableColumn *)tableColumn row:(int)rowIndex{ /*new from BAH*/\r
-       PostGuiEvent( BBEVENT_GADGETACTION,self,rowIndex,0,0,0,0 );\r
-       return NO;\r
-}\r
--(void)clear{\r
-       [table setDelegate:nil];\r
-\r
-       ImageString *item;\r
-       int count,i;\r
-       count=[items count];\r
-       for (i=0;i<count;i++){\r
-               item=(ImageString*)[items objectAtIndex:i];\r
-               [item release];\r
-       }\r
-\r
-       [items removeAllObjects];\r
-       [table reloadData];\r
-       [table setDelegate:self];\r
-       [self queueWidthUpdate];\r
-}\r
--(void)addItem:(NSString*)text atIndex:(unsigned)index withImage:(NSImage*)image withTip:(NSString*)tip withExtra:(BBObject*)extra{\r
-       ImageString *item;\r
-       item=[[ImageString alloc] initWithString:text image:image tip:tip extra:extra];\r
-       [items insertObject:item atIndex:index];\r
-       [self updateWidthForString:item];\r
-       [table noteNumberOfRowsChanged];\r
-}\r
--(void)setItem:(NSString*)text atIndex:(unsigned)index withImage:(NSImage*)image withTip:(NSString*)tip withExtra:(BBObject*)extra{\r
-       ImageString *item;\r
-       item=(ImageString*)[items objectAtIndex:index];\r
-       [item release];\r
-       item=[[ImageString alloc] initWithString:text image:image tip:tip extra:extra];\r
-       [items replaceObjectAtIndex:index withObject:item];\r
-       [table reloadData];\r
-       [self queueWidthUpdate];\r
-}\r
--(void)selectItem:(unsigned)index{\r
-       [table setDelegate:nil];\r
-       [table selectRowIndexes:[NSIndexSet indexSetWithIndex:index] byExtendingSelection:NO];\r
-       [table setDelegate:self];\r
-}\r
--(void)deselectItem:(unsigned)index{\r
-       [table setDelegate:nil];\r
-       [table deselectRow:index];\r
-       [table setDelegate:self];\r
-}\r
--(void)tableViewSelectionDidChange:(NSNotification *)aNotification{/*new from BAH*/\r
-        int index=[table selectedRow];\r
-        ImageString *item=nil;\r
-        if (index>=0) item=(ImageString*)[items objectAtIndex:index]; else index=-1;\r
-        if (item){\r
-                PostGuiEvent( BBEVENT_GADGETSELECT,self,index,0,0,0,[item extra]);\r
-        }else{\r
-                PostGuiEvent( BBEVENT_GADGETSELECT,self,-1,0,0,0,&bbNullObject);\r
-        }\r
-}\r
--(void)tableView:(NSTableView *)table willDisplayCell:(id)aCell forTableColumn:(NSTableColumn *)aTableColumn row:(int)rowIndex{\r
-       NSString *text=[[items objectAtIndex:rowIndex] string];\r
-       if (textstyle){\r
-               NSAttributedString *atext=[[[NSAttributedString alloc] initWithString:text attributes:textstyle] autorelease];\r
-               [aCell setAttributedStringValue:atext];\r
-       }else{\r
-               [aCell setStringValue:text];\r
-       }\r
-       [aCell setImage:[[items objectAtIndex:rowIndex] image]];\r
-}\r
--(void)updateWidthForString:(ImageString *) imgstring{\r
-       \r
-       NSCell* dcell;\r
-       float   cellWidth;\r
-       \r
-       dcell = [column dataCell];\r
-       [dcell setStringValue:[imgstring string]];\r
-       [dcell setImage:[imgstring image]];\r
-       cellWidth = ((NSSize)[dcell cellSize]).width;\r
-\r
-       if([column minWidth] < cellWidth){\r
-               [column setMinWidth:cellWidth];\r
-               [column setWidth:cellWidth];\r
-               [table setNeedsDisplay:YES];\r
-       }\r
-       \r
-}\r
--(void)updateWidth{\r
-       int i, count;\r
-       count = [items count];\r
-       [column setMinWidth:0];\r
-       for (i=0;i<count;i++)\r
-               [self updateWidthForString:(ImageString*)[items objectAtIndex:i]];\r
-}\r
--(void)queueWidthUpdate{\r
-       [NSObject cancelPreviousPerformRequestsWithTarget: self selector:@selector(updateWidth) object:nil];\r
-       [self performSelector:@selector(updateWidth) withObject:nil afterDelay:0.0];\r
-}\r
--(void)dealloc{\r
-       ImageString *item;\r
-       int count,i;\r
-       count=[items count];\r
-       for (i=0;i<count;i++){\r
-               item=(ImageString*)[items objectAtIndex:i];\r
-               [item release];\r
-       }\r
-\r
-       [table release];\r
-       [column release];\r
-       [cell release];\r
-       [items release];\r
-       if (textstyle) {\r
-               [textstyle release];\r
-       }\r
-       [super dealloc];\r
-}\r
--(void)setFont:(NSFont*)font{\r
-       if (font) {\r
-               [table setRowHeight:[font defaultLineHeightForFont]+2];\r
-               [[column dataCell] setFont:font];\r
-               [table reloadData];\r
-               [self updateWidth];\r
-       }\r
-}\r
-\r
-- (NSString *)tableView:(NSTableView *)aTableView toolTipForCell:(NSCell *)aCell rect:(NSRectPointer)rect \r
-tableColumn:(NSTableColumn *)aTableColumn row:(int)row mouseLocation:(NSPoint)mouseLocation{\r
-       \r
-       return [[items objectAtIndex:row] description];\r
-}\r
-\r
-@end\r
-\r
-// TableView\r
-\r
-@implementation TableView\r
--(NSMenu*)menuForEvent:(NSEvent *)theEvent{\r
-       int             row = -1;\r
-       NSPoint p=[self convertPoint:[theEvent locationInWindow] fromView:nil];\r
-       row = [self rowAtPoint:p];\r
-\r
-       if (row < [self numberOfRows]) {\r
-               [self selectRowIndexes:[NSIndexSet indexSetWithIndex:row] byExtendingSelection:NO];\r
-               PostGuiEvent( BBEVENT_GADGETMENU,[self dataSource],row,0,0,0,0 );\r
-       }\r
-\r
-       return nil;\r
-}\r
-@end\r
-\r
-// OutlineView\r
-\r
-@implementation OutlineView\r
--(NSMenu*)menuForEvent:(NSEvent *)theEvent{\r
-       id              node;\r
-       NSPoint p=[self convertPoint:[theEvent locationInWindow] fromView:nil];\r
-       int i=[self rowAtPoint:p];\r
-       if (i>-1 && i<[self numberOfRows]){\r
-               node=[self itemAtRow:i];\r
-               PostGuiEvent( BBEVENT_GADGETMENU,[self dataSource],(int)node,0,0,0,0 ); //[self superview]\r
-       }\r
-       return nil;\r
-}\r
-@end\r
-\r
-// TreeView\r
-\r
-@implementation TreeView\r
--(id)initWithFrame:(NSRect)rect{\r
-       [super initWithFrame:rect];\r
-       [self setBorderType:NSNoBorder];\r
-       [self setHasVerticalScroller:YES];\r
-       [self setHasHorizontalScroller:YES];\r
-       [self setAutohidesScrollers:YES];\r
-       rootNode=[[NodeItem alloc] initWithTitle:@"root"];\r
-       [rootNode setOwner:self];\r
-       NSSize contentSize = [self contentSize];        \r
-       outline=[[OutlineView alloc] initWithFrame:NSMakeRect(0, 0,contentSize.width, contentSize.height)];\r
-       [outline setHeaderView:nil];    \r
-       [outline setAutoresizingMask:(NSViewWidthSizable|NSViewHeightSizable)];\r
-       [outline setDataSource:self];\r
-       [outline setDelegate:self];\r
-       column=[[NSTableColumn alloc] init];\r
-       [outline addTableColumn:column];\r
-       [outline setOutlineTableColumn:column];\r
-       cell=[[NSBrowserCell alloc] init];\r
-       [cell setLeaf:YES];\r
-       [cell setScrollable:YES];\r
-       [column setDataCell:cell];              \r
-       [self setDocumentView:outline];\r
-       [outline sizeLastColumnToFit];\r
-       return self;\r
-}\r
--(void)dealloc{\r
-       [outline autorelease];\r
-       [column autorelease];\r
-       [cell autorelease];\r
-       if (textstyle) {\r
-               [textstyle release];\r
-       }\r
-       [super dealloc];\r
-}\r
--(void)refresh{\r
-       [rootNode updateWidth];\r
-       [outline reloadData];\r
-}\r
--(int)outlineView:(NSOutlineView*)outlineView numberOfChildrenOfItem:(id)item{\r
-       if( !item ) item=rootNode;\r
-       return [[item kids] count];\r
-}\r
--(id)outlineView:(NSOutlineView*)outlineView child:(int)index ofItem:(id)item{\r
-       if( !item ) item=rootNode;\r
-       if (index>=[[item kids] count]) return 0;\r
-       return [[item kids] objectAtIndex:index];\r
-}\r
--(BOOL)outlineView:(NSOutlineView*)outlineView isItemExpandable:(id)item{\r
-       if( !item ) item=rootNode;\r
-       return [item canExpand];\r
-}\r
--(id)outlineView:(NSOutlineView*)outlineView objectValueForTableColumn:(NSTableColumn*)tableColumn byItem:(id)item{\r
-       if (tableColumn==colin) return @"";     \r
-       if( !item ) item=rootNode;\r
-       return [item value];\r
-}\r
--(unsigned)count{\r
-       return [rootNode count];\r
-}\r
--(id)rootNode{\r
-       return rootNode;\r
-}\r
--(id)selectedNode{\r
-       int             index;\r
-       index=[outline selectedRow];\r
-       if (index==-1) return nil;\r
-       return [outline itemAtRow:index];\r
-}\r
--(void)selectNode:(id)node{\r
-       int index;\r
-       [node show];\r
-       [outline setDelegate:nil];\r
-       index = [outline rowForItem:node];\r
-       [outline selectRowIndexes:[NSIndexSet indexSetWithIndex:index] byExtendingSelection:NO];\r
-       [outline setDelegate:self];\r
-       [outline scrollRowToVisible:index];     \r
-}\r
--(void)expandNode:(id)node{\r
-       [outline setDelegate:nil];\r
-       [outline expandItem:node];\r
-       [outline tile];\r
-       [outline setDelegate:self];\r
-       [node queueWidthUpdate];\r
-}\r
--(void)collapseNode:(id)node{\r
-       [outline setDelegate:nil];\r
-       [outline collapseItem:node];\r
-       [outline tile];\r
-       [outline setDelegate:self];\r
-       [column setMinWidth:0];\r
-       [rootNode queueWidthUpdate];\r
-}\r
--(void)outlineViewItemDidExpand:(NSNotification *)notification{\r
-       id              node;\r
-       node=[[notification userInfo] objectForKey:@"NSObject"];\r
-       [node queueWidthUpdate];\r
-       PostGuiEvent( BBEVENT_GADGETOPEN,self,(int)node,0,0,0,0 );\r
-}\r
--(void)outlineViewItemDidCollapse:(NSNotification *)notification{\r
-       id              node;\r
-       node=[[notification userInfo] objectForKey:@"NSObject"];\r
-       [column setMinWidth:0];\r
-       [rootNode queueWidthUpdate];\r
-       PostGuiEvent( BBEVENT_GADGETCLOSE,self,(int)node,0,0,0,0 );\r
-}\r
--(void)outlineViewSelectionDidChange:(NSNotification *)notification{\r
-       id              node;\r
-       node=[self selectedNode];\r
-       PostGuiEvent( BBEVENT_GADGETSELECT,self,(int)node,0,0,0,0 );\r
-}\r
--(BOOL)outlineView:(NSOutlineView *)outlineView shouldEditTableColumn:(NSTableColumn *)tableColumn item:(id)item{\r
-       PostGuiEvent( BBEVENT_GADGETACTION,self,(int)item,0,0,0,0 );\r
-       return NO;\r
-}\r
--(void)setColor:(NSColor*)color{\r
-       [outline setBackgroundColor:color];\r
-}\r
--(void)setTextColor:(NSColor*)color{\r
-       if (textstyle) {[textstyle release];textstyle=nil;}\r
-       if (color){\r
-               textstyle=[NSDictionary dictionaryWithObjectsAndKeys:color,NSForegroundColorAttributeName,nil];\r
-               [textstyle retain];     \r
-       }\r
-}\r
-- (void)setFont:(NSFont*)font{\r
-       if (font) {\r
-               NSLayoutManager* layoutManager = [[[NSLayoutManager alloc] init] autorelease];\r
-               int i;\r
-               NSArray *columnsArray = [outline tableColumns];\r
-               for (i= 0; i < [columnsArray count]; i++)\r
-               [[[columnsArray objectAtIndex:i] dataCell] setFont:font];\r
-               [outline setRowHeight: [layoutManager defaultLineHeightForFont:font]+1];\r
-               [rootNode queueWidthUpdate];\r
-       }\r
-}\r
-- (void)outlineView:(NSOutlineView *)outlineView willDisplayCell:(id)dcell forTableColumn:(NSTableColumn *)tableColumn item:(id)node{\r
-       if (textstyle){\r
-               NSAttributedString *atext=[[[NSAttributedString alloc] initWithString:[node value] attributes:textstyle] autorelease];\r
-               [dcell setAttributedStringValue:atext];\r
-       }\r
-       else{\r
-               [dcell setStringValue:[node value]];\r
-       }\r
-       [dcell setImage:[node icon]];\r
-}\r
--(void)setEnabled:(BOOL)e{\r
-       [outline setEnabled:e];\r
-}\r
--(BOOL)isEnabled{\r
-       return [outline isEnabled];\r
-}\r
-@end\r
-\r
-// NodeItem\r
-\r
-@implementation NodeItem\r
--(void)dealloc{}\r
--(id)initWithTitle:(NSString*)text{\r
-       owner=nil;\r
-       parent=nil;\r
-       title=text;\r
-       icon=nil;\r
-       [title retain];\r
-       kids=[[NSMutableArray alloc] initWithCapacity:10];\r
-       [kids retain];\r
-       return self;\r
-}\r
--(void)updateWidth{\r
-       int             i;\r
-       float       cellWidth;\r
-       float       indentationWidth;\r
-       \r
-       NSCell* dcell;\r
-       NSArray*        columnsArray;\r
-       \r
-       if(owner==nil) return;\r
-       \r
-       NSOutlineView*  outline = owner->outline;\r
-       NSTableColumn*  tableColumn = owner->column;\r
-       \r
-       if(tableColumn!=nil){\r
-               dcell = [tableColumn dataCell];\r
-               [dcell setStringValue:title];\r
-               [dcell setImage:icon];\r
-               cellWidth = ((NSSize)[dcell cellSize]).width;\r
-               indentationWidth = [outline levelForItem: self];\r
-               if(isnan(indentationWidth)) indentationWidth = 0; else indentationWidth=([outline indentationPerLevel]*(indentationWidth+1));\r
-               if((owner->rootNode == self) || [outline isItemExpanded:self])\r
-                       for (i= 0; i < [kids count]; i++) [[kids objectAtIndex:i] updateWidth];\r
-               if([tableColumn minWidth] < (cellWidth+indentationWidth)){\r
-                       [tableColumn setMinWidth:(cellWidth+indentationWidth)];\r
-                       [tableColumn setWidth:(cellWidth+indentationWidth)];\r
-               }\r
-       }\r
-}\r
--(void)queueWidthUpdate{\r
-       [NSObject cancelPreviousPerformRequestsWithTarget: self selector:@selector(updateWidth) object:nil];\r
-       [self performSelector:@selector(updateWidth) withObject:nil afterDelay:0.0];\r
-}\r
--(void)setOwner:(TreeView*)treeview{\r
-       owner=treeview;\r
-}\r
--(id)getOwner{\r
-       return owner;\r
-}\r
--(void)show{\r
-       if (parent){\r
-               [parent show];\r
-               [owner expandNode:parent];\r
-       }\r
-}\r
--(void)attach:(NodeItem*)parent_ atIndex:(unsigned)index_{\r
-       parent=parent_;\r
-       if( parent ){\r
-               owner=parent->owner;\r
-               [[parent kids] insertObject:self atIndex:index_];\r
-               [self release];\r
-       }\r
-       if (owner) [owner refresh];\r
-}\r
--(void)remove{\r
-       if( parent ) [[parent kids] removeObject:self];\r
-       if (owner) [owner refresh];\r
-}\r
--(BOOL)canExpand{\r
-       return [kids count]>0;\r
-}\r
--(NSMutableArray*)kids{\r
-       return kids;\r
-}\r
--(NSString *)value{return title;}\r
--(NSImage *)icon{return icon;}\r
--(void)setTitle:(NSString*)text{\r
-       [title release];\r
-       title=text;\r
-       [title retain];\r
-       if (owner){\r
-               [owner->outline reloadItem:self];\r
-               [owner->rootNode queueWidthUpdate];\r
-       }\r
-}\r
--(void)setIcon:(NSImage*)image{\r
-       if (icon) [icon release];\r
-       icon=image;\r
-       if (icon) [icon retain];\r
-       if (owner){\r
-               [owner->outline reloadItem:self];\r
-               [(icon ? self : owner->rootNode) queueWidthUpdate];\r
-       }\r
-}\r
--(unsigned)count{\r
-       return [kids count];\r
-}\r
-@end\r
-\r
-// TextView\r
-\r
-@implementation TextView\r
--(id)initWithFrame:(NSRect)rect{\r
-       \r
-       scroll=[[NSScrollView alloc] initWithFrame:rect];\r
-\r
-//     [scroll setVerticalScroller:[[Scroller alloc] init]];\r
-//     [scroll setHorizontalScroller:[[Scroller alloc] init]];\r
-\r
-       [scroll setHasVerticalScroller:YES];\r
-       [scroll setHasHorizontalScroller:YES];\r
-\r
-       [scroll setDrawsBackground:NO];\r
-       [scroll setRulersVisible:NO];\r
-       [scroll setBorderType:NSNoBorder];\r
-       [scroll setAutohidesScrollers:YES];\r
-                               \r
-       NSSize contentSize = [scroll contentSize];      \r
-\r
-       self=[super initWithFrame:NSMakeRect(0, 0,contentSize.width,contentSize.height)];\r
-       [self setMinSize:NSMakeSize(contentSize.width, contentSize.height)];\r
-       [self setMaxSize:NSMakeSize(FLT_MAX, FLT_MAX)];\r
-       [self setVerticallyResizable:YES];\r
-       [self setHorizontallyResizable:YES];\r
-       [self setAutoresizingMask:(NSViewWidthSizable|NSViewHeightSizable)];\r
-       [[self textContainer] setContainerSize:NSMakeSize(FLT_MAX,FLT_MAX)];\r
-       [[self textContainer] setWidthTracksTextView:NO];       \r
-       [self setDelegate:self];\r
-       [self setUsesRuler:NO];\r
-\r
-       [scroll setDocumentView:self];\r
-\r
-       style=[[NSParagraphStyle defaultParagraphStyle] mutableCopy];\r
-       [style setLineBreakMode:NSLineBreakByClipping];\r
-       \r
-       styles=[NSMutableDictionary dictionaryWithObject:style forKey:NSParagraphStyleAttributeName];\r
-       [styles retain];\r
-       storage=[self textStorage];\r
-       [storage setDelegate:self];\r
-       \r
-       lockedNest=0;\r
-       \r
-       [self setTabs: 4];\r
-       if ([self respondsToSelector: @selector(setDefaultParagraphStyle)])\r
-               [self setDefaultParagraphStyle: style];\r
-       \r
-       if ([self respondsToSelector: @selector(setAutomaticLinkDetectionEnabled)])\r
-               [self setAutomaticLinkDetectionEnabled: NO];\r
-       if ([self respondsToSelector: @selector(setAutomaticQuoteSubstitutionEnabled)])\r
-               [self setAutomaticQuoteSubstitutionEnabled: NO];\r
-       if ([self respondsToSelector: @selector(setAutomaticSpellingCorrectionEnabled)])\r
-               [self setAutomaticSpellingCorrectionEnabled: NO];\r
-       if ([self respondsToSelector: @selector(setAutomaticTextReplacementEnabled)])\r
-               [self setAutomaticTextReplacementEnabled: NO];\r
-       if ([self respondsToSelector: @selector(setAutomaticDataDetectionEnabled)])\r
-               [self setAutomaticDataDetectionEnabled: NO];\r
-       \r
-       return self;\r
-}\r
--(void)free{\r
-       [scroll setDocumentView:nil];\r
-       [scroll release];\r
-       [style release];\r
-       [styles release];\r
-       [storage release];\r
-}\r
--(void)setHidden:(BOOL)flag{\r
-       [scroll setHidden:flag];\r
-}\r
--(id)storage{\r
-       return storage;\r
-}\r
--(NSSize)contentSize{\r
-       return [scroll contentSize];\r
-}\r
--(id)getScroll{\r
-       return scroll;\r
-}\r
--(void)setWordWrap:(BOOL)flag{\r
-       NSSize contentSize=[self contentSize];\r
-       if (flag){\r
-               [scroll setHasHorizontalScroller:NO];\r
-               [self setHorizontallyResizable:NO];\r
-               [self setAutoresizingMask:NSViewWidthSizable];\r
-               [[self textContainer] setContainerSize:NSMakeSize(contentSize.width, FLT_MAX)];\r
-               [[self textContainer] setWidthTracksTextView:YES];\r
-               [style setLineBreakMode:NSLineBreakByWordWrapping];\r
-       }\r
-       else{\r
-               [scroll setHasHorizontalScroller:YES];\r
-               [self setHorizontallyResizable:YES];\r
-               [self setAutoresizingMask:(NSViewWidthSizable | NSViewHeightSizable)];\r
-               [[self textContainer] setContainerSize:NSMakeSize(FLT_MAX, FLT_MAX)];\r
-               [[self textContainer] setWidthTracksTextView:NO];\r
-               [style setLineBreakMode:NSLineBreakByClipping];\r
-       }\r
-       [storage addAttribute:NSParagraphStyleAttributeName value:style range:NSMakeRange(0,[storage length])]; \r
-}\r
-\r
--(void)setTabs:(int)tabs{      \r
-       [style setTabStops:[NSArray array]];    //Clear any TabStops\r
-       [style setDefaultTabInterval: tabs];    //Set recurring TabStops remembering to convert from twips->pixels\r
-       [storage addAttribute:NSParagraphStyleAttributeName value:style range:NSMakeRange(0,[storage length])];\r
-}\r
-\r
--(void)setMargins:(int)leftmargin{\r
-\r
-       [self setTextContainerInset:NSMakeSize( leftmargin, 0) ];\r
-//     [style setFirstLineHeadIndent: leftmargin*8];\r
-//     [style setHeadIndent: leftmargin*8];\r
-//     [storage addAttribute:NSParagraphStyleAttributeName value:style range:NSMakeRange(0,[storage length])]; \r
-}\r
-\r
--(void)setText:(NSString*)text{\r
-       NSAttributedString      *astring;\r
-       astring=[[NSAttributedString alloc] initWithString:text attributes:styles];\r
-       if (lockedNest) [storage endEditing];\r
-       [storage setAttributedString:astring];\r
-       if (lockedNest) [storage beginEditing]; else [self setSelectedRange:NSMakeRange(0,0)];\r
-}\r
--(void)addText:(NSString*)text{\r
-       NSAttributedString      *astring;\r
-       astring=[[NSAttributedString alloc] initWithString:text attributes:styles];\r
-       if (lockedNest) [storage endEditing];\r
-       [storage appendAttributedString:astring];\r
-       if (lockedNest) [storage beginEditing];\r
-}\r
--(void)setScrollFrame:(NSRect)rect{\r
-       [scroll setFrame:rect];\r
-}\r
--(void)setTextColor:(NSColor*)color{\r
-       [styles setObject:color forKey:NSForegroundColorAttributeName];\r
-       [storage addAttribute:NSForegroundColorAttributeName value:color range:NSMakeRange(0,[storage length])];\r
-       [self setInsertionPointColor:color];    \r
-}\r
--(void)setColor:(NSColor*)color{\r
-       if(color){\r
-               [self setBackgroundColor:color];        \r
-               [self setDrawsBackground:true];\r
-               [scroll setBackgroundColor:color];\r
-               [scroll setDrawsBackground:true];\r
-       }else{\r
-               [self setDrawsBackground:false];\r
-               [scroll setDrawsBackground:false];\r
-       }\r
-}\r
--(void)setFont:(NSFont*)font{\r
-       [styles setObject:font forKey:NSFontAttributeName];\r
-       [storage setFont:font]; \r
-       [super setFont:font];   \r
-}\r
--(NSMenu *)menuForEvent:(NSEvent *)event{\r
-       NSPoint p;\r
-       int             x,y;\r
-       p=[event locationInWindow];     \r
-       x=(int)p.x;y=(int)p.y;\r
-       PostGuiEvent( BBEVENT_GADGETMENU,self,0,0,x,y,0 );\r
-       return nil;\r
-}\r
--(void)updateDragTypeRegistration{\r
-}\r
--(NSArray *)acceptableDragTypes{\r
-       return nil;\r
-}\r
--(void)textDidBeginEditing:(NSNotification*)n{\r
-//     printf( "textDidBeginEditing:%p\n",_textEditor );fflush(stdout);\r
-}\r
--(void)textDidChange:(NSNotification*)n{\r
-       PostGuiEvent( BBEVENT_GADGETACTION,self,0,0,0,0,0 );\r
-}\r
--(void)textDidEndEditing:(NSNotification*)n{\r
-//     printf( "textDidEndEditing:%p\n",_textEditor );fflush(stdout);\r
-       PostGuiEvent( BBEVENT_GADGETLOSTFOCUS,[n object],0,0,0,0,0 );\r
-}\r
--(void)textViewDidChangeSelection:(NSNotification *)aNotification{\r
-       PostGuiEvent( BBEVENT_GADGETSELECT,self,0,0,0,0,0 );\r
-}\r
--(void)textStorageDidProcessEditing:(NSNotification *)aNotification{\r
-\r
-}\r
--(void)textStorageWillProcessEditing:(NSNotification *)aNotification{\r
-       [storage removeAttribute:NSLinkAttributeName range:[storage editedRange]];\r
-}\r
-@end\r
-\r
-\r
-// TabViewItem\r
-\r
-@class TabViewItem;\r
-@interface TabViewItem:NSTabViewItem{\r
-       NSImage *_image;\r
-}\r
--(id)initWithIdentifier:(NSString *)text;\r
--(void)setImage:(NSImage*)image;\r
--(id)copyWithZone:(NSZone *)zone;\r
--(NSImage*)image;\r
--(NSSize)sizeOfLabel:(BOOL)shouldTruncateLabel;\r
--(void)drawLabel:(BOOL)shouldTruncateLabel inRect:(NSRect)tabRect;\r
-@end\r
-@implementation TabViewItem\r
--(id)initWithIdentifier:(NSString *)string{\r
-       self=[super initWithIdentifier:string];\r
-       _image=nil;\r
-       return self;\r
-}\r
--(void)setImage:(NSImage*)image{\r
-       _image=image;\r
-       if (_image) [_image setScalesWhenResized:YES];\r
-}\r
--(id)copyWithZone:(NSZone *)zone{\r
-       TabViewItem *copy=[[[self class] allocWithZone:zone] initWithIdentifier:[self identifier]];\r
-       return copy;\r
-}\r
--(NSImage*)image{\r
-       return _image;\r
-}\r
--(NSSize)sizeOfLabel:(BOOL)shouldTruncateLabel{\r
-       NSSize  size;\r
-       NSSize  imageDimensions;\r
-       float           ratio;\r
-       size=[super sizeOfLabel:shouldTruncateLabel];\r
-       \r
-       if (_image) {\r
-               imageDimensions = [_image size];\r
-               if (imageDimensions.height > size.height){\r
-                       ratio = size.height/imageDimensions.height;\r
-                       imageDimensions.width*=ratio;imageDimensions.height*=ratio;\r
-                       [_image setSize: imageDimensions];\r
-               }\r
-               size.width += imageDimensions.height;\r
-       }\r
-       return size;\r
-}\r
--(void)drawLabel:(BOOL)shouldTruncateLabel inRect:(NSRect)content{\r
-       NSSize  imageDimensions;\r
-       NSPoint point;\r
-       if (_image){\r
-               imageDimensions = [_image size];\r
-               point = NSMakePoint(content.origin.x,content.origin.y+imageDimensions.height);\r
-               [_image compositeToPoint:point operation:NSCompositeSourceOver];\r
-               content.origin.x+=imageDimensions.width;content.size.width-=imageDimensions.width;              \r
-       }\r
-       [super drawLabel:shouldTruncateLabel inRect:content];\r
-}\r
-@end\r
-\r
-// TabView\r
-\r
-@implementation TabView\r
--(id)initWithFrame:(NSRect)rect{\r
-       rect.size.height+=8;\r
-       self=[super initWithFrame:rect];\r
-       [super setControlSize:NSSmallControlSize];\r
-       [super setFont:[NSFont labelFontOfSize:[NSFont smallSystemFontSize]]];  \r
-       client=[[FlippedView alloc] initWithFrame:[self contentRect]];\r
-       [client setAutoresizingMask:(NSViewWidthSizable|NSViewHeightSizable)];  \r
-       [client retain];\r
-       user=1; \r
-       [self setDelegate:self];\r
-       return self;\r
-}\r
--(id)clientView{\r
-       return client;\r
-}\r
--(void)selectTabViewItemAtIndex:(int)index{\r
-       user=0;\r
-       [super selectTabViewItemAtIndex:index];\r
-       user=1;\r
-} \r
--(void)setFrame:(NSRect)rect{\r
-       rect.size.height+=8;\r
-       [super setFrame:rect];\r
-}\r
--(BOOL)tabView:(NSTabView *)tabView shouldSelectTabViewItem:(NSTabViewItem *)tabViewItem{\r
-       int             index;\r
-       [tabViewItem setView:client];\r
-       [client setFrame:[self contentRect]];\r
-       if (user){\r
-               index=[self indexOfTabViewItem:tabViewItem];\r
-               PostGuiEvent( BBEVENT_GADGETACTION,self,index,0,0,0,0);\r
-       }\r
-       return YES;\r
-}\r
--(void)dealloc{\r
-       NSArray                 *items;\r
-       int                             i,n;\r
-       \r
-       items=[self tabViewItems];\r
-       n=[items count];\r
-       for (i=0;i<n;i++) [self removeTabViewItem:[items objectAtIndex:0]];\r
-\r
-       [client release];\r
-       [super dealloc];\r
-}\r
--(NSMenu *)menuForEvent:(NSEvent *)event{\r
-       int     index;\r
-       NSTabViewItem*  tabItem;\r
-       tabItem = [self tabViewItemAtPoint:[self convertPoint:[event locationInWindow] fromView:nil]];\r
-       if (tabItem) index = [self indexOfTabViewItem:tabItem]; else index = -1;\r
-       PostGuiEvent( BBEVENT_GADGETMENU,self,index,0,0,0,0);\r
-       return [super menuForEvent:event];\r
-}\r
-@end\r
-\r
-// WindowView\r
-\r
-@implementation WindowView\r
--(id)textFirstResponder{\r
-       id r=[self firstResponder];\r
-       //if ([r isKindOfClass:[PanelView class]]) return r;\r
-       if ([r isKindOfClass:[NSTextView class]]){\r
-               id d=[r delegate];\r
-               if( [d isKindOfClass:[NSTextField class]] ) return d;\r
-       }\r
-       return r;\r
-}\r
--(id)initWithContentRect:(NSRect)rect styleMask:(unsigned int)mask backing:(NSBackingStoreType)backing defer:(BOOL)flag withGadget:(nsgadget*)_gadget{\r
-//withStatus:(BOOL)status{\r
-       id              client;\r
-       int             i;\r
-       NSText  *l;\r
-       NSBox   *box;\r
-       dragging = nil;\r
-       self=[super initWithContentRect:rect styleMask:mask backing:backing defer:flag];\r
-       gadget=_gadget;\r
-       view=[[FlippedView alloc] init];\r
-       enabled=true;\r
-       [self setContentView:view];\r
-       [self setAcceptsMouseMovedEvents:YES];\r
-       [self disableCursorRects];      //Fixes NSSetPointer not sticking.\r
-       if (gadget->style&WINDOW_STATUS){\r
-               rect.origin.x=rect.origin.y=0;\r
-               rect.size.height-=STATUSBARHEIGHT;\r
-               client=[[FlippedView alloc] initWithFrame:rect];\r
-               [client setAutoresizingMask:(NSViewWidthSizable|NSViewHeightSizable)];  \r
-               [view addSubview:client];\r
-// label for window status\r
-               rect.origin.y=rect.size.height+3;\r
-               rect.size.height=STATUSBARHEIGHT-4;             \r
-               rect.size.width-=[NSScroller scrollerWidth];\r
-               for (i=0;i<3;i++){\r
-                       l=[[NSText alloc] initWithFrame:rect];\r
-                       [l setDrawsBackground:NO];\r
-                       [l setEditable:NO];\r
-                       [l setSelectable:NO];\r
-                       [l setAutoresizingMask:NSViewWidthSizable|NSViewMinYMargin];\r
-                       switch (i){\r
-                               case 0:[l setAlignment:NSLeftTextAlignment];break;\r
-                               case 1:[l setAlignment:NSCenterTextAlignment];break;\r
-                               case 2:[l setAlignment:NSRightTextAlignment];break;\r
-                       }\r
-                       if (view) [view addSubview:l];\r
-                       label[i]=l;\r
-               }\r
-               \r
-               rect.origin.y-=3;\r
-               rect.size.height=2;\r
-               rect.size.width+=[NSScroller scrollerWidth];\r
-               \r
-               box=[[NSBox alloc] initWithFrame:rect];\r
-               [box setBoxType:NSBoxSeparator];\r
-               [box setTitlePosition:NSNoTitle];\r
-               [box setAutoresizingMask:NSViewWidthSizable|NSViewMinYMargin];\r
-               if (view) [view addSubview:box];\r
-               \r
-// set clientview to inner view\r
-               view=client;            \r
-       }\r
-       return self;\r
-}\r
--(id)clientView{\r
-       return view;\r
-}\r
--(void)setStatus:(NSString*)text align:(int)pos{\r
-       if (label[pos]) [label[pos] setString:text];\r
-}\r
--(void)sendEvent:(NSEvent*)event{\r
-       \r
-       static int lastHotKey;\r
-       int key;\r
-       id source;\r
-       \r
-       // Handling of Generic Key/Mouse Events\r
-       \r
-       switch( [event type] ){\r
-       case NSMouseEntered:\r
-               [self disableCursorRects];\r
-       case NSLeftMouseDown:\r
-       case NSRightMouseDown:\r
-       case NSOtherMouseDown:\r
-               if( [event type] != NSMouseEntered ){\r
-                       dragging = [[self contentView] hitTest:[event locationInWindow]];\r
-                       [self makeFirstResponder:dragging];\r
-               }\r
-       case NSMouseMoved:\r
-       case NSMouseExited:\r
-       case NSScrollWheel:\r
-       {\r
-               NSView *hitView = [[self contentView] hitTest:[event locationInWindow]];\r
-               if (hitView) EmitMouseEvent( event, hitView );\r
-               if(![self isEnabled]) return;\r
-               break;\r
-       }\r
-       case NSLeftMouseUp:\r
-       case NSRightMouseUp:\r
-       case NSOtherMouseUp:\r
-       {\r
-               //fire event for the dragged view\r
-               if (dragging) {\r
-                       EmitMouseEvent( event, dragging );\r
-                       dragging = nil;\r
-               } else {\r
-                       //fire the event for the recieving view (if it exists)\r
-                       NSView *hitView = [[self contentView] hitTest:[event locationInWindow]];\r
-                       if (hitView) EmitMouseEvent( event, hitView );\r
-               }\r
-               \r
-               if(![self isEnabled]) return;\r
-               break;\r
-       }\r
-       case NSLeftMouseDragged:\r
-       case NSRightMouseDragged:\r
-       case NSOtherMouseDragged:\r
-       {\r
-               if( dragging == nil ) dragging = [[self contentView] hitTest:[event locationInWindow]];\r
-               if( dragging ) EmitMouseEvent( event, dragging );\r
-               if(![self isEnabled]) return;\r
-               break;\r
-       }\r
-       case NSKeyDown:\r
-       case NSKeyUp:\r
-       case NSFlagsChanged:\r
-       {\r
-               NSResponder *handle=(NSResponder*)NSActiveGadget();\r
-               if( handle && EmitKeyEvent( event, handle )) return;\r
-               break;\r
-       }\r
-       }\r
-       \r
-       // End of Generic Key/Mouse Events\r
-       \r
-       // Gadget Filterkey Processing\r
-       \r
-       switch( [event type] ){\r
-       case NSKeyDown:\r
-               if( key=bbSystemTranslateKey( [event keyCode] ) ){\r
-                       int mods=bbSystemTranslateMods( [event modifierFlags] );\r
-                       BBObject *event=maxgui_maxgui_HotKeyEvent( key,mods );\r
-                       if( event!=&bbNullObject ){\r
-                               lastHotKey=key;\r
-                               brl_event_EmitEvent( event );\r
-                               return;\r
-                       }\r
-               }\r
-               source=[self textFirstResponder];\r
-               if( source && !filterKeyDownEvent( event,source ) ) return;             \r
-               if(![self isEnabled]) return;\r
-               break;\r
-       case NSKeyUp:\r
-               key=bbSystemTranslateKey([event keyCode]);\r
-               if( lastHotKey && (key==lastHotKey ) ){\r
-                       lastHotKey=0;\r
-                       return;\r
-               }\r
-               if(![self isEnabled]) return;\r
-               break;\r
-       }\r
-       lastHotKey=0;\r
-       \r
-       // End of FilterKey Processing\r
-       \r
-       [super sendEvent:event];\r
-}\r
-- (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender{\r
-//     printf("windowview got dragenter\n");fflush(stdout);\r
-       return YES;\r
-}\r
-- (BOOL)performDragOperation:(id <NSDraggingInfo>)sender{\r
-       NSPasteboard *pboard = [sender draggingPasteboard];\r
-       if ( [[pboard types] containsObject:NSFilenamesPboardType] ) {\r
-               NSArray *files = [pboard propertyListForType:NSFilenamesPboardType];\r
-               int numberOfFiles = [files count];\r
-               // Perform operation using the list of files\r
-               // printf("windowview got drag\n");fflush(stdout);\r
-               int i;\r
-               for (i=0;i<numberOfFiles;i++)\r
-               {\r
-                       BBString *name=bbStringFromNSString([files objectAtIndex:i]);\r
-                       maxgui_cocoamaxgui_PostCocoaGuiEvent( BBEVENT_WINDOWACCEPT,self,0,0,0,0,(BBObject*)name );\r
-               }\r
-               \r
-       }\r
-       return YES;\r
-}\r
--(void)didResize{\r
-       NSRect rect=[self localRect];\r
-       [self didMove];\r
-       PostGuiEvent( BBEVENT_WINDOWSIZE,self,0,0,rect.size.width,rect.size.height,0 );\r
-}\r
--(void)didMove{\r
-       NSRect rect=[self localRect];\r
-       PostGuiEvent( BBEVENT_WINDOWMOVE,self,0,0,rect.origin.x,rect.origin.y,0 );              \r
-}\r
--(void)zoom{\r
-       zooming = 1;\r
-}\r
--(NSRect)localRect{\r
-       NSRect rect,vis;\r
-       int style;\r
-\r
-       rect=[self frame];\r
-       style=gadget->style;\r
-       if (style&WINDOW_CLIENTCOORDS){\r
-               rect=[self contentRectForFrameRect:rect];\r
-               if (style&WINDOW_STATUS) {\r
-                       rect.size.height-=STATUSBARHEIGHT;              \r
-                       rect.origin.y+=STATUSBARHEIGHT;         \r
-               }\r
-       }\r
-       vis=[[NSScreen deepestScreen] visibleFrame];\r
-       rect.origin.x-=vis.origin.x;\r
-       rect.origin.y=vis.size.height-(rect.origin.y-vis.origin.y)-rect.size.height;    \r
-       return rect;\r
-}\r
--(BOOL)canBecomeKeyWindow{\r
-       return ([self isEnabled]);\r
-}\r
--(BOOL)canBecomeMainWindow{\r
-       return ([self isEnabled] && [self isVisible] && ([self parentWindow]==nil));\r
-}\r
--(BOOL)becomeFirstResponder{\r
-       return ([self isEnabled] && [self isVisible]);\r
-}\r
--(void)setEnabled:(BOOL)e{\r
-       enabled=e;\r
-       if (enabled) [self makeKeyWindow];\r
-}\r
--(BOOL)isEnabled{\r
-       return (enabled)?YES:NO;\r
-}\r
--(void)dealloc{\r
-       int i;\r
-       id sview;\r
-       if (gadget->style&WINDOW_STATUS) {\r
-               for (i = 0; i < 3; i++) {\r
-                       if (label[i]) {\r
-                               [label[i] removeFromSuperview];\r
-                               [label[i] release];\r
-                       }\r
-               }\r
-               \r
-               sview = [view superview];\r
-               [view removeFromSuperview];\r
-               [view release];\r
-\r
-               [sview removeFromSuperview];\r
-               [sview release];\r
-       } else {\r
-               [view removeFromSuperview];\r
-               [view release];\r
-       }\r
-\r
-       [super dealloc];\r
-}\r
-@end\r
-\r
-// ToolView\r
-\r
-@implementation ToolView\r
--(id)textFirstResponder{\r
-       id r=[self firstResponder];\r
-       //if ([r isKindOfClass:[PanelView class]]) return r;\r
-       if ([r isKindOfClass:[NSTextView class]]){\r
-               id d=[r delegate];\r
-               if( [d isKindOfClass:[NSTextField class]] ) return d;\r
-       }\r
-       return r;\r
-}\r
--(id)initWithContentRect:(NSRect)rect styleMask:(unsigned int)mask backing:(NSBackingStoreType)backing defer:(BOOL)flag withGadget:(nsgadget*)_gadget{\r
-//withStatus:(BOOL)status{\r
-       id              client;\r
-       int             i;\r
-       NSText  *l;\r
-       NSBox   *box;\r
-       dragging = nil;\r
-       self=[super initWithContentRect:rect styleMask:mask backing:backing defer:flag];\r
-       gadget=_gadget;\r
-       view=[[FlippedView alloc] init];\r
-       enabled=true;\r
-       [self setContentView:view];\r
-       [self setAcceptsMouseMovedEvents:YES];\r
-       [self disableCursorRects];      //Fixes NSSetPointer not sticking.\r
-       if (gadget->style&WINDOW_STATUS){                       //status){      //mask&NSTexturedBackgroundWindowMask)\r
-               rect.origin.x=rect.origin.y=0;\r
-               rect.size.height-=STATUSBARHEIGHT;\r
-               client=[[FlippedView alloc] initWithFrame:rect];\r
-               [client setAutoresizingMask:(NSViewWidthSizable|NSViewHeightSizable)];  \r
-               [view addSubview:client];\r
-// label for window status\r
-               rect.origin.y=rect.size.height+3;\r
-               rect.size.height=STATUSBARHEIGHT-4;             \r
-               rect.size.width-=[NSScroller scrollerWidth];\r
-               for (i=0;i<3;i++){\r
-                       l=[[NSText alloc] initWithFrame:rect];\r
-                       [l setDrawsBackground:NO];\r
-                       [l setEditable:NO];\r
-                       [l setSelectable:NO];\r
-                       [l setAutoresizingMask:NSViewWidthSizable|NSViewMinYMargin];\r
-                       switch (i){\r
-                               case 0:[l setAlignment:NSLeftTextAlignment];break;\r
-                               case 1:[l setAlignment:NSCenterTextAlignment];break;\r
-                               case 2:[l setAlignment:NSRightTextAlignment];break;\r
-                       }\r
-                       if (view) [view addSubview:l];\r
-                       label[i]=l;\r
-               }\r
-               \r
-               rect.origin.y-=3;\r
-               rect.size.height=2;\r
-               rect.size.width+=[NSScroller scrollerWidth];\r
-               \r
-               box=[[NSBox alloc] initWithFrame:rect];\r
-               [box setBoxType:NSBoxSeparator];\r
-               [box setTitlePosition:NSNoTitle];\r
-               [box setAutoresizingMask:NSViewWidthSizable|NSViewMinYMargin];\r
-               if (view) [view addSubview:box];\r
-               \r
-// set clientview to inner view\r
-               view=client;            \r
-       }\r
-       if ([self respondsToSelector: @selector(setShowsToolbarButton)]) [self setShowsToolbarButton: NO];\r
-       return self;\r
-}\r
--(id)clientView{\r
-       return view;\r
-}\r
--(void)setStatus:(NSString*)text align:(int)pos{\r
-       if (label[pos]) [label[pos] setString:text];\r
-}\r
--(void)sendEvent:(NSEvent*)event{\r
-       \r
-       static int lastHotKey;\r
-       int key;\r
-       id source;\r
-       \r
-       // Handling of Generic Key/Mouse Events\r
-       \r
-       switch( [event type] ){\r
-       case NSMouseEntered:\r
-               [self disableCursorRects];\r
-       case NSLeftMouseDown:\r
-       case NSRightMouseDown:\r
-       case NSOtherMouseDown:\r
-       {\r
-               if( [event type] != NSMouseEntered ){\r
-                       dragging = [[self contentView] hitTest:[event locationInWindow]];\r
-                       [self makeFirstResponder:dragging];\r
-               }\r
-       }\r
-       case NSMouseMoved:\r
-       case NSMouseExited:\r
-       case NSScrollWheel:\r
-       {\r
-               NSView *hitView = [[self contentView] hitTest:[event locationInWindow]];\r
-               if (hitView) EmitMouseEvent( event, hitView );\r
-               if(![self isEnabled]) return;\r
-               break;\r
-       }\r
-       case NSLeftMouseUp:\r
-       case NSRightMouseUp:\r
-       case NSOtherMouseUp:\r
-       {\r
-               //fire event for the dragged view\r
-               if (dragging) {\r
-                       EmitMouseEvent( event, dragging );\r
-                       dragging = nil;\r
-               } else {\r
-                       //fire the event for the recieving view (if it exists)\r
-                       NSView *hitView = [[self contentView] hitTest:[event locationInWindow]];\r
-                       if (hitView) EmitMouseEvent( event, hitView );\r
-               }\r
-               \r
-               if(![self isEnabled]) return;\r
-               break;\r
-       }\r
-       case NSLeftMouseDragged:\r
-       case NSRightMouseDragged:\r
-       case NSOtherMouseDragged:\r
-       {\r
-               if( dragging == nil ) dragging = [[self contentView] hitTest:[event locationInWindow]];\r
-               if( dragging ) EmitMouseEvent( event, dragging );\r
-               if(![self isEnabled]) return;\r
-               break;\r
-       }\r
-       case NSKeyDown:\r
-       case NSKeyUp:\r
-       case NSFlagsChanged:\r
-       {\r
-               NSResponder *handle=(NSResponder*)NSActiveGadget();\r
-               if( handle && EmitKeyEvent( event, handle )) return;\r
-               break;\r
-       }\r
-       }\r
-       \r
-       // End of Generic Key/Mouse Events\r
-       \r
-       // Gadget Filterkey Processing\r
-       \r
-       switch( [event type] ){\r
-       case NSKeyDown:\r
-               if( key=bbSystemTranslateKey( [event keyCode] ) ){\r
-                       int mods=bbSystemTranslateMods( [event modifierFlags] );\r
-                       BBObject *event=maxgui_maxgui_HotKeyEvent( key,mods );\r
-                       if( event!=&bbNullObject ){\r
-                               lastHotKey=key;\r
-                               brl_event_EmitEvent( event );\r
-                               return;\r
-                       }\r
-               }\r
-               source=[self textFirstResponder];\r
-               if( source && !filterKeyDownEvent( event,source ) ) return;             \r
-               if(![self isEnabled]) return;\r
-               break;\r
-       case NSKeyUp:\r
-               key=bbSystemTranslateKey([event keyCode]);\r
-               if( lastHotKey && (key==lastHotKey ) ){\r
-                       lastHotKey=0;\r
-                       return;\r
-               }\r
-               if(![self isEnabled]) return;\r
-               break;\r
-       }\r
-       lastHotKey=0;\r
-       \r
-       // End of FilterKey Processing\r
-       \r
-       [super sendEvent:event];\r
-}\r
-- (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender{\r
-//     printf("windowview got dragenter\n");fflush(stdout);\r
-       return YES;\r
-}\r
-- (BOOL)performDragOperation:(id <NSDraggingInfo>)sender{\r
-       NSPasteboard *pboard = [sender draggingPasteboard];\r
-       if ( [[pboard types] containsObject:NSFilenamesPboardType] ) {\r
-               NSArray *files = [pboard propertyListForType:NSFilenamesPboardType];\r
-               int numberOfFiles = [files count];\r
-               // Perform operation using the list of files\r
-               // printf("windowview got drag\n");fflush(stdout);\r
-               int i;\r
-               for (i=0;i<numberOfFiles;i++)\r
-               {\r
-                       BBString *name=bbStringFromNSString([files objectAtIndex:i]);\r
-                       maxgui_cocoamaxgui_PostCocoaGuiEvent( BBEVENT_WINDOWACCEPT,self,0,0,0,0,(BBObject*)name );\r
-               }\r
-               \r
-       }\r
-       return YES;\r
-}\r
--(void)didResize{\r
-       if (zooming) {\r
-               zooming = 0;\r
-               [self didMove];\r
-       }\r
-       NSRect rect=[self localRect];\r
-       PostGuiEvent( BBEVENT_WINDOWSIZE,self,0,0,rect.size.width,rect.size.height,0 );\r
-}\r
--(void)didMove{\r
-       NSRect rect=[self localRect];\r
-       PostGuiEvent( BBEVENT_WINDOWMOVE,self,0,0,rect.origin.x,rect.origin.y,0 );              \r
-}\r
--(void)zoom{\r
-       zooming = 1;\r
-}\r
--(NSRect)localRect{\r
-       NSRect rect,vis;\r
-       int style;\r
-\r
-       rect=[self frame];\r
-       style=gadget->style;\r
-       if (style&WINDOW_CLIENTCOORDS){\r
-               rect=[self contentRectForFrameRect:rect];\r
-               if (style&WINDOW_STATUS) {\r
-                       rect.size.height-=STATUSBARHEIGHT;              \r
-                       rect.origin.y+=STATUSBARHEIGHT;         \r
-               }\r
-       }\r
-       vis=[[NSScreen deepestScreen] visibleFrame];\r
-       rect.origin.x=rect.origin.x-vis.origin.x;\r
-       rect.origin.y=vis.size.height-(rect.origin.y-vis.origin.y)-rect.size.height;    \r
-       return rect;\r
-}\r
--(BOOL)canBecomeKeyWindow{\r
-       return ([self isEnabled]);\r
-}\r
--(BOOL)canBecomeMainWindow{\r
-       return ([self isEnabled] && [self isVisible] && ([self parentWindow]==nil));\r
-}\r
--(BOOL)becomeFirstResponder{\r
-       return ([self isEnabled] && [self isVisible]);\r
-}\r
--(void)setEnabled:(BOOL)e{\r
-       enabled=e;\r
-       if (enabled) [self makeKeyWindow];\r
-}\r
--(BOOL)isEnabled{\r
-       return (enabled)?YES:NO;\r
-}\r
--(void)dealloc{\r
-       int i;\r
-       id sview;\r
-       if (gadget->style&WINDOW_STATUS) {\r
-               for (i = 0; i < 3; i++) {\r
-                       if (label[i]) {\r
-                               [label[i] removeFromSuperview];\r
-                               [label[i] release];\r
-                       }\r
-               }\r
-               \r
-               sview = [view superview];\r
-               [view removeFromSuperview];\r
-               [view release];\r
-\r
-               [sview removeFromSuperview];\r
-               [sview release];\r
-       } else {\r
-               [view removeFromSuperview];\r
-               [view release];\r
-       }\r
-\r
-       [super dealloc];\r
-}\r
-@end\r
-\r
-// global app stuff\r
-\r
-void NSBegin(){\r
-       GlobalApp=[[CocoaApp alloc] init];\r
-       HaltMouseEvents=0;\r
-}\r
-\r
-void NSEnd(){\r
-       [GlobalApp release];\r
-}\r
-\r
-int NSActiveGadget(){\r
-       NSWindow        *window;\r
-       NSResponder *responder;\r
-       window=[NSApp keyWindow];\r
-       if (!window) return 0;\r
-       responder=[window firstResponder];\r
-       if (!responder) return (int)window;\r
-       if ([responder isKindOfClass:[NSTextView class]] && \r
-               [window fieldEditor:NO forObject:nil] != nil ) { \r
-                       NSTextView *view=(NSTextView*)responder;\r
-                       return (int)[view delegate];\r
-               }\r
-       return (int)responder;\r
-}\r
-\r
-void NSInitGadget(nsgadget *gadget){\r
-       NSRect                          rect,vis;\r
-       NSString                        *text;\r
-       NSView                          *view;\r
-       NSWindow                *window;\r
-       NSButton                        *button;\r
-       NSTextField                     *textfield;\r
-       TextView                        *textarea;\r
-       NSControl               *combobox;\r
-       Toolbar                 *toolbar;\r
-       TabView                         *tabber;\r
-       TreeView                        *treeview;\r
-       HTMLView                        *htmlview;\r
-       PanelView                       *panel;\r
-       PanelViewContent                *pnlcontent;\r
-       CanvasView                      *canvas;\r
-       ListView                                *listbox;\r
-       NSText                          *label;\r
-       NSBox                           *box;\r
-       NSSlider                                *slider;\r
-       NSScroller                      *scroller;\r
-       NSStepper                               *stepper;\r
-       NSProgressIndicator     *progbar;\r
-       NSMenu                          *menu;\r
-       NSMenuItem                      *menuitem;\r
-       NodeItem                        *node,*parent;\r
-       nsgadget                                *group;\r
-       int                                     style,flags;\r
-       NSImage                 *image;\r
-               \r
-       rect=NSMakeRect(gadget->x,gadget->y,gadget->w,gadget->h);\r
-       text=NSStringFromBBString(gadget->textarg);\r
-       style=gadget->style;flags=0;\r
-       group=gadget->group;\r
-       if (group==(nsgadget*)&bbNullObject) group=0;\r
-       if (group) view=gadget->group->view;\r
-       \r
-       switch (gadget->internalclass){\r
-       case GADGET_DESKTOP:\r
-               rect=[[NSScreen deepestScreen] frame];\r
-               gadget->x=rect.origin.x;\r
-               gadget->y=rect.origin.y;\r
-               gadget->w=rect.size.width;\r
-               gadget->h=rect.size.height;\r
-               break;\r
-       case GADGET_WINDOW:\r
-               vis=[[NSScreen deepestScreen] visibleFrame];\r
-               rect.origin.x+=vis.origin.x;\r
-               rect.origin.y=vis.origin.y+vis.size.height-rect.origin.y-rect.size.height;\r
-               if (style&WINDOW_TITLEBAR) flags|=NSTitledWindowMask|NSClosableWindowMask;\r
-               if (style&WINDOW_RESIZABLE){\r
-                       flags|=NSResizableWindowMask;\r
-                       if (!(group && (group->internalclass==GADGET_WINDOW))) flags |=NSMiniaturizableWindowMask;\r
-               }\r
-               if (style&WINDOW_TOOL) flags|=NSUtilityWindowMask;\r
-               [NSApp activateIgnoringOtherApps:YES];\r
-               if (!(style&WINDOW_CLIENTCOORDS)){\r
-                       rect=[NSWindow contentRectForFrameRect:rect styleMask:flags];\r
-               }else{\r
-                       if (style&WINDOW_STATUS) {\r
-                               rect.origin.y-=STATUSBARHEIGHT;         \r
-                               rect.size.height+=STATUSBARHEIGHT;              \r
-                       }\r
-               }\r
-               if (!(style&WINDOW_TOOL)) {\r
-                       window=[[WindowView alloc] initWithContentRect:rect styleMask:flags backing:NSBackingStoreBuffered defer:YES withGadget:gadget];\r
-               } else {\r
-                       window=[[ToolView alloc] initWithContentRect:rect styleMask:flags backing:NSBackingStoreBuffered defer:YES withGadget:gadget];\r
-               }\r
-               [window setOpaque:NO];\r
-               [window setAlphaValue:.999f];   \r
-               \r
-               if (style&WINDOW_HIDDEN) [window orderOut:window]; else [window makeKeyAndOrderFront:NSApp];\r
-               \r
-               if (group && (group->internalclass==GADGET_WINDOW)){\r
-                       NSWindow        *parent;\r
-                       parent=(NSWindow*)group->handle;\r
-                       if(!(style&WINDOW_HIDDEN)) [parent addChildWindow:window ordered:NSWindowAbove];\r
-                       [window setParentWindow:parent];\r
-               }\r
-               \r
-               if (style&WINDOW_ACCEPTFILES)\r
-                       [window registerForDraggedTypes:[NSArray arrayWithObject:NSFilenamesPboardType]]; \r
-               \r
-               [window setTitle:text]; \r
-               [window setDelegate:GlobalApp];\r
-               gadget->handle=window;\r
-               gadget->view=[window clientView];\r
-               break;\r
-               \r
-       case GADGET_BUTTON:\r
-               button=[[NSButton alloc] initWithFrame:rect];\r
-               [button setTitle:text];\r
-               \r
-               [button setBezelStyle:NSRoundedBezelStyle];\r
-               \r
-               switch (style&7){\r
-                       case 0:\r
-                               // Push Button Size Hack\r
-                               if (gadget->h > 30) {\r
-                                       [button setBezelStyle:NSRegularSquareBezelStyle];\r
-                               } else {\r
-                                       if (gadget->h < 24) [button setBezelStyle:NSShadowlessSquareBezelStyle];\r
-                                       else [button setBezelStyle:NSRoundedBezelStyle];\r
-                               }\r
-                               break;\r
-                       case BUTTON_CHECKBOX:\r
-                               if (style&BUTTON_PUSH){\r
-                                       [button setBezelStyle:NSShadowlessSquareBezelStyle];\r
-                                       [button setButtonType:NSPushOnPushOffButton];\r
-                               } else {\r
-                                       [button setButtonType:NSSwitchButton];\r
-                               }\r
-                               break;\r
-                       case BUTTON_RADIO:\r
-                               if (style&BUTTON_PUSH){\r
-                                       [button setBezelStyle:NSShadowlessSquareBezelStyle];\r
-                                       [button setButtonType:NSPushOnPushOffButton];\r
-                               } else {\r
-                                       [button setButtonType:NSRadioButton];\r
-                               }\r
-                               break;\r
-                       case BUTTON_OK:\r
-                               [button setKeyEquivalent:@"\r"];\r
-                               break;\r
-                       case BUTTON_CANCEL:\r
-                               [button setKeyEquivalent:@"\x1b"];\r
-                               break;\r
-               }\r
-               [button setTarget:GlobalApp];\r
-               [button setAction:@selector(buttonPush:)];\r
-               if (view) [view addSubview:button];             \r
-               gadget->handle=button;\r
-               gadget->view=button;\r
-               break;\r
-       case GADGET_PANEL:\r
-               panel=[[PanelView alloc] initWithFrame:rect];\r
-               [panel setContentViewMargins:NSMakeSize(0.0,0.0)];\r
-               pnlcontent=[[PanelViewContent alloc] initWithFrame:[[panel contentView] frame]];\r
-               [pnlcontent setAutoresizesSubviews:NO];\r
-               [panel setContentView:pnlcontent];\r
-               [panel setGadget:gadget];\r
-               [panel setStyle:style];\r
-               [panel setEnabled:true];\r
-               [panel setTitle:text];\r
-               [pnlcontent setAlpha:1.0];\r
-               if (view) [view addSubview:panel];\r
-               gadget->view=pnlcontent;\r
-               gadget->handle=panel;\r
-               break;\r
-       case GADGET_CANVAS:\r
-               canvas=[[CanvasView alloc] initWithFrame:rect];\r
-               [canvas setAutoresizesSubviews:NO];\r
-               [canvas setGadget:gadget];\r
-               if (view) [view addSubview:canvas];\r
-               [canvas setStyle:style|PANEL_ACTIVE];\r
-               [canvas setEnabled:true];\r
-               gadget->view=[canvas contentView];\r
-               gadget->handle=canvas;\r
-               break;  \r
-       case GADGET_TEXTFIELD:\r
-               if (style==TEXTFIELD_PASSWORD){\r
-                       textfield=[[NSSecureTextField alloc] initWithFrame:rect];\r
-               }else{\r
-                       textfield=[[NSTextField alloc] initWithFrame:rect];\r
-               }\r
-               [textfield setDelegate:GlobalApp];\r
-               [textfield setEditable:YES];\r
-               [[textfield cell] setWraps:NO];\r
-               [[textfield cell] setScrollable:YES];\r
-               if (view) [view addSubview:textfield];          \r
-               gadget->handle=textfield;\r
-               gadget->view=textfield;\r
-               break;\r
-       case GADGET_TEXTAREA://http://developer.apple.com/documentation/Cocoa/Conceptual/TextUILayer/Tasks/TextInScrollView.html\r
-               textarea=[[TextView alloc] initWithFrame:rect];\r
-               if (style&TEXTAREA_READONLY) [textarea setEditable:NO];\r
-               if (style&TEXTAREA_WORDWRAP) [textarea setWordWrap:YES];\r
-               if (view) [view addSubview:[textarea getScroll]];\r
-               gadget->handle=textarea;\r
-               gadget->view=[textarea getScroll];// simon was here textarea;\r
-               break;          \r
-       case GADGET_COMBOBOX:\r
-               if (rect.size.height > 26) rect.size.height = 26;\r
-               combobox=[[NSComboBox alloc] initWithFrame:rect];\r
-               [combobox setUsesDataSource:NO];\r
-               [combobox setCompletes:YES];\r
-               [combobox setDelegate:GlobalApp];               \r
-               [combobox setEditable:(style&COMBOBOX_EDITABLE)?YES:NO];                        \r
-               [combobox setSelectable:YES];                   \r
-               if (view) [view addSubview:combobox];           \r
-               gadget->handle=combobox;\r
-               gadget->view=combobox;\r
-               break;\r
-       case GADGET_LISTBOX:\r
-               listbox=[[ListView alloc] initWithFrame:rect];\r
-               if (view) [view addSubview:listbox];            \r
-               gadget->handle=listbox;\r
-               gadget->view=listbox;\r
-               break;\r
-       case GADGET_TOOLBAR:\r
-               toolbar=[[Toolbar alloc] initWithIdentifier:text];\r
-               [toolbar setSizeMode:NSToolbarSizeModeSmall];\r
-               [toolbar setDisplayMode:NSToolbarDisplayModeIconOnly];\r
-               [toolbar setDelegate:GlobalApp];\r
-               window=(WindowView*)group->handle;\r
-               [window setToolbar:toolbar];\r
-               gadget->handle=toolbar;\r
-               gadget->view=[window clientView];\r
-               break;\r
-       case GADGET_TABBER:\r
-               tabber=[[TabView alloc] initWithFrame:rect];\r
-               [tabber setAutoresizesSubviews:NO];\r
-               if (view) [view addSubview:tabber];             //[tabber hostView]];           \r
-               gadget->handle=tabber;\r
-               gadget->view=[tabber clientView];\r
-               break;\r
-       case GADGET_TREEVIEW:\r
-               treeview=[[TreeView alloc] initWithFrame:rect]; //NSOutlineView\r
-               if (view) [view addSubview:treeview];           \r
-               gadget->handle=treeview;\r
-               gadget->view=treeview;\r
-               break;\r
-       case GADGET_HTMLVIEW:\r
-               htmlview=[[HTMLView alloc] initWithFrame:rect];\r
-               if (view) [view addSubview:htmlview];\r
-               [htmlview setStyle: style];\r
-               gadget->handle=htmlview;\r
-               gadget->view=htmlview;\r
-               break;\r
-    case GADGET_LABEL: /* BaH */\r
-               switch (style&3) {\r
-               case LABEL_SEPARATOR:\r
-                       \r
-                       box=[[NSBox alloc] initWithFrame:rect];\r
-                       \r
-                       [box setTitle:text];\r
-                       [box setBoxType:NSBoxSeparator];\r
-                       [box setTitlePosition:NSNoTitle];\r
-                       \r
-                       [box setContentView:[[FlippedView alloc] init]];\r
-                       \r
-                       if (view) [view addSubview:box];\r
-                       gadget->handle=box;\r
-                       gadget->view=[box contentView];\r
-                       \r
-                       break;\r
-                       \r
-               default:\r
-                       \r
-                       textfield = [[NSTextField alloc] initWithFrame:rect];\r
-                       \r
-                       [textfield setEditable:NO];\r
-                       [textfield setDrawsBackground:NO];\r
-                       \r
-                       if ((style&3)==LABEL_SUNKENFRAME) {\r
-                               [textfield setBezeled:YES];\r
-                               [textfield setBezelStyle:NSTextFieldSquareBezel];\r
-                       } else {\r
-                               [textfield setBezeled:NO];\r
-                               if ((style&3)==LABEL_FRAME)\r
-                                       [textfield setBordered:YES];\r
-                               else\r
-                                       [textfield setBordered:NO];\r
-                       }\r
-                       \r
-                       [[textfield cell] setWraps:YES];\r
-                       [[textfield cell] setScrollable:NO];\r
-                       [textfield setStringValue:text];\r
-                       \r
-                       switch (style&24){\r
-                               case LABEL_LEFT:[textfield setAlignment:NSLeftTextAlignment];break;\r
-                               case LABEL_RIGHT:[textfield setAlignment:NSRightTextAlignment];break;\r
-                               case LABEL_CENTER:[textfield setAlignment:NSCenterTextAlignment];break;\r
-                       }               \r
-                       \r
-                       if (view) [view addSubview: textfield];\r
-                       gadget->handle=textfield;\r
-                       gadget->view=textfield;\r
-                       \r
-                       break;\r
-               }\r
-               break;                  \r
-       case GADGET_SLIDER:\r
-               switch (style&12){\r
-               case SLIDER_SCROLLBAR:\r
-                       if (rect.size.width>rect.size.height)           {\r
-                               rect.size.height=[NSScroller scrollerWidth];\r
-                       }\r
-                       else{\r
-                               rect.size.width=[NSScroller scrollerWidth];\r
-                       }\r
-                       scroller=[[NSScroller alloc] initWithFrame:rect];\r
-                       [scroller setEnabled:YES];\r
-                       [scroller setArrowsPosition:NSScrollerArrowsDefaultSetting];\r
-                       [scroller setAction:@selector(scrollerSelect:)];\r
-                       if (view) [view addSubview:scroller];           \r
-                       gadget->handle=scroller;\r
-                       gadget->view=scroller;\r
-                       break;\r
-               case SLIDER_TRACKBAR:\r
-                       slider=[[NSSlider alloc] initWithFrame:rect];\r
-                       [slider setEnabled:YES];\r
-                       [slider setAction:@selector(sliderSelect:)];\r
-                       if (view) [view addSubview:slider];\r
-                       gadget->handle=slider;\r
-                       gadget->view=slider;\r
-                       break;\r
-               case SLIDER_STEPPER:\r
-                       stepper=[[NSStepper alloc] initWithFrame:rect];\r
-                       [stepper setEnabled:YES];\r
-                       [stepper setAction:@selector(sliderSelect:)];\r
-                       [stepper setValueWraps:NO];\r
-                       if (view) [view addSubview:stepper];\r
-                       gadget->handle=stepper;\r
-                       gadget->view=stepper;\r
-                       break;\r
-               }\r
-               break;\r
-       case GADGET_PROGBAR:\r
-               progbar=[[NSProgressIndicator alloc] initWithFrame:rect];\r
-               [progbar setStyle:NSProgressIndicatorBarStyle];         \r
-               [progbar setIndeterminate:NO];\r
-               [progbar setMaxValue:1.0];\r
-               if (view) [view addSubview:progbar];            \r
-               gadget->handle=progbar;\r
-               gadget->view=progbar;\r
-               break;\r
-       case GADGET_MENUITEM:\r
-               // Allows a popup-menu to be created with no text without crashing.\r
-               if ([text length] || (group->internalclass == GADGET_DESKTOP)) {\r
-                       menuitem=[[NSMenuItem alloc] initWithTitle:text action:@selector(menuSelect:) keyEquivalent:@""];\r
-                       [menuitem setTag:style];\r
-                       [GlobalApp addMenuItem:menuitem];\r
-               }\r
-               else{\r
-                       menuitem=(NSMenuItem*)[NSMenuItem separatorItem];\r
-               }\r
-               if (group){\r
-                       switch (group->internalclass){\r
-                               case GADGET_WINDOW:             \r
-                                       menu=[[NSMenu alloc] initWithTitle:text];\r
-                                       [menu setAutoenablesItems:NO];\r
-                                       [menu setSubmenu:menu forItem:menuitem];\r
-                                       [menu release];\r
-                                       menu=[NSApp mainMenu];\r
-                                       [menu addItem:menuitem];\r
-                                       if ([text length]){\r
-                                               [menuitem release];\r
-                                       }\r
-                                       break;\r
-                               case GADGET_MENUITEM:\r
-                                       menu=(NSMenu*)[group->handle submenu];\r
-                                       if (!menu){\r
-                                               menu=(NSMenu*)[[NSMenu alloc] initWithTitle:text];\r
-                                               [menu setAutoenablesItems:NO];\r
-                                               [group->handle setSubmenu:menu];\r
-                                               [menu addItem:menuitem];\r
-                                               [menu release];\r
-                                       } else {\r
-                                               [menu addItem:menuitem];\r
-                                       }\r
-                                       if ([text length]){\r
-                                               [menuitem release];\r
-                                       }\r
-                                       break;\r
-                       }\r
-               }\r
-               gadget->handle=menuitem;\r
-               break;\r
-       case GADGET_NODE:\r
-               if (!group) break;\r
-               parent=0;\r
-               switch (group->internalclass){\r
-                       case GADGET_TREEVIEW:\r
-                               parent=[((TreeView*)group->handle) rootNode];\r
-                               break;\r
-                       case GADGET_NODE:\r
-                               parent=(NodeItem*)group->handle;\r
-                               break;\r
-               }\r
-               if (!parent) break;\r
-               node=[[NodeItem alloc] initWithTitle:text];\r
-               int index=style;\r
-               if (index==-1) index=[parent count];\r
-               if (index>[parent count]) index=[parent count];\r
-               [node attach:parent atIndex:index];\r
-               gadget->handle=node;\r
-               break;\r
-       }\r
-}\r
-\r
-@class color_delegate;\r
-@interface color_delegate:NSObject{}\r
-@end\r
-@implementation color_delegate\r
-- (void)windowWillClose:(NSNotification *)aNotification{[NSApp stopModal];}\r
-@end\r
-\r
-int NSColorRequester(int r,int g,int b){\r
-       NSColorPanel    *panel;\r
-       NSColor                 *color;\r
-       color_delegate  *dele;\r
-       dele=[[color_delegate alloc] init];\r
-       color=[NSColor colorWithCalibratedRed:r/255.0L green:g/255.0L blue:b/255.0L alpha:1.0];\r
-       panel=[NSColorPanel sharedColorPanel];\r
-       [panel setColor:color];\r
-       [panel setDelegate:dele];\r
-       [NSApp runModalForWindow:panel];\r
-       color=[panel color];\r
-       if (color){\r
-               color=[color colorUsingColorSpaceName:NSCalibratedRGBColorSpace];\r
-               r=(int)((255*[color redComponent])+0.5);\r
-               g=(int)((255*[color greenComponent])+0.5);\r
-               b=(int)((255*[color blueComponent])+0.5);\r
-       }\r
-       return 0xff000000|(r<<16)|(g<<8)|b;\r
-}\r
-\r
-@class font_delegate;\r
-@interface font_delegate:NSObject{\r
-       NSFont          *_font;\r
-}\r
--(id)initWithFont:(NSFont*)font;\r
--(void)changeFont:(id)sender;\r
--(id)font;\r
--(void)windowWillClose:(NSNotification *)aNotification;\r
--(unsigned int)validModesForFontPanel:(NSFontPanel *)fontPanel;\r
-@end\r
-@implementation font_delegate\r
--(id)initWithFont:(NSFont*)font{\r
-       _font=font;\r
-       return self;\r
-}\r
--(id)font{\r
-       return _font;\r
-}\r
--(void)changeFont:(id)sender{\r
-       _font=[sender convertFont:_font];\r
-       return; \r
-}\r
-- (void)windowWillClose:(NSNotification *)aNotification{\r
-       [NSApp stopModal];\r
-}\r
--(unsigned int)validModesForFontPanel:(NSFontPanel *)fontPanel{\r
-       return NSFontPanelFaceModeMask|NSFontPanelSizeModeMask|NSFontPanelCollectionModeMask;//|NSFontPanelUnderlineEffectModeMask;\r
-}\r
-@end\r
-\r
-int NSGetSysColor( int colorindex, int* red, int* green, int* blue ){\r
-       \r
-       float r, g, b;\r
-       NSColor* c;\r
-       NSWindow* w;\r
-       \r
-       switch(colorindex){\r
-               case GUICOLOR_WINDOWBG:\r
-                       w = [[NSWindow alloc] initWithContentRect:NSZeroRect styleMask:NSTitledWindowMask backing:NSBackingStoreBuffered defer:YES];\r
-                       c = [w backgroundColor];\r
-                       [w release];\r
-                       break;\r
-               case GUICOLOR_GADGETBG:\r
-                       c = [NSColor controlBackgroundColor];\r
-                       break;\r
-               case GUICOLOR_GADGETFG:\r
-                       c = [NSColor controlTextColor];\r
-                       break;\r
-               case GUICOLOR_SELECTIONBG:\r
-                       c = [NSColor selectedTextBackgroundColor];\r
-                       break;\r
-               default:\r
-                       return 0;\r
-                       break;\r
-       }\r
-       \r
-       [[c colorUsingColorSpaceName:NSCalibratedRGBColorSpace] getRed:&r green:&g blue:&b alpha:NULL];\r
-       *red = (int)(255 * r);\r
-       *green = (int)(255 * g);\r
-       *blue = (int)(255 * b);\r
-       \r
-       return 1;\r
-}\r
-\r
-NSFont *NSRequestFont(NSFont *font){\r
-       NSFontPanel             *panel;\r
-       font_delegate           *dele;\r
-       if (!font) font=[NSFont userFontOfSize:0];\r
-       dele=[[font_delegate alloc] initWithFont:font];\r
-       panel=[NSFontPanel sharedFontPanel];\r
-       if (font) [panel setPanelFont:font isMultiple:NO];\r
-       [panel setEnabled:YES];\r
-       [panel setDelegate:dele];\r
-       [NSApp runModalForWindow:panel];\r
-       return [dele font];\r
-}\r
-\r
-NSFont *NSLoadFont(BBString *name,double size,int flags){\r
-       NSString                        *text;\r
-       NSFont                          *font;\r
-       NSFontManager           *manager;\r
-\r
-       text=NSStringFromBBString(name);\r
-       font=[NSFont fontWithName:text size:size];\r
-       if (!font) font=[NSFont systemFontOfSize:size];\r
-       if (flags){\r
-               manager=[NSFontManager sharedFontManager];\r
-               if (flags&FONT_BOLD) font=[manager convertFont:font toHaveTrait:NSBoldFontMask];\r
-               if (flags&FONT_ITALIC) font=[manager convertFont:font toHaveTrait:NSItalicFontMask];\r
-       }\r
-       [font retain];\r
-       return font;\r
-}\r
-\r
-NSFont *NSGetDefaultFont(){\r
-       return [NSFont systemFontOfSize:[NSFont systemFontSize]];\r
-}\r
-\r
-BBString *NSFontName(NSFont *font){\r
-       return bbStringFromNSString([font displayName]);        \r
-}\r
-\r
-int NSFontStyle(NSFont *font){\r
-       int     intBBStyleFlags;\r
-       int     intCocoaFontTraits;\r
-       NSFontManager *manager;\r
-       \r
-       manager = [NSFontManager sharedFontManager];\r
-       intCocoaFontTraits = [manager traitsOfFont: font];\r
-       \r
-       intBBStyleFlags = 0;\r
-       if (intCocoaFontTraits & NSBoldFontMask) intBBStyleFlags|=FONT_BOLD;\r
-       if (intCocoaFontTraits & NSItalicFontMask) intBBStyleFlags|=FONT_ITALIC;\r
-       \r
-       return intBBStyleFlags;\r
-}\r
-\r
-double NSFontSize(NSFont *font){\r
-       return (double)[font pointSize];\r
-}\r
-\r
-void* NSSuperview(NSView* handle){\r
-       if(handle) return [handle superview];\r
-       return 0;\r
-}\r
-\r
-// generic gadget commands\r
-\r
-void NSFreeGadget(nsgadget *gadget){\r
-       nsgadget *group;\r
-       NSWindow *parent;\r
-       TextView *textview;\r
-       FlippedView * flipped;\r
-       if (gadget->textcolor){\r
-               [gadget->textcolor release];\r
-               gadget->textcolor = 0;\r
-       }\r
-       if (gadget->handle){\r
-               switch (gadget->internalclass){\r
-               case GADGET_WINDOW:\r
-                       if ([gadget->handle parentWindow]!=nil){                        \r
-                               [[gadget->handle parentWindow] removeChildWindow:(NSWindow*)gadget->handle];\r
-                       }                       \r
-                       [gadget->handle close];\r
-                       break;\r
-               case GADGET_NODE:\r
-                       [gadget->handle remove];\r
-                       [gadget->handle autorelease];\r
-                       break;\r
-               case GADGET_MENUITEM:\r
-                       [GlobalApp removeMenuItem:gadget->handle];\r
-                       [[gadget->handle menu] removeItem:gadget->handle];\r
-                       break;\r
-               case GADGET_TEXTAREA:\r
-                       textview=(TextView*)gadget->handle;                                     \r
-                       [gadget->view removeFromSuperview];\r
-                       [textview free];\r
-                       [textview autorelease];\r
-                       break;\r
-               case GADGET_LABEL:\r
-                       switch (gadget->style&3) {\r
-                       case LABEL_SEPARATOR:\r
-                               flipped=(FlippedView*)gadget->view;\r
-                               [flipped removeFromSuperview];\r
-                               [gadget->handle removeFromSuperview];\r
-                               [flipped release];\r
-                               break;\r
-                       default:\r
-                               [gadget->view removeFromSuperview];\r
-                               break;\r
-                       }\r
-                       [gadget->handle autorelease];\r
-                       break;\r
-               case GADGET_TABBER:\r
-                       flipped=(FlippedView*)gadget->view;\r
-                       [flipped removeFromSuperview];\r
-                       [gadget->handle removeFromSuperview];\r
-                       [flipped release];\r
-                       //Cocoa throws an exception if items exist when handle is autoreleased.\r
-                       NSClearItems(gadget);\r
-                       [gadget->handle autorelease];\r
-                       break;\r
-               case GADGET_PANEL:\r
-                       [gadget->handle setColor:nil];\r
-                       [gadget->handle removeFromSuperview];\r
-                       [gadget->handle autorelease];\r
-                       break;\r
-               default:\r
-                       [[gadget->view superview] setNeedsDisplayInRect:[gadget->view frame]];\r
-                       [gadget->view removeFromSuperview];\r
-                       [gadget->handle autorelease];\r
-                       break;\r
-               }       \r
-       }\r
-       gadget->handle=0;\r
-}\r
-\r
-void NSEnable(nsgadget *gadget,int state){\r
-       switch (gadget->internalclass){\r
-       case GADGET_WINDOW:\r
-       case GADGET_SLIDER:\r
-       case GADGET_TEXTFIELD:\r
-       case GADGET_MENUITEM:\r
-       case GADGET_BUTTON:\r
-       case GADGET_LISTBOX:\r
-       case GADGET_COMBOBOX:\r
-       case GADGET_TREEVIEW:\r
-       case GADGET_PANEL:\r
-       case GADGET_CANVAS:\r
-               [gadget->handle setEnabled:state];\r
-               break;\r
-       case GADGET_TEXTAREA:\r
-               [gadget->handle setSelectable:state];\r
-               if (!(gadget->style&TEXTAREA_READONLY)) [gadget->handle setEditable:state];\r
-               break;\r
-       }\r
-}\r
-\r
-void NSShow(nsgadget *gadget,int state){\r
-       switch (gadget->internalclass){\r
-       case GADGET_WINDOW:\r
-               if (state==[gadget->handle isVisible]) return;\r
-               if (state) {\r
-                       if((gadget->group!=&bbNullObject) && (gadget->group->internalclass==GADGET_WINDOW) &&\r
-                       ([gadget->handle parentWindow]==nil)) [gadget->group->handle addChildWindow: gadget->handle ordered:NSWindowAbove];\r
-                       [gadget->handle makeKeyAndOrderFront:NSApp];\r
-               } else {\r
-                       if([gadget->handle parentWindow]!=nil) [[gadget->handle parentWindow] removeChildWindow:(NSWindow*)gadget->handle];\r
-                       [gadget->handle orderOut:NSApp];\r
-               }\r
-               break;\r
-       case GADGET_TOOLBAR:\r
-               [gadget->handle setVisible:state];\r
-               break;\r
-       default:\r
-               [gadget->handle setHidden:!state];\r
-       }\r
-}\r
-\r
-void NSCheck(nsgadget *gadget,int state){\r
-       NSButton                        *button;\r
-       switch (gadget->internalclass){\r
-       case GADGET_MENUITEM:\r
-               [gadget->handle setState:state];\r
-               break;\r
-       case GADGET_BUTTON:\r
-               button=(NSButton *)gadget->handle;\r
-               if(state==NSMixedState) [button setAllowsMixedState:YES]; else [button setAllowsMixedState:NO];\r
-               [button setState:state];\r
-               break; \r
-       }\r
-}\r
-\r
-void NSPopupMenu(nsgadget *gadget,nsgadget *menugadget){\r
-       NSView                  *view;\r
-       NSWindow                        *window;\r
-       NSMenuItem              *menuitem;\r
-       NSEvent                 *event;\r
-       NSPoint                 loc;\r
-       \r
-       window=(NSWindow*)gadget->handle;\r
-       view=gadget->view;\r
-       menuitem=(NSMenuItem*)menugadget->handle;\r
-       event=[NSEvent \r
-               mouseEventWithType:NSRightMouseUp \r
-               location:[window convertScreenToBase:[NSEvent mouseLocation]]\r
-               modifierFlags:nil \r
-               timestamp:0 \r
-               windowNumber:[window windowNumber] \r
-       context:nil\r
-               eventNumber:nil\r
-               clickCount:1 \r
-               pressure:0];\r
-       [NSMenu popUpContextMenu:[menuitem submenu] withEvent:event forView:view];              \r
-//     [event release];\r
-}\r
-\r
-int NSState(nsgadget *gadget){\r
-       NSWindow                *window;\r
-       TextView                *textview;\r
-       NSButton                *button;\r
-       NSView          *view;\r
-       Toolbar         *toolbar;\r
-       HTMLView                *browser;\r
-       NSMenuItem      *menuItem;\r
-       int                     state;\r
-\r
-       state=0;\r
-\r
-       switch (gadget->internalclass){\r
-       case GADGET_TEXTAREA:\r
-               textview=(TextView*)gadget->handle;\r
-               if ([textview isHidden]) state|=STATE_HIDDEN;\r
-               if ((!(gadget->style&TEXTAREA_READONLY)) && (![textview isEditable])) state|=STATE_DISABLED;\r
-               break;\r
-       case GADGET_HTMLVIEW:\r
-               browser=(HTMLView*)gadget->handle;\r
-               return [browser loaded];\r
-       case GADGET_WINDOW:\r
-               window=(NSWindow*)gadget->handle;\r
-               if ([window isMiniaturized]) state|=STATE_MINIMIZED;\r
-               if ([window isZoomed]) state|=STATE_MAXIMIZED;\r
-               if (![window isVisible]) state|=STATE_HIDDEN;\r
-               break;\r
-       case GADGET_MENUITEM:\r
-               menuItem=(NSMenuItem*)gadget->handle;\r
-               if ([menuItem state]==NSOnState) state|=STATE_SELECTED;\r
-               if (![menuItem isEnabled]) state|=STATE_DISABLED;\r
-               break;\r
-       case GADGET_BUTTON:\r
-               button=(NSButton *)gadget->handle;\r
-               switch (gadget->style&7){\r
-                       case BUTTON_RADIO: case BUTTON_CHECKBOX:\r
-                       if ([button state]==NSOnState) state|=STATE_SELECTED;\r
-                       if ([button state]==NSMixedState) state|=STATE_INDETERMINATE;\r
-               }\r
-               if ([button isHidden]) state|=STATE_HIDDEN;\r
-               if (![button isEnabled]) state|=STATE_DISABLED;\r
-               break;\r
-       case GADGET_TOOLBAR:\r
-               toolbar=(Toolbar*)gadget->handle;\r
-               if ([toolbar isVisible]==NO) state|=STATE_HIDDEN;\r
-               break;          \r
-       case GADGET_PROGBAR:\r
-               view=(NSView*)gadget->handle;\r
-               if ([view isHidden]) state|=STATE_HIDDEN;\r
-               break;\r
-       default:\r
-               view=(NSView*)gadget->handle;\r
-               if ([view isHidden]) state|=STATE_HIDDEN;\r
-               if (![view isEnabled]) state|=STATE_DISABLED;\r
-               break;\r
-       }\r
-       return state;\r
-}\r
-\r
-void NSSetMinimumSize(nsgadget *gadget,int width,int height){\r
-       NSWindow        *window;\r
-       NSRect  rect;\r
-       int             style;\r
-       window=(NSWindow*)gadget->handle;\r
-       rect.origin.x=0;\r
-       rect.origin.y=0;\r
-       rect.size.width=width;\r
-       rect.size.height=height;\r
-       style=gadget->style;\r
-       if (!(style&WINDOW_CLIENTCOORDS)){\r
-               rect=[window contentRectForFrameRect:rect];\r
-               rect.size.width-=rect.origin.x;\r
-               rect.size.height-=rect.origin.y;\r
-       }else{\r
-               if (style&WINDOW_STATUS) rect.size.height+=STATUSBARHEIGHT;             \r
-       }\r
-       [window setContentMinSize:rect.size];\r
-}\r
-\r
-void NSSetMaximumSize(nsgadget *gadget,int width,int height){\r
-       NSWindow        *window;\r
-       NSRect  rect;\r
-       int             style;\r
-       window=(NSWindow*)gadget->handle;\r
-       rect.origin.x=0;\r
-       rect.origin.y=0;\r
-       rect.size.width=width;\r
-       rect.size.height=height;\r
-       style=gadget->style;\r
-       if (!(style&WINDOW_CLIENTCOORDS)){\r
-               rect=[window contentRectForFrameRect:rect];\r
-               rect.size.width-=rect.origin.x;\r
-               rect.size.height-=rect.origin.y;\r
-       }else{\r
-               if (style&WINDOW_STATUS) rect.size.height+=STATUSBARHEIGHT;             \r
-       }\r
-       [window setContentMaxSize:rect.size];\r
-}\r
-\r
-\r
-void NSSetStatus(nsgadget *gadget,BBString *data,int pos){\r
-       NSString                        *text;\r
-       WindowView                      *window;\r
-       ToolView                        *toolview;\r
-\r
-       text=NSStringFromBBString(data);\r
-       if ((gadget->style&WINDOW_TOOL) == 0) {\r
-               window=(WindowView*)gadget->handle;\r
-               [window setStatus:text align:pos];\r
-       } else {\r
-               toolview =(ToolView*)gadget->handle;\r
-               [toolview setStatus:text align:pos];\r
-       }\r
-}\r
-\r
-int NSClientWidth(nsgadget *gadget){\r
-       NSRect          frame;  \r
-       if (gadget->internalclass==GADGET_DESKTOP){\r
-               frame=[[NSScreen deepestScreen] visibleFrame];\r
-               return frame.size.width;\r
-       }\r
-       if (!gadget->view) return gadget->w;\r
-       frame=[gadget->view frame]; \r
-       return frame.size.width;\r
-}\r
-\r
-int NSClientHeight(nsgadget *gadget){\r
-       NSRect          frame;\r
-       if (gadget->internalclass==GADGET_DESKTOP){\r
-               frame=[[NSScreen deepestScreen] visibleFrame];\r
-               return frame.size.height;\r
-       }\r
-       if (!gadget->view) return gadget->h;\r
-       frame=[gadget->view frame]; \r
-       return frame.size.height;\r
-}\r
-\r
-void NSRedraw(nsgadget *gadget){\r
-       NSView  *view;\r
-       \r
-       view=(NSView*)gadget->handle;\r
-       [view display]; //Can just call the display method\r
-}\r
-\r
-void NSActivate(nsgadget *gadget,int code){\r
-       NSWindow        *window;\r
-       NSView          *view;\r
-       NSRect          frame;\r
-       NodeItem        *node;\r
-       TreeView        *treeview;\r
-       HTMLView        *browser;\r
-       TextView        *textview;\r
-       NSTextField *textfield;\r
-       NSText *text;\r
-       NSComboBox *combo;\r
-\r
-// generic commands\r
-\r
-       switch (code){\r
-       case ACTIVATE_REDRAW:\r
-               NSRedraw(gadget);\r
-               return;\r
-       }\r
-       \r
-// gadget specific     \r
-\r
-       switch (gadget->internalclass){\r
-       case GADGET_WINDOW:\r
-               window=(NSWindow*)gadget->handle;\r
-               switch (code){\r
-               case ACTIVATE_FOCUS:\r
-                       if([window isVisible]) [window makeKeyAndOrderFront:NSApp];             \r
-                       break;\r
-               case ACTIVATE_CUT:\r
-                       break;\r
-               case ACTIVATE_COPY:\r
-                       break;\r
-               case ACTIVATE_PASTE:\r
-                       break;\r
-               case ACTIVATE_MINIMIZE:\r
-                       NSShow(gadget,true);\r
-                       [window miniaturize:window];\r
-                       break;\r
-               case ACTIVATE_MAXIMIZE:\r
-                       if ([window isMiniaturized]) [window deminiaturize:window];\r
-                       if ([window isZoomed]==NO) [window performZoom:window];\r
-                       NSShow(gadget,true);\r
-                       break;\r
-               case ACTIVATE_RESTORE:\r
-                       if ([window isMiniaturized]) [window deminiaturize:window];\r
-                       if ([window isZoomed]) [window performZoom:window];\r
-                       NSShow(gadget,true);\r
-                       break;\r
-               }\r
-               break;\r
-\r
-       case GADGET_TEXTFIELD:\r
-               textfield=(NSTextField*)gadget->handle;\r
-               window=[textfield window];\r
-               if (window) \r
-               switch (code){\r
-               case ACTIVATE_FOCUS:\r
-                       [window makeFirstResponder:textfield];\r
-                       break;\r
-               case ACTIVATE_CUT:\r
-                       text=[[textfield window] fieldEditor:YES forObject:textfield];\r
-                       [text cut:textfield];\r
-                       break;  \r
-               case ACTIVATE_COPY:\r
-                       text=[[textfield window] fieldEditor:YES forObject:textfield];\r
-                       [text copy:textfield];\r
-                       break;  \r
-               case ACTIVATE_PASTE:\r
-                       text=[[textfield window] fieldEditor:YES forObject:textfield];\r
-                       [text paste:textfield];\r
-                       break;\r
-               }\r
-               break;\r
-\r
-       case GADGET_TEXTAREA:\r
-               textview=(TextView*)gadget->handle;\r
-               switch (code){\r
-               case ACTIVATE_FOCUS:\r
-                       window=[textview window];\r
-                       if (window) [window makeFirstResponder:textview];\r
-                       break;\r
-               case ACTIVATE_CUT:\r
-                       [textview cut:textview];\r
-                       break;  \r
-               case ACTIVATE_COPY:\r
-                       [textview copy:textview];\r
-                       break;  \r
-               case ACTIVATE_PASTE:\r
-                       [textview pasteAsPlainText:textview];//paste:textview];\r
-                       break;          \r
-               case ACTIVATE_PRINT:\r
-                       [textview print:textview];\r
-                       break;\r
-               }\r
-               break;\r
-\r
-       case GADGET_NODE:\r
-               node=(NodeItem*)gadget->handle;\r
-               treeview=[node getOwner];\r
-               switch (code){  \r
-               case ACTIVATE_SELECT:\r
-                       [treeview selectNode:node];                     \r
-                       break;\r
-               case ACTIVATE_EXPAND:\r
-                       [treeview expandNode:node];\r
-                       break;\r
-               case ACTIVATE_COLLAPSE:\r
-                       [treeview collapseNode:node];\r
-                       break;\r
-               }\r
-               break;\r
-                               \r
-       case GADGET_COMBOBOX:\r
-               switch (code){\r
-               case ACTIVATE_FOCUS:\r
-                       combo=(NSComboBox*)gadget->handle;\r
-                       [combo selectText:nil];\r
-                       break;  \r
-               }\r
-               break;\r
-\r
-       case GADGET_HTMLVIEW:\r
-               browser=(HTMLView*)gadget->handle;\r
-               switch(code){\r
-               case ACTIVATE_COPY:\r
-                       [browser copy:browser];\r
-                       break;  \r
-               case ACTIVATE_BACK:\r
-                       [browser goBack:browser];\r
-                       break;\r
-               case ACTIVATE_FORWARD:\r
-                       [browser goForward:browser];\r
-                       break;\r
-               case ACTIVATE_PRINT:\r
-                       view = [[[browser mainFrame] frameView] documentView];\r
-                       if (view != nil) [view print:view];\r
-                       break;\r
-               }\r
-                                               \r
-       default:\r
-               switch (code){\r
-               case ACTIVATE_FOCUS:\r
-                       window=[gadget->handle window];\r
-                       if (window) [window makeFirstResponder:gadget->handle];\r
-                       break;\r
-               }\r
-       }\r
-}\r
-\r
-void NSRethink(nsgadget *gadget){\r
-       NSView          *view;\r
-       NSRect          rect,vis;\r
-       TextView        *textview;\r
-       TabView         *tabber;\r
-       NSButton                *button;\r
-       NSControl       *combobox;\r
-       int                     shouldhide;\r
-       \r
-       view=(NSView*)gadget->handle;\r
-       rect=NSMakeRect(gadget->x,gadget->y,gadget->w,gadget->h);\r
-       \r
-       shouldhide = FALSE;\r
-       \r
-       switch(gadget->internalclass){\r
-       case GADGET_WINDOW:\r
-               vis=[[NSScreen deepestScreen] visibleFrame];\r
-               rect.origin.x+=vis.origin.x;\r
-               rect.origin.y=vis.origin.y+vis.size.height-rect.origin.y-rect.size.height;\r
-               if ((gadget->style&WINDOW_CLIENTCOORDS)!=0){\r
-                       if (gadget->style&WINDOW_STATUS) {\r
-                               rect.origin.y-=STATUSBARHEIGHT;         \r
-                               rect.size.height+=STATUSBARHEIGHT;              \r
-                       }\r
-                       rect = [(NSWindow*)view frameRectForContentRect:rect];\r
-               }\r
-               \r
-               if(![view isVisible]) shouldhide = TRUE;\r
-               [view setFrame:rect display:YES];\r
-               if(shouldhide) [view orderOut:view];\r
-               return;\r
-       case GADGET_NODE:\r
-       case GADGET_MENUITEM:\r
-       case GADGET_TOOLBAR:\r
-               return;\r
-       case GADGET_TEXTAREA:\r
-               textview=(TextView*)view;\r
-               [textview setScrollFrame:rect];\r
-               return;\r
-       case GADGET_COMBOBOX:\r
-               if (rect.size.height > 26) rect.size.height = 26;\r
-               break;\r
-       case GADGET_BUTTON:\r
-               button=(NSButton*)view;\r
-               // Push Button Size Hack\r
-               if ((gadget->style&7)==0){\r
-                       if (gadget->h > 30) {\r
-                               [button setBezelStyle:NSRegularSquareBezelStyle];\r
-                       } else {\r
-                               if (gadget->h < 24) { \r
-                                       [button setBezelStyle:NSShadowlessSquareBezelStyle];\r
-                               } else {\r
-                                       [button setBezelStyle:NSRoundedBezelStyle];\r
-                               }\r
-                       }       \r
-               }\r
-               break;\r
-       case GADGET_SLIDER:\r
-               switch (gadget->style&12){\r
-                       case SLIDER_SCROLLBAR:\r
-                               if (gadget->style & SLIDER_HORIZONTAL)\r
-                                       rect.size.height = [NSScroller scrollerWidth];\r
-                               else\r
-                                       rect.size.width = [NSScroller scrollerWidth];           \r
-                               break;\r
-               }\r
-       }\r
-       [[view superview] setNeedsDisplayInRect:[view frame]];\r
-       [view setFrame:rect];\r
-       [view setNeedsDisplay:YES];     \r
-}\r
-\r
-void NSRemoveColor(nsgadget *gadget){\r
-       switch (gadget->internalclass){\r
-       case GADGET_BUTTON:\r
-               if ([[gadget->handle cell] respondsToSelector:@selector(setDrawsBackground)]){\r
-                       [[gadget->handle cell] setDrawsBackground:false];\r
-               }\r
-               break;\r
-       case GADGET_WINDOW:\r
-               [gadget->handle setBackgroundColor:nil];\r
-               [gadget->handle display];\r
-               break;\r
-       case GADGET_LABEL:\r
-               if((gadget->style&3)==LABEL_SEPARATOR) break;\r
-       case GADGET_COMBOBOX:\r
-       case GADGET_TEXTFIELD:\r
-               [gadget->handle setDrawsBackground:false];\r
-               break;\r
-       case GADGET_LISTBOX:\r
-       case GADGET_TREEVIEW:\r
-       case GADGET_PANEL:\r
-       case GADGET_TEXTAREA:\r
-               [gadget->handle setColor:nil];\r
-               break;  \r
-       }\r
-}\r
-\r
-void NSSetColor(nsgadget *gadget,int r,int g,int b){\r
-       NSColor                         *color;\r
-\r
-       color=[NSColor colorWithDeviceRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:1.0];\r
-       \r
-       switch (gadget->internalclass){\r
-       case GADGET_BUTTON:\r
-               if ([[gadget->handle cell] respondsToSelector:@selector(setBackgroundColor)]) [[gadget->handle cell] setBackgroundColor:color];\r
-               break;\r
-       case GADGET_COMBOBOX:\r
-       case GADGET_WINDOW:\r
-               [gadget->handle setBackgroundColor:color];\r
-               [gadget->handle display];\r
-               break;\r
-       case GADGET_LABEL:\r
-               if((gadget->style&3)==LABEL_SEPARATOR) break;\r
-               [gadget->handle setDrawsBackground:YES];\r
-       case GADGET_TEXTFIELD:\r
-               [gadget->handle setBackgroundColor:color];\r
-               break;\r
-       case GADGET_LISTBOX:\r
-       case GADGET_TREEVIEW:\r
-       case GADGET_PANEL:\r
-       case GADGET_TEXTAREA:\r
-               [gadget->handle setColor:color];\r
-               break;  \r
-       }\r
-}\r
-\r
-void NSSetAlpha(nsgadget *gadget,float alpha){\r
-       NSWindow        *window;\r
-       PanelView       *panel;\r
-       \r
-       switch (gadget->internalclass){\r
-       case GADGET_WINDOW:\r
-               window=(NSWindow*)gadget->handle;\r
-               [window setAlphaValue:alpha];\r
-               break;          \r
-       case GADGET_PANEL:\r
-               panel=(PanelView*)gadget->handle;\r
-               [panel setAlpha:alpha];\r
-               break;  \r
-       }\r
-}\r
-\r
-BBString *NSGetUserName(){\r
-       return bbStringFromNSString(CSCopyUserName(true));\r
-}\r
-\r
-BBString *NSGetComputerName(){\r
-       return bbStringFromNSString(CSCopyMachineName());\r
-}\r
-\r
-BBString *NSRun(nsgadget *gadget,BBString *text){\r
-       HTMLView                        *htmlview;\r
-       NSString                        *script;\r
-       BBString                        *result;\r
-\r
-       result=&bbEmptyString;\r
-       switch (gadget->internalclass){\r
-       case GADGET_HTMLVIEW:\r
-               htmlview=(HTMLView*)gadget->handle;\r
-               script=NSStringFromBBString(text);\r
-               script=[htmlview stringByEvaluatingJavaScriptFromString:script];\r
-               result=bbStringFromNSString(script);\r
-               break;\r
-       }\r
-       return result;\r
-}\r
-\r
-void NSSetText(nsgadget *gadget,BBString *data){\r
-       NSString                                *text;\r
-       NSMutableDictionary     *textAttributes;\r
-       NSMutableParagraphStyle *parastyle;\r
-       NSAttributedString              *attribtext;\r
-       NSObject                                *nsobject;\r
-       \r
-       attribtext = nil;\r
-       \r
-       if(data == nil) data = &bbEmptyString;\r
-       \r
-       text = NSStringFromBBString(data);\r
-       \r
-       nsobject = (NSObject*)gadget->handle;\r
-       \r
-       //printf( "data->length: %d\n", data->length );fflush(stdout);\r
-       \r
-       switch (gadget->internalclass){\r
-       case GADGET_TEXTAREA:\r
-               [nsobject setText:text];\r
-               break;\r
-       case GADGET_HTMLVIEW:\r
-               [nsobject setAddress:text];\r
-               break;\r
-       case GADGET_LABEL: /* BaH */\r
-               switch (gadget->style&3) {\r
-               case LABEL_SEPARATOR:\r
-                       return;\r
-               default:\r
-                       [nsobject setStringValue:text];\r
-                       return;\r
-               }\r
-               break;\r
-       case GADGET_BUTTON:\r
-               \r
-               //if ([nsobject respondsToSelector:@selector(setAttributedTitle)] /*&& [nsobject respondsToSelector:@selector(font)]*/){\r
-                       \r
-                       // Create attribute dictionary (autorelease'd)\r
-                       textAttributes = [NSMutableDictionary dictionary];\r
-                       \r
-                       // Font\r
-                       [textAttributes setObject: [nsobject font] forKey:NSFontAttributeName];\r
-       \r
-                       // Paragraph style\r
-                       parastyle = [[NSMutableParagraphStyle alloc] init];\r
-                       [parastyle setParagraphStyle:[NSParagraphStyle defaultParagraphStyle]];\r
-                       \r
-                       if(gadget->internalclass == GADGET_BUTTON){\r
-                               if(((gadget->style & BUTTON_PUSH) == BUTTON_PUSH) ||\r
-                                 (((gadget->style & 7) != BUTTON_RADIO) &&\r
-                                  ((gadget->style & 7) != BUTTON_CHECKBOX)))\r
-                                       [parastyle setAlignment:NSCenterTextAlignment];\r
-                       }\r
-                       \r
-                       [textAttributes setObject: parastyle forKey:NSParagraphStyleAttributeName];\r
-                       [parastyle release];\r
-                       \r
-                       // Text color\r
-                       if(gadget->textcolor) [textAttributes setObject: gadget->textcolor forKey: NSForegroundColorAttributeName];\r
-                       \r
-                       // Underline / strikethrough\r
-                       [textAttributes setObject: [NSNumber numberWithInt:0] forKey: NSUnderlineStyleAttributeName];\r
-                       [textAttributes setObject: [NSNumber numberWithInt:0] forKey: NSStrikethroughStyleAttributeName];\r
-                       \r
-                       if ((gadget->intFontStyle&FONT_UNDERLINE)!=0) [textAttributes setObject: [NSNumber numberWithInt:(NSUnderlineStyleSingle|NSUnderlinePatternSolid)] forKey: NSUnderlineStyleAttributeName];\r
-                       if ((gadget->intFontStyle&FONT_STRIKETHROUGH)!=0) [textAttributes setObject: [NSNumber numberWithInt:(NSUnderlineStyleSingle|NSUnderlinePatternSolid)] forKey: NSStrikethroughStyleAttributeName];\r
-                       \r
-                       // Create attibuted text\r
-                       attribtext = [[NSAttributedString alloc] initWithString: text attributes: textAttributes];\r
-                       \r
-                       [nsobject setAttributedTitle:attribtext];\r
-                       break;\r
-               //}\r
-       case GADGET_MENUITEM:\r
-               [nsobject setTitle:text];\r
-               // Required otherwise root window menus aren't updated.\r
-               [[nsobject submenu] setTitle:text];\r
-               break;\r
-       case GADGET_PANEL:\r
-       case GADGET_NODE:\r
-       case GADGET_WINDOW:\r
-               [nsobject setTitle:text];\r
-               break;\r
-       case GADGET_COMBOBOX:\r
-               if(!(gadget->style & COMBOBOX_EDITABLE)) break;\r
-       case GADGET_TEXTFIELD:\r
-               [nsobject setStringValue:text];\r
-               break;\r
-       }\r
-}\r
-\r
-BBString *NSGetText(nsgadget *gadget){\r
-       \r
-       NSObject                *nsobject;\r
-       BBString                *result;\r
-\r
-       result=&bbEmptyString;\r
-       nsobject=(NSObject*)gadget->handle;\r
-       \r
-       switch (gadget->internalclass){\r
-       case GADGET_TEXTAREA:\r
-               result=bbStringFromNSString([[nsobject storage] string]);\r
-               break;\r
-       case GADGET_TEXTFIELD:\r
-       case GADGET_COMBOBOX:\r
-               result=bbStringFromNSString([nsobject stringValue]);\r
-               break;  \r
-       case GADGET_HTMLVIEW:\r
-               result=bbStringFromNSString([nsobject address]);\r
-               break;\r
-       case GADGET_NODE:\r
-               result=bbStringFromNSString([nsobject value]);\r
-               break;\r
-       case GADGET_LABEL: /* BaH */\r
-               switch (gadget->style&3) {\r
-               case 0:\r
-               case LABEL_FRAME:\r
-               case LABEL_SUNKENFRAME:\r
-                       result=bbStringFromNSString([nsobject stringValue]);\r
-               }\r
-               break;\r
-       case GADGET_PANEL:\r
-       case GADGET_WINDOW:\r
-       case GADGET_BUTTON:\r
-       case GADGET_MENUITEM:\r
-               result=bbStringFromNSString([nsobject title]);\r
-               break;\r
-       }\r
-       return result;\r
-}\r
-\r
-int NSCharWidth(NSFont *font,int charcode){    \r
-       NSSize size=[font advancementForGlyph:charcode];\r
-       return (int)size.width;\r
-}\r
-\r
-void NSSetFont(nsgadget *gadget,NSFont *font){\r
-       NSView                  *view;\r
-       \r
-       view = (NSView*)gadget->handle;\r
-       \r
-       switch (gadget->internalclass){\r
-               case GADGET_LABEL:\r
-                       if ((gadget->style&3)==LABEL_SEPARATOR) break;\r
-               case GADGET_BUTTON:\r
-                       [view setFont:font];\r
-                       NSSetText(gadget, NSGetText(gadget));           //Apply underline/strikethough formatting as attributed text in NSSetText().\r
-                       break;\r
-               case GADGET_LISTBOX:\r
-               case GADGET_TREEVIEW:\r
-               case GADGET_COMBOBOX:\r
-               case GADGET_TEXTAREA:\r
-               case GADGET_TEXTFIELD:\r
-               case GADGET_TABBER:\r
-                       [view setFont:font];\r
-                       break;\r
-               \r
-       }\r
-}\r
-\r
-BBString * NSGetTooltip(nsgadget *gadget){\r
-\r
-       BBString                        *result;\r
-       NSView                  *view;\r
-       \r
-       result=&bbEmptyString;\r
-       view=(NSView*)gadget->handle;\r
-       \r
-       if(view) result=bbStringFromNSString([view toolTip]);\r
-       \r
-       return result;\r
-}\r
-\r
-int NSSetTooltip(nsgadget *gadget,BBString *data){\r
-       \r
-       NSString                        *text;\r
-       NSView                  *view;\r
-       \r
-       view =(NSView*)gadget->handle;\r
-       text=NSStringFromBBString(data);\r
-       \r
-       if(view){\r
-               [view setToolTip:text];\r
-               return 1;\r
-       }\r
-       \r
-       return 0;\r
-}\r
-\r
-// gadgetitem commands\r
-\r
-void NSClearItems(nsgadget *gadget)\r
-{\r
-       ListView                        *listbox;\r
-       NSControl               *combo;\r
-       NSTabView                       *tabber;\r
-       Toolbar                 *toolbar;\r
-       NSToolbarItem           *item;\r
-       NSArray                 *items;\r
-       int                             i,n;\r
-               \r
-       switch (gadget->internalclass){\r
-       case GADGET_LISTBOX:\r
-               listbox=(ListView*)gadget->handle;\r
-               [listbox clear];\r
-               break;\r
-       case GADGET_COMBOBOX:\r
-               combo=(NSControl*)gadget->handle;\r
-               [combo removeAllItems];\r
-               break;\r
-       case GADGET_TABBER:\r
-               tabber=(NSTabView*)gadget->handle;\r
-               items=[tabber tabViewItems];\r
-               n=[tabber numberOfTabViewItems];\r
-               for (i=0;i<n;i++) [tabber removeTabViewItem:[tabber tabViewItemAtIndex:0]];\r
-               break;\r
-       case GADGET_TOOLBAR:\r
-               toolbar=(Toolbar*)gadget->handle;\r
-               items=[toolbar items];\r
-               n=[items count];\r
-               for (i=0;i<n;i++)       [toolbar removeItemAtIndex:0];\r
-               break;\r
-       }\r
-}\r
-\r
-void NSAddItem(nsgadget *gadget,int index,BBString *data,BBString *tip,NSImage *image,BBObject *extra){\r
-       NSString                        *text,*tiptext;\r
-       NSControl               *combo;\r
-       NSTabView                       *tabber;\r
-       TabViewItem             *tabitem;\r
-       ListView                        *listbox;\r
-       Toolbar                 *toolbar;\r
-       NSToolbarItem           *item;\r
-\r
-       text=NSStringFromBBString(data);\r
-       tiptext=NSStringFromBBString(tip);\r
-       switch (gadget->internalclass){\r
-       case GADGET_LISTBOX:\r
-               listbox=(ListView*)gadget->handle;\r
-               [listbox addItem:text atIndex:index withImage:image withTip:tiptext withExtra:extra];\r
-               break;\r
-       case GADGET_COMBOBOX:\r
-               combo=(NSControl*)gadget->handle;\r
-               [combo insertItemWithObjectValue:text atIndex:index];\r
-//             [[combo itemAtIndex:index] setImage:image];\r
-               break;\r
-       case GADGET_TABBER:\r
-               tabber=(NSTabView*)gadget->handle;      \r
-               tabitem=[[TabViewItem alloc] initWithIdentifier:text];\r
-               [tabitem setLabel:text];\r
-               [tabitem setImage:image];\r
-               [tabber insertTabViewItem:tabitem atIndex:index];       \r
-               [tabitem release];\r
-               break;\r
-       case GADGET_TOOLBAR:    \r
-               toolbar=(Toolbar*)gadget->handle;\r
-               if (image==0){                  \r
-                       int v;\r
-                       Gestalt( 'sysv',&v );\r
-                       if( v>=0x1070 ){\r
-                               [toolbar insertItemWithItemIdentifier:NSToolbarSpaceItemIdentifier atIndex:index];\r
-                       }else{\r
-                               [toolbar insertItemWithItemIdentifier:NSToolbarSeparatorItemIdentifier atIndex:index];\r
-                       }\r
-               }\r
-               else{\r
-                       item=[[NSToolbarItem alloc] initWithItemIdentifier:text];\r
-                       [item setImage:image];\r
-//                     [item setLabel:text];\r
-                       [item setAction:@selector(iconSelect:)];\r
-                       [item setTarget:GlobalApp];\r
-                       [item setToolTip:tiptext];\r
-                       [item setTag:0];\r
-                       [GlobalApp addToolbarItem:item];\r
-                       [toolbar addToolbarItem:item];\r
-                       [toolbar insertItemWithItemIdentifier:text atIndex:index];                                                              \r
-               }\r
-               break;\r
-       }\r
-}\r
-\r
-NSToolbarItem *FindToolbarItem(NSToolbar *toolbar,int index){\r
-       return (NSToolbarItem*)[[toolbar items] objectAtIndex:index];\r
-}\r
-\r
-void NSSetItem(nsgadget *gadget,int index,BBString *data,BBString *tip,NSImage *image,BBObject *extra){\r
-       NSString                        *text,*tiptext;\r
-       NSControl               *combo;\r
-       NSTabView                       *tabber;\r
-       TabViewItem             *tabitem;\r
-       ListView                        *listbox;\r
-       Toolbar                 *toolbar;\r
-       NSToolbarItem           *item;\r
-\r
-       text=NSStringFromBBString(data);\r
-       tiptext=NSStringFromBBString(tip);\r
-\r
-       switch (gadget->internalclass){\r
-       case GADGET_LISTBOX:\r
-               listbox=(ListView*)gadget->handle;\r
-               [listbox setItem:text atIndex:index withImage:image withTip:tiptext withExtra:extra];\r
-               break;\r
-       case GADGET_COMBOBOX:\r
-               combo=(NSControl*)gadget->handle;\r
-               [combo removeItemAtIndex:index];\r
-               [combo insertItemWithObjectValue:text atIndex:index];\r
-//             [[combo itemAtIndex:index] setImage:image];\r
-               break;\r
-       case GADGET_TABBER:\r
-               tabber=(NSTabView*)gadget->handle;\r
-               tabitem=(TabViewItem*)[tabber tabViewItemAtIndex:index];\r
-               [tabitem setLabel:text];\r
-               [tabitem setImage:image];\r
-               break;\r
-       case GADGET_TOOLBAR:    \r
-               toolbar=(Toolbar*)gadget->handle;\r
-               item=FindToolbarItem(toolbar,index);\r
-               if (item)       {\r
-//                     [item setLabel:text];\r
-                       [item setImage:image];\r
-                       [item setToolTip:tiptext];\r
-                       [item setTag:0];\r
-               }\r
-               break;\r
-       }\r
-}\r
-\r
-void NSRemoveItem(nsgadget *gadget,int index){\r
-       ListView                *listbox;\r
-       NSControl       *combo;\r
-       NSTabView               *tabber;\r
-       TabViewItem     *tabitem;\r
-       Toolbar         *toolbar;\r
-\r
-       switch (gadget->internalclass){\r
-       case GADGET_LISTBOX:\r
-               listbox=(ListView*)gadget->handle;\r
-               [listbox removeItemAtIndex:index];\r
-               break;\r
-       case GADGET_COMBOBOX:\r
-               combo=(NSControl*)gadget->handle;\r
-               [combo removeItemAtIndex:index];\r
-               break;\r
-       case GADGET_TABBER:\r
-               tabber=(NSTabView*)gadget->handle;\r
-               tabitem=(TabViewItem*)[tabber tabViewItemAtIndex:index];\r
-               [tabber removeTabViewItem:tabitem];\r
-               break;\r
-       case GADGET_TOOLBAR:\r
-               toolbar=(Toolbar*)gadget->handle;\r
-               [toolbar removeItemAtIndex:(int)index];\r
-               break;\r
-       }\r
-}\r
-\r
-void NSSelectItem(nsgadget *gadget,int index,int state){\r
-       NSControl               *combo;\r
-       NSTabView                       *tabber;\r
-       ListView                        *listbox;\r
-       Toolbar                 *toolbar;\r
-       NSToolbarItem           *item;\r
-\r
-       switch (gadget->internalclass){\r
-       case GADGET_LISTBOX:\r
-               listbox=(ListView*)gadget->handle;\r
-               if(state) [listbox selectItem:index]; else [listbox deselectItem:index];\r
-               break;\r
-       case GADGET_COMBOBOX:\r
-               combo=(NSControl*)gadget->handle;\r
-               [combo setDelegate:nil];\r
-               [combo selectItemAtIndex:index];\r
-               [combo setObjectValue:[combo objectValueOfSelectedItem]];\r
-               [combo setDelegate:GlobalApp];\r
-               break;\r
-       case GADGET_TABBER:\r
-               tabber=(NSTabView*)gadget->handle;\r
-               [tabber selectTabViewItemAtIndex:index];\r
-               break;\r
-       case GADGET_TOOLBAR:    \r
-               toolbar=(Toolbar*)gadget->handle;\r
-               item=FindToolbarItem(toolbar,index);\r
-               BOOL enable=(state&STATE_DISABLED)?false:true;\r
-               [item setEnabled:enable];\r
-               int pressed=(state&STATE_SELECTED)?1:0;\r
-               [item setTag:pressed];\r
-               break;\r
-       }\r
-}\r
-\r
-int NSSelectedItem(nsgadget *gadget,int index){\r
-       NSComboBox              *combo;\r
-       NSTabView                       *tabber;\r
-       ListView                        *listbox;\r
-       Toolbar                 *toolbar;\r
-       NSToolbarItem           *item;\r
-       int                             state;\r
-\r
-       state=0;\r
-       switch (gadget->internalclass){\r
-       case GADGET_LISTBOX:\r
-               listbox=(ListView*)gadget->handle;\r
-               if ([[listbox table] selectedRow]==index) state|=STATE_SELECTED;\r
-               break;\r
-       case GADGET_COMBOBOX:\r
-               combo=(NSControl*)gadget->handle;\r
-               if ([combo indexOfSelectedItem]==index) state|=STATE_SELECTED;\r
-               break;\r
-       case GADGET_TABBER:\r
-               tabber=(NSTabView*)gadget->handle;\r
-               if ([tabber indexOfTabViewItem:[tabber selectedTabViewItem]]==index) state|=STATE_SELECTED;\r
-               break;\r
-       case GADGET_TOOLBAR:    \r
-               toolbar=(Toolbar*)gadget->handle;\r
-               item=FindToolbarItem(toolbar,index);\r
-               if (![item isEnabled]) state|=STATE_DISABLED;\r
-               if ([item tag]!=0) state|=STATE_SELECTED;\r
-               break;\r
-       }\r
-       return state;\r
-}\r
-\r
-// treeview commands\r
-\r
-int NSCountKids(nsgadget *gadget){\r
-       TreeView                *treeview;\r
-       NodeItem                *node;\r
-\r
-       switch (gadget->internalclass){\r
-       case GADGET_TREEVIEW:\r
-               treeview=(TreeView*)gadget->handle;\r
-               return [treeview count];\r
-       case GADGET_NODE:\r
-               node=(NodeItem*)gadget->handle;\r
-               return [node count];\r
-       }\r
-       return 0;\r
-}\r
-\r
-int NSSelectedNode(nsgadget *gadget){\r
-       TreeView                *treeview;\r
-\r
-       switch (gadget->internalclass){\r
-       case GADGET_TREEVIEW:\r
-               treeview=(TreeView*)gadget->handle;\r
-               return (int)[treeview selectedNode];            \r
-       }\r
-       return -1;\r
-}\r
-\r
-// textarea commands\r
-\r
-int LinePos(NSString *text,int pos){\r
-       int                     line,i;\r
-\r
-       line=0;\r
-       for (i=0;i<pos;i++) {if ([text characterAtIndex:i]=='\n' ) line++;}\r
-       return line;\r
-}\r
-\r
-int CharPos(NSString *text,int line){\r
-       int                     pos,n;\r
-\r
-       pos=0;\r
-       n=[text length];\r
-       while (pos<n && line>0){\r
-               if ([text characterAtIndex:pos]=='\n') line--;\r
-               pos++;\r
-       }\r
-       return pos;\r
-}\r
-\r
-NSRange GetRange(NSTextStorage *storage,int pos,int count,int units){\r
-       \r
-       NSString        *text;\r
-       unsigned int max;\r
-       \r
-       if (units==TEXTAREA_LINES){\r
-               text=[storage string];\r
-               if (count==TEXTAREA_ALL)\r
-                       count=[storage length];\r
-               else\r
-                       count=CharPos(text,pos+count);\r
-               pos=CharPos(text,pos);\r
-               max = [storage length]-pos;\r
-               count-=pos;\r
-       }\r
-       else{\r
-               max = [storage length]-pos;\r
-               if (count==TEXTAREA_ALL) count=max;\r
-       }\r
-       \r
-       if (count > max) count = max;\r
-       if (count<0) count=0;\r
-       \r
-       //NSLog(@"GetRange() pos: %d,  count: %d,  length: %d\n", pos, count, [storage length]);\r
-       \r
-       return NSMakeRange(pos,count);\r
-       \r
-}\r
-\r
-void NSReplaceText(nsgadget *gadget,int pos,int count,BBString *data,int units){\r
-       NSString                        *text;\r
-       TextView                        *textarea;\r
-       NSRange                 range,snap;\r
-       NSTextStorage           *storage;\r
-       unsigned int                    size;\r
-       \r
-       text=NSStringFromBBString(data);\r
-       textarea=(TextView*)gadget->handle;\r
-       \r
-       if(([[textarea string] length] == 0) || ((pos == 0) && (count == TEXTAREA_ALL))){\r
-               \r
-               [textarea setText:text];\r
-               \r
-       } else {\r
-               \r
-               snap=[textarea selectedRange];\r
-               range=GetRange([textarea storage],pos,count,units);\r
-               storage=[textarea storage];\r
-               [storage replaceCharactersInRange:range withString:text];       \r
-               size=[storage length];\r
-               if (snap.location>size) snap.location=size;\r
-               if (snap.location+snap.length>size) snap.length=size-snap.location;     \r
-               [textarea setSelectedRange:snap];\r
-               \r
-       }\r
-       \r
-}\r
-\r
-void NSAddText(nsgadget *gadget,BBString *data){\r
-       NSString                        *text;\r
-       TextView                        *textarea;\r
-       NSRange                 range;\r
-\r
-       text=NSStringFromBBString(data);\r
-       textarea=(TextView*)gadget->handle;\r
-       [textarea addText:text];\r
-       range=GetRange([textarea textStorage],[[textarea string] length],0,0);\r
-       [textarea setSelectedRange:range];\r
-       [textarea scrollRangeToVisible:range];\r
-}\r
-\r
-BBString *NSAreaText(nsgadget *gadget,int pos,int length,int units){\r
-       TextView                        *textarea;\r
-       NSRange                 range;\r
-       NSAttributedString      *astring;\r
-       BBString                                *bstring;\r
-\r
-       textarea=(TextView*)gadget->handle;\r
-       range=GetRange([textarea storage],pos,length,units);\r
-       astring=[[textarea storage] attributedSubstringFromRange:range];        \r
-       bstring=bbStringFromNSString([astring string]);\r
-       return bstring;\r
-}\r
-\r
-int NSAreaLen(nsgadget *gadget,int units){\r
-       TextView                        *textarea;\r
-       NSTextStorage           *storage;\r
-       unsigned                        ulen;\r
-\r
-       textarea=(TextView*)gadget->handle;\r
-       storage=[textarea storage];\r
-       ulen=[storage length];\r
-       if (units==TEXTAREA_LINES) ulen=LinePos([storage string],ulen)+1;\r
-       return ulen;    \r
-}\r
-\r
-void NSSetSelection(nsgadget *gadget,int pos,int length,int units){\r
-       TextView                        *textarea;\r
-       NSRange                 range;\r
-\r
-       textarea=(TextView*)gadget->handle;     \r
-       range=GetRange([textarea textStorage],pos,length,units);\r
-       [textarea setSelectedRange:range];\r
-       if( !textarea->lockedNest ) [textarea scrollRangeToVisible:range];\r
-}\r
-\r
-void NSLockText(nsgadget *gadget){\r
-       TextView                        *textarea;\r
-\r
-       textarea=(TextView*)gadget->handle;\r
-       \r
-       if( !textarea->lockedNest ){\r
-               textarea->lockedRange=[textarea rangeForUserTextChange];\r
-               [textarea->storage beginEditing];\r
-       }\r
-\r
-       ++textarea->lockedNest;\r
-}\r
-\r
-void NSUnlockText(nsgadget *gadget){\r
-       TextView                        *textarea;\r
-       \r
-       textarea=(TextView*)gadget->handle;\r
-       \r
-       --textarea->lockedNest;\r
-\r
-       if( !textarea->lockedNest ){\r
-               NSRange range=textarea->lockedRange;\r
-               [textarea->storage endEditing];\r
-               if( range.location+range.length>[textarea->storage length] ) range=NSMakeRange( 0,0 );\r
-               [textarea setSelectedRange:range];\r
-       }\r
-}\r
-\r
-void NSSetTabs(nsgadget *gadget,int tabwidth){\r
-       TextView *textarea;\r
-       textarea=(TextView*)gadget->handle;     \r
-       [textarea setTabs:tabwidth];\r
-}\r
-\r
-void NSSetMargins(nsgadget *gadget,int leftmargin){\r
-       TextView *textarea;\r
-       textarea=(TextView*)gadget->handle;     \r
-       [textarea setMargins:leftmargin];\r
-}\r
-\r
-int NSCharAt(nsgadget *gadget,int line){\r
-       TextView                *textarea;\r
-       NSString                *text;\r
-       int                             n,i;\r
-\r
-       textarea=(TextView*)gadget->handle;     \r
-       text=[[textarea storage] string];\r
-       n=[text length];i=0;\r
-       while (line){\r
-               if (i==n) break;\r
-               if ([text characterAtIndex:i]=='\n' ) line--;\r
-               i++;\r
-       }\r
-       return i;\r
-}\r
-\r
-int NSLineAt(nsgadget *gadget,int pos){\r
-       TextView                        *textarea;\r
-       textarea=(TextView*)gadget->handle;     \r
-       return LinePos([[textarea storage] string],pos);\r
-}\r
-\r
-int NSCharX(nsgadget *gadget,int pos){\r
-       unsigned int rectCount;\r
-       NSRectArray rectArray;\r
-       TextView        *textarea = (TextView*)gadget->handle;\r
-       NSRange range = GetRange([textarea textStorage],pos,0,TEXTAREA_CHARS);\r
-       rectArray = [[textarea layoutManager] rectArrayForCharacterRange:range withinSelectedCharacterRange:range inTextContainer: [textarea textContainer] rectCount:&rectCount];\r
-       if(rectCount > 0) return (int)(((NSRect)rectArray[0]).origin.x-([textarea visibleRect].origin.x-[textarea textContainerOrigin].x));\r
-}\r
-\r
-int NSCharY(nsgadget *gadget,int pos){\r
-       unsigned int rectCount;\r
-       NSRectArray rectArray;\r
-       TextView        *textarea = (TextView*)gadget->handle;\r
-       NSRange range = GetRange([textarea textStorage],pos,0,TEXTAREA_CHARS);\r
-       rectArray = [[textarea layoutManager] rectArrayForCharacterRange:range withinSelectedCharacterRange:range inTextContainer: [textarea textContainer] rectCount:&rectCount];\r
-       if(rectCount > 0) return (int)(((NSRect)rectArray[0]).origin.y-([textarea visibleRect].origin.y-[textarea textContainerOrigin].y));\r
-}\r
-\r
-int NSGetCursorPos(nsgadget *gadget,int units){\r
-       TextView                        *textarea;\r
-       NSRange                 range;\r
-\r
-       textarea=(TextView*)gadget->handle;     \r
-       range=[textarea rangeForUserTextChange];\r
-       if (range.location == NSNotFound) return 0; //KORIOLIS (avoids read-only text-area crash)\r
-       if (units==TEXTAREA_LINES) return NSLineAt(gadget,range.location);\r
-       return range.location;\r
-}\r
-\r
-int NSGetSelectionlength(nsgadget *gadget,int units){\r
-       TextView                        *textarea;\r
-       NSRange                 range;\r
-\r
-       textarea=(TextView*)gadget->handle;     \r
-       range=[textarea rangeForUserTextChange];\r
-       if (range.location == NSNotFound) return 0; //KORIOLIS (avoids read-only text-area crash)\r
-       if (range.length == 0) return 0;\r
-       if (units == TEXTAREA_LINES){\r
-               int l0=NSLineAt(gadget,range.location);\r
-               int l1=NSLineAt(gadget,range.location+range.length-1);\r
-               return (l1-l0+1);\r
-       }\r
-       return range.length;\r
-}\r
-\r
-void NSSetTextColor(nsgadget *gadget,int r,int g,int b){\r
-       \r
-       if(gadget->textcolor) [gadget->textcolor release];\r
-       gadget->textcolor = [[NSColor colorWithDeviceRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:1.0] retain];\r
-       \r
-       switch (gadget->internalclass){\r
-       case GADGET_LABEL:\r
-               switch (gadget->style&3) {\r
-                       case LABEL_SEPARATOR:\r
-                               return;\r
-               }\r
-       case GADGET_TEXTFIELD:\r
-       case GADGET_LISTBOX:\r
-       case GADGET_TREEVIEW:\r
-       case GADGET_TEXTAREA:\r
-               [gadget->handle setTextColor:gadget->textcolor];\r
-               break;\r
-       default:\r
-               NSSetText(gadget, NSGetText(gadget));   //Attempt to reset text with NSAttributedString\r
-               break;\r
-       }\r
-}\r
-\r
-void NSSetStyle(nsgadget *gadget,int r,int g,int b,int flags,int pos,int length,int units)     {\r
-       TextView                        *textarea;\r
-       NSRange                 _range;\r
-       NSColor                         *color;\r
-       int traits = 0;\r
-\r
-       textarea=(TextView*)gadget->handle;     \r
-       _range=GetRange([textarea storage],pos,length,units);\r
-       color=[NSColor colorWithDeviceRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:1.0];\r
-       \r
-       [[textarea storage] removeAttribute:NSLinkAttributeName range:_range];\r
-       [[textarea storage] addAttribute:NSForegroundColorAttributeName value:color range:_range];\r
-       [[textarea storage] addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInt:(flags & 4)?NSUnderlineStyleSingle:NSUnderlineStyleNone] range:_range];\r
-       [[textarea storage] addAttribute:NSStrikethroughStyleAttributeName value:[NSNumber numberWithInt:(flags & 8)?NSUnderlineStyleSingle:NSUnderlineStyleNone] range:_range];\r
-\r
-       traits |= (flags & 1)?NSBoldFontMask:NSUnboldFontMask;\r
-       traits |= (flags & 2)?NSItalicFontMask:NSUnitalicFontMask;\r
-\r
-       [[textarea storage] applyFontTraits: traits range:_range];\r
-}\r
-\r
-void NSSetValue(nsgadget *gadget,float value){\r
-       NSProgressIndicator     *progbar;\r
-       NSDate                          *date;\r
-       NSValue                         *info;\r
-       NSRunLoop                       *runloop;\r
-       \r
-       switch (gadget->internalclass){\r
-       case GADGET_PROGBAR:\r
-               progbar=(NSProgressIndicator*)gadget->handle;\r
-               [progbar setDoubleValue:value];\r
-               break;\r
-       }\r
-}\r
-\r
-// slider / scrollbar\r
-\r
-void NSSetSlider(nsgadget *gadget,double value,double small,double big){\r
-       NSScroller              *scroller;\r
-       NSSlider                        *slider;\r
-       NSStepper                       *stepper;\r
-       NSRect                  frame;\r
-       float                   size;\r
-       \r
-       switch (gadget->style&12){\r
-       case SLIDER_SCROLLBAR:\r
-               scroller=(NSScroller*)gadget->handle;\r
-               if(value > (big-small))\r
-                       value = 1.0L;\r
-               else if(big-small)\r
-                       value/=(big-small);\r
-               else\r
-                       value = 0.0L;\r
-               [scroller setKnobProportion:(small/big)];\r
-               [scroller setDoubleValue:value];\r
-               break;\r
-       case SLIDER_TRACKBAR:\r
-               slider=(NSSlider*)gadget->handle;\r
-               [slider setMinValue:small];\r
-               [slider setMaxValue:big];\r
-               [slider setDoubleValue:value];\r
-               break;\r
-       case SLIDER_STEPPER:\r
-               stepper=(NSStepper*)gadget->handle;\r
-               [stepper setMinValue:small];\r
-               [stepper setMaxValue:big];\r
-               [stepper setDoubleValue:value];\r
-               break;\r
-       }\r
-}\r
-\r
-double NSGetSlider(nsgadget *gadget){\r
-       NSControl       *control;\r
-       control = (NSControl*)gadget->handle;\r
-       return [control doubleValue];\r
-}\r
-\r
-\r
-NSCursor* NSCursorCreateStock(short sIndex)\r
-{\r
-\r
-    // Adapted from wxWidgets - if you believe this contravenes wxWidget's licensing\r
-    // agreements, please let the BRL team know and it will be removed.\r
-    \r
-    int i;\r
-    ArrayCursor* tmpCursor = &arrCursors[sIndex];\r
-    NSImage *tmpImage = [[NSImage alloc] initWithSize:NSMakeSize(16.0,16.0)];\r
-    \r
-    NSBitmapImageRep *tmpRep = [[NSBitmapImageRep alloc]\r
-        initWithBitmapDataPlanes: NULL\r
-        pixelsWide: 16\r
-        pixelsHigh: 16\r
-        bitsPerSample: 1\r
-        samplesPerPixel: 2\r
-        hasAlpha: YES\r
-        isPlanar: YES\r
-        colorSpaceName: NSCalibratedWhiteColorSpace\r
-        bytesPerRow: 2\r
-        bitsPerPixel: 1];\r
-    \r
-    unsigned char *planes[5];\r
-    [tmpRep getBitmapDataPlanes:planes];\r
-    \r
-    for(i=0; i<16; ++i)\r
-    {\r
-        planes[0][2*i  ] = (~tmpCursor->bits[i] & tmpCursor->mask[i]) >> 8 & 0xff;\r
-        planes[1][2*i  ] = tmpCursor->mask[i] >> 8 & 0xff;\r
-        planes[0][2*i+1] = (~tmpCursor->bits[i] & tmpCursor->mask[i]) & 0xff;\r
-        planes[1][2*i+1] = tmpCursor->mask[i] & 0xff;\r
-    }\r
-    \r
-    [tmpImage addRepresentation:tmpRep];\r
-    \r
-    NSCursor* tmpNSCursor =  [[NSCursor alloc]  initWithImage:tmpImage hotSpot:NSMakePoint(tmpCursor->hitpoint[1], tmpCursor->hitpoint[0])];\r
-    \r
-    [tmpRep release];[tmpImage release];\r
-    \r
-    return tmpNSCursor;\r
-}\r
-\r
-void NSSetPointer(int shape){\r
-       NSCursor *cursor;\r
-       cursor=[NSCursor arrowCursor];\r
-       \r
-       switch (shape){\r
-//     case POINTER_DEFAULT:cursor=[NSCursor ];break;\r
-       case POINTER_ARROW:cursor=[NSCursor arrowCursor];break;\r
-       case POINTER_IBEAM:cursor=[NSCursor IBeamCursor];break;\r
-//     case POINTER_WAIT:cursor=[NSCursor ];break;\r
-       case POINTER_CROSS:cursor=[NSCursor crosshairCursor];break;\r
-       case POINTER_UPARROW:cursor=[NSCursor resizeUpCursor];break;\r
-       case POINTER_SIZENWSE:cursor=NSCursorCreateStock(curNWSE);break;\r
-       case POINTER_SIZENESW:cursor=NSCursorCreateStock(curNESW);break;\r
-       case POINTER_SIZEWE:cursor=[NSCursor resizeLeftRightCursor];break;\r
-       case POINTER_SIZENS:cursor=[NSCursor resizeUpDownCursor];break;\r
-       case POINTER_SIZEALL:cursor=NSCursorCreateStock(curSizeAll);break;\r
-       case POINTER_NO:cursor=NSCursorCreateStock(curNoEntry);break;\r
-       case POINTER_HAND:cursor=[NSCursor pointingHandCursor];break;\r
-//     case POINTER_APPSTARTING:cursor=[NSCursor ];break;\r
-       case POINTER_HELP:cursor=NSCursorCreateStock(curHelp);break;\r
-       }\r
-       [cursor set];\r
-}\r
-\r
-typedef struct bbpixmap bbpixmap;\r
-\r
-struct bbpixmap{\r
-// BBObject\r
-       void            *class;\r
-       int             refs;\r
-// pixmap\r
-       unsigned char *pixels;\r
-       int             width,height,pitch,format,capacity;\r
-};\r
-\r
-\r
-#define PF_I8 1\r
-#define PF_A8 2\r
-#define PF_BGR888 3\r
-#define PF_RGB888 4\r
-#define PF_BGRA8888 5\r
-#define PF_RGBA8888 6\r
-#define PF_STDFORMAT PF_RGBA8888\r
-\r
-const static char BytesPerPixel[]={0,1,1,3,3,4,4};\r
-const static char BitsPerPixel[]={0,8,8,24,24,32,32};\r
-const static char RedBitsPerPixel[]={0,0,0,8,8,8,8};\r
-const static char GreenBitsPerPixel[]={0,0,0,8,8,8,8};\r
-const static char BlueBitsPerPixel[]={0,0,0,8,8,8,8};\r
-const static char AlphaBitsPerPixel[]={0,0,8,0,0,8,8};\r
-\r
-NSImage *NSPixmapImage(bbpixmap *pix){\r
-       NSImage *image;\r
-       NSBitmapImageRep *bitmap;\r
-       int spp,bpp,i;\r
-       int bytesperrow;\r
-       BOOL    alpha;\r
-       unsigned char * data;\r
-               \r
-       alpha=AlphaBitsPerPixel[pix->format]?YES:NO;\r
-       spp=BytesPerPixel[pix->format];\r
-       bpp=BitsPerPixel[pix->format];\r
-       bytesperrow=pix->width*spp;\r
-       \r
-       bitmap=[[[NSBitmapImageRep alloc] \r
-               initWithBitmapDataPlanes:NULL\r
-               pixelsWide:pix->width\r
-               pixelsHigh:pix->height\r
-               bitsPerSample:8 \r
-               samplesPerPixel:spp \r
-               hasAlpha:alpha \r
-               isPlanar:NO \r
-               colorSpaceName:NSDeviceRGBColorSpace \r
-//             bitmapFormat:NSAlphaNonpremultipliedBitmapFormat\r
-               bytesPerRow:bytesperrow \r
-               bitsPerPixel:bpp] autorelease];\r
-               \r
-       data = [bitmap bitmapData];\r
-       \r
-       for( i = 0; i < pix->height; i++) {\r
-               memcpy( data + ( i * bytesperrow ), pix->pixels + ( i * pix->pitch ), bytesperrow );\r
-       }\r
-\r
-       image=[[NSImage alloc] initWithSize:NSMakeSize(pix->width,  pix->height)];\r
-       [image addRepresentation:bitmap];\r
-       [image retain];\r
-       return image;\r
-}\r
-\r
-void NSSetImage(nsgadget *gadget,NSImage *image,int flags){\r
-       PanelView *panel;\r
-       NSButton *button;\r
-       NSMenuItem *menu;\r
-       \r
-       switch (gadget->internalclass){\r
-       case GADGET_PANEL:\r
-               panel=(PanelView*)gadget->handle;\r
-               [panel setImage:image withFlags:flags];\r
-               break;\r
-       case GADGET_BUTTON:\r
-               if ((flags & GADGETPIXMAP_ICON) && (gadget->style <= BUTTON_PUSH)){ \r
-                       button=(NSButton *)gadget->handle;\r
-                       [button setImage:image];\r
-                       if (flags & GADGETPIXMAP_NOTEXT) {\r
-                               [button setImagePosition:NSImageOnly];\r
-                       } else {\r
-                               [button setImagePosition:NSImageLeft];\r
-                       }\r
-               }\r
-               break; \r
-       case GADGET_MENUITEM:\r
-               if (flags & GADGETPIXMAP_ICON){\r
-                       menu=(NSMenuItem*)gadget->handle;\r
-                       [menu setImage:image];\r
-               }\r
-               break;\r
-       }\r
-}\r
-\r
-void NSSetIcon(nsgadget *gadget,NSImage *image){\r
-       NodeItem        *node;\r
-               \r
-       switch (gadget->internalclass){\r
-       case GADGET_NODE:\r
-               node=(NodeItem*)gadget->handle;\r
-               [node setIcon:image];\r
-               break;\r
-       }\r
-}\r
-\r
-void NSSetNextView(nsgadget *gadget,nsgadget *nextgadget){\r
-       NSView          *view,*nextview;\r
-       view=(NSView*)gadget->handle;\r
-       nextview=(NSView*)nextgadget->handle;\r
-       [view setNextKeyView:nextview];\r
-}\r
-\r
-static int keyToChar( int key ){\r
-       if( key>=KEY_A && key<=KEY_Z ) return key-KEY_A+'a';\r
-       if( key>=KEY_F1 && key<=KEY_F12 ) return key-KEY_F1+NSF1FunctionKey;\r
-       \r
-       switch( key ){\r
-       case KEY_BACKSPACE:return 8;\r
-       case KEY_TAB:return 9;\r
-       case KEY_ESC:return 27;\r
-       case KEY_SPACE:return 32;\r
-       case KEY_PAGEUP:return NSPageUpFunctionKey;\r
-       case KEY_PAGEDOWN:return NSPageDownFunctionKey;\r
-       case KEY_END:return NSEndFunctionKey;\r
-       case KEY_HOME:return NSHomeFunctionKey;\r
-       case KEY_UP:return NSUpArrowFunctionKey;\r
-       case KEY_DOWN:return NSDownArrowFunctionKey;\r
-       case KEY_LEFT:return NSLeftArrowFunctionKey;\r
-       case KEY_RIGHT:return NSRightArrowFunctionKey;\r
-       case KEY_INSERT:return NSInsertFunctionKey;\r
-       case KEY_DELETE:return NSDeleteFunctionKey;\r
-       case KEY_TILDE:return '~';\r
-       case KEY_MINUS:return '-';\r
-       case KEY_EQUALS:return '=';\r
-       case KEY_OPENBRACKET:return '[';\r
-       case KEY_CLOSEBRACKET:return ']';\r
-       case KEY_BACKSLASH:return '\\';\r
-       case KEY_SEMICOLON:return ';';\r
-       case KEY_QUOTES:return '\'';\r
-       case KEY_COMMA:return ',';\r
-       case KEY_PERIOD:return '.';\r
-       case KEY_SLASH:return '/';\r
-       }\r
-       return 0;\r
-}\r
-\r
-void NSSetHotKey(nsgadget *gadget,int key,int modifier){\r
-       int chr;\r
-       unichar uchar[1];\r
-       NSString *keyStr;\r
-       int modMask;\r
-       NSMenuItem *menuItem;\r
-       if( gadget->internalclass!=GADGET_MENUITEM ) return;\r
-       modMask=0;\r
-       if( modifier & 1 ) modMask|=NSShiftKeyMask;\r
-       if( modifier & 2 ) modMask|=NSControlKeyMask;\r
-       if( modifier & 4 ) modMask|=NSAlternateKeyMask;\r
-       if( modifier & 8 ) modMask|=NSCommandKeyMask;\r
-       menuItem=(NSMenuItem*)gadget->handle;\r
-       chr=keyToChar( key );\r
-       if( !chr ) {\r
-               [menuItem setKeyEquivalent:@""];\r
-               [menuItem setKeyEquivalentModifierMask:0];\r
-               return;\r
-       }\r
-       uchar[0]=chr;\r
-       keyStr=[NSString stringWithCharacters:uchar length:1];\r
-       [menuItem setKeyEquivalent:keyStr];\r
-       [menuItem setKeyEquivalentModifierMask:modMask];\r
+// cocoa.macos.m
+// blitzmax cocoa interface 
+// by simonarmstrong@blitzbasic.com
+
+#include <AppKit/AppKit.h>
+#include <WebKit/WebView.h>
+#include <WebKit/WebFrame.h>a
+#include <WebKit/WebPolicyDelegate.h>
+#include <WebKit/WebFrameLoadDelegate.h>
+#include <WebKit/WebDataSource.h>
+#include <ApplicationServices/ApplicationServices.h>
+
+#include <brl.mod/blitz.mod/blitz.h>
+#include <maxgui.mod/maxgui.mod/maxgui.h>
+#include <pub.mod/macos.mod/macos.h>
+
+#define STATUSBARHEIGHT 18
+
+// Custom Cursor Stuff
+
+const int curNoEntry = 0;
+const int curHelp = 1;
+const int curSizeAll = 2;
+const int curNESW = 3;
+const int curNWSE = 4;
+
+typedef struct { short bits[16]; short mask[16]; short hitpoint[2]; } ArrayCursor;
+
+ArrayCursor arrCursors[5] =
+{{{0x0000, 0x07E0, 0x1FF0, 0x3838, 0x3C0C, 0x6E0E, 0x6706, 0x6386, 0x61C6, 0x60E6, 0x7076, 0x303C, 0x1C1C, 0x0FF8, 0x07E0, 0x0000},
+{0x0540, 0x0FF0, 0x3FF8, 0x3C3C, 0x7E0E, 0xFF0F, 0x6F86, 0xE7C7, 0x63E6, 0xE1F7, 0x70FE, 0x707E, 0x3C3C, 0x1FFC, 0x0FF0, 0x0540},
+{0x0007, 0x0007}},
+{{0x0000, 0x4078, 0x60FC, 0x71CE, 0x7986, 0x7C06, 0x7E0E, 0x7F1C, 0x7FB8, 0x7C30, 0x6C30, 0x4600, 0x0630, 0x0330, 0x0300, 0x0000},
+{0xC078, 0xE0FC, 0xF1FE, 0xFBFF, 0xFFCF, 0xFF8F, 0xFF1F, 0xFFBE, 0xFFFC, 0xFE78, 0xFF78, 0xEFF8, 0xCFF8, 0x87F8, 0x07F8, 0x0300},
+{0x0001, 0x0001}},
+{{0x0000, 0x0080, 0x01C0, 0x03E0, 0x0080, 0x0888, 0x188C, 0x3FFE, 0x188C, 0x0888, 0x0080, 0x03E0, 0x01C0, 0x0080, 0x0000, 0x0000},
+{0x0080, 0x01C0, 0x03E0, 0x07F0, 0x0BE8, 0x1DDC, 0x3FFE, 0x7FFF, 0x3FFE, 0x1DDC, 0x0BE8, 0x07F0, 0x03E0, 0x01C0, 0x0080, 0x0000},
+{0x0007, 0x0008}},
+{{0x0000, 0x001E, 0x000E, 0x060E, 0x0712, 0x03A0, 0x01C0, 0x00E0, 0x0170, 0x1238, 0x1C18, 0x1C00, 0x1E00, 0x0000, 0x0000, 0x0000},
+{0x007F, 0x003F, 0x0E1F, 0x0F0F, 0x0F97, 0x07E3, 0x03E1, 0x21F0, 0x31F8, 0x3A7C, 0x3C3C, 0x3E1C, 0x3F00, 0x3F80, 0x0000, 0x0000},
+{0x0006, 0x0009}},
+{{0x0000, 0x7800, 0x7000, 0x7060, 0x48E0, 0x05C0, 0x0380, 0x0700, 0x0E80, 0x1C48, 0x1838, 0x0038, 0x0078, 0x0000, 0x0000, 0x0000},
+{0xFE00, 0xFC00, 0xF870, 0xF0F0, 0xE9F0, 0xC7E0, 0x87C0, 0x0F84, 0x1F8C, 0x3E5C, 0x3C3C, 0x387C, 0x00FC, 0x01FC, 0x0000, 0x0000},
+{0x0006, 0x0006}}};
+
+// End of Cursor Stuff
+
+
+void brl_event_EmitEvent( BBObject *event );
+BBObject *maxgui_maxgui_HotKeyEvent( int key,int mods );
+void maxgui_maxgui_DispatchGuiEvents();
+void maxgui_cocoamaxgui_EmitCocoaOSEvent( NSEvent *event,void *handle,BBObject *gadget );
+int maxgui_cocoamaxgui_EmitCocoaMouseEvent( NSEvent *event,void *handle );
+int maxgui_cocoamaxgui_EmitCocoaKeyEvent( NSEvent *event,void *handle );
+void maxgui_cocoamaxgui_PostCocoaGuiEvent( int ev,void *handle,int data,int mods,int x,int y,BBObject *extra );
+
+int maxgui_cocoamaxgui_FilterChar( void *handle,int key,int mods );
+int maxgui_cocoamaxgui_FilterKeyDown( void *handle,int key,int mods );
+
+static void EmitOSEvent( NSEvent *event,void *handle ){
+       maxgui_cocoamaxgui_EmitCocoaOSEvent( event,handle,&bbNullObject );
+}
+
+int HaltMouseEvents;
+
+static int EmitMouseEvent( NSEvent *event,void *handle ){
+       if(([event type] == NSScrollWheel) && ([event deltaY] == 0)) return 0;
+       if(!HaltMouseEvents) return maxgui_cocoamaxgui_EmitCocoaMouseEvent( event,handle );
+}
+
+static int EmitKeyEvent( NSEvent *event,void *handle ){
+       return maxgui_cocoamaxgui_EmitCocoaKeyEvent( event,handle );
+}
+
+static void PostGuiEvent( int ev,void *handle,int data,int mods,int x,int y,BBObject *extra ){
+       if (extra==0) extra=&bbNullObject;
+       maxgui_cocoamaxgui_PostCocoaGuiEvent( ev,handle,data,mods,x,y,extra );
+}
+
+static int filterKeyDownEvent( NSEvent *event,id source ){
+       int i,sz,res,key,mods;
+       NSString *ch;
+       key=bbSystemTranslateKey( [event keyCode] );
+       mods=bbSystemTranslateMods( [event modifierFlags] );
+       res=maxgui_cocoamaxgui_FilterKeyDown( source,key,mods );
+       if (res==0) return 0;
+       ch=[event characters];
+       sz=[ch length];
+       for( i=0;i<sz;++i ){
+               key=[ch characterAtIndex:i];
+               switch( key ){
+                       case 3:key=13;break;    //Brucey's numberpad enter-key hack
+                       case 127:key=8;break;
+                       case 63272:key=127;break;
+               }
+               res=maxgui_cocoamaxgui_FilterChar( source,key,mods );
+               if (res==0) return 0;
+       }
+       return 1;
+}
+
+void NSRelease( NSObject *obj ){[obj release];}
+
+typedef struct nsgadget nsgadget;
+
+struct nsgadget{
+// BBObject
+       BBClass*        clas;
+       int                     refs;
+// gadget
+       BBObject        *target;        
+       nsgadget        *group;
+       BBObject        *kidlist;
+       int                     x,y,w,h;
+       BBString                *textarg;
+       void                    *extra;
+       int                     style, sensitivity;
+       int                     visible,total;
+       int                     lockl,lockr,lockt,lockb;
+       int                     lockx,locky,lockw,lockh,lockcw,lockch;
+       void                    *filter,*context;
+       void                    *items;
+       int                     *arrPrevSelection;
+       BBObject                *datasource;
+       void                    *datakeys;//$[]
+// nsGadget
+       int                     internalclass, origclass;
+       id                      handle;         
+       NSView          *view;
+       NSColor         *textcolor;
+       int                     intFontStyle;
+};
+
+// prototypes
+
+void NSClearItems(nsgadget *gadget);
+
+void NSSetSelection(nsgadget *gadget,int pos,int length,int units);
+
+@class CocoaApp;
+@class FlippedView;
+@class PanelView;
+@class CanvasView;
+@class ListView;
+@class TreeView;
+@class NodeItem;
+@class TextView;
+@class TabView;
+@class WindowView;
+@class ImageString;
+@class TableView;
+@class ToolView;
+@class Scroller;
+
+@interface CocoaApp:NSObject{
+       NSMutableDictionary     *toolbaritems;
+       NSMutableArray          *menuitems;
+}
+-(id)init;
++(void)delayedGadgetAction:(NSNotification*)n;
++(void)dispatchGuiEvents;
+-(BOOL)windowShouldClose:(id)sender;
+-(void)windowDidResize:(NSNotification *)aNotification;
+-(void)windowDidMove:(NSNotification *)aNotification;
+-(BOOL)windowShouldZoom:(NSWindow *)sender toFrame:(NSRect)newFrame;
+-(void)windowDidBecomeKey:(NSNotification *)aNotification;
+-(void)menuSelect:(id)sender;
+-(void)iconSelect:(id)sender;
+-(void)sliderSelect:(id)sender;
+-(void)scrollerSelect:(id)sender;
+-(void)buttonPush:(id)sender;
+-(void)textEdit:(id)sender;
+-(void)comboBoxSelectionDidChange:(NSNotification *)notification;
+-(void)addToolbarItem:(NSToolbarItem *)item;
+-(NSToolbarItem *)toolbar:(NSToolbar *)toolbar itemForItemIdentifier:(NSString *)itemIdentifier willBeInsertedIntoToolbar:(BOOL)flag;
+-(NSArray *)toolbarAllowedItemIdentifiers:(NSToolbar *)toolbar;
+-(NSArray *)toolbarDefaultItemIdentifiers:(NSToolbar *)toolbar;
+-(BOOL)validateToolbarItem:(NSToolbarItem *)theItem;
+-(void)addMenuItem:(NSMenuItem *)item;
+-(void)removeMenuItem:(NSMenuItem *)item;
+@end
+
+void ScheduleEventDispatch(){
+       [CocoaApp performSelector:@selector(dispatchGuiEvents) withObject:nil afterDelay:0.0];
+}
+
+@interface Scroller:NSScroller{
+}
+-(id)init;
+//-(id)initWithFrame:(NSRect)rect;
+//-(void)drawParts;
+//-(void)drawKnob;
+//-(void)drawKnobSlotInRect:(NSRect)slotRect highlight:(BOOL)flag;
+//-(void)drawArrow:(NSScrollerArrow)arrow highlight:(BOOL)flag;
+//-(void)highlight:(BOOL)flag;
+@end
+
+@interface FlippedView:NSView{
+}
+-(BOOL)isFlipped;
+-(BOOL)mouseDownCanMoveWindow;
+@end
+
+@interface PanelView:NSBox{
+       int                     style;
+       int                     enabled;
+       nsgadget                *gadget;
+}
+-(BOOL)isFlipped;
+-(BOOL)mouseDownCanMoveWindow;
+-(void)setColor:(NSColor*)rgb;
+-(void)setAlpha:(float)alpha;
+-(void)setGadget:(nsgadget*)_gadget;
+-(void)setStyle:(int)s;
+-(void)setImage:(NSImage *)image withFlags:(int)flags;
+-(BOOL)acceptsFirstResponder;
+-(BOOL)becomeFirstResponder;
+
+-(void)setEnabled:(BOOL)flag;
+-(BOOL)isEnabled;
+@end
+
+@interface PanelViewContent:NSView{
+       NSColor         *color;
+       NSImage         *image;
+       int                     imageflags;
+       float           alpha;
+}
+-(BOOL)isFlipped;
+-(BOOL)mouseDownCanMoveWindow;
+-(void)setColor:(NSColor*)rgb;
+-(void)setAlpha:(float)alpha;
+-(void)setImage:(NSImage *)image withFlags:(int)flags;
+-(void)drawRect:(NSRect)rect;
+@end
+
+@interface CanvasView:PanelView{
+}
+-(void)drawRect:(NSRect)rect;
+-(BOOL)acceptsFirstResponder;
+-(BOOL)becomeFirstResponder;
+@end
+
+@interface ListView:NSScrollView{
+       TableView *table;
+       NSTableColumn *column;
+       NSBrowserCell *cell;
+       NSMutableArray *items;
+       NSDictionary    *textstyle;
+}
+-(id)initWithFrame:(NSRect)rect;
+-(id)table;
+-(id)items;
+-(void)removeItemAtIndex:(int)index;
+-(void)setColor:(NSColor*)color;
+-(void)setTextColor:(NSColor*)color;
+-(int)numberOfRowsInTableView:(NSTableView *)aTableView;
+-(id)tableView:(NSTableView *)aTableView objectValueForTableColumn:(NSTableColumn *)aTableColumn row:(int)rowIndex;
+-(BOOL)tableView:(NSTableView *)tableView shouldEditTableColumn:(NSTableColumn *)tableColumn row:(int)rowIndex;
+-(void)clear;
+-(void)addItem:(NSString*)text atIndex:(unsigned)index withImage:(NSImage*)image withTip:(NSString*)tip withExtra:(BBObject*)extra;
+-(void)setItem:(NSString*)text atIndex:(unsigned)index withImage:(NSImage*)image withTip:(NSString*)tip withExtra:(BBObject*)extra;
+-(void)selectItem:(unsigned)index;
+-(void)deselectItem:(unsigned)index;
+-(void)tableViewSelectionDidChange:(NSNotification *)aNotification;
+-(void)tableView:(NSTableView *)aTableView willDisplayCell:(id)aCell forTableColumn:(NSTableColumn *)aTableColumn row:(int)rowIndex;
+-(void)setEnabled:(BOOL)flag;
+-(BOOL)isEnabled;
+-(void)updateWidthForString:(ImageString *) string;
+-(void)updateWidth;
+-(void)queueWidthUpdate;
+-(void)dealloc;
+-(void)setFont:(NSFont*)font;
+-(NSString *)view:(NSView *)view stringForToolTip:(NSToolTipTag)tag point:(NSPoint)point userData:( void  *)data;
+@end
+
+@interface TableView:NSTableView{
+}
+-(NSMenu*)menuForEvent:(NSEvent *)theEvent;
+@end
+
+@interface OutlineView:NSOutlineView{
+}
+-(NSMenu*)menuForEvent:(NSEvent *)theEvent;
+@end
+
+@interface NodeItem:NSObject{
+       TreeView                *owner;
+       NodeItem                *parent;
+       NSMutableArray *kids;
+       NSString                *title;
+       NSImage         *icon;
+}
+-(void)dealloc;
+-(id)initWithTitle:(NSString*)text;
+-(void)updateWidth;
+-(void)setOwner:(TreeView*)treeview;
+-(id)getOwner;
+-(void)show;
+-(void)attach:(NodeItem*)parent_ atIndex:(unsigned)index_;
+-(void)remove;
+-(BOOL)canExpand;
+-(NSMutableArray*)kids;
+-(NSString *)value;
+-(NSImage *)icon;
+-(void)setTitle:(NSString*)text;
+-(void)setIcon:(NSImage*)image;
+-(unsigned)count;
+@end
+
+@interface TreeView:NSScrollView{
+@public
+       NSOutlineView   *outline;
+       NSTableColumn   *column,*colin;
+       NSBrowserCell   *cell;
+       NodeItem                *rootNode;
+       NSDictionary    *textstyle;
+}
+-(id)initWithFrame:(NSRect)rect;
+-(void)reloadItem:(id)item;
+-(void)refresh;
+-(int)outlineView:(NSOutlineView*)outlineView numberOfChildrenOfItem:(id)item;
+-(id)outlineView:(NSOutlineView*)outlineView child:(int)index ofItem:(id)item;
+-(BOOL)outlineView:(NSOutlineView*)outlineView isItemExpandable:(id)item;
+-(id)outlineView:(NSOutlineView*)outlineView objectValueForTableColumn:(NSTableColumn*)tableColumn byItem:(id)item;
+-(unsigned)count;
+-(id)rootNode;
+-(id)selectedNode;
+-(void)selectNode:(id)node;
+-(void)expandNode:(id)node;
+-(void)collapseNode:(id)node;
+-(void)outlineViewItemDidExpand:(NSNotification *)notification;
+-(void)outlineViewItemDidCollapse:(NSNotification *)notification;
+-(void)outlineViewSelectionDidChange:(NSNotification *)notification;
+-(BOOL)outlineView:(NSOutlineView *)outlineView shouldEditTableColumn:(NSTableColumn *)tableColumn item:(id)item;
+-(void)outlineView:(NSOutlineView *)outlineView willDisplayCell:(id)dcell forTableColumn:(NSTableColumn *)tableColumn item:(id)item;
+-(void)setColor:(NSColor*)color;
+-(void)setTextColor:(NSColor*)color;
+-(void)setFont:(NSFont*)font;
+-(void)setEnabled:(BOOL)e;
+-(BOOL)isEnabled;
+-(void)dealloc;
+@end
+
+@interface TextView:NSTextView{
+@public
+       NSScrollView    *scroll;
+       NSMutableParagraphStyle *style;
+       NSMutableDictionary *styles;
+       NSTextStorage *storage;
+       int lockedNest;
+       NSRange lockedRange;
+}
+-(NSSize)contentSize;
+-(id)storage;
+-(id)initWithFrame:(NSRect)rect;
+-(id)getScroll;
+-(void)setHidden:(BOOL)flag;
+-(void)setWordWrap:(BOOL)flag;
+-(void)setTabs:(int)tabs;
+-(void)setMargins:(int)leftmargin;
+-(void)setText:(NSString*)text;
+-(void)addText:(NSString*)text;
+-(void)setScrollFrame:(NSRect)rect;
+-(void)setTextColor:(NSColor*)color;
+-(void)setColor:(NSColor*)color;
+-(void)setFont:(NSFont*)font;
+-(NSMenu *)menuForEvent:(NSEvent*)theEvent;
+-(void)textDidChange:(NSNotification*)aNotification;
+-(void)textDidEndEditing:(NSNotification*)aNotification;
+-(void)textViewDidChangeSelection:(NSNotification *)aNotification;
+-(void)textStorageDidProcessEditing:(NSNotification *)aNotification;
+-(void)textStorageWillProcessEditing:(NSNotification *)aNotification;
+-(void)updateDragTypeRegistration;
+-(NSArray *)acceptableDragTypes;
+-(void)free;
+@end
+
+@interface TabView:NSTabView{
+       id              client;
+       int             user;
+}
+-(id)initWithFrame:(NSRect)rect;
+-(id)clientView;
+-(void)setFrame:(NSRect)frameRect;
+-(void)selectTabViewItemAtIndex:(int)index;
+-(BOOL)tabView:(NSTabView *)tabView shouldSelectTabViewItem:(NSTabViewItem *)tabViewItem;
+-(void)dealloc;
+@end
+
+@interface WindowView:NSWindow{
+       id      view;
+       id      label[3];
+       nsgadget *gadget;
+       int enabled;
+       int zooming;
+       NSView *dragging;
+}
+-(id)textFirstResponder;
+-(id)initWithContentRect:(NSRect)rect styleMask:(unsigned int)mask backing:(NSBackingStoreType)backing defer:(BOOL)flag withGadget:(nsgadget*)_gadget ;
+-(id)clientView;
+-(void)setStatus:(NSString*)text align:(int)pos;
+-(void)sendEvent:(NSEvent*)event;
+-(NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender;
+-(BOOL)performDragOperation:(id <NSDraggingInfo>)sender;
+-(void)didResize;
+-(void)didMove;
+-(void)zoom;
+-(NSRect)localRect;
+-(BOOL)canBecomeKeyWindow;
+-(BOOL)canBecomeMainWindow;
+-(BOOL)becomeFirstResponder;
+-(void)setEnabled:(BOOL)flag;
+-(BOOL)isEnabled;
+-(void)dealloc;
+@end
+
+@interface ToolView:NSPanel{
+       id      view;
+       id      label[3];
+       nsgadget *gadget;
+       int enabled;
+       int zooming;
+       NSView *dragging;
+}
+-(id)textFirstResponder;
+-(id)initWithContentRect:(NSRect)rect styleMask:(unsigned int)mask backing:(NSBackingStoreType)backing defer:(BOOL)flag withGadget:(nsgadget*)_gadget ;
+-(id)clientView;
+-(void)setStatus:(NSString*)text align:(int)pos;
+-(void)sendEvent:(NSEvent*)event;
+-(NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender;
+-(BOOL)performDragOperation:(id <NSDraggingInfo>)sender;
+-(void)didResize;
+-(void)didMove;
+-(void)zoom;
+-(NSRect)localRect;
+-(BOOL)canBecomeKeyWindow;
+-(BOOL)canBecomeMainWindow;
+-(BOOL)becomeFirstResponder;
+-(void)setEnabled:(BOOL)flag;
+-(BOOL)isEnabled;
+-(void)dealloc;
+@end
+
+static CocoaApp *GlobalApp;
+
+@class HTMLView;
+@interface HTMLView:WebView{
+       int             _state, _style;
+}
+-(id)initWithFrame:(NSRect)rect;
+-(int)loaded;
+-(void)setStyle:(int)style;
+-(void)setAddress:(NSString*)address;
+-(NSString*)address;
+@end
+@implementation HTMLView
+-(id)initWithFrame:(NSRect)rect{
+       self=[super initWithFrame:rect];
+       [self setAutoresizingMask:NSViewNotSizable];
+       [self setPolicyDelegate:self];
+       [self setFrameLoadDelegate:self];
+       [self setUIDelegate:self];
+       [self unregisterDraggedTypes];
+       _state=0;
+       return self;
+}
+-(int)loaded{
+       return _state;
+}
+-(void)setStyle:(int)style{
+       _style = style;
+}
+-(NSString*)address{
+       WebDataSource           *datasource;
+       datasource = [[self mainFrame] provisionalDataSource];
+       if(datasource==nil) datasource = [[self mainFrame] dataSource];
+       if(datasource==nil) return [[NSString alloc] initWithString:@""];
+       return [[[datasource request] URL] absoluteString];
+}
+-(void)setAddress:(NSString*)address{
+       NSURL                   *url;
+       NSURLRequest            *request;
+       WebFrame                        *frame;
+               
+       url=[NSURL URLWithString:address];
+       if (url==nil) url=[NSURL fileURLWithPath:address];
+       if (url==nil) return;
+       _state=1;
+       request=[NSURLRequest requestWithURL:url];
+       frame=[self mainFrame];
+       [frame loadRequest:request];
+}
+- (void)webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame{
+       int oldstate = _state;
+       NSURLRequest *url;
+       BBString*text;
+       
+       _state=0;
+       
+       url=[[frame dataSource]initialRequest];
+       text=bbStringFromCString((char*)[[[url URL] relativePath] cString]);
+       
+       if(oldstate)
+               PostGuiEvent( BBEVENT_GADGETDONE,sender,0,0,0,0,(BBObject*)text );
+}
+- (void)webView:(WebView *)sender didChangeLocationWithinPageForFrame:(WebFrame *)frame{
+       int oldstate = _state;
+       NSURLRequest *url;
+       BBString*text;
+       
+       _state=0;
+       
+       url=[[frame dataSource]initialRequest];
+       text=bbStringFromCString((char*)[[[url URL] relativePath] cString]);
+       
+       if(oldstate)
+               PostGuiEvent( BBEVENT_GADGETDONE,sender,0,0,0,0,(BBObject*)text );
+}
+- (void)webView:(WebView *)sender decidePolicyForNavigationAction:(NSDictionary *)actionInformation request:(NSURLRequest *)url frame:(WebFrame *)frame decisionListener:(id<WebPolicyDecisionListener>)listener{
+       BBString*text;
+       int     key;
+       key=(int)[[actionInformation objectForKey:WebActionNavigationTypeKey] intValue];
+       switch (key){
+       case WebNavigationTypeOther:
+       case WebNavigationTypeLinkClicked:
+               if ((_state==0) && (_style & HTMLVIEW_NONAVIGATE)) {
+                       [listener ignore];
+                       text=bbStringFromCString((char*)[[[url URL] absoluteString] cString]);
+                       PostGuiEvent( BBEVENT_GADGETACTION,sender,0,0,0,0,(BBObject*)text );
+               }else{
+                       [listener use];
+               }
+       default:
+               [listener use];
+       }
+}
+- (NSArray *)webView:(WebView *)sender contextMenuItemsForElement:(NSDictionary *)element defaultMenuItems:(NSArray *)defaultMenuItems{
+       if(_style&HTMLVIEW_NOCONTEXTMENU)
+               return [NSArray array];
+       else
+               return defaultMenuItems;
+}
+@end
+
+
+//Toolbar
+
+@class Toolbar;
+@interface Toolbar:NSToolbar{
+       NSMutableDictionary     *items;
+}
+-(id)initWithIdentifier:(NSString *)string;
+-(void)addToolbarItem:(NSToolbarItem *)item;
+-(NSArray *)toolbarAllowedItemIdentifiers;
+-(NSArray *)toolbarDefaultItemIdentifiers;
+@end
+@implementation Toolbar
+-(id)initWithIdentifier:(NSString *)string{
+       self=[super initWithIdentifier:string];
+       items=[[NSMutableDictionary dictionaryWithCapacity:10] retain];
+       return self;
+}
+-(void)addToolbarItem:(NSToolbarItem *)item{
+       [items setObject:item forKey:[item itemIdentifier]];
+}
+-(NSArray *)toolbarAllowedItemIdentifiers{
+       return [items allValues];
+}
+-(NSArray *)toolbarDefaultItemIdentifiers{
+       return [items allValues];
+}
+@end
+
+
+// CocoaApp
+@implementation CocoaApp
++(void)dispatchGuiEvents{
+       maxgui_maxgui_DispatchGuiEvents();
+}
++(void)delayedGadgetAction:(NSObject*)o{  // See controlTextDidChange
+       PostGuiEvent( BBEVENT_GADGETACTION, 
+                     o, 
+                     [o respondsToSelector:@selector(indexOfSelectedItem)] ? [o indexOfSelectedItem] : 0,
+                     0,0,0,0 );
+}
+-(void)controlTextDidEndEditing:(NSNotification*)n{
+       PostGuiEvent( BBEVENT_GADGETLOSTFOCUS,[n object],0,0,0,0,0 );
+}
+-(void)controlTextDidChange:(NSNotification*)n{
+       NSObject *o = [n object];
+       [CocoaApp performSelector:@selector(delayedGadgetAction:) withObject:o afterDelay:0.0];
+}
+
+-(id)init{
+       toolbaritems=[[NSMutableDictionary dictionaryWithCapacity:10] retain];
+       menuitems=[[NSMutableArray arrayWithCapacity:10] retain];
+       return self;
+}
+-(BOOL)windowShouldClose:(id)sender{
+       PostGuiEvent( BBEVENT_WINDOWCLOSE,sender,0,0,0,0,0 );
+       return NO;
+}
+-(void)windowDidResize:(NSNotification *)aNotification{
+       WindowView *window;
+       ToolView * panel;
+       if ([[aNotification object] isKindOfClass:[WindowView class]]) {
+               window=(WindowView*)[aNotification object];
+               [window didResize];
+       } else {
+               panel =(ToolView*)[aNotification object];
+               [panel didResize];
+       }
+}
+-(void)windowDidMove:(NSNotification *)aNotification{
+       WindowView *window;
+       ToolView * panel;
+       if ([[aNotification object] isKindOfClass:[WindowView class]]) {
+               window=(WindowView*)[aNotification object];
+               [window didMove];
+       } else {
+               panel =(ToolView*)[aNotification object];
+               [panel didMove];
+       }
+}
+-(BOOL)windowShouldZoom:(NSWindow *)sender toFrame:(NSRect)newFrame{
+       [(WindowView*)sender zoom];
+       return YES;
+}
+-(void)windowDidBecomeKey:(NSNotification *)aNotification{
+       NSWindow *window;
+       window=(NSWindow*)[aNotification object];
+       PostGuiEvent( BBEVENT_WINDOWACTIVATE,window,0,0,0,0,0 );
+}
+-(void)menuSelect:(id)sender{
+       PostGuiEvent( BBEVENT_MENUACTION,sender,[sender tag],0,0,0,0 );
+}
+-(void)iconSelect:(id)sender{
+       NSToolbar       *toolbar;
+       int                     index;
+       toolbar=[sender toolbar];
+       index=[[toolbar items] indexOfObject:sender];
+       PostGuiEvent( BBEVENT_GADGETACTION,toolbar,index,0,0,0,0 );
+}
+-(void)sliderSelect:(id)sender{
+       PostGuiEvent( BBEVENT_GADGETACTION,sender,0,0,0,0,0 );
+}
+-(void)scrollerSelect:(id)sender{
+       NSScroller *scroller;
+       int delta=0;
+       scroller=(NSScroller *)sender;
+       switch([scroller hitPart]){
+       case NSScrollerDecrementLine:
+               delta=-1;
+               break;
+       case NSScrollerDecrementPage:
+               delta=-2;
+               break;
+       case NSScrollerIncrementLine:
+               delta=1;
+               break;
+       case NSScrollerIncrementPage:
+               delta=2;
+               break;  
+       }
+       PostGuiEvent( BBEVENT_GADGETACTION,sender,delta,0,0,0,0 );
+}
+-(void)buttonPush:(id)sender{
+       if([sender allowsMixedState]) [sender setAllowsMixedState:NO];
+       PostGuiEvent( BBEVENT_GADGETACTION,sender,0,0,0,0,0 );
+}
+-(void)textEdit:(id)sender{
+       PostGuiEvent( BBEVENT_GADGETACTION,sender,0,0,0,0,0 );
+}
+-(void)comboBoxSelectionDidChange:(NSNotification *)notification{
+       NSControl *o=(NSComboBox*)[notification object];
+       [CocoaApp performSelector:@selector(delayedGadgetAction:) withObject:o afterDelay:0.0];
+}
+-(void)comboBoxSelectionIsChanging:(NSNotification *)notification{
+       
+}
+-(void)comboBoxWillPopUp:(NSNotification *)notification{
+       HaltMouseEvents = 1;
+}
+-(void)comboBoxWillDismiss:(NSNotification *)notification{
+       HaltMouseEvents = 0;
+}
+-(void)addToolbarItem:(NSToolbarItem *)item{
+       [toolbaritems setObject:item forKey:[item itemIdentifier]];
+}
+-(NSToolbarItem *)toolbar:(NSToolbar *)toolbar itemForItemIdentifier:(NSString *)itemIdentifier willBeInsertedIntoToolbar:(BOOL)flag{
+       return [toolbaritems objectForKey:itemIdentifier];
+}
+-(NSArray *)toolbarAllowedItemIdentifiers:(NSToolbar *)toolbar{
+       Toolbar *mytoolbar=(Toolbar*)toolbar;
+       return [mytoolbar toolbarAllowedItemIdentifiers];
+}
+-(NSArray *)toolbarDefaultItemIdentifiers:(NSToolbar *)toolbar{
+       Toolbar *mytoolbar=(Toolbar*)toolbar;
+       return [mytoolbar toolbarDefaultItemIdentifiers];
+}
+-(BOOL)validateToolbarItem:(NSToolbarItem *)item{
+       return [item isEnabled];
+}
+-(void)addMenuItem:(NSMenuItem *)item{
+       [menuitems addObject:item];
+}
+-(void)removeMenuItem:(NSMenuItem *)item{
+       [menuitems removeObject:item];
+}
+
+@end
+
+// Scroller
+
+@implementation Scroller
+-(id)init{
+       [super init];
+       [self setAlphaValue:.5f];               
+       return self;
+}
+//-(void)drawKnob{}
+//-(void)drawParts{}
+//-(void)drawKnobSlotInRect:(NSRect)slotRect highlight:(BOOL)flag{}
+//-(void)drawArrow:(NSScrollerArrow)arrow highlight:(BOOL)flag{}
+//-(void)highlight:(BOOL)flag{}
+@end
+
+// FlippedView
+
+@implementation FlippedView
+-(BOOL)isFlipped{
+       return YES;
+}
+-(BOOL)mouseDownCanMoveWindow{
+       return YES;
+}
+@end
+
+// PanelView
+
+@implementation PanelView
+- (BOOL)acceptsFirstResponder{
+       return YES;
+}
+-(BOOL)becomeFirstResponder{
+       return [self isEnabled];
+}
+-(void)setColor:(NSColor *)rgb{
+       [[self contentView] setColor:rgb];
+}
+-(void)setAlpha:(float)al{
+       [[self contentView] setAlpha:al];
+}
+-(void)setImage:(NSImage *)img withFlags:(int)flags{
+       [[self contentView] setImage:img withFlags:flags];
+}
+-(void)setEnabled:(BOOL)e{
+       enabled=e;
+}
+-(BOOL)isEnabled{
+       return (enabled)?YES:NO;
+}
+-(void)setStyle:(int)s{
+       
+       gadget->sensitivity |= (s & PANEL_ACTIVE) ? (SENSITIZE_MOUSE|SENSITIZE_KEYS) : 0;
+       
+       switch ( s & (PANEL_SUNKEN|PANEL_RAISED|PANEL_GROUP) ){
+               case PANEL_GROUP:
+                       [self setContentViewMargins: NSMakeSize(4.0,4.0)];
+                       [self setBoxType:NSBoxPrimary];
+                       [self setBorderType: NSBezelBorder];
+                       [self setTitlePosition: NSAtTop];
+                       break;
+               case PANEL_RAISED:
+               case PANEL_SUNKEN:
+                       [self setContentViewMargins: NSMakeSize(0.0,0.0)];
+                       [self setBoxType: NSBoxOldStyle];
+                       [self setBorderType: NSLineBorder];
+                       [self setTitlePosition: NSNoTitle];
+                       break;
+               default:
+                       [self setContentViewMargins: NSMakeSize(0.0,0.0)];
+                       [self setBorderType: NSNoBorder];
+                       [self setTitlePosition: NSNoTitle];
+       }
+       
+       style=s;
+}
+-(void)setGadget:(nsgadget*)_gadget{
+       gadget=_gadget;
+}
+-(BOOL)mouseDownCanMoveWindow{
+       return NO;
+}
+@end
+
+//PanelViewContent
+@implementation PanelViewContent
+-(BOOL)isFlipped{
+       return YES;
+}
+-(BOOL)mouseDownCanMoveWindow{
+       return NO;
+}
+-(void)setColor:(NSColor *)rgb{
+       if (color){
+               [color release];
+               color=0;
+       }
+       if(rgb){
+               color=[rgb colorWithAlphaComponent:1.0];
+               [color retain];
+       }
+       [self setNeedsDisplay:YES];
+}
+-(void)setImage:(NSImage *)img withFlags:(int)flags{
+       if (img) [img retain];
+       if (image) [image release];
+       image=img;
+       imageflags=flags;
+       [self setNeedsDisplay:YES];
+}
+-(void)setAlpha:(float)al{
+       alpha=al;
+       if (color){
+               [color release];
+               color=[color colorWithAlphaComponent:alpha];
+               [color retain];
+       }
+       [self setNeedsDisplay:YES];
+}
+-(void)drawRect:(NSRect)rect{
+       
+       NSRect dest = NSUnionRect(rect,[self frame]);
+       
+       if (color){
+               [color set];
+               if (alpha<1.0)
+                       NSRectFillUsingOperation( dest,NSCompositeSourceOver );
+               else
+                       NSRectFill( dest );
+       }
+       
+       if (image){
+               int             op,x,y,w,h;
+               float   a;
+               float   m,mm;
+               NSRect  src,tile;
+
+               a=alpha;
+               op=NSCompositeSourceOver;
+               src.origin.x=0;
+               src.origin.y=0;
+               src.size=[image size];
+               [image setFlipped:YES];
+
+               switch (imageflags&(GADGETPIXMAP_ICON-1)){
+               case PANELPIXMAP_TILE:
+                       tile.size=[image size];
+                       for (y=0;y<dest.size.height;y+=src.size.height){
+                               tile.origin.y=y;
+                               for (x=0;x<dest.size.width;x+=src.size.width){
+                                       tile.origin.x=x;
+                                       [image drawInRect:tile fromRect:src operation:op fraction:a];
+                               }
+                       }                                       
+                       break;
+               case PANELPIXMAP_CENTER:
+                       dest.origin.x=(dest.size.width-src.size.width)/2;
+                       dest.origin.y=(dest.size.height-src.size.height)/2;
+                       dest.size=src.size;
+                       [image drawInRect:dest fromRect:src operation:op fraction:a];
+                       break;
+               case PANELPIXMAP_FIT:
+                       m=dest.size.width/src.size.width;
+                       mm=dest.size.height/src.size.height;
+                       if (m>mm) m=mm;
+                       dest.origin.x+=(dest.size.width-src.size.width*m)/2;
+                       dest.origin.y+=(dest.size.height-src.size.height*m)/2;
+                       dest.size.width=src.size.width*m;
+                       dest.size.height=src.size.height*m;
+                       [image drawInRect:dest fromRect:src operation:op fraction:a];
+                       break;
+               case PANELPIXMAP_STRETCH:
+                       [image drawInRect:dest fromRect:src operation:op fraction:a];
+                       break;
+               case PANELPIXMAP_FIT2:
+                       m = dest.size.width/dest.size.height;
+                       
+                       if ((dest.size.width/src.size.width)<(dest.size.height/src.size.height)){
+                               src.origin.x = (src.size.width-(src.size.height*m))/2;
+                               src.size.width = src.size.height*m;
+                       } else {
+                               src.origin.y = (src.size.height-(src.size.width/m))/2;
+                               src.size.height = src.size.width/m;
+                       }
+                       
+                       [image drawInRect:dest fromRect:src operation:op fraction:a];
+                       break;
+               }
+               [image setFlipped:NO];
+       }
+       
+       [super drawRect:rect];
+} 
+@end
+
+// CanvasView
+@implementation CanvasView
+-(void)drawRect:(NSRect)rect{
+       [super drawRect:rect];
+       PostGuiEvent( BBEVENT_GADGETPAINT,self,0,0,0,0,0 );
+} 
+- (BOOL)acceptsFirstResponder{
+       return YES;
+}
+-(BOOL)becomeFirstResponder{
+       return [self isEnabled];
+}
+@end
+
+// ImageString
+
+@class ImageString;
+@interface ImageString:NSObject{
+       NSString        *_string;
+       NSImage *_image;
+       NSString        *_tip;
+       BBObject        *_extra;
+}
+-(id)initWithString:(NSString *)text image:(NSImage *)image tip:(NSString *)tip extra:(BBObject*)extra;
+-(void)dealloc;
+-(id)copyWithZone:(NSZone *)zone;
+-(NSString*)string;
+-(NSImage*)image;
+-(NSString*)description;
+-(BBObject*)extra;
+@end
+@implementation ImageString
+-(id)initWithString:(NSString *)string image:(NSImage *)image tip:(NSString*)tip extra:(BBObject*)extra{
+       _string=string;
+       _image=image;
+       _tip=tip;
+       _extra=extra;
+       if (string) [string retain];
+       if (image) [image retain];
+       if (tip) [tip retain];
+       return self;
+}
+-(void)dealloc{
+       if (_string) [_string release];
+       if (_image) [_image release];
+       if (_tip) [_tip release];
+       [super dealloc];
+}
+-(id)copyWithZone:(NSZone *)zone{
+       ImageString *copy=[[[self class] allocWithZone:zone] initWithString:_string image:_image tip:_tip extra:_extra];
+       return copy;
+}
+-(NSString*)string{return _string;}
+-(NSImage*)image{return _image;}
+-(NSString*)description{return _tip;}
+-(BBObject*)extra{return _extra;}
+@end
+
+// ListView
+
+@implementation ListView
+-(id)initWithFrame:(NSRect)rect{
+       [super initWithFrame:rect];
+       [self setBorderType:NSNoBorder];
+       [self setHasVerticalScroller:YES];
+       [self setHasHorizontalScroller:YES];
+       [self setAutohidesScrollers:YES];
+       column=[[NSTableColumn alloc] init];
+       cell=[[NSBrowserCell alloc] init];
+       [cell setLeaf:YES];
+       [column setDataCell:cell];
+       NSSize contentSize = [self contentSize];        
+       table=[[TableView alloc] initWithFrame:NSMakeRect(0, 0,contentSize.width, contentSize.height)];
+       [table setAutoresizingMask:(NSViewWidthSizable|NSViewHeightSizable)];
+       items=[[NSMutableArray alloc] initWithCapacity:10];
+       [table setHeaderView:nil];      
+       [table setDataSource:self];
+       [table setDelegate:self];
+       [self setDocumentView:table];
+       [table addTableColumn:column];
+       [table sizeLastColumnToFit];
+       return self;
+}
+-(id)table{
+       return table;
+}
+-(id)items{
+       return items;
+}
+-(void)removeItemAtIndex:(int)index{
+       ImageString *item=(ImageString*)[items objectAtIndex:index];
+       [items removeObjectAtIndex:index];
+       [item release];
+       [table reloadData];
+       [self queueWidthUpdate];
+}
+-(void)setColor:(NSColor*)color{
+       [table setBackgroundColor:color];
+}
+-(void)setEnabled:(BOOL)e{
+       [table setEnabled:e];
+}
+-(BOOL)isEnabled{
+       return [table isEnabled];
+}
+-(void)setTextColor:(NSColor*)color{
+       if (textstyle) {[textstyle release];textstyle=nil;}
+       if (color){
+               textstyle=[NSDictionary dictionaryWithObjectsAndKeys:color,NSForegroundColorAttributeName,nil];
+               [textstyle retain];     
+       }
+}
+-(int)numberOfRowsInTableView:(NSTableView *)aTableView{
+       return [items count];
+}
+-(id)tableView:(NSTableView *)aTableView objectValueForTableColumn:(NSTableColumn *)aTableColumn row:(int)rowIndex{
+       return [items objectAtIndex:rowIndex];
+}
+-(BOOL)tableView:(NSTableView *)tableView shouldEditTableColumn:(NSTableColumn *)tableColumn row:(int)rowIndex{ /*new from BAH*/
+       PostGuiEvent( BBEVENT_GADGETACTION,self,rowIndex,0,0,0,0 );
+       return NO;
+}
+-(void)clear{
+       [table setDelegate:nil];
+
+       ImageString *item;
+       int count,i;
+       count=[items count];
+       for (i=0;i<count;i++){
+               item=(ImageString*)[items objectAtIndex:i];
+               [item release];
+       }
+
+       [items removeAllObjects];
+       [table reloadData];
+       [table setDelegate:self];
+       [self queueWidthUpdate];
+}
+-(void)addItem:(NSString*)text atIndex:(unsigned)index withImage:(NSImage*)image withTip:(NSString*)tip withExtra:(BBObject*)extra{
+       ImageString *item;
+       item=[[ImageString alloc] initWithString:text image:image tip:tip extra:extra];
+       [items insertObject:item atIndex:index];
+       [self updateWidthForString:item];
+       [table noteNumberOfRowsChanged];
+}
+-(void)setItem:(NSString*)text atIndex:(unsigned)index withImage:(NSImage*)image withTip:(NSString*)tip withExtra:(BBObject*)extra{
+       ImageString *item;
+       item=(ImageString*)[items objectAtIndex:index];
+       [item release];
+       item=[[ImageString alloc] initWithString:text image:image tip:tip extra:extra];
+       [items replaceObjectAtIndex:index withObject:item];
+       [table reloadData];
+       [self queueWidthUpdate];
+}
+-(void)selectItem:(unsigned)index{
+       [table setDelegate:nil];
+       [table selectRowIndexes:[NSIndexSet indexSetWithIndex:index] byExtendingSelection:NO];
+       [table setDelegate:self];
+}
+-(void)deselectItem:(unsigned)index{
+       [table setDelegate:nil];
+       [table deselectRow:index];
+       [table setDelegate:self];
+}
+-(void)tableViewSelectionDidChange:(NSNotification *)aNotification{/*new from BAH*/
+        int index=[table selectedRow];
+        ImageString *item=nil;
+        if (index>=0) item=(ImageString*)[items objectAtIndex:index]; else index=-1;
+        if (item){
+                PostGuiEvent( BBEVENT_GADGETSELECT,self,index,0,0,0,[item extra]);
+        }else{
+                PostGuiEvent( BBEVENT_GADGETSELECT,self,-1,0,0,0,&bbNullObject);
+        }
+}
+-(void)tableView:(NSTableView *)table willDisplayCell:(id)aCell forTableColumn:(NSTableColumn *)aTableColumn row:(int)rowIndex{
+       NSString *text=[[items objectAtIndex:rowIndex] string];
+       if (textstyle){
+               NSAttributedString *atext=[[[NSAttributedString alloc] initWithString:text attributes:textstyle] autorelease];
+               [aCell setAttributedStringValue:atext];
+       }else{
+               [aCell setStringValue:text];
+       }
+       [aCell setImage:[[items objectAtIndex:rowIndex] image]];
+}
+-(void)updateWidthForString:(ImageString *) imgstring{
+       
+       NSCell* dcell;
+       float   cellWidth;
+       
+       dcell = [column dataCell];
+       [dcell setStringValue:[imgstring string]];
+       [dcell setImage:[imgstring image]];
+       cellWidth = ((NSSize)[dcell cellSize]).width;
+
+       if([column minWidth] < cellWidth){
+               [column setMinWidth:cellWidth];
+               [column setWidth:cellWidth];
+               [table setNeedsDisplay:YES];
+       }
+       
+}
+-(void)updateWidth{
+       int i, count;
+       count = [items count];
+       [column setMinWidth:0];
+       for (i=0;i<count;i++)
+               [self updateWidthForString:(ImageString*)[items objectAtIndex:i]];
+}
+-(void)queueWidthUpdate{
+       [NSObject cancelPreviousPerformRequestsWithTarget: self selector:@selector(updateWidth) object:nil];
+       [self performSelector:@selector(updateWidth) withObject:nil afterDelay:0.0];
+}
+-(void)dealloc{
+       ImageString *item;
+       int count,i;
+       count=[items count];
+       for (i=0;i<count;i++){
+               item=(ImageString*)[items objectAtIndex:i];
+               [item release];
+       }
+
+       [table release];
+       [column release];
+       [cell release];
+       [items release];
+       if (textstyle) {
+               [textstyle release];
+       }
+       [super dealloc];
+}
+-(void)setFont:(NSFont*)font{
+       if (font) {
+               [table setRowHeight:[font defaultLineHeightForFont]+2];
+               [[column dataCell] setFont:font];
+               [table reloadData];
+               [self updateWidth];
+       }
+}
+
+- (NSString *)tableView:(NSTableView *)aTableView toolTipForCell:(NSCell *)aCell rect:(NSRectPointer)rect 
+tableColumn:(NSTableColumn *)aTableColumn row:(int)row mouseLocation:(NSPoint)mouseLocation{
+       
+       return [[items objectAtIndex:row] description];
+}
+
+@end
+
+// TableView
+
+@implementation TableView
+-(NSMenu*)menuForEvent:(NSEvent *)theEvent{
+       int             row = -1;
+       NSPoint p=[self convertPoint:[theEvent locationInWindow] fromView:nil];
+       row = [self rowAtPoint:p];
+
+       if (row < [self numberOfRows]) {
+               [self selectRowIndexes:[NSIndexSet indexSetWithIndex:row] byExtendingSelection:NO];
+               PostGuiEvent( BBEVENT_GADGETMENU,[self dataSource],row,0,0,0,0 );
+       }
+
+       return nil;
+}
+@end
+
+// OutlineView
+
+@implementation OutlineView
+-(NSMenu*)menuForEvent:(NSEvent *)theEvent{
+       id              node;
+       NSPoint p=[self convertPoint:[theEvent locationInWindow] fromView:nil];
+       int i=[self rowAtPoint:p];
+       if (i>-1 && i<[self numberOfRows]){
+               node=[self itemAtRow:i];
+               PostGuiEvent( BBEVENT_GADGETMENU,[self dataSource],(int)node,0,0,0,0 ); //[self superview]
+       }
+       return nil;
+}
+@end
+
+// TreeView
+
+@implementation TreeView
+-(id)initWithFrame:(NSRect)rect{
+       [super initWithFrame:rect];
+       [self setBorderType:NSNoBorder];
+       [self setHasVerticalScroller:YES];
+       [self setHasHorizontalScroller:YES];
+       [self setAutohidesScrollers:YES];
+       rootNode=[[NodeItem alloc] initWithTitle:@"root"];
+       [rootNode setOwner:self];
+       NSSize contentSize = [self contentSize];        
+       outline=[[OutlineView alloc] initWithFrame:NSMakeRect(0, 0,contentSize.width, contentSize.height)];
+       [outline setHeaderView:nil];    
+       [outline setAutoresizingMask:(NSViewWidthSizable|NSViewHeightSizable)];
+       [outline setDataSource:self];
+       [outline setDelegate:self];
+       column=[[NSTableColumn alloc] init];
+       [outline addTableColumn:column];
+       [outline setOutlineTableColumn:column];
+       cell=[[NSBrowserCell alloc] init];
+       [cell setLeaf:YES];
+       [cell setScrollable:YES];
+       [column setDataCell:cell];              
+       [self setDocumentView:outline];
+       [outline sizeLastColumnToFit];
+       return self;
+}
+-(void)dealloc{
+       [outline autorelease];
+       [column autorelease];
+       [cell autorelease];
+       if (textstyle) {
+               [textstyle release];
+       }
+       [super dealloc];
+}
+-(void)refresh{
+       [rootNode updateWidth];
+       [outline reloadData];
+}
+-(int)outlineView:(NSOutlineView*)outlineView numberOfChildrenOfItem:(id)item{
+       if( !item ) item=rootNode;
+       return [[item kids] count];
+}
+-(id)outlineView:(NSOutlineView*)outlineView child:(int)index ofItem:(id)item{
+       if( !item ) item=rootNode;
+       if (index>=[[item kids] count]) return 0;
+       return [[item kids] objectAtIndex:index];
+}
+-(BOOL)outlineView:(NSOutlineView*)outlineView isItemExpandable:(id)item{
+       if( !item ) item=rootNode;
+       return [item canExpand];
+}
+-(id)outlineView:(NSOutlineView*)outlineView objectValueForTableColumn:(NSTableColumn*)tableColumn byItem:(id)item{
+       if (tableColumn==colin) return @"";     
+       if( !item ) item=rootNode;
+       return [item value];
+}
+-(unsigned)count{
+       return [rootNode count];
+}
+-(id)rootNode{
+       return rootNode;
+}
+-(id)selectedNode{
+       int             index;
+       index=[outline selectedRow];
+       if (index==-1) return nil;
+       return [outline itemAtRow:index];
+}
+-(void)selectNode:(id)node{
+       int index;
+       [node show];
+       [outline setDelegate:nil];
+       index = [outline rowForItem:node];
+       [outline selectRowIndexes:[NSIndexSet indexSetWithIndex:index] byExtendingSelection:NO];
+       [outline setDelegate:self];
+       [outline scrollRowToVisible:index];     
+}
+-(void)expandNode:(id)node{
+       [outline setDelegate:nil];
+       [outline expandItem:node];
+       [outline tile];
+       [outline setDelegate:self];
+       [node queueWidthUpdate];
+}
+-(void)collapseNode:(id)node{
+       [outline setDelegate:nil];
+       [outline collapseItem:node];
+       [outline tile];
+       [outline setDelegate:self];
+       [column setMinWidth:0];
+       [rootNode queueWidthUpdate];
+}
+-(void)outlineViewItemDidExpand:(NSNotification *)notification{
+       id              node;
+       node=[[notification userInfo] objectForKey:@"NSObject"];
+       [node queueWidthUpdate];
+       PostGuiEvent( BBEVENT_GADGETOPEN,self,(int)node,0,0,0,0 );
+}
+-(void)outlineViewItemDidCollapse:(NSNotification *)notification{
+       id              node;
+       node=[[notification userInfo] objectForKey:@"NSObject"];
+       [column setMinWidth:0];
+       [rootNode queueWidthUpdate];
+       PostGuiEvent( BBEVENT_GADGETCLOSE,self,(int)node,0,0,0,0 );
+}
+-(void)outlineViewSelectionDidChange:(NSNotification *)notification{
+       id              node;
+       node=[self selectedNode];
+       PostGuiEvent( BBEVENT_GADGETSELECT,self,(int)node,0,0,0,0 );
+}
+-(BOOL)outlineView:(NSOutlineView *)outlineView shouldEditTableColumn:(NSTableColumn *)tableColumn item:(id)item{
+       PostGuiEvent( BBEVENT_GADGETACTION,self,(int)item,0,0,0,0 );
+       return NO;
+}
+-(void)setColor:(NSColor*)color{
+       [outline setBackgroundColor:color];
+}
+-(void)setTextColor:(NSColor*)color{
+       if (textstyle) {[textstyle release];textstyle=nil;}
+       if (color){
+               textstyle=[NSDictionary dictionaryWithObjectsAndKeys:color,NSForegroundColorAttributeName,nil];
+               [textstyle retain];     
+       }
+}
+- (void)setFont:(NSFont*)font{
+       if (font) {
+               NSLayoutManager* layoutManager = [[[NSLayoutManager alloc] init] autorelease];
+               int i;
+               NSArray *columnsArray = [outline tableColumns];
+               for (i= 0; i < [columnsArray count]; i++)
+               [[[columnsArray objectAtIndex:i] dataCell] setFont:font];
+               [outline setRowHeight: [layoutManager defaultLineHeightForFont:font]+1];
+               [rootNode queueWidthUpdate];
+       }
+}
+- (void)outlineView:(NSOutlineView *)outlineView willDisplayCell:(id)dcell forTableColumn:(NSTableColumn *)tableColumn item:(id)node{
+       if (textstyle){
+               NSAttributedString *atext=[[[NSAttributedString alloc] initWithString:[node value] attributes:textstyle] autorelease];
+               [dcell setAttributedStringValue:atext];
+       }
+       else{
+               [dcell setStringValue:[node value]];
+       }
+       [dcell setImage:[node icon]];
+}
+-(void)setEnabled:(BOOL)e{
+       [outline setEnabled:e];
+}
+-(BOOL)isEnabled{
+       return [outline isEnabled];
+}
+@end
+
+// NodeItem
+
+@implementation NodeItem
+-(void)dealloc{}
+-(id)initWithTitle:(NSString*)text{
+       owner=nil;
+       parent=nil;
+       title=text;
+       icon=nil;
+       [title retain];
+       kids=[[NSMutableArray alloc] initWithCapacity:10];
+       [kids retain];
+       return self;
+}
+-(void)updateWidth{
+       int             i;
+       float       cellWidth;
+       float       indentationWidth;
+       
+       NSCell* dcell;
+       NSArray*        columnsArray;
+       
+       if(owner==nil) return;
+       
+       NSOutlineView*  outline = owner->outline;
+       NSTableColumn*  tableColumn = owner->column;
+       
+       if(tableColumn!=nil){
+               dcell = [tableColumn dataCell];
+               [dcell setStringValue:title];
+               [dcell setImage:icon];
+               cellWidth = ((NSSize)[dcell cellSize]).width;
+               indentationWidth = [outline levelForItem: self];
+               if(isnan(indentationWidth)) indentationWidth = 0; else indentationWidth=([outline indentationPerLevel]*(indentationWidth+1));
+               if((owner->rootNode == self) || [outline isItemExpanded:self])
+                       for (i= 0; i < [kids count]; i++) [[kids objectAtIndex:i] updateWidth];
+               if([tableColumn minWidth] < (cellWidth+indentationWidth)){
+                       [tableColumn setMinWidth:(cellWidth+indentationWidth)];
+                       [tableColumn setWidth:(cellWidth+indentationWidth)];
+               }
+       }
+}
+-(void)queueWidthUpdate{
+       [NSObject cancelPreviousPerformRequestsWithTarget: self selector:@selector(updateWidth) object:nil];
+       [self performSelector:@selector(updateWidth) withObject:nil afterDelay:0.0];
+}
+-(void)setOwner:(TreeView*)treeview{
+       owner=treeview;
+}
+-(id)getOwner{
+       return owner;
+}
+-(void)show{
+       if (parent){
+               [parent show];
+               [owner expandNode:parent];
+       }
+}
+-(void)attach:(NodeItem*)parent_ atIndex:(unsigned)index_{
+       parent=parent_;
+       if( parent ){
+               owner=parent->owner;
+               [[parent kids] insertObject:self atIndex:index_];
+               [self release];
+       }
+       if (owner) [owner refresh];
+}
+-(void)remove{
+       if( parent ) [[parent kids] removeObject:self];
+       if (owner) [owner refresh];
+}
+-(BOOL)canExpand{
+       return [kids count]>0;
+}
+-(NSMutableArray*)kids{
+       return kids;
+}
+-(NSString *)value{return title;}
+-(NSImage *)icon{return icon;}
+-(void)setTitle:(NSString*)text{
+       [title release];
+       title=text;
+       [title retain];
+       if (owner){
+               [owner->outline reloadItem:self];
+               [owner->rootNode queueWidthUpdate];
+       }
+}
+-(void)setIcon:(NSImage*)image{
+       if (icon) [icon release];
+       icon=image;
+       if (icon) [icon retain];
+       if (owner){
+               [owner->outline reloadItem:self];
+               [(icon ? self : owner->rootNode) queueWidthUpdate];
+       }
+}
+-(unsigned)count{
+       return [kids count];
+}
+@end
+
+// TextView
+
+@implementation TextView
+-(id)initWithFrame:(NSRect)rect{
+       
+       scroll=[[NSScrollView alloc] initWithFrame:rect];
+
+//     [scroll setVerticalScroller:[[Scroller alloc] init]];
+//     [scroll setHorizontalScroller:[[Scroller alloc] init]];
+
+       [scroll setHasVerticalScroller:YES];
+       [scroll setHasHorizontalScroller:YES];
+
+       [scroll setDrawsBackground:NO];
+       [scroll setRulersVisible:NO];
+       [scroll setBorderType:NSNoBorder];
+       [scroll setAutohidesScrollers:YES];
+                               
+       NSSize contentSize = [scroll contentSize];      
+
+       self=[super initWithFrame:NSMakeRect(0, 0,contentSize.width,contentSize.height)];
+       [self setMinSize:NSMakeSize(contentSize.width, contentSize.height)];
+       [self setMaxSize:NSMakeSize(FLT_MAX, FLT_MAX)];
+       [self setVerticallyResizable:YES];
+       [self setHorizontallyResizable:YES];
+       [self setAutoresizingMask:(NSViewWidthSizable|NSViewHeightSizable)];
+       [[self textContainer] setContainerSize:NSMakeSize(FLT_MAX,FLT_MAX)];
+       [[self textContainer] setWidthTracksTextView:NO];       
+       [self setDelegate:self];
+       [self setUsesRuler:NO];
+
+       [scroll setDocumentView:self];
+
+       style=[[NSParagraphStyle defaultParagraphStyle] mutableCopy];
+       [style setLineBreakMode:NSLineBreakByClipping];
+       
+       styles=[NSMutableDictionary dictionaryWithObject:style forKey:NSParagraphStyleAttributeName];
+       [styles retain];
+       storage=[self textStorage];
+       [storage setDelegate:self];
+       
+       lockedNest=0;
+       
+       [self setTabs: 4];
+       if ([self respondsToSelector: @selector(setDefaultParagraphStyle:)])
+               [self setDefaultParagraphStyle: style];
+       
+       if ([self respondsToSelector: @selector(setAutomaticLinkDetectionEnabled:)])
+               [self setAutomaticLinkDetectionEnabled: NO];
+       if ([self respondsToSelector: @selector(setAutomaticQuoteSubstitutionEnabled:)])
+               [self setAutomaticQuoteSubstitutionEnabled: NO];
+       if ([self respondsToSelector: @selector(setAutomaticDashSubstitutionEnabled:)])
+               [self setAutomaticDashSubstitutionEnabled: NO];
+       if ([self respondsToSelector: @selector(setAutomaticSpellingCorrectionEnabled:)])
+               [self setAutomaticSpellingCorrectionEnabled: NO];
+       if ([self respondsToSelector: @selector(setAutomaticTextReplacementEnabled:)])
+               [self setAutomaticTextReplacementEnabled: NO];
+       if ([self respondsToSelector: @selector(setAutomaticDataDetectionEnabled:)])
+               [self setAutomaticDataDetectionEnabled: NO];
+       
+       return self;
+}
+-(void)free{
+       [scroll setDocumentView:nil];
+       [scroll release];
+       [style release];
+       [styles release];
+       [storage release];
+}
+-(void)setHidden:(BOOL)flag{
+       [scroll setHidden:flag];
+}
+-(id)storage{
+       return storage;
+}
+-(NSSize)contentSize{
+       return [scroll contentSize];
+}
+-(id)getScroll{
+       return scroll;
+}
+-(void)setWordWrap:(BOOL)flag{
+       NSSize contentSize=[self contentSize];
+       if (flag){
+               [scroll setHasHorizontalScroller:NO];
+               [self setHorizontallyResizable:NO];
+               [self setAutoresizingMask:NSViewWidthSizable];
+               [[self textContainer] setContainerSize:NSMakeSize(contentSize.width, FLT_MAX)];
+               [[self textContainer] setWidthTracksTextView:YES];
+               [style setLineBreakMode:NSLineBreakByWordWrapping];
+       }
+       else{
+               [scroll setHasHorizontalScroller:YES];
+               [self setHorizontallyResizable:YES];
+               [self setAutoresizingMask:(NSViewWidthSizable | NSViewHeightSizable)];
+               [[self textContainer] setContainerSize:NSMakeSize(FLT_MAX, FLT_MAX)];
+               [[self textContainer] setWidthTracksTextView:NO];
+               [style setLineBreakMode:NSLineBreakByClipping];
+       }
+       [storage addAttribute:NSParagraphStyleAttributeName value:style range:NSMakeRange(0,[storage length])]; 
+}
+
+-(void)setTabs:(int)tabs{      
+       [style setTabStops:[NSArray array]];    //Clear any TabStops
+       [style setDefaultTabInterval: tabs];    //Set recurring TabStops remembering to convert from twips->pixels
+       [storage addAttribute:NSParagraphStyleAttributeName value:style range:NSMakeRange(0,[storage length])];
+}
+
+-(void)setMargins:(int)leftmargin{
+
+       [self setTextContainerInset:NSMakeSize( leftmargin, 0) ];
+//     [style setFirstLineHeadIndent: leftmargin*8];
+//     [style setHeadIndent: leftmargin*8];
+//     [storage addAttribute:NSParagraphStyleAttributeName value:style range:NSMakeRange(0,[storage length])]; 
+}
+
+-(void)setText:(NSString*)text{
+       NSAttributedString      *astring;
+       astring=[[NSAttributedString alloc] initWithString:text attributes:styles];
+       if (lockedNest) [storage endEditing];
+       [storage setAttributedString:astring];
+       if (lockedNest) [storage beginEditing]; else [self setSelectedRange:NSMakeRange(0,0)];
+}
+-(void)addText:(NSString*)text{
+       NSAttributedString      *astring;
+       astring=[[NSAttributedString alloc] initWithString:text attributes:styles];
+       if (lockedNest) [storage endEditing];
+       [storage appendAttributedString:astring];
+       if (lockedNest) [storage beginEditing];
+}
+-(void)setScrollFrame:(NSRect)rect{
+       [scroll setFrame:rect];
+}
+-(void)setTextColor:(NSColor*)color{
+       [styles setObject:color forKey:NSForegroundColorAttributeName];
+       [storage addAttribute:NSForegroundColorAttributeName value:color range:NSMakeRange(0,[storage length])];
+       [self setInsertionPointColor:color];    
+}
+-(void)setColor:(NSColor*)color{
+       if(color){
+               [self setBackgroundColor:color];        
+               [self setDrawsBackground:true];
+               [scroll setBackgroundColor:color];
+               [scroll setDrawsBackground:true];
+       }else{
+               [self setDrawsBackground:false];
+               [scroll setDrawsBackground:false];
+       }
+}
+-(void)setFont:(NSFont*)font{
+       [styles setObject:font forKey:NSFontAttributeName];
+       [storage setFont:font]; 
+       [super setFont:font];   
+}
+-(NSMenu *)menuForEvent:(NSEvent *)event{
+       NSPoint p;
+       int             x,y;
+       p=[event locationInWindow];     
+       x=(int)p.x;y=(int)p.y;
+       PostGuiEvent( BBEVENT_GADGETMENU,self,0,0,x,y,0 );
+       return nil;
+}
+-(void)updateDragTypeRegistration{
+}
+-(NSArray *)acceptableDragTypes{
+       return nil;
+}
+-(void)textDidBeginEditing:(NSNotification*)n{
+//     printf( "textDidBeginEditing:%p\n",_textEditor );fflush(stdout);
+}
+-(void)textDidChange:(NSNotification*)n{
+       PostGuiEvent( BBEVENT_GADGETACTION,self,0,0,0,0,0 );
+}
+-(void)textDidEndEditing:(NSNotification*)n{
+//     printf( "textDidEndEditing:%p\n",_textEditor );fflush(stdout);
+       PostGuiEvent( BBEVENT_GADGETLOSTFOCUS,[n object],0,0,0,0,0 );
+}
+-(void)textViewDidChangeSelection:(NSNotification *)aNotification{
+       PostGuiEvent( BBEVENT_GADGETSELECT,self,0,0,0,0,0 );
+}
+-(void)textStorageDidProcessEditing:(NSNotification *)aNotification{
+
+}
+-(void)textStorageWillProcessEditing:(NSNotification *)aNotification{
+       [storage removeAttribute:NSLinkAttributeName range:[storage editedRange]];
+}
+@end
+
+
+// TabViewItem
+
+@class TabViewItem;
+@interface TabViewItem:NSTabViewItem{
+       NSImage *_image;
+}
+-(id)initWithIdentifier:(NSString *)text;
+-(void)setImage:(NSImage*)image;
+-(id)copyWithZone:(NSZone *)zone;
+-(NSImage*)image;
+-(NSSize)sizeOfLabel:(BOOL)shouldTruncateLabel;
+-(void)drawLabel:(BOOL)shouldTruncateLabel inRect:(NSRect)tabRect;
+@end
+@implementation TabViewItem
+-(id)initWithIdentifier:(NSString *)string{
+       self=[super initWithIdentifier:string];
+       _image=nil;
+       return self;
+}
+-(void)setImage:(NSImage*)image{
+       _image=image;
+       if (_image) [_image setScalesWhenResized:YES];
+}
+-(id)copyWithZone:(NSZone *)zone{
+       TabViewItem *copy=[[[self class] allocWithZone:zone] initWithIdentifier:[self identifier]];
+       return copy;
+}
+-(NSImage*)image{
+       return _image;
+}
+-(NSSize)sizeOfLabel:(BOOL)shouldTruncateLabel{
+       NSSize  size;
+       NSSize  imageDimensions;
+       float           ratio;
+       size=[super sizeOfLabel:shouldTruncateLabel];
+       
+       if (_image) {
+               imageDimensions = [_image size];
+               if (imageDimensions.height > size.height){
+                       ratio = size.height/imageDimensions.height;
+                       imageDimensions.width*=ratio;imageDimensions.height*=ratio;
+                       [_image setSize: imageDimensions];
+               }
+               size.width += imageDimensions.height;
+       }
+       return size;
+}
+-(void)drawLabel:(BOOL)shouldTruncateLabel inRect:(NSRect)content{
+       NSSize  imageDimensions;
+       NSPoint point;
+       if (_image){
+               imageDimensions = [_image size];
+               point = NSMakePoint(content.origin.x,content.origin.y+imageDimensions.height);
+               [_image compositeToPoint:point operation:NSCompositeSourceOver];
+               content.origin.x+=imageDimensions.width;content.size.width-=imageDimensions.width;              
+       }
+       [super drawLabel:shouldTruncateLabel inRect:content];
+}
+@end
+
+// TabView
+
+@implementation TabView
+-(id)initWithFrame:(NSRect)rect{
+       rect.size.height+=8;
+       self=[super initWithFrame:rect];
+       [super setControlSize:NSSmallControlSize];
+       [super setFont:[NSFont labelFontOfSize:[NSFont smallSystemFontSize]]];  
+       client=[[FlippedView alloc] initWithFrame:[self contentRect]];
+       [client setAutoresizingMask:(NSViewWidthSizable|NSViewHeightSizable)];  
+       [client retain];
+       user=1; 
+       [self setDelegate:self];
+       return self;
+}
+-(id)clientView{
+       return client;
+}
+-(void)selectTabViewItemAtIndex:(int)index{
+       user=0;
+       [super selectTabViewItemAtIndex:index];
+       user=1;
+} 
+-(void)setFrame:(NSRect)rect{
+       rect.size.height+=8;
+       [super setFrame:rect];
+}
+-(BOOL)tabView:(NSTabView *)tabView shouldSelectTabViewItem:(NSTabViewItem *)tabViewItem{
+       int             index;
+       [tabViewItem setView:client];
+       [client setFrame:[self contentRect]];
+       if (user){
+               index=[self indexOfTabViewItem:tabViewItem];
+               PostGuiEvent( BBEVENT_GADGETACTION,self,index,0,0,0,0);
+       }
+       return YES;
+}
+-(void)dealloc{
+       NSArray                 *items;
+       int                             i,n;
+       
+       items=[self tabViewItems];
+       n=[items count];
+       for (i=0;i<n;i++) [self removeTabViewItem:[items objectAtIndex:0]];
+
+       [client release];
+       [super dealloc];
+}
+-(NSMenu *)menuForEvent:(NSEvent *)event{
+       int     index;
+       NSTabViewItem*  tabItem;
+       tabItem = [self tabViewItemAtPoint:[self convertPoint:[event locationInWindow] fromView:nil]];
+       if (tabItem) index = [self indexOfTabViewItem:tabItem]; else index = -1;
+       PostGuiEvent( BBEVENT_GADGETMENU,self,index,0,0,0,0);
+       return [super menuForEvent:event];
+}
+@end
+
+// WindowView
+
+@implementation WindowView
+-(id)textFirstResponder{
+       id r=[self firstResponder];
+       //if ([r isKindOfClass:[PanelView class]]) return r;
+       if ([r isKindOfClass:[NSTextView class]]){
+               id d=[r delegate];
+               if( [d isKindOfClass:[NSTextField class]] ) return d;
+       }
+       return r;
+}
+-(id)initWithContentRect:(NSRect)rect styleMask:(unsigned int)mask backing:(NSBackingStoreType)backing defer:(BOOL)flag withGadget:(nsgadget*)_gadget{
+//withStatus:(BOOL)status{
+       id              client;
+       int             i;
+       NSText  *l;
+       NSBox   *box;
+       dragging = nil;
+       self=[super initWithContentRect:rect styleMask:mask backing:backing defer:flag];
+       gadget=_gadget;
+       view=[[FlippedView alloc] init];
+       enabled=true;
+       [self setContentView:view];
+       [self setAcceptsMouseMovedEvents:YES];
+       [self disableCursorRects];      //Fixes NSSetPointer not sticking.
+       if (gadget->style&WINDOW_STATUS){
+               rect.origin.x=rect.origin.y=0;
+               rect.size.height-=STATUSBARHEIGHT;
+               client=[[FlippedView alloc] initWithFrame:rect];
+               [client setAutoresizingMask:(NSViewWidthSizable|NSViewHeightSizable)];  
+               [view addSubview:client];
+// label for window status
+               rect.origin.y=rect.size.height+3;
+               rect.size.height=STATUSBARHEIGHT-4;             
+               rect.size.width-=[NSScroller scrollerWidth];
+               for (i=0;i<3;i++){
+                       l=[[NSText alloc] initWithFrame:rect];
+                       [l setDrawsBackground:NO];
+                       [l setEditable:NO];
+                       [l setSelectable:NO];
+                       [l setAutoresizingMask:NSViewWidthSizable|NSViewMinYMargin];
+                       switch (i){
+                               case 0:[l setAlignment:NSLeftTextAlignment];break;
+                               case 1:[l setAlignment:NSCenterTextAlignment];break;
+                               case 2:[l setAlignment:NSRightTextAlignment];break;
+                       }
+                       if (view) [view addSubview:l];
+                       label[i]=l;
+               }
+               
+               rect.origin.y-=3;
+               rect.size.height=2;
+               rect.size.width+=[NSScroller scrollerWidth];
+               
+               box=[[NSBox alloc] initWithFrame:rect];
+               [box setBoxType:NSBoxSeparator];
+               [box setTitlePosition:NSNoTitle];
+               [box setAutoresizingMask:NSViewWidthSizable|NSViewMinYMargin];
+               if (view) [view addSubview:box];
+               
+// set clientview to inner view
+               view=client;            
+       }
+       return self;
+}
+-(id)clientView{
+       return view;
+}
+-(void)setStatus:(NSString*)text align:(int)pos{
+       if (label[pos]) [label[pos] setString:text];
+}
+-(void)sendEvent:(NSEvent*)event{
+       
+       static int lastHotKey;
+       int key;
+       id source;
+       
+       // Handling of Generic Key/Mouse Events
+       
+       switch( [event type] ){
+       case NSMouseEntered:
+               [self disableCursorRects];
+       case NSLeftMouseDown:
+       case NSRightMouseDown:
+       case NSOtherMouseDown:
+               if( [event type] != NSMouseEntered ){
+                       dragging = [[self contentView] hitTest:[event locationInWindow]];
+                       [self makeFirstResponder:dragging];
+               }
+       case NSMouseMoved:
+       case NSMouseExited:
+       case NSScrollWheel:
+       {
+               NSView *hitView = [[self contentView] hitTest:[event locationInWindow]];
+               if (hitView) EmitMouseEvent( event, hitView );
+               if(![self isEnabled]) return;
+               break;
+       }
+       case NSLeftMouseUp:
+       case NSRightMouseUp:
+       case NSOtherMouseUp:
+       {
+               //fire event for the dragged view
+               if (dragging) {
+                       EmitMouseEvent( event, dragging );
+                       dragging = nil;
+               } else {
+                       //fire the event for the recieving view (if it exists)
+                       NSView *hitView = [[self contentView] hitTest:[event locationInWindow]];
+                       if (hitView) EmitMouseEvent( event, hitView );
+               }
+               
+               if(![self isEnabled]) return;
+               break;
+       }
+       case NSLeftMouseDragged:
+       case NSRightMouseDragged:
+       case NSOtherMouseDragged:
+       {
+               if( dragging == nil ) dragging = [[self contentView] hitTest:[event locationInWindow]];
+               if( dragging ) EmitMouseEvent( event, dragging );
+               if(![self isEnabled]) return;
+               break;
+       }
+       case NSKeyDown:
+       case NSKeyUp:
+       case NSFlagsChanged:
+       {
+               NSResponder *handle=(NSResponder*)NSActiveGadget();
+               if( handle && EmitKeyEvent( event, handle )) return;
+               break;
+       }
+       }
+       
+       // End of Generic Key/Mouse Events
+       
+       // Gadget Filterkey Processing
+       
+       switch( [event type] ){
+       case NSKeyDown:
+               if( key=bbSystemTranslateKey( [event keyCode] ) ){
+                       int mods=bbSystemTranslateMods( [event modifierFlags] );
+                       BBObject *event=maxgui_maxgui_HotKeyEvent( key,mods );
+                       if( event!=&bbNullObject ){
+                               lastHotKey=key;
+                               brl_event_EmitEvent( event );
+                               return;
+                       }
+               }
+               source=[self textFirstResponder];
+               if( source && !filterKeyDownEvent( event,source ) ) return;             
+               if(![self isEnabled]) return;
+               break;
+       case NSKeyUp:
+               key=bbSystemTranslateKey([event keyCode]);
+               if( lastHotKey && (key==lastHotKey ) ){
+                       lastHotKey=0;
+                       return;
+               }
+               if(![self isEnabled]) return;
+               break;
+       }
+       lastHotKey=0;
+       
+       // End of FilterKey Processing
+       
+       [super sendEvent:event];
+}
+- (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender{
+//     printf("windowview got dragenter\n");fflush(stdout);
+       return YES;
+}
+- (BOOL)performDragOperation:(id <NSDraggingInfo>)sender{
+       NSPasteboard *pboard = [sender draggingPasteboard];
+       if ( [[pboard types] containsObject:NSFilenamesPboardType] ) {
+               NSArray *files = [pboard propertyListForType:NSFilenamesPboardType];
+               int numberOfFiles = [files count];
+               // Perform operation using the list of files
+               // printf("windowview got drag\n");fflush(stdout);
+               int i;
+               for (i=0;i<numberOfFiles;i++)
+               {
+                       BBString *name=bbStringFromNSString([files objectAtIndex:i]);
+                       maxgui_cocoamaxgui_PostCocoaGuiEvent( BBEVENT_WINDOWACCEPT,self,0,0,0,0,(BBObject*)name );
+               }
+               
+       }
+       return YES;
+}
+-(void)didResize{
+       NSRect rect=[self localRect];
+       [self didMove];
+       PostGuiEvent( BBEVENT_WINDOWSIZE,self,0,0,rect.size.width,rect.size.height,0 );
+}
+-(void)didMove{
+       NSRect rect=[self localRect];
+       PostGuiEvent( BBEVENT_WINDOWMOVE,self,0,0,rect.origin.x,rect.origin.y,0 );              
+}
+-(void)zoom{
+       zooming = 1;
+}
+-(NSRect)localRect{
+       NSRect rect,vis;
+       int style;
+
+       rect=[self frame];
+       style=gadget->style;
+       if (style&WINDOW_CLIENTCOORDS){
+               rect=[self contentRectForFrameRect:rect];
+               if (style&WINDOW_STATUS) {
+                       rect.size.height-=STATUSBARHEIGHT;              
+                       rect.origin.y+=STATUSBARHEIGHT;         
+               }
+       }
+       vis=[[NSScreen deepestScreen] visibleFrame];
+       rect.origin.x-=vis.origin.x;
+       rect.origin.y=vis.size.height-(rect.origin.y-vis.origin.y)-rect.size.height;    
+       return rect;
+}
+-(BOOL)canBecomeKeyWindow{
+       return ([self isEnabled]);
+}
+-(BOOL)canBecomeMainWindow{
+       return ([self isEnabled] && [self isVisible] && ([self parentWindow]==nil));
+}
+-(BOOL)becomeFirstResponder{
+       return ([self isEnabled] && [self isVisible]);
+}
+-(void)setEnabled:(BOOL)e{
+       enabled=e;
+       if (enabled) [self makeKeyWindow];
+}
+-(BOOL)isEnabled{
+       return (enabled)?YES:NO;
+}
+-(void)dealloc{
+       int i;
+       id sview;
+       if (gadget->style&WINDOW_STATUS) {
+               for (i = 0; i < 3; i++) {
+                       if (label[i]) {
+                               [label[i] removeFromSuperview];
+                               [label[i] release];
+                       }
+               }
+               
+               sview = [view superview];
+               [view removeFromSuperview];
+               [view release];
+
+               [sview removeFromSuperview];
+               [sview release];
+       } else {
+               [view removeFromSuperview];
+               [view release];
+       }
+
+       [super dealloc];
+}
+@end
+
+// ToolView
+
+@implementation ToolView
+-(id)textFirstResponder{
+       id r=[self firstResponder];
+       //if ([r isKindOfClass:[PanelView class]]) return r;
+       if ([r isKindOfClass:[NSTextView class]]){
+               id d=[r delegate];
+               if( [d isKindOfClass:[NSTextField class]] ) return d;
+       }
+       return r;
+}
+-(id)initWithContentRect:(NSRect)rect styleMask:(unsigned int)mask backing:(NSBackingStoreType)backing defer:(BOOL)flag withGadget:(nsgadget*)_gadget{
+//withStatus:(BOOL)status{
+       id              client;
+       int             i;
+       NSText  *l;
+       NSBox   *box;
+       dragging = nil;
+       self=[super initWithContentRect:rect styleMask:mask backing:backing defer:flag];
+       gadget=_gadget;
+       view=[[FlippedView alloc] init];
+       enabled=true;
+       [self setContentView:view];
+       [self setAcceptsMouseMovedEvents:YES];
+       [self disableCursorRects];      //Fixes NSSetPointer not sticking.
+       if (gadget->style&WINDOW_STATUS){                       //status){      //mask&NSTexturedBackgroundWindowMask)
+               rect.origin.x=rect.origin.y=0;
+               rect.size.height-=STATUSBARHEIGHT;
+               client=[[FlippedView alloc] initWithFrame:rect];
+               [client setAutoresizingMask:(NSViewWidthSizable|NSViewHeightSizable)];  
+               [view addSubview:client];
+// label for window status
+               rect.origin.y=rect.size.height+3;
+               rect.size.height=STATUSBARHEIGHT-4;             
+               rect.size.width-=[NSScroller scrollerWidth];
+               for (i=0;i<3;i++){
+                       l=[[NSText alloc] initWithFrame:rect];
+                       [l setDrawsBackground:NO];
+                       [l setEditable:NO];
+                       [l setSelectable:NO];
+                       [l setAutoresizingMask:NSViewWidthSizable|NSViewMinYMargin];
+                       switch (i){
+                               case 0:[l setAlignment:NSLeftTextAlignment];break;
+                               case 1:[l setAlignment:NSCenterTextAlignment];break;
+                               case 2:[l setAlignment:NSRightTextAlignment];break;
+                       }
+                       if (view) [view addSubview:l];
+                       label[i]=l;
+               }
+               
+               rect.origin.y-=3;
+               rect.size.height=2;
+               rect.size.width+=[NSScroller scrollerWidth];
+               
+               box=[[NSBox alloc] initWithFrame:rect];
+               [box setBoxType:NSBoxSeparator];
+               [box setTitlePosition:NSNoTitle];
+               [box setAutoresizingMask:NSViewWidthSizable|NSViewMinYMargin];
+               if (view) [view addSubview:box];
+               
+// set clientview to inner view
+               view=client;            
+       }
+       if ([self respondsToSelector: @selector(setShowsToolbarButton:)]) [self setShowsToolbarButton: NO];
+       return self;
+}
+-(id)clientView{
+       return view;
+}
+-(void)setStatus:(NSString*)text align:(int)pos{
+       if (label[pos]) [label[pos] setString:text];
+}
+-(void)sendEvent:(NSEvent*)event{
+       
+       static int lastHotKey;
+       int key;
+       id source;
+       
+       // Handling of Generic Key/Mouse Events
+       
+       switch( [event type] ){
+       case NSMouseEntered:
+               [self disableCursorRects];
+       case NSLeftMouseDown:
+       case NSRightMouseDown:
+       case NSOtherMouseDown:
+       {
+               if( [event type] != NSMouseEntered ){
+                       dragging = [[self contentView] hitTest:[event locationInWindow]];
+                       [self makeFirstResponder:dragging];
+               }
+       }
+       case NSMouseMoved:
+       case NSMouseExited:
+       case NSScrollWheel:
+       {
+               NSView *hitView = [[self contentView] hitTest:[event locationInWindow]];
+               if (hitView) EmitMouseEvent( event, hitView );
+               if(![self isEnabled]) return;
+               break;
+       }
+       case NSLeftMouseUp:
+       case NSRightMouseUp:
+       case NSOtherMouseUp:
+       {
+               //fire event for the dragged view
+               if (dragging) {
+                       EmitMouseEvent( event, dragging );
+                       dragging = nil;
+               } else {
+                       //fire the event for the recieving view (if it exists)
+                       NSView *hitView = [[self contentView] hitTest:[event locationInWindow]];
+                       if (hitView) EmitMouseEvent( event, hitView );
+               }
+               
+               if(![self isEnabled]) return;
+               break;
+       }
+       case NSLeftMouseDragged:
+       case NSRightMouseDragged:
+       case NSOtherMouseDragged:
+       {
+               if( dragging == nil ) dragging = [[self contentView] hitTest:[event locationInWindow]];
+               if( dragging ) EmitMouseEvent( event, dragging );
+               if(![self isEnabled]) return;
+               break;
+       }
+       case NSKeyDown:
+       case NSKeyUp:
+       case NSFlagsChanged:
+       {
+               NSResponder *handle=(NSResponder*)NSActiveGadget();
+               if( handle && EmitKeyEvent( event, handle )) return;
+               break;
+       }
+       }
+       
+       // End of Generic Key/Mouse Events
+       
+       // Gadget Filterkey Processing
+       
+       switch( [event type] ){
+       case NSKeyDown:
+               if( key=bbSystemTranslateKey( [event keyCode] ) ){
+                       int mods=bbSystemTranslateMods( [event modifierFlags] );
+                       BBObject *event=maxgui_maxgui_HotKeyEvent( key,mods );
+                       if( event!=&bbNullObject ){
+                               lastHotKey=key;
+                               brl_event_EmitEvent( event );
+                               return;
+                       }
+               }
+               source=[self textFirstResponder];
+               if( source && !filterKeyDownEvent( event,source ) ) return;             
+               if(![self isEnabled]) return;
+               break;
+       case NSKeyUp:
+               key=bbSystemTranslateKey([event keyCode]);
+               if( lastHotKey && (key==lastHotKey ) ){
+                       lastHotKey=0;
+                       return;
+               }
+               if(![self isEnabled]) return;
+               break;
+       }
+       lastHotKey=0;
+       
+       // End of FilterKey Processing
+       
+       [super sendEvent:event];
+}
+- (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender{
+//     printf("windowview got dragenter\n");fflush(stdout);
+       return YES;
+}
+- (BOOL)performDragOperation:(id <NSDraggingInfo>)sender{
+       NSPasteboard *pboard = [sender draggingPasteboard];
+       if ( [[pboard types] containsObject:NSFilenamesPboardType] ) {
+               NSArray *files = [pboard propertyListForType:NSFilenamesPboardType];
+               int numberOfFiles = [files count];
+               // Perform operation using the list of files
+               // printf("windowview got drag\n");fflush(stdout);
+               int i;
+               for (i=0;i<numberOfFiles;i++)
+               {
+                       BBString *name=bbStringFromNSString([files objectAtIndex:i]);
+                       maxgui_cocoamaxgui_PostCocoaGuiEvent( BBEVENT_WINDOWACCEPT,self,0,0,0,0,(BBObject*)name );
+               }
+               
+       }
+       return YES;
+}
+-(void)didResize{
+       if (zooming) {
+               zooming = 0;
+               [self didMove];
+       }
+       NSRect rect=[self localRect];
+       PostGuiEvent( BBEVENT_WINDOWSIZE,self,0,0,rect.size.width,rect.size.height,0 );
+}
+-(void)didMove{
+       NSRect rect=[self localRect];
+       PostGuiEvent( BBEVENT_WINDOWMOVE,self,0,0,rect.origin.x,rect.origin.y,0 );              
+}
+-(void)zoom{
+       zooming = 1;
+}
+-(NSRect)localRect{
+       NSRect rect,vis;
+       int style;
+
+       rect=[self frame];
+       style=gadget->style;
+       if (style&WINDOW_CLIENTCOORDS){
+               rect=[self contentRectForFrameRect:rect];
+               if (style&WINDOW_STATUS) {
+                       rect.size.height-=STATUSBARHEIGHT;              
+                       rect.origin.y+=STATUSBARHEIGHT;         
+               }
+       }
+       vis=[[NSScreen deepestScreen] visibleFrame];
+       rect.origin.x=rect.origin.x-vis.origin.x;
+       rect.origin.y=vis.size.height-(rect.origin.y-vis.origin.y)-rect.size.height;    
+       return rect;
+}
+-(BOOL)canBecomeKeyWindow{
+       return ([self isEnabled]);
+}
+-(BOOL)canBecomeMainWindow{
+       return ([self isEnabled] && [self isVisible] && ([self parentWindow]==nil));
+}
+-(BOOL)becomeFirstResponder{
+       return ([self isEnabled] && [self isVisible]);
+}
+-(void)setEnabled:(BOOL)e{
+       enabled=e;
+       if (enabled) [self makeKeyWindow];
+}
+-(BOOL)isEnabled{
+       return (enabled)?YES:NO;
+}
+-(void)dealloc{
+       int i;
+       id sview;
+       if (gadget->style&WINDOW_STATUS) {
+               for (i = 0; i < 3; i++) {
+                       if (label[i]) {
+                               [label[i] removeFromSuperview];
+                               [label[i] release];
+                       }
+               }
+               
+               sview = [view superview];
+               [view removeFromSuperview];
+               [view release];
+
+               [sview removeFromSuperview];
+               [sview release];
+       } else {
+               [view removeFromSuperview];
+               [view release];
+       }
+
+       [super dealloc];
+}
+@end
+
+// global app stuff
+
+void NSBegin(){
+       GlobalApp=[[CocoaApp alloc] init];
+       HaltMouseEvents=0;
+}
+
+void NSEnd(){
+       [GlobalApp release];
+}
+
+int NSActiveGadget(){
+       NSWindow        *window;
+       NSResponder *responder;
+       window=[NSApp keyWindow];
+       if (!window) return 0;
+       responder=[window firstResponder];
+       if (!responder) return (int)window;
+       if ([responder isKindOfClass:[NSTextView class]] && 
+               [window fieldEditor:NO forObject:nil] != nil ) { 
+                       NSTextView *view=(NSTextView*)responder;
+                       return (int)[view delegate];
+               }
+       return (int)responder;
+}
+
+void NSInitGadget(nsgadget *gadget){
+       NSRect                          rect,vis;
+       NSString                        *text;
+       NSView                          *view;
+       NSWindow                *window;
+       NSButton                        *button;
+       NSTextField                     *textfield;
+       TextView                        *textarea;
+       NSControl               *combobox;
+       Toolbar                 *toolbar;
+       TabView                         *tabber;
+       TreeView                        *treeview;
+       HTMLView                        *htmlview;
+       PanelView                       *panel;
+       PanelViewContent                *pnlcontent;
+       CanvasView                      *canvas;
+       ListView                                *listbox;
+       NSText                          *label;
+       NSBox                           *box;
+       NSSlider                                *slider;
+       NSScroller                      *scroller;
+       NSStepper                               *stepper;
+       NSProgressIndicator     *progbar;
+       NSMenu                          *menu;
+       NSMenuItem                      *menuitem;
+       NodeItem                        *node,*parent;
+       nsgadget                                *group;
+       int                                     style,flags;
+       NSImage                 *image;
+               
+       rect=NSMakeRect(gadget->x,gadget->y,gadget->w,gadget->h);
+       text=NSStringFromBBString(gadget->textarg);
+       style=gadget->style;flags=0;
+       group=gadget->group;
+       if (group==(nsgadget*)&bbNullObject) group=0;
+       if (group) view=gadget->group->view;
+       
+       switch (gadget->internalclass){
+       case GADGET_DESKTOP:
+               rect=[[NSScreen deepestScreen] frame];
+               gadget->x=rect.origin.x;
+               gadget->y=rect.origin.y;
+               gadget->w=rect.size.width;
+               gadget->h=rect.size.height;
+               break;
+       case GADGET_WINDOW:
+               vis=[[NSScreen deepestScreen] visibleFrame];
+               rect.origin.x+=vis.origin.x;
+               rect.origin.y=vis.origin.y+vis.size.height-rect.origin.y-rect.size.height;
+               if (style&WINDOW_TITLEBAR) flags|=NSTitledWindowMask|NSClosableWindowMask;
+               if (style&WINDOW_RESIZABLE){
+                       flags|=NSResizableWindowMask;
+                       if (!(group && (group->internalclass==GADGET_WINDOW))) flags |=NSMiniaturizableWindowMask;
+               }
+               if (style&WINDOW_TOOL) flags|=NSUtilityWindowMask;
+               [NSApp activateIgnoringOtherApps:YES];
+               if (!(style&WINDOW_CLIENTCOORDS)){
+                       rect=[NSWindow contentRectForFrameRect:rect styleMask:flags];
+               }else{
+                       if (style&WINDOW_STATUS) {
+                               rect.origin.y-=STATUSBARHEIGHT;         
+                               rect.size.height+=STATUSBARHEIGHT;              
+                       }
+               }
+               if (!(style&WINDOW_TOOL)) {
+                       window=[[WindowView alloc] initWithContentRect:rect styleMask:flags backing:NSBackingStoreBuffered defer:YES withGadget:gadget];
+               } else {
+                       window=[[ToolView alloc] initWithContentRect:rect styleMask:flags backing:NSBackingStoreBuffered defer:YES withGadget:gadget];
+               }
+               [window setOpaque:NO];
+               [window setAlphaValue:.999f];   
+               
+               if (style&WINDOW_HIDDEN) [window orderOut:window]; else [window makeKeyAndOrderFront:NSApp];
+               
+               if (group && (group->internalclass==GADGET_WINDOW)){
+                       NSWindow        *parent;
+                       parent=(NSWindow*)group->handle;
+                       if(!(style&WINDOW_HIDDEN)) [parent addChildWindow:window ordered:NSWindowAbove];
+                       [window setParentWindow:parent];
+               }
+               
+               if (style&WINDOW_ACCEPTFILES)
+                       [window registerForDraggedTypes:[NSArray arrayWithObject:NSFilenamesPboardType]]; 
+               
+               [window setTitle:text]; 
+               [window setDelegate:GlobalApp];
+               gadget->handle=window;
+               gadget->view=[window clientView];
+               break;
+               
+       case GADGET_BUTTON:
+               button=[[NSButton alloc] initWithFrame:rect];
+               [button setTitle:text];
+               
+               [button setBezelStyle:NSRoundedBezelStyle];
+               
+               switch (style&7){
+                       case 0:
+                               // Push Button Size Hack
+                               if (gadget->h > 30) {
+                                       [button setBezelStyle:NSRegularSquareBezelStyle];
+                               } else {
+                                       if (gadget->h < 24) [button setBezelStyle:NSShadowlessSquareBezelStyle];
+                                       else [button setBezelStyle:NSRoundedBezelStyle];
+                               }
+                               break;
+                       case BUTTON_CHECKBOX:
+                               if (style&BUTTON_PUSH){
+                                       [button setBezelStyle:NSShadowlessSquareBezelStyle];
+                                       [button setButtonType:NSPushOnPushOffButton];
+                               } else {
+                                       [button setButtonType:NSSwitchButton];
+                               }
+                               break;
+                       case BUTTON_RADIO:
+                               if (style&BUTTON_PUSH){
+                                       [button setBezelStyle:NSShadowlessSquareBezelStyle];
+                                       [button setButtonType:NSPushOnPushOffButton];
+                               } else {
+                                       [button setButtonType:NSRadioButton];
+                               }
+                               break;
+                       case BUTTON_OK:
+                               [button setKeyEquivalent:@"\r"];
+                               break;
+                       case BUTTON_CANCEL:
+                               [button setKeyEquivalent:@"\x1b"];
+                               break;
+               }
+               [button setTarget:GlobalApp];
+               [button setAction:@selector(buttonPush:)];
+               if (view) [view addSubview:button];             
+               gadget->handle=button;
+               gadget->view=button;
+               break;
+       case GADGET_PANEL:
+               panel=[[PanelView alloc] initWithFrame:rect];
+               [panel setContentViewMargins:NSMakeSize(0.0,0.0)];
+               pnlcontent=[[PanelViewContent alloc] initWithFrame:[[panel contentView] frame]];
+               [pnlcontent setAutoresizesSubviews:NO];
+               [panel setContentView:pnlcontent];
+               [panel setGadget:gadget];
+               [panel setStyle:style];
+               [panel setEnabled:true];
+               [panel setTitle:text];
+               [pnlcontent setAlpha:1.0];
+               if (view) [view addSubview:panel];
+               gadget->view=pnlcontent;
+               gadget->handle=panel;
+               break;
+       case GADGET_CANVAS:
+               canvas=[[CanvasView alloc] initWithFrame:rect];
+               [canvas setAutoresizesSubviews:NO];
+               [canvas setGadget:gadget];
+               if (view) [view addSubview:canvas];
+               [canvas setStyle:style|PANEL_ACTIVE];
+               [canvas setEnabled:true];
+               gadget->view=[canvas contentView];
+               gadget->handle=canvas;
+               break;  
+       case GADGET_TEXTFIELD:
+               if (style==TEXTFIELD_PASSWORD){
+                       textfield=[[NSSecureTextField alloc] initWithFrame:rect];
+               }else{
+                       textfield=[[NSTextField alloc] initWithFrame:rect];
+               }
+               [textfield setDelegate:GlobalApp];
+               [textfield setEditable:YES];
+               [[textfield cell] setWraps:NO];
+               [[textfield cell] setScrollable:YES];
+               if (view) [view addSubview:textfield];          
+               gadget->handle=textfield;
+               gadget->view=textfield;
+               break;
+       case GADGET_TEXTAREA://http://developer.apple.com/documentation/Cocoa/Conceptual/TextUILayer/Tasks/TextInScrollView.html
+               textarea=[[TextView alloc] initWithFrame:rect];
+               if (style&TEXTAREA_READONLY) [textarea setEditable:NO];
+               if (style&TEXTAREA_WORDWRAP) [textarea setWordWrap:YES];
+               if (view) [view addSubview:[textarea getScroll]];
+               gadget->handle=textarea;
+               gadget->view=[textarea getScroll];// simon was here textarea;
+               break;          
+       case GADGET_COMBOBOX:
+               if (rect.size.height > 26) rect.size.height = 26;
+               combobox=[[NSComboBox alloc] initWithFrame:rect];
+               [combobox setUsesDataSource:NO];
+               [combobox setCompletes:YES];
+               [combobox setDelegate:GlobalApp];               
+               [combobox setEditable:(style&COMBOBOX_EDITABLE)?YES:NO];                        
+               [combobox setSelectable:YES];                   
+               if (view) [view addSubview:combobox];           
+               gadget->handle=combobox;
+               gadget->view=combobox;
+               break;
+       case GADGET_LISTBOX:
+               listbox=[[ListView alloc] initWithFrame:rect];
+               if (view) [view addSubview:listbox];            
+               gadget->handle=listbox;
+               gadget->view=listbox;
+               break;
+       case GADGET_TOOLBAR:
+               toolbar=[[Toolbar alloc] initWithIdentifier:text];
+               [toolbar setSizeMode:NSToolbarSizeModeSmall];
+               [toolbar setDisplayMode:NSToolbarDisplayModeIconOnly];
+               [toolbar setDelegate:GlobalApp];
+               window=(WindowView*)group->handle;
+               [window setToolbar:toolbar];
+               gadget->handle=toolbar;
+               gadget->view=[window clientView];
+               break;
+       case GADGET_TABBER:
+               tabber=[[TabView alloc] initWithFrame:rect];
+               [tabber setAutoresizesSubviews:NO];
+               if (view) [view addSubview:tabber];             //[tabber hostView]];           
+               gadget->handle=tabber;
+               gadget->view=[tabber clientView];
+               break;
+       case GADGET_TREEVIEW:
+               treeview=[[TreeView alloc] initWithFrame:rect]; //NSOutlineView
+               if (view) [view addSubview:treeview];           
+               gadget->handle=treeview;
+               gadget->view=treeview;
+               break;
+       case GADGET_HTMLVIEW:
+               htmlview=[[HTMLView alloc] initWithFrame:rect];
+               if (view) [view addSubview:htmlview];
+               [htmlview setStyle: style];
+               gadget->handle=htmlview;
+               gadget->view=htmlview;
+               break;
+    case GADGET_LABEL: /* BaH */
+               switch (style&3) {
+               case LABEL_SEPARATOR:
+                       
+                       box=[[NSBox alloc] initWithFrame:rect];
+                       
+                       [box setTitle:text];
+                       [box setBoxType:NSBoxSeparator];
+                       [box setTitlePosition:NSNoTitle];
+                       
+                       [box setContentView:[[FlippedView alloc] init]];
+                       
+                       if (view) [view addSubview:box];
+                       gadget->handle=box;
+                       gadget->view=[box contentView];
+                       
+                       break;
+                       
+               default:
+                       
+                       textfield = [[NSTextField alloc] initWithFrame:rect];
+                       
+                       [textfield setEditable:NO];
+                       [textfield setDrawsBackground:NO];
+                       
+                       if ((style&3)==LABEL_SUNKENFRAME) {
+                               [textfield setBezeled:YES];
+                               [textfield setBezelStyle:NSTextFieldSquareBezel];
+                       } else {
+                               [textfield setBezeled:NO];
+                               if ((style&3)==LABEL_FRAME)
+                                       [textfield setBordered:YES];
+                               else
+                                       [textfield setBordered:NO];
+                       }
+                       
+                       [[textfield cell] setWraps:YES];
+                       [[textfield cell] setScrollable:NO];
+                       [textfield setStringValue:text];
+                       
+                       switch (style&24){
+                               case LABEL_LEFT:[textfield setAlignment:NSLeftTextAlignment];break;
+                               case LABEL_RIGHT:[textfield setAlignment:NSRightTextAlignment];break;
+                               case LABEL_CENTER:[textfield setAlignment:NSCenterTextAlignment];break;
+                       }               
+                       
+                       if (view) [view addSubview: textfield];
+                       gadget->handle=textfield;
+                       gadget->view=textfield;
+                       
+                       break;
+               }
+               break;                  
+       case GADGET_SLIDER:
+               switch (style&12){
+               case SLIDER_SCROLLBAR:
+                       if (rect.size.width>rect.size.height)           {
+                               rect.size.height=[NSScroller scrollerWidth];
+                       }
+                       else{
+                               rect.size.width=[NSScroller scrollerWidth];
+                       }
+                       scroller=[[NSScroller alloc] initWithFrame:rect];
+                       [scroller setEnabled:YES];
+                       [scroller setArrowsPosition:NSScrollerArrowsDefaultSetting];
+                       [scroller setAction:@selector(scrollerSelect:)];
+                       if (view) [view addSubview:scroller];           
+                       gadget->handle=scroller;
+                       gadget->view=scroller;
+                       break;
+               case SLIDER_TRACKBAR:
+                       slider=[[NSSlider alloc] initWithFrame:rect];
+                       [slider setEnabled:YES];
+                       [slider setAction:@selector(sliderSelect:)];
+                       if (view) [view addSubview:slider];
+                       gadget->handle=slider;
+                       gadget->view=slider;
+                       break;
+               case SLIDER_STEPPER:
+                       stepper=[[NSStepper alloc] initWithFrame:rect];
+                       [stepper setEnabled:YES];
+                       [stepper setAction:@selector(sliderSelect:)];
+                       [stepper setValueWraps:NO];
+                       if (view) [view addSubview:stepper];
+                       gadget->handle=stepper;
+                       gadget->view=stepper;
+                       break;
+               }
+               break;
+       case GADGET_PROGBAR:
+               progbar=[[NSProgressIndicator alloc] initWithFrame:rect];
+               [progbar setStyle:NSProgressIndicatorBarStyle];         
+               [progbar setIndeterminate:NO];
+               [progbar setMaxValue:1.0];
+               if (view) [view addSubview:progbar];            
+               gadget->handle=progbar;
+               gadget->view=progbar;
+               break;
+       case GADGET_MENUITEM:
+               // Allows a popup-menu to be created with no text without crashing.
+               if ([text length] || (group->internalclass == GADGET_DESKTOP)) {
+                       menuitem=[[NSMenuItem alloc] initWithTitle:text action:@selector(menuSelect:) keyEquivalent:@""];
+                       [menuitem setTag:style];
+                       [GlobalApp addMenuItem:menuitem];
+               }
+               else{
+                       menuitem=(NSMenuItem*)[NSMenuItem separatorItem];
+               }
+               if (group){
+                       switch (group->internalclass){
+                               case GADGET_WINDOW:             
+                                       menu=[[NSMenu alloc] initWithTitle:text];
+                                       [menu setAutoenablesItems:NO];
+                                       [menu setSubmenu:menu forItem:menuitem];
+                                       [menu release];
+                                       menu=[NSApp mainMenu];
+                                       [menu addItem:menuitem];
+                                       if ([text length]){
+                                               [menuitem release];
+                                       }
+                                       break;
+                               case GADGET_MENUITEM:
+                                       menu=(NSMenu*)[group->handle submenu];
+                                       if (!menu){
+                                               menu=(NSMenu*)[[NSMenu alloc] initWithTitle:text];
+                                               [menu setAutoenablesItems:NO];
+                                               [group->handle setSubmenu:menu];
+                                               [menu addItem:menuitem];
+                                               [menu release];
+                                       } else {
+                                               [menu addItem:menuitem];
+                                       }
+                                       if ([text length]){
+                                               [menuitem release];
+                                       }
+                                       break;
+                       }
+               }
+               gadget->handle=menuitem;
+               break;
+       case GADGET_NODE:
+               if (!group) break;
+               parent=0;
+               switch (group->internalclass){
+                       case GADGET_TREEVIEW:
+                               parent=[((TreeView*)group->handle) rootNode];
+                               break;
+                       case GADGET_NODE:
+                               parent=(NodeItem*)group->handle;
+                               break;
+               }
+               if (!parent) break;
+               node=[[NodeItem alloc] initWithTitle:text];
+               int index=style;
+               if (index==-1) index=[parent count];
+               if (index>[parent count]) index=[parent count];
+               [node attach:parent atIndex:index];
+               gadget->handle=node;
+               break;
+       }
+}
+
+@class color_delegate;
+@interface color_delegate:NSObject{}
+@end
+@implementation color_delegate
+- (void)windowWillClose:(NSNotification *)aNotification{[NSApp stopModal];}
+@end
+
+int NSColorRequester(int r,int g,int b){
+       NSColorPanel    *panel;
+       NSColor                 *color;
+       color_delegate  *dele;
+       dele=[[color_delegate alloc] init];
+       color=[NSColor colorWithCalibratedRed:r/255.0L green:g/255.0L blue:b/255.0L alpha:1.0];
+       panel=[NSColorPanel sharedColorPanel];
+       [panel setColor:color];
+       [panel setDelegate:dele];
+       [NSApp runModalForWindow:panel];
+       color=[panel color];
+       if (color){
+               color=[color colorUsingColorSpaceName:NSCalibratedRGBColorSpace];
+               r=(int)((255*[color redComponent])+0.5);
+               g=(int)((255*[color greenComponent])+0.5);
+               b=(int)((255*[color blueComponent])+0.5);
+       }
+       return 0xff000000|(r<<16)|(g<<8)|b;
+}
+
+@class font_delegate;
+@interface font_delegate:NSObject{
+       NSFont          *_font;
+}
+-(id)initWithFont:(NSFont*)font;
+-(void)changeFont:(id)sender;
+-(id)font;
+-(void)windowWillClose:(NSNotification *)aNotification;
+-(unsigned int)validModesForFontPanel:(NSFontPanel *)fontPanel;
+@end
+@implementation font_delegate
+-(id)initWithFont:(NSFont*)font{
+       _font=font;
+       return self;
+}
+-(id)font{
+       return _font;
+}
+-(void)changeFont:(id)sender{
+       _font=[sender convertFont:_font];
+       return; 
+}
+- (void)windowWillClose:(NSNotification *)aNotification{
+       [NSApp stopModal];
+}
+-(unsigned int)validModesForFontPanel:(NSFontPanel *)fontPanel{
+       return NSFontPanelFaceModeMask|NSFontPanelSizeModeMask|NSFontPanelCollectionModeMask;//|NSFontPanelUnderlineEffectModeMask;
+}
+@end
+
+int NSGetSysColor( int colorindex, int* red, int* green, int* blue ){
+       
+       float r, g, b;
+       NSColor* c;
+       NSWindow* w;
+       
+       switch(colorindex){
+               case GUICOLOR_WINDOWBG:
+                       w = [[NSWindow alloc] initWithContentRect:NSZeroRect styleMask:NSTitledWindowMask backing:NSBackingStoreBuffered defer:YES];
+                       c = [w backgroundColor];
+                       [w release];
+                       break;
+               case GUICOLOR_GADGETBG:
+                       c = [NSColor controlBackgroundColor];
+                       break;
+               case GUICOLOR_GADGETFG:
+                       c = [NSColor controlTextColor];
+                       break;
+               case GUICOLOR_SELECTIONBG:
+                       c = [NSColor selectedTextBackgroundColor];
+                       break;
+               default:
+                       return 0;
+                       break;
+       }
+       
+       [[c colorUsingColorSpaceName:NSCalibratedRGBColorSpace] getRed:&r green:&g blue:&b alpha:NULL];
+       *red = (int)(255 * r);
+       *green = (int)(255 * g);
+       *blue = (int)(255 * b);
+       
+       return 1;
+}
+
+NSFont *NSRequestFont(NSFont *font){
+       NSFontPanel             *panel;
+       font_delegate           *dele;
+       if (!font) font=[NSFont userFontOfSize:0];
+       dele=[[font_delegate alloc] initWithFont:font];
+       panel=[NSFontPanel sharedFontPanel];
+       if (font) [panel setPanelFont:font isMultiple:NO];
+       [panel setEnabled:YES];
+       [panel setDelegate:dele];
+       [NSApp runModalForWindow:panel];
+       return [dele font];
+}
+
+NSFont *NSLoadFont(BBString *name,double size,int flags){
+       NSString                        *text;
+       NSFont                          *font;
+       NSFontManager           *manager;
+
+       text=NSStringFromBBString(name);
+       font=[NSFont fontWithName:text size:size];
+       if (!font) font=[NSFont systemFontOfSize:size];
+       if (flags){
+               manager=[NSFontManager sharedFontManager];
+               if (flags&FONT_BOLD) font=[manager convertFont:font toHaveTrait:NSBoldFontMask];
+               if (flags&FONT_ITALIC) font=[manager convertFont:font toHaveTrait:NSItalicFontMask];
+       }
+       [font retain];
+       return font;
+}
+
+NSFont *NSGetDefaultFont(){
+       return [NSFont systemFontOfSize:[NSFont systemFontSize]];
+}
+
+BBString *NSFontName(NSFont *font){
+       return bbStringFromNSString([font displayName]);        
+}
+
+int NSFontStyle(NSFont *font){
+       int     intBBStyleFlags;
+       int     intCocoaFontTraits;
+       NSFontManager *manager;
+       
+       manager = [NSFontManager sharedFontManager];
+       intCocoaFontTraits = [manager traitsOfFont: font];
+       
+       intBBStyleFlags = 0;
+       if (intCocoaFontTraits & NSBoldFontMask) intBBStyleFlags|=FONT_BOLD;
+       if (intCocoaFontTraits & NSItalicFontMask) intBBStyleFlags|=FONT_ITALIC;
+       
+       return intBBStyleFlags;
+}
+
+double NSFontSize(NSFont *font){
+       return (double)[font pointSize];
+}
+
+void* NSSuperview(NSView* handle){
+       if(handle) return [handle superview];
+       return 0;
+}
+
+// generic gadget commands
+
+void NSFreeGadget(nsgadget *gadget){
+       nsgadget *group;
+       NSWindow *parent;
+       TextView *textview;
+       FlippedView * flipped;
+       if (gadget->textcolor){
+               [gadget->textcolor release];
+               gadget->textcolor = 0;
+       }
+       if (gadget->handle){
+               switch (gadget->internalclass){
+               case GADGET_WINDOW:
+                       if ([gadget->handle parentWindow]!=nil){                        
+                               [[gadget->handle parentWindow] removeChildWindow:(NSWindow*)gadget->handle];
+                       }                       
+                       [gadget->handle close];
+                       break;
+               case GADGET_NODE:
+                       [gadget->handle remove];
+                       [gadget->handle autorelease];
+                       break;
+               case GADGET_MENUITEM:
+                       [GlobalApp removeMenuItem:gadget->handle];
+                       [[gadget->handle menu] removeItem:gadget->handle];
+                       break;
+               case GADGET_TEXTAREA:
+                       textview=(TextView*)gadget->handle;                                     
+                       [gadget->view removeFromSuperview];
+                       [textview free];
+                       [textview autorelease];
+                       break;
+               case GADGET_LABEL:
+                       switch (gadget->style&3) {
+                       case LABEL_SEPARATOR:
+                               flipped=(FlippedView*)gadget->view;
+                               [flipped removeFromSuperview];
+                               [gadget->handle removeFromSuperview];
+                               [flipped release];
+                               break;
+                       default:
+                               [gadget->view removeFromSuperview];
+                               break;
+                       }
+                       [gadget->handle autorelease];
+                       break;
+               case GADGET_TABBER:
+                       flipped=(FlippedView*)gadget->view;
+                       [flipped removeFromSuperview];
+                       [gadget->handle removeFromSuperview];
+                       [flipped release];
+                       //Cocoa throws an exception if items exist when handle is autoreleased.
+                       NSClearItems(gadget);
+                       [gadget->handle autorelease];
+                       break;
+               case GADGET_PANEL:
+                       [gadget->handle setColor:nil];
+                       [gadget->handle removeFromSuperview];
+                       [gadget->handle autorelease];
+                       break;
+               default:
+                       [[gadget->view superview] setNeedsDisplayInRect:[gadget->view frame]];
+                       [gadget->view removeFromSuperview];
+                       [gadget->handle autorelease];
+                       break;
+               }       
+       }
+       gadget->handle=0;
+}
+
+void NSEnable(nsgadget *gadget,int state){
+       switch (gadget->internalclass){
+       case GADGET_WINDOW:
+       case GADGET_SLIDER:
+       case GADGET_TEXTFIELD:
+       case GADGET_MENUITEM:
+       case GADGET_BUTTON:
+       case GADGET_LISTBOX:
+       case GADGET_COMBOBOX:
+       case GADGET_TREEVIEW:
+       case GADGET_PANEL:
+       case GADGET_CANVAS:
+               [gadget->handle setEnabled:state];
+               break;
+       case GADGET_TEXTAREA:
+               [gadget->handle setSelectable:state];
+               if (!(gadget->style&TEXTAREA_READONLY)) [gadget->handle setEditable:state];
+               break;
+       }
+}
+
+void NSShow(nsgadget *gadget,int state){
+       switch (gadget->internalclass){
+       case GADGET_WINDOW:
+               if (state==[gadget->handle isVisible]) return;
+               if (state) {
+                       if((gadget->group!=&bbNullObject) && (gadget->group->internalclass==GADGET_WINDOW) &&
+                       ([gadget->handle parentWindow]==nil)) [gadget->group->handle addChildWindow: gadget->handle ordered:NSWindowAbove];
+                       [gadget->handle makeKeyAndOrderFront:NSApp];
+               } else {
+                       if([gadget->handle parentWindow]!=nil) [[gadget->handle parentWindow] removeChildWindow:(NSWindow*)gadget->handle];
+                       [gadget->handle orderOut:NSApp];
+               }
+               break;
+       case GADGET_TOOLBAR:
+               [gadget->handle setVisible:state];
+               break;
+       default:
+               [gadget->handle setHidden:!state];
+       }
+}
+
+void NSCheck(nsgadget *gadget,int state){
+       NSButton                        *button;
+       switch (gadget->internalclass){
+       case GADGET_MENUITEM:
+               [gadget->handle setState:state];
+               break;
+       case GADGET_BUTTON:
+               button=(NSButton *)gadget->handle;
+               if(state==NSMixedState) [button setAllowsMixedState:YES]; else [button setAllowsMixedState:NO];
+               [button setState:state];
+               break; 
+       }
+}
+
+void NSPopupMenu(nsgadget *gadget,nsgadget *menugadget){
+       NSView                  *view;
+       NSWindow                        *window;
+       NSMenuItem              *menuitem;
+       NSEvent                 *event;
+       NSPoint                 loc;
+       
+       window=(NSWindow*)gadget->handle;
+       view=gadget->view;
+       menuitem=(NSMenuItem*)menugadget->handle;
+       event=[NSEvent 
+               mouseEventWithType:NSRightMouseUp 
+               location:[window convertScreenToBase:[NSEvent mouseLocation]]
+               modifierFlags:nil 
+               timestamp:0 
+               windowNumber:[window windowNumber] 
+       context:nil
+               eventNumber:nil
+               clickCount:1 
+               pressure:0];
+       [NSMenu popUpContextMenu:[menuitem submenu] withEvent:event forView:view];              
+//     [event release];
+}
+
+int NSState(nsgadget *gadget){
+       NSWindow                *window;
+       TextView                *textview;
+       NSButton                *button;
+       NSView          *view;
+       Toolbar         *toolbar;
+       HTMLView                *browser;
+       NSMenuItem      *menuItem;
+       int                     state;
+
+       state=0;
+
+       switch (gadget->internalclass){
+       case GADGET_TEXTAREA:
+               textview=(TextView*)gadget->handle;
+               if ([textview isHidden]) state|=STATE_HIDDEN;
+               if ((!(gadget->style&TEXTAREA_READONLY)) && (![textview isEditable])) state|=STATE_DISABLED;
+               break;
+       case GADGET_HTMLVIEW:
+               browser=(HTMLView*)gadget->handle;
+               return [browser loaded];
+       case GADGET_WINDOW:
+               window=(NSWindow*)gadget->handle;
+               if ([window isMiniaturized]) state|=STATE_MINIMIZED;
+               if ([window isZoomed]) state|=STATE_MAXIMIZED;
+               if (![window isVisible]) state|=STATE_HIDDEN;
+               break;
+       case GADGET_MENUITEM:
+               menuItem=(NSMenuItem*)gadget->handle;
+               if ([menuItem state]==NSOnState) state|=STATE_SELECTED;
+               if (![menuItem isEnabled]) state|=STATE_DISABLED;
+               break;
+       case GADGET_BUTTON:
+               button=(NSButton *)gadget->handle;
+               switch (gadget->style&7){
+                       case BUTTON_RADIO: case BUTTON_CHECKBOX:
+                       if ([button state]==NSOnState) state|=STATE_SELECTED;
+                       if ([button state]==NSMixedState) state|=STATE_INDETERMINATE;
+               }
+               if ([button isHidden]) state|=STATE_HIDDEN;
+               if (![button isEnabled]) state|=STATE_DISABLED;
+               break;
+       case GADGET_TOOLBAR:
+               toolbar=(Toolbar*)gadget->handle;
+               if ([toolbar isVisible]==NO) state|=STATE_HIDDEN;
+               break;          
+       case GADGET_PROGBAR:
+               view=(NSView*)gadget->handle;
+               if ([view isHidden]) state|=STATE_HIDDEN;
+               break;
+       default:
+               view=(NSView*)gadget->handle;
+               if ([view isHidden]) state|=STATE_HIDDEN;
+               if (![view isEnabled]) state|=STATE_DISABLED;
+               break;
+       }
+       return state;
+}
+
+void NSSetMinimumSize(nsgadget *gadget,int width,int height){
+       NSWindow        *window;
+       NSRect  rect;
+       int             style;
+       window=(NSWindow*)gadget->handle;
+       rect.origin.x=0;
+       rect.origin.y=0;
+       rect.size.width=width;
+       rect.size.height=height;
+       style=gadget->style;
+       if (!(style&WINDOW_CLIENTCOORDS)){
+               rect=[window contentRectForFrameRect:rect];
+               rect.size.width-=rect.origin.x;
+               rect.size.height-=rect.origin.y;
+       }else{
+               if (style&WINDOW_STATUS) rect.size.height+=STATUSBARHEIGHT;             
+       }
+       [window setContentMinSize:rect.size];
+}
+
+void NSSetMaximumSize(nsgadget *gadget,int width,int height){
+       NSWindow        *window;
+       NSRect  rect;
+       int             style;
+       window=(NSWindow*)gadget->handle;
+       rect.origin.x=0;
+       rect.origin.y=0;
+       rect.size.width=width;
+       rect.size.height=height;
+       style=gadget->style;
+       if (!(style&WINDOW_CLIENTCOORDS)){
+               rect=[window contentRectForFrameRect:rect];
+               rect.size.width-=rect.origin.x;
+               rect.size.height-=rect.origin.y;
+       }else{
+               if (style&WINDOW_STATUS) rect.size.height+=STATUSBARHEIGHT;             
+       }
+       [window setContentMaxSize:rect.size];
+}
+
+
+void NSSetStatus(nsgadget *gadget,BBString *data,int pos){
+       NSString                        *text;
+       WindowView                      *window;
+       ToolView                        *toolview;
+
+       text=NSStringFromBBString(data);
+       if ((gadget->style&WINDOW_TOOL) == 0) {
+               window=(WindowView*)gadget->handle;
+               [window setStatus:text align:pos];
+       } else {
+               toolview =(ToolView*)gadget->handle;
+               [toolview setStatus:text align:pos];
+       }
+}
+
+int NSClientWidth(nsgadget *gadget){
+       NSRect          frame;  
+       if (gadget->internalclass==GADGET_DESKTOP){
+               frame=[[NSScreen deepestScreen] visibleFrame];
+               return frame.size.width;
+       }
+       if (!gadget->view) return gadget->w;
+       frame=[gadget->view frame]; 
+       return frame.size.width;
+}
+
+int NSClientHeight(nsgadget *gadget){
+       NSRect          frame;
+       if (gadget->internalclass==GADGET_DESKTOP){
+               frame=[[NSScreen deepestScreen] visibleFrame];
+               return frame.size.height;
+       }
+       if (!gadget->view) return gadget->h;
+       frame=[gadget->view frame]; 
+       return frame.size.height;
+}
+
+void NSRedraw(nsgadget *gadget){
+       NSView  *view;
+       
+       view=(NSView*)gadget->handle;
+       [view display]; //Can just call the display method
+}
+
+void NSActivate(nsgadget *gadget,int code){
+       NSWindow        *window;
+       NSView          *view;
+       NSRect          frame;
+       NodeItem        *node;
+       TreeView        *treeview;
+       HTMLView        *browser;
+       TextView        *textview;
+       NSTextField *textfield;
+       NSText *text;
+       NSComboBox *combo;
+
+// generic commands
+
+       switch (code){
+       case ACTIVATE_REDRAW:
+               NSRedraw(gadget);
+               return;
+       }
+       
+// gadget specific     
+
+       switch (gadget->internalclass){
+       case GADGET_WINDOW:
+               window=(NSWindow*)gadget->handle;
+               switch (code){
+               case ACTIVATE_FOCUS:
+                       if([window isVisible]) [window makeKeyAndOrderFront:NSApp];             
+                       break;
+               case ACTIVATE_CUT:
+                       break;
+               case ACTIVATE_COPY:
+                       break;
+               case ACTIVATE_PASTE:
+                       break;
+               case ACTIVATE_MINIMIZE:
+                       NSShow(gadget,true);
+                       [window miniaturize:window];
+                       break;
+               case ACTIVATE_MAXIMIZE:
+                       if ([window isMiniaturized]) [window deminiaturize:window];
+                       if ([window isZoomed]==NO) [window performZoom:window];
+                       NSShow(gadget,true);
+                       break;
+               case ACTIVATE_RESTORE:
+                       if ([window isMiniaturized]) [window deminiaturize:window];
+                       if ([window isZoomed]) [window performZoom:window];
+                       NSShow(gadget,true);
+                       break;
+               }
+               break;
+
+       case GADGET_TEXTFIELD:
+               textfield=(NSTextField*)gadget->handle;
+               window=[textfield window];
+               if (window) 
+               switch (code){
+               case ACTIVATE_FOCUS:
+                       [window makeFirstResponder:textfield];
+                       break;
+               case ACTIVATE_CUT:
+                       text=[[textfield window] fieldEditor:YES forObject:textfield];
+                       [text cut:textfield];
+                       break;  
+               case ACTIVATE_COPY:
+                       text=[[textfield window] fieldEditor:YES forObject:textfield];
+                       [text copy:textfield];
+                       break;  
+               case ACTIVATE_PASTE:
+                       text=[[textfield window] fieldEditor:YES forObject:textfield];
+                       [text paste:textfield];
+                       break;
+               }
+               break;
+
+       case GADGET_TEXTAREA:
+               textview=(TextView*)gadget->handle;
+               switch (code){
+               case ACTIVATE_FOCUS:
+                       window=[textview window];
+                       if (window) [window makeFirstResponder:textview];
+                       break;
+               case ACTIVATE_CUT:
+                       [textview cut:textview];
+                       break;  
+               case ACTIVATE_COPY:
+                       [textview copy:textview];
+                       break;  
+               case ACTIVATE_PASTE:
+                       [textview pasteAsPlainText:textview];//paste:textview];
+                       break;          
+               case ACTIVATE_PRINT:
+                       [textview print:textview];
+                       break;
+               }
+               break;
+
+       case GADGET_NODE:
+               node=(NodeItem*)gadget->handle;
+               treeview=[node getOwner];
+               switch (code){  
+               case ACTIVATE_SELECT:
+                       [treeview selectNode:node];                     
+                       break;
+               case ACTIVATE_EXPAND:
+                       [treeview expandNode:node];
+                       break;
+               case ACTIVATE_COLLAPSE:
+                       [treeview collapseNode:node];
+                       break;
+               }
+               break;
+                               
+       case GADGET_COMBOBOX:
+               switch (code){
+               case ACTIVATE_FOCUS:
+                       combo=(NSComboBox*)gadget->handle;
+                       [combo selectText:nil];
+                       break;  
+               }
+               break;
+
+       case GADGET_HTMLVIEW:
+               browser=(HTMLView*)gadget->handle;
+               switch(code){
+               case ACTIVATE_COPY:
+                       [browser copy:browser];
+                       break;  
+               case ACTIVATE_BACK:
+                       [browser goBack:browser];
+                       break;
+               case ACTIVATE_FORWARD:
+                       [browser goForward:browser];
+                       break;
+               case ACTIVATE_PRINT:
+                       view = [[[browser mainFrame] frameView] documentView];
+                       if (view != nil) [view print:view];
+                       break;
+               }
+                                               
+       default:
+               switch (code){
+               case ACTIVATE_FOCUS:
+                       window=[gadget->handle window];
+                       if (window) [window makeFirstResponder:gadget->handle];
+                       break;
+               }
+       }
+}
+
+void NSRethink(nsgadget *gadget){
+       NSView          *view;
+       NSRect          rect,vis;
+       TextView        *textview;
+       TabView         *tabber;
+       NSButton                *button;
+       NSControl       *combobox;
+       int                     shouldhide;
+       
+       view=(NSView*)gadget->handle;
+       rect=NSMakeRect(gadget->x,gadget->y,gadget->w,gadget->h);
+       
+       shouldhide = FALSE;
+       
+       switch(gadget->internalclass){
+       case GADGET_WINDOW:
+               vis=[[NSScreen deepestScreen] visibleFrame];
+               rect.origin.x+=vis.origin.x;
+               rect.origin.y=vis.origin.y+vis.size.height-rect.origin.y-rect.size.height;
+               if ((gadget->style&WINDOW_CLIENTCOORDS)!=0){
+                       if (gadget->style&WINDOW_STATUS) {
+                               rect.origin.y-=STATUSBARHEIGHT;         
+                               rect.size.height+=STATUSBARHEIGHT;              
+                       }
+                       rect = [(NSWindow*)view frameRectForContentRect:rect];
+               }
+               
+               if(![view isVisible]) shouldhide = TRUE;
+               [view setFrame:rect display:YES];
+               if(shouldhide) [view orderOut:view];
+               return;
+       case GADGET_NODE:
+       case GADGET_MENUITEM:
+       case GADGET_TOOLBAR:
+               return;
+       case GADGET_TEXTAREA:
+               textview=(TextView*)view;
+               [textview setScrollFrame:rect];
+               return;
+       case GADGET_COMBOBOX:
+               if (rect.size.height > 26) rect.size.height = 26;
+               break;
+       case GADGET_BUTTON:
+               button=(NSButton*)view;
+               // Push Button Size Hack
+               if ((gadget->style&7)==0){
+                       if (gadget->h > 30) {
+                               [button setBezelStyle:NSRegularSquareBezelStyle];
+                       } else {
+                               if (gadget->h < 24) { 
+                                       [button setBezelStyle:NSShadowlessSquareBezelStyle];
+                               } else {
+                                       [button setBezelStyle:NSRoundedBezelStyle];
+                               }
+                       }       
+               }
+               break;
+       case GADGET_SLIDER:
+               switch (gadget->style&12){
+                       case SLIDER_SCROLLBAR:
+                               if (gadget->style & SLIDER_HORIZONTAL)
+                                       rect.size.height = [NSScroller scrollerWidth];
+                               else
+                                       rect.size.width = [NSScroller scrollerWidth];           
+                               break;
+               }
+       }
+       [[view superview] setNeedsDisplayInRect:[view frame]];
+       [view setFrame:rect];
+       [view setNeedsDisplay:YES];     
+}
+
+void NSRemoveColor(nsgadget *gadget){
+       switch (gadget->internalclass){
+       case GADGET_BUTTON:
+               if ([[gadget->handle cell] respondsToSelector:@selector(setDrawsBackground:)]){
+                       [[gadget->handle cell] setDrawsBackground:false];
+               }
+               break;
+       case GADGET_WINDOW:
+               [gadget->handle setBackgroundColor:nil];
+               [gadget->handle display];
+               break;
+       case GADGET_LABEL:
+               if((gadget->style&3)==LABEL_SEPARATOR) break;
+       case GADGET_COMBOBOX:
+       case GADGET_TEXTFIELD:
+               [gadget->handle setDrawsBackground:false];
+               break;
+       case GADGET_LISTBOX:
+       case GADGET_TREEVIEW:
+       case GADGET_PANEL:
+       case GADGET_TEXTAREA:
+               [gadget->handle setColor:nil];
+               break;  
+       }
+}
+
+void NSSetColor(nsgadget *gadget,int r,int g,int b){
+       NSColor                         *color;
+
+       color=[NSColor colorWithDeviceRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:1.0];
+       
+       switch (gadget->internalclass){
+       case GADGET_BUTTON:
+               if ([[gadget->handle cell] respondsToSelector:@selector(setBackgroundColor:)]) [[gadget->handle cell] setBackgroundColor:color];
+               break;
+       case GADGET_COMBOBOX:
+       case GADGET_WINDOW:
+               [gadget->handle setBackgroundColor:color];
+               [gadget->handle display];
+               break;
+       case GADGET_LABEL:
+               if((gadget->style&3)==LABEL_SEPARATOR) break;
+               [gadget->handle setDrawsBackground:YES];
+       case GADGET_TEXTFIELD:
+               [gadget->handle setBackgroundColor:color];
+               break;
+       case GADGET_LISTBOX:
+       case GADGET_TREEVIEW:
+       case GADGET_PANEL:
+       case GADGET_TEXTAREA:
+               [gadget->handle setColor:color];
+               break;  
+       }
+}
+
+void NSSetAlpha(nsgadget *gadget,float alpha){
+       NSWindow        *window;
+       PanelView       *panel;
+       
+       switch (gadget->internalclass){
+       case GADGET_WINDOW:
+               window=(NSWindow*)gadget->handle;
+               [window setAlphaValue:alpha];
+               break;          
+       case GADGET_PANEL:
+               panel=(PanelView*)gadget->handle;
+               [panel setAlpha:alpha];
+               break;  
+       }
+}
+
+BBString *NSGetUserName(){
+       return bbStringFromNSString(CSCopyUserName(true));
+}
+
+BBString *NSGetComputerName(){
+       return bbStringFromNSString(CSCopyMachineName());
+}
+
+BBString *NSRun(nsgadget *gadget,BBString *text){
+       HTMLView                        *htmlview;
+       NSString                        *script;
+       BBString                        *result;
+
+       result=&bbEmptyString;
+       switch (gadget->internalclass){
+       case GADGET_HTMLVIEW:
+               htmlview=(HTMLView*)gadget->handle;
+               script=NSStringFromBBString(text);
+               script=[htmlview stringByEvaluatingJavaScriptFromString:script];
+               result=bbStringFromNSString(script);
+               break;
+       }
+       return result;
+}
+
+void NSSetText(nsgadget *gadget,BBString *data){
+       NSString                                *text;
+       NSMutableDictionary     *textAttributes;
+       NSMutableParagraphStyle *parastyle;
+       NSAttributedString              *attribtext;
+       NSObject                                *nsobject;
+       
+       attribtext = nil;
+       
+       if(data == nil) data = &bbEmptyString;
+       
+       text = NSStringFromBBString(data);
+       
+       nsobject = (NSObject*)gadget->handle;
+       
+       //printf( "data->length: %d\n", data->length );fflush(stdout);
+       
+       switch (gadget->internalclass){
+       case GADGET_TEXTAREA:
+               [nsobject setText:text];
+               break;
+       case GADGET_HTMLVIEW:
+               [nsobject setAddress:text];
+               break;
+       case GADGET_LABEL: /* BaH */
+               switch (gadget->style&3) {
+               case LABEL_SEPARATOR:
+                       return;
+               default:
+                       [nsobject setStringValue:text];
+                       return;
+               }
+               break;
+       case GADGET_BUTTON:
+               
+               //if ([nsobject respondsToSelector:@selector(setAttributedTitle:)] /*&& [nsobject respondsToSelector:@selector(font)]*/){
+                       
+                       // Create attribute dictionary (autorelease'd)
+                       textAttributes = [NSMutableDictionary dictionary];
+                       
+                       // Font
+                       [textAttributes setObject: [nsobject font] forKey:NSFontAttributeName];
+       
+                       // Paragraph style
+                       parastyle = [[NSMutableParagraphStyle alloc] init];
+                       [parastyle setParagraphStyle:[NSParagraphStyle defaultParagraphStyle]];
+                       
+                       if(gadget->internalclass == GADGET_BUTTON){
+                               if(((gadget->style & BUTTON_PUSH) == BUTTON_PUSH) ||
+                                 (((gadget->style & 7) != BUTTON_RADIO) &&
+                                  ((gadget->style & 7) != BUTTON_CHECKBOX)))
+                                       [parastyle setAlignment:NSCenterTextAlignment];
+                       }
+                       
+                       [textAttributes setObject: parastyle forKey:NSParagraphStyleAttributeName];
+                       [parastyle release];
+                       
+                       // Text color
+                       if(gadget->textcolor) [textAttributes setObject: gadget->textcolor forKey: NSForegroundColorAttributeName];
+                       
+                       // Underline / strikethrough
+                       [textAttributes setObject: [NSNumber numberWithInt:0] forKey: NSUnderlineStyleAttributeName];
+                       [textAttributes setObject: [NSNumber numberWithInt:0] forKey: NSStrikethroughStyleAttributeName];
+                       
+                       if ((gadget->intFontStyle&FONT_UNDERLINE)!=0) [textAttributes setObject: [NSNumber numberWithInt:(NSUnderlineStyleSingle|NSUnderlinePatternSolid)] forKey: NSUnderlineStyleAttributeName];
+                       if ((gadget->intFontStyle&FONT_STRIKETHROUGH)!=0) [textAttributes setObject: [NSNumber numberWithInt:(NSUnderlineStyleSingle|NSUnderlinePatternSolid)] forKey: NSStrikethroughStyleAttributeName];
+                       
+                       // Create attibuted text
+                       attribtext = [[NSAttributedString alloc] initWithString: text attributes: textAttributes];
+                       
+                       [nsobject setAttributedTitle:attribtext];
+                       break;
+               //}
+       case GADGET_MENUITEM:
+               [nsobject setTitle:text];
+               // Required otherwise root window menus aren't updated.
+               [[nsobject submenu] setTitle:text];
+               break;
+       case GADGET_PANEL:
+       case GADGET_NODE:
+       case GADGET_WINDOW:
+               [nsobject setTitle:text];
+               break;
+       case GADGET_COMBOBOX:
+               if(!(gadget->style & COMBOBOX_EDITABLE)) break;
+       case GADGET_TEXTFIELD:
+               [nsobject setStringValue:text];
+               break;
+       }
+}
+
+BBString *NSGetText(nsgadget *gadget){
+       
+       NSObject                *nsobject;
+       BBString                *result;
+
+       result=&bbEmptyString;
+       nsobject=(NSObject*)gadget->handle;
+       
+       switch (gadget->internalclass){
+       case GADGET_TEXTAREA:
+               result=bbStringFromNSString([[nsobject storage] string]);
+               break;
+       case GADGET_TEXTFIELD:
+       case GADGET_COMBOBOX:
+               result=bbStringFromNSString([nsobject stringValue]);
+               break;  
+       case GADGET_HTMLVIEW:
+               result=bbStringFromNSString([nsobject address]);
+               break;
+       case GADGET_NODE:
+               result=bbStringFromNSString([nsobject value]);
+               break;
+       case GADGET_LABEL: /* BaH */
+               switch (gadget->style&3) {
+               case 0:
+               case LABEL_FRAME:
+               case LABEL_SUNKENFRAME:
+                       result=bbStringFromNSString([nsobject stringValue]);
+               }
+               break;
+       case GADGET_PANEL:
+       case GADGET_WINDOW:
+       case GADGET_BUTTON:
+       case GADGET_MENUITEM:
+               result=bbStringFromNSString([nsobject title]);
+               break;
+       }
+       return result;
+}
+
+int NSCharWidth(NSFont *font,int charcode){    
+       NSSize size=[font advancementForGlyph:charcode];
+       return (int)size.width;
+}
+
+void NSSetFont(nsgadget *gadget,NSFont *font){
+       NSView                  *view;
+       
+       view = (NSView*)gadget->handle;
+       
+       switch (gadget->internalclass){
+               case GADGET_LABEL:
+                       if ((gadget->style&3)==LABEL_SEPARATOR) break;
+               case GADGET_BUTTON:
+                       [view setFont:font];
+                       NSSetText(gadget, NSGetText(gadget));           //Apply underline/strikethough formatting as attributed text in NSSetText().
+                       break;
+               case GADGET_LISTBOX:
+               case GADGET_TREEVIEW:
+               case GADGET_COMBOBOX:
+               case GADGET_TEXTAREA:
+               case GADGET_TEXTFIELD:
+               case GADGET_TABBER:
+                       [view setFont:font];
+                       break;
+               
+       }
+}
+
+BBString * NSGetTooltip(nsgadget *gadget){
+
+       BBString                        *result;
+       NSView                  *view;
+       
+       result=&bbEmptyString;
+       view=(NSView*)gadget->handle;
+       
+       if(view) result=bbStringFromNSString([view toolTip]);
+       
+       return result;
+}
+
+int NSSetTooltip(nsgadget *gadget,BBString *data){
+       
+       NSString                        *text;
+       NSView                  *view;
+       
+       view =(NSView*)gadget->handle;
+       text=NSStringFromBBString(data);
+       
+       if(view){
+               [view setToolTip:text];
+               return 1;
+       }
+       
+       return 0;
+}
+
+// gadgetitem commands
+
+void NSClearItems(nsgadget *gadget)
+{
+       ListView                        *listbox;
+       NSControl               *combo;
+       NSTabView                       *tabber;
+       Toolbar                 *toolbar;
+       NSToolbarItem           *item;
+       NSArray                 *items;
+       int                             i,n;
+               
+       switch (gadget->internalclass){
+       case GADGET_LISTBOX:
+               listbox=(ListView*)gadget->handle;
+               [listbox clear];
+               break;
+       case GADGET_COMBOBOX:
+               combo=(NSControl*)gadget->handle;
+               [combo removeAllItems];
+               break;
+       case GADGET_TABBER:
+               tabber=(NSTabView*)gadget->handle;
+               items=[tabber tabViewItems];
+               n=[tabber numberOfTabViewItems];
+               for (i=0;i<n;i++) [tabber removeTabViewItem:[tabber tabViewItemAtIndex:0]];
+               break;
+       case GADGET_TOOLBAR:
+               toolbar=(Toolbar*)gadget->handle;
+               items=[toolbar items];
+               n=[items count];
+               for (i=0;i<n;i++)       [toolbar removeItemAtIndex:0];
+               break;
+       }
+}
+
+void NSAddItem(nsgadget *gadget,int index,BBString *data,BBString *tip,NSImage *image,BBObject *extra){
+       NSString                        *text,*tiptext;
+       NSControl               *combo;
+       NSTabView                       *tabber;
+       TabViewItem             *tabitem;
+       ListView                        *listbox;
+       Toolbar                 *toolbar;
+       NSToolbarItem           *item;
+
+       text=NSStringFromBBString(data);
+       tiptext=NSStringFromBBString(tip);
+       switch (gadget->internalclass){
+       case GADGET_LISTBOX:
+               listbox=(ListView*)gadget->handle;
+               [listbox addItem:text atIndex:index withImage:image withTip:tiptext withExtra:extra];
+               break;
+       case GADGET_COMBOBOX:
+               combo=(NSControl*)gadget->handle;
+               [combo insertItemWithObjectValue:text atIndex:index];
+//             [[combo itemAtIndex:index] setImage:image];
+               break;
+       case GADGET_TABBER:
+               tabber=(NSTabView*)gadget->handle;      
+               tabitem=[[TabViewItem alloc] initWithIdentifier:text];
+               [tabitem setLabel:text];
+               [tabitem setImage:image];
+               [tabber insertTabViewItem:tabitem atIndex:index];       
+               [tabitem release];
+               break;
+       case GADGET_TOOLBAR:    
+               toolbar=(Toolbar*)gadget->handle;
+               if (image==0){                  
+                       int v;
+                       Gestalt( 'sysv',&v );
+                       if( v>=0x1070 ){
+                               [toolbar insertItemWithItemIdentifier:NSToolbarSpaceItemIdentifier atIndex:index];
+                       }else{
+                               [toolbar insertItemWithItemIdentifier:NSToolbarSeparatorItemIdentifier atIndex:index];
+                       }
+               }
+               else{
+                       item=[[NSToolbarItem alloc] initWithItemIdentifier:text];
+                       [item setImage:image];
+//                     [item setLabel:text];
+                       [item setAction:@selector(iconSelect:)];
+                       [item setTarget:GlobalApp];
+                       [item setToolTip:tiptext];
+                       [item setTag:0];
+                       [GlobalApp addToolbarItem:item];
+                       [toolbar addToolbarItem:item];
+                       [toolbar insertItemWithItemIdentifier:text atIndex:index];                                                              
+               }
+               break;
+       }
+}
+
+NSToolbarItem *FindToolbarItem(NSToolbar *toolbar,int index){
+       return (NSToolbarItem*)[[toolbar items] objectAtIndex:index];
+}
+
+void NSSetItem(nsgadget *gadget,int index,BBString *data,BBString *tip,NSImage *image,BBObject *extra){
+       NSString                        *text,*tiptext;
+       NSControl               *combo;
+       NSTabView                       *tabber;
+       TabViewItem             *tabitem;
+       ListView                        *listbox;
+       Toolbar                 *toolbar;
+       NSToolbarItem           *item;
+
+       text=NSStringFromBBString(data);
+       tiptext=NSStringFromBBString(tip);
+
+       switch (gadget->internalclass){
+       case GADGET_LISTBOX:
+               listbox=(ListView*)gadget->handle;
+               [listbox setItem:text atIndex:index withImage:image withTip:tiptext withExtra:extra];
+               break;
+       case GADGET_COMBOBOX:
+               combo=(NSControl*)gadget->handle;
+               [combo removeItemAtIndex:index];
+               [combo insertItemWithObjectValue:text atIndex:index];
+//             [[combo itemAtIndex:index] setImage:image];
+               break;
+       case GADGET_TABBER:
+               tabber=(NSTabView*)gadget->handle;
+               tabitem=(TabViewItem*)[tabber tabViewItemAtIndex:index];
+               [tabitem setLabel:text];
+               [tabitem setImage:image];
+               break;
+       case GADGET_TOOLBAR:    
+               toolbar=(Toolbar*)gadget->handle;
+               item=FindToolbarItem(toolbar,index);
+               if (item)       {
+//                     [item setLabel:text];
+                       [item setImage:image];
+                       [item setToolTip:tiptext];
+                       [item setTag:0];
+               }
+               break;
+       }
+}
+
+void NSRemoveItem(nsgadget *gadget,int index){
+       ListView                *listbox;
+       NSControl       *combo;
+       NSTabView               *tabber;
+       TabViewItem     *tabitem;
+       Toolbar         *toolbar;
+
+       switch (gadget->internalclass){
+       case GADGET_LISTBOX:
+               listbox=(ListView*)gadget->handle;
+               [listbox removeItemAtIndex:index];
+               break;
+       case GADGET_COMBOBOX:
+               combo=(NSControl*)gadget->handle;
+               [combo removeItemAtIndex:index];
+               break;
+       case GADGET_TABBER:
+               tabber=(NSTabView*)gadget->handle;
+               tabitem=(TabViewItem*)[tabber tabViewItemAtIndex:index];
+               [tabber removeTabViewItem:tabitem];
+               break;
+       case GADGET_TOOLBAR:
+               toolbar=(Toolbar*)gadget->handle;
+               [toolbar removeItemAtIndex:(int)index];
+               break;
+       }
+}
+
+void NSSelectItem(nsgadget *gadget,int index,int state){
+       NSControl               *combo;
+       NSTabView                       *tabber;
+       ListView                        *listbox;
+       Toolbar                 *toolbar;
+       NSToolbarItem           *item;
+
+       switch (gadget->internalclass){
+       case GADGET_LISTBOX:
+               listbox=(ListView*)gadget->handle;
+               if(state) [listbox selectItem:index]; else [listbox deselectItem:index];
+               break;
+       case GADGET_COMBOBOX:
+               combo=(NSControl*)gadget->handle;
+               [combo setDelegate:nil];
+               [combo selectItemAtIndex:index];
+               [combo setObjectValue:[combo objectValueOfSelectedItem]];
+               [combo setDelegate:GlobalApp];
+               break;
+       case GADGET_TABBER:
+               tabber=(NSTabView*)gadget->handle;
+               [tabber selectTabViewItemAtIndex:index];
+               break;
+       case GADGET_TOOLBAR:    
+               toolbar=(Toolbar*)gadget->handle;
+               item=FindToolbarItem(toolbar,index);
+               BOOL enable=(state&STATE_DISABLED)?false:true;
+               [item setEnabled:enable];
+               int pressed=(state&STATE_SELECTED)?1:0;
+               [item setTag:pressed];
+               break;
+       }
+}
+
+int NSSelectedItem(nsgadget *gadget,int index){
+       NSComboBox              *combo;
+       NSTabView                       *tabber;
+       ListView                        *listbox;
+       Toolbar                 *toolbar;
+       NSToolbarItem           *item;
+       int                             state;
+
+       state=0;
+       switch (gadget->internalclass){
+       case GADGET_LISTBOX:
+               listbox=(ListView*)gadget->handle;
+               if ([[listbox table] selectedRow]==index) state|=STATE_SELECTED;
+               break;
+       case GADGET_COMBOBOX:
+               combo=(NSControl*)gadget->handle;
+               if ([combo indexOfSelectedItem]==index) state|=STATE_SELECTED;
+               break;
+       case GADGET_TABBER:
+               tabber=(NSTabView*)gadget->handle;
+               if ([tabber indexOfTabViewItem:[tabber selectedTabViewItem]]==index) state|=STATE_SELECTED;
+               break;
+       case GADGET_TOOLBAR:    
+               toolbar=(Toolbar*)gadget->handle;
+               item=FindToolbarItem(toolbar,index);
+               if (![item isEnabled]) state|=STATE_DISABLED;
+               if ([item tag]!=0) state|=STATE_SELECTED;
+               break;
+       }
+       return state;
+}
+
+// treeview commands
+
+int NSCountKids(nsgadget *gadget){
+       TreeView                *treeview;
+       NodeItem                *node;
+
+       switch (gadget->internalclass){
+       case GADGET_TREEVIEW:
+               treeview=(TreeView*)gadget->handle;
+               return [treeview count];
+       case GADGET_NODE:
+               node=(NodeItem*)gadget->handle;
+               return [node count];
+       }
+       return 0;
+}
+
+int NSSelectedNode(nsgadget *gadget){
+       TreeView                *treeview;
+
+       switch (gadget->internalclass){
+       case GADGET_TREEVIEW:
+               treeview=(TreeView*)gadget->handle;
+               return (int)[treeview selectedNode];            
+       }
+       return -1;
+}
+
+// textarea commands
+
+int LinePos(NSString *text,int pos){
+       int                     line,i;
+
+       line=0;
+       for (i=0;i<pos;i++) {if ([text characterAtIndex:i]=='\n' ) line++;}
+       return line;
+}
+
+int CharPos(NSString *text,int line){
+       int                     pos,n;
+
+       pos=0;
+       n=[text length];
+       while (pos<n && line>0){
+               if ([text characterAtIndex:pos]=='\n') line--;
+               pos++;
+       }
+       return pos;
+}
+
+NSRange GetRange(NSTextStorage *storage,int pos,int count,int units){
+       
+       NSString        *text;
+       unsigned int max;
+       
+       if (units==TEXTAREA_LINES){
+               text=[storage string];
+               if (count==TEXTAREA_ALL)
+                       count=[storage length];
+               else
+                       count=CharPos(text,pos+count);
+               pos=CharPos(text,pos);
+               max = [storage length]-pos;
+               count-=pos;
+       }
+       else{
+               max = [storage length]-pos;
+               if (count==TEXTAREA_ALL) count=max;
+       }
+       
+       if (count > max) count = max;
+       if (count<0) count=0;
+       
+       //NSLog(@"GetRange() pos: %d,  count: %d,  length: %d\n", pos, count, [storage length]);
+       
+       return NSMakeRange(pos,count);
+       
+}
+
+void NSReplaceText(nsgadget *gadget,int pos,int count,BBString *data,int units){
+       NSString                        *text;
+       TextView                        *textarea;
+       NSRange                 range,snap;
+       NSTextStorage           *storage;
+       unsigned int                    size;
+       
+       text=NSStringFromBBString(data);
+       textarea=(TextView*)gadget->handle;
+       
+       if(([[textarea string] length] == 0) || ((pos == 0) && (count == TEXTAREA_ALL))){
+               
+               [textarea setText:text];
+               
+       } else {
+               
+               snap=[textarea selectedRange];
+               range=GetRange([textarea storage],pos,count,units);
+               storage=[textarea storage];
+               [storage replaceCharactersInRange:range withString:text];       
+               size=[storage length];
+               if (snap.location>size) snap.location=size;
+               if (snap.location+snap.length>size) snap.length=size-snap.location;     
+               [textarea setSelectedRange:snap];
+               
+       }
+       
+}
+
+void NSAddText(nsgadget *gadget,BBString *data){
+       NSString                        *text;
+       TextView                        *textarea;
+       NSRange                 range;
+
+       text=NSStringFromBBString(data);
+       textarea=(TextView*)gadget->handle;
+       [textarea addText:text];
+       range=GetRange([textarea textStorage],[[textarea string] length],0,0);
+       [textarea setSelectedRange:range];
+       [textarea scrollRangeToVisible:range];
+}
+
+BBString *NSAreaText(nsgadget *gadget,int pos,int length,int units){
+       TextView                        *textarea;
+       NSRange                 range;
+       NSAttributedString      *astring;
+       BBString                                *bstring;
+
+       textarea=(TextView*)gadget->handle;
+       range=GetRange([textarea storage],pos,length,units);
+       astring=[[textarea storage] attributedSubstringFromRange:range];        
+       bstring=bbStringFromNSString([astring string]);
+       return bstring;
+}
+
+int NSAreaLen(nsgadget *gadget,int units){
+       TextView                        *textarea;
+       NSTextStorage           *storage;
+       unsigned                        ulen;
+
+       textarea=(TextView*)gadget->handle;
+       storage=[textarea storage];
+       ulen=[storage length];
+       if (units==TEXTAREA_LINES) ulen=LinePos([storage string],ulen)+1;
+       return ulen;    
+}
+
+void NSSetSelection(nsgadget *gadget,int pos,int length,int units){
+       TextView                        *textarea;
+       NSRange                 range;
+
+       textarea=(TextView*)gadget->handle;     
+       range=GetRange([textarea textStorage],pos,length,units);
+       [textarea setSelectedRange:range];
+       if( !textarea->lockedNest ) [textarea scrollRangeToVisible:range];
+}
+
+void NSLockText(nsgadget *gadget){
+       TextView                        *textarea;
+
+       textarea=(TextView*)gadget->handle;
+       
+       if( !textarea->lockedNest ){
+               textarea->lockedRange=[textarea rangeForUserTextChange];
+               [textarea->storage beginEditing];
+       }
+
+       ++textarea->lockedNest;
+}
+
+void NSUnlockText(nsgadget *gadget){
+       TextView                        *textarea;
+       
+       textarea=(TextView*)gadget->handle;
+       
+       --textarea->lockedNest;
+
+       if( !textarea->lockedNest ){
+               NSRange range=textarea->lockedRange;
+               [textarea->storage endEditing];
+               if( range.location+range.length>[textarea->storage length] ) range=NSMakeRange( 0,0 );
+               [textarea setSelectedRange:range];
+       }
+}
+
+void NSSetTabs(nsgadget *gadget,int tabwidth){
+       TextView *textarea;
+       textarea=(TextView*)gadget->handle;     
+       [textarea setTabs:tabwidth];
+}
+
+void NSSetMargins(nsgadget *gadget,int leftmargin){
+       TextView *textarea;
+       textarea=(TextView*)gadget->handle;     
+       [textarea setMargins:leftmargin];
+}
+
+int NSCharAt(nsgadget *gadget,int line){
+       TextView                *textarea;
+       NSString                *text;
+       int                             n,i;
+
+       textarea=(TextView*)gadget->handle;     
+       text=[[textarea storage] string];
+       n=[text length];i=0;
+       while (line){
+               if (i==n) break;
+               if ([text characterAtIndex:i]=='\n' ) line--;
+               i++;
+       }
+       return i;
+}
+
+int NSLineAt(nsgadget *gadget,int pos){
+       TextView                        *textarea;
+       textarea=(TextView*)gadget->handle;     
+       return LinePos([[textarea storage] string],pos);
+}
+
+int NSCharX(nsgadget *gadget,int pos){
+       unsigned int rectCount;
+       NSRectArray rectArray;
+       TextView        *textarea = (TextView*)gadget->handle;
+       NSRange range = GetRange([textarea textStorage],pos,0,TEXTAREA_CHARS);
+       rectArray = [[textarea layoutManager] rectArrayForCharacterRange:range withinSelectedCharacterRange:range inTextContainer: [textarea textContainer] rectCount:&rectCount];
+       if(rectCount > 0) return (int)(((NSRect)rectArray[0]).origin.x-([textarea visibleRect].origin.x-[textarea textContainerOrigin].x));
+}
+
+int NSCharY(nsgadget *gadget,int pos){
+       unsigned int rectCount;
+       NSRectArray rectArray;
+       TextView        *textarea = (TextView*)gadget->handle;
+       NSRange range = GetRange([textarea textStorage],pos,0,TEXTAREA_CHARS);
+       rectArray = [[textarea layoutManager] rectArrayForCharacterRange:range withinSelectedCharacterRange:range inTextContainer: [textarea textContainer] rectCount:&rectCount];
+       if(rectCount > 0) return (int)(((NSRect)rectArray[0]).origin.y-([textarea visibleRect].origin.y-[textarea textContainerOrigin].y));
+}
+
+int NSGetCursorPos(nsgadget *gadget,int units){
+       TextView                        *textarea;
+       NSRange                 range;
+
+       textarea=(TextView*)gadget->handle;     
+       range=[textarea rangeForUserTextChange];
+       if (range.location == NSNotFound) return 0; //KORIOLIS (avoids read-only text-area crash)
+       if (units==TEXTAREA_LINES) return NSLineAt(gadget,range.location);
+       return range.location;
+}
+
+int NSGetSelectionlength(nsgadget *gadget,int units){
+       TextView                        *textarea;
+       NSRange                 range;
+
+       textarea=(TextView*)gadget->handle;     
+       range=[textarea rangeForUserTextChange];
+       if (range.location == NSNotFound) return 0; //KORIOLIS (avoids read-only text-area crash)
+       if (range.length == 0) return 0;
+       if (units == TEXTAREA_LINES){
+               int l0=NSLineAt(gadget,range.location);
+               int l1=NSLineAt(gadget,range.location+range.length-1);
+               return (l1-l0+1);
+       }
+       return range.length;
+}
+
+void NSSetTextColor(nsgadget *gadget,int r,int g,int b){
+       
+       if(gadget->textcolor) [gadget->textcolor release];
+       gadget->textcolor = [[NSColor colorWithDeviceRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:1.0] retain];
+       
+       switch (gadget->internalclass){
+       case GADGET_LABEL:
+               switch (gadget->style&3) {
+                       case LABEL_SEPARATOR:
+                               return;
+               }
+       case GADGET_TEXTFIELD:
+       case GADGET_LISTBOX:
+       case GADGET_TREEVIEW:
+       case GADGET_TEXTAREA:
+               [gadget->handle setTextColor:gadget->textcolor];
+               break;
+       default:
+               NSSetText(gadget, NSGetText(gadget));   //Attempt to reset text with NSAttributedString
+               break;
+       }
+}
+
+void NSSetStyle(nsgadget *gadget,int r,int g,int b,int flags,int pos,int length,int units)     {
+       TextView                        *textarea;
+       NSRange                 _range;
+       NSColor                         *color;
+       int traits = 0;
+
+       textarea=(TextView*)gadget->handle;     
+       _range=GetRange([textarea storage],pos,length,units);
+       color=[NSColor colorWithDeviceRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:1.0];
+       
+       [[textarea storage] removeAttribute:NSLinkAttributeName range:_range];
+       [[textarea storage] addAttribute:NSForegroundColorAttributeName value:color range:_range];
+       [[textarea storage] addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInt:(flags & 4)?NSUnderlineStyleSingle:NSUnderlineStyleNone] range:_range];
+       [[textarea storage] addAttribute:NSStrikethroughStyleAttributeName value:[NSNumber numberWithInt:(flags & 8)?NSUnderlineStyleSingle:NSUnderlineStyleNone] range:_range];
+
+       traits |= (flags & 1)?NSBoldFontMask:NSUnboldFontMask;
+       traits |= (flags & 2)?NSItalicFontMask:NSUnitalicFontMask;
+
+       [[textarea storage] applyFontTraits: traits range:_range];
+}
+
+void NSSetValue(nsgadget *gadget,float value){
+       NSProgressIndicator     *progbar;
+       NSDate                          *date;
+       NSValue                         *info;
+       NSRunLoop                       *runloop;
+       
+       switch (gadget->internalclass){
+       case GADGET_PROGBAR:
+               progbar=(NSProgressIndicator*)gadget->handle;
+               [progbar setDoubleValue:value];
+               break;
+       }
+}
+
+// slider / scrollbar
+
+void NSSetSlider(nsgadget *gadget,double value,double small,double big){
+       NSScroller              *scroller;
+       NSSlider                        *slider;
+       NSStepper                       *stepper;
+       NSRect                  frame;
+       float                   size;
+       
+       switch (gadget->style&12){
+       case SLIDER_SCROLLBAR:
+               scroller=(NSScroller*)gadget->handle;
+               if(value > (big-small))
+                       value = 1.0L;
+               else if(big-small)
+                       value/=(big-small);
+               else
+                       value = 0.0L;
+               [scroller setKnobProportion:(small/big)];
+               [scroller setDoubleValue:value];
+               break;
+       case SLIDER_TRACKBAR:
+               slider=(NSSlider*)gadget->handle;
+               [slider setMinValue:small];
+               [slider setMaxValue:big];
+               [slider setDoubleValue:value];
+               break;
+       case SLIDER_STEPPER:
+               stepper=(NSStepper*)gadget->handle;
+               [stepper setMinValue:small];
+               [stepper setMaxValue:big];
+               [stepper setDoubleValue:value];
+               break;
+       }
+}
+
+double NSGetSlider(nsgadget *gadget){
+       NSControl       *control;
+       control = (NSControl*)gadget->handle;
+       return [control doubleValue];
+}
+
+
+NSCursor* NSCursorCreateStock(short sIndex)
+{
+
+    // Adapted from wxWidgets - if you believe this contravenes wxWidget's licensing
+    // agreements, please let the BRL team know and it will be removed.
+    
+    int i;
+    ArrayCursor* tmpCursor = &arrCursors[sIndex];
+    NSImage *tmpImage = [[NSImage alloc] initWithSize:NSMakeSize(16.0,16.0)];
+    
+    NSBitmapImageRep *tmpRep = [[NSBitmapImageRep alloc]
+        initWithBitmapDataPlanes: NULL
+        pixelsWide: 16
+        pixelsHigh: 16
+        bitsPerSample: 1
+        samplesPerPixel: 2
+        hasAlpha: YES
+        isPlanar: YES
+        colorSpaceName: NSCalibratedWhiteColorSpace
+        bytesPerRow: 2
+        bitsPerPixel: 1];
+    
+    unsigned char *planes[5];
+    [tmpRep getBitmapDataPlanes:planes];
+    
+    for(i=0; i<16; ++i)
+    {
+        planes[0][2*i  ] = (~tmpCursor->bits[i] & tmpCursor->mask[i]) >> 8 & 0xff;
+        planes[1][2*i  ] = tmpCursor->mask[i] >> 8 & 0xff;
+        planes[0][2*i+1] = (~tmpCursor->bits[i] & tmpCursor->mask[i]) & 0xff;
+        planes[1][2*i+1] = tmpCursor->mask[i] & 0xff;
+    }
+    
+    [tmpImage addRepresentation:tmpRep];
+    
+    NSCursor* tmpNSCursor =  [[NSCursor alloc]  initWithImage:tmpImage hotSpot:NSMakePoint(tmpCursor->hitpoint[1], tmpCursor->hitpoint[0])];
+    
+    [tmpRep release];[tmpImage release];
+    
+    return tmpNSCursor;
+}
+
+void NSSetPointer(int shape){
+       NSCursor *cursor;
+       cursor=[NSCursor arrowCursor];
+       
+       switch (shape){
+//     case POINTER_DEFAULT:cursor=[NSCursor ];break;
+       case POINTER_ARROW:cursor=[NSCursor arrowCursor];break;
+       case POINTER_IBEAM:cursor=[NSCursor IBeamCursor];break;
+//     case POINTER_WAIT:cursor=[NSCursor ];break;
+       case POINTER_CROSS:cursor=[NSCursor crosshairCursor];break;
+       case POINTER_UPARROW:cursor=[NSCursor resizeUpCursor];break;
+       case POINTER_SIZENWSE:cursor=NSCursorCreateStock(curNWSE);break;
+       case POINTER_SIZENESW:cursor=NSCursorCreateStock(curNESW);break;
+       case POINTER_SIZEWE:cursor=[NSCursor resizeLeftRightCursor];break;
+       case POINTER_SIZENS:cursor=[NSCursor resizeUpDownCursor];break;
+       case POINTER_SIZEALL:cursor=NSCursorCreateStock(curSizeAll);break;
+       case POINTER_NO:cursor=NSCursorCreateStock(curNoEntry);break;
+       case POINTER_HAND:cursor=[NSCursor pointingHandCursor];break;
+//     case POINTER_APPSTARTING:cursor=[NSCursor ];break;
+       case POINTER_HELP:cursor=NSCursorCreateStock(curHelp);break;
+       }
+       [cursor set];
+}
+
+typedef struct bbpixmap bbpixmap;
+
+struct bbpixmap{
+// BBObject
+       void            *class;
+       int             refs;
+// pixmap
+       unsigned char *pixels;
+       int             width,height,pitch,format,capacity;
+};
+
+
+#define PF_I8 1
+#define PF_A8 2
+#define PF_BGR888 3
+#define PF_RGB888 4
+#define PF_BGRA8888 5
+#define PF_RGBA8888 6
+#define PF_STDFORMAT PF_RGBA8888
+
+const static char BytesPerPixel[]={0,1,1,3,3,4,4};
+const static char BitsPerPixel[]={0,8,8,24,24,32,32};
+const static char RedBitsPerPixel[]={0,0,0,8,8,8,8};
+const static char GreenBitsPerPixel[]={0,0,0,8,8,8,8};
+const static char BlueBitsPerPixel[]={0,0,0,8,8,8,8};
+const static char AlphaBitsPerPixel[]={0,0,8,0,0,8,8};
+
+NSImage *NSPixmapImage(bbpixmap *pix){
+       NSImage *image;
+       NSBitmapImageRep *bitmap;
+       int spp,bpp,i;
+       int bytesperrow;
+       BOOL    alpha;
+       unsigned char * data;
+               
+       alpha=AlphaBitsPerPixel[pix->format]?YES:NO;
+       spp=BytesPerPixel[pix->format];
+       bpp=BitsPerPixel[pix->format];
+       bytesperrow=pix->width*spp;
+       
+       bitmap=[[[NSBitmapImageRep alloc] 
+               initWithBitmapDataPlanes:NULL
+               pixelsWide:pix->width
+               pixelsHigh:pix->height
+               bitsPerSample:8 
+               samplesPerPixel:spp 
+               hasAlpha:alpha 
+               isPlanar:NO 
+               colorSpaceName:NSDeviceRGBColorSpace 
+//             bitmapFormat:NSAlphaNonpremultipliedBitmapFormat
+               bytesPerRow:bytesperrow 
+               bitsPerPixel:bpp] autorelease];
+               
+       data = [bitmap bitmapData];
+       
+       for( i = 0; i < pix->height; i++) {
+               memcpy( data + ( i * bytesperrow ), pix->pixels + ( i * pix->pitch ), bytesperrow );
+       }
+
+       image=[[NSImage alloc] initWithSize:NSMakeSize(pix->width,  pix->height)];
+       [image addRepresentation:bitmap];
+       [image retain];
+       return image;
+}
+
+void NSSetImage(nsgadget *gadget,NSImage *image,int flags){
+       PanelView *panel;
+       NSButton *button;
+       NSMenuItem *menu;
+       
+       switch (gadget->internalclass){
+       case GADGET_PANEL:
+               panel=(PanelView*)gadget->handle;
+               [panel setImage:image withFlags:flags];
+               break;
+       case GADGET_BUTTON:
+               if ((flags & GADGETPIXMAP_ICON) && (gadget->style <= BUTTON_PUSH)){ 
+                       button=(NSButton *)gadget->handle;
+                       [button setImage:image];
+                       if (flags & GADGETPIXMAP_NOTEXT) {
+                               [button setImagePosition:NSImageOnly];
+                       } else {
+                               [button setImagePosition:NSImageLeft];
+                       }
+               }
+               break; 
+       case GADGET_MENUITEM:
+               if (flags & GADGETPIXMAP_ICON){
+                       menu=(NSMenuItem*)gadget->handle;
+                       [menu setImage:image];
+               }
+               break;
+       }
+}
+
+void NSSetIcon(nsgadget *gadget,NSImage *image){
+       NodeItem        *node;
+               
+       switch (gadget->internalclass){
+       case GADGET_NODE:
+               node=(NodeItem*)gadget->handle;
+               [node setIcon:image];
+               break;
+       }
+}
+
+void NSSetNextView(nsgadget *gadget,nsgadget *nextgadget){
+       NSView          *view,*nextview;
+       view=(NSView*)gadget->handle;
+       nextview=(NSView*)nextgadget->handle;
+       [view setNextKeyView:nextview];
+}
+
+static int keyToChar( int key ){
+       if( key>=KEY_A && key<=KEY_Z ) return key-KEY_A+'a';
+       if( key>=KEY_F1 && key<=KEY_F12 ) return key-KEY_F1+NSF1FunctionKey;
+       
+       switch( key ){
+       case KEY_BACKSPACE:return 8;
+       case KEY_TAB:return 9;
+       case KEY_ESC:return 27;
+       case KEY_SPACE:return 32;
+       case KEY_PAGEUP:return NSPageUpFunctionKey;
+       case KEY_PAGEDOWN:return NSPageDownFunctionKey;
+       case KEY_END:return NSEndFunctionKey;
+       case KEY_HOME:return NSHomeFunctionKey;
+       case KEY_UP:return NSUpArrowFunctionKey;
+       case KEY_DOWN:return NSDownArrowFunctionKey;
+       case KEY_LEFT:return NSLeftArrowFunctionKey;
+       case KEY_RIGHT:return NSRightArrowFunctionKey;
+       case KEY_INSERT:return NSInsertFunctionKey;
+       case KEY_DELETE:return NSDeleteFunctionKey;
+       case KEY_TILDE:return '~';
+       case KEY_MINUS:return '-';
+       case KEY_EQUALS:return '=';
+       case KEY_OPENBRACKET:return '[';
+       case KEY_CLOSEBRACKET:return ']';
+       case KEY_BACKSLASH:return '\\';
+       case KEY_SEMICOLON:return ';';
+       case KEY_QUOTES:return '\'';
+       case KEY_COMMA:return ',';
+       case KEY_PERIOD:return '.';
+       case KEY_SLASH:return '/';
+       }
+       return 0;
+}
+
+void NSSetHotKey(nsgadget *gadget,int key,int modifier){
+       int chr;
+       unichar uchar[1];
+       NSString *keyStr;
+       int modMask;
+       NSMenuItem *menuItem;
+       if( gadget->internalclass!=GADGET_MENUITEM ) return;
+       modMask=0;
+       if( modifier & 1 ) modMask|=NSShiftKeyMask;
+       if( modifier & 2 ) modMask|=NSControlKeyMask;
+       if( modifier & 4 ) modMask|=NSAlternateKeyMask;
+       if( modifier & 8 ) modMask|=NSCommandKeyMask;
+       menuItem=(NSMenuItem*)gadget->handle;
+       chr=keyToChar( key );
+       if( !chr ) {
+               [menuItem setKeyEquivalent:@""];
+               [menuItem setKeyEquivalentModifierMask:0];
+               return;
+       }
+       uchar[0]=chr;
+       keyStr=[NSString stringWithCharacters:uchar length:1];
+       [menuItem setKeyEquivalent:keyStr];
+       [menuItem setKeyEquivalentModifierMask:modMask];
 }
\ No newline at end of file