Tweaked cocoamaxgui so it's 10.4->10.9 friendly!
authorblitz-research <blitzmunter@gmail.com>
Wed, 29 Jan 2014 02:11:14 +0000 (15:11 +1300)
committerblitz-research <blitzmunter@gmail.com>
Wed, 29 Jan 2014 02:11:14 +0000 (15:11 +1300)
mod/maxgui.mod/cocoamaxgui.mod/cocoa.macos_tiger.m [new file with mode: 0644]
mod/maxgui.mod/cocoamaxgui.mod/cocoagui.bmx

diff --git a/mod/maxgui.mod/cocoamaxgui.mod/cocoa.macos_tiger.m b/mod/maxgui.mod/cocoamaxgui.mod/cocoa.macos_tiger.m
new file mode 100644 (file)
index 0000000..440e131
--- /dev/null
@@ -0,0 +1,4486 @@
+// 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
+}
\ No newline at end of file
index ebf62fd7d95a27d845cf6a7e9c327516ff8208f2..4017104e2452f4f6ad314654da76826041607972 100644 (file)
-Strict
-
-Import MaxGUI.MaxGUI
-Import Pub.MacOs
-
-Import "-framework WebKit"
-Import "cocoa.macos.m"
-
-Extern
-       
-       Function bbSystemEmitOSEvent( nsevent:Byte Ptr,nsview:Byte Ptr,source:Object )
-       
-       Function ScheduleEventDispatch()
-       
-       Function NSBegin()
-       Function NSEnd()
-       
-       Function NSGetSysColor(colorindex,r:Int Ptr,g:Int Ptr, b:Int Ptr)
-       Function NSColorRequester(r,g,b)
-       Function NSSetPointer(shape)
-       
-       Function NSCharWidth(font,charcode)
-       ' create
-       Function NSInitGadget(gadget:TNSGadget)
-       ' generic
-       Function NSActiveGadget()
-       Function NSFreeGadget(gadget:TNSGadget)
-       Function NSClientWidth(gadget:TNSGadget)
-       Function NSClientHeight(gadget:TNSGadget)
-       Function NSRethink(gadget:TNSGadget)
-       Function NSRedraw(gadget:TNSGadget)
-       Function NSActivate(gadget:TNSGadget,code)
-       Function NSState(gadget:TNSGadget)
-       Function NSShow(gadget:TNSGadget,bool)
-       Function NSEnable(gadget:TNSGadget,bool)
-       Function NSCheck(gadget:TNSGadget,bool)
-       Function NSSetNextView(gadget:TNSGadget,nextgadget:TNSGadget)
-       Function NSSetHotKey(gadget:TNSGadget,hotkey,modifier)
-       Function NSSetTooltip(gadget:TNSGadget,tip$)
-       Function NSGetTooltip$(gadget:TNSGadget)
-       Function NSSuperview(view:Int)
-       ' window
-       Function NSSetStatus(gadget:TNSGadget,text$,pos)
-       Function NSSetMinimumSize(gadget:TNSGadget,width,height)
-       Function NSSetMaximumSize(gadget:TNSGadget,width,height)
-       Function NSPopupMenu(gadget:TNSGadget,menu:TNSGadget)
-       ' font
-       Function NSRequestFont(font)
-       Function NSLoadFont(name$,size:Double,flags)
-       Function NSGetDefaultFont()
-       Function NSSetFont(gadget:TNSGadget,font)
-       Function NSFontName$(font)
-       Function NSFontStyle(font)
-       Function NSFontSize:Double(font)
-       ' items
-       Function NSClearItems(gadget:TNSGadget)
-       Function NSAddItem(gadget:TNSGadget,index,text$,tip$,image,extra:Object)
-       Function NSSetItem(gadget:TNSGadget,index,text$,tip$,image,extra:Object)
-       Function NSRemoveItem(gadget:TNSGadget,index)
-       Function NSSelectItem(gadget:TNSGadget,index,state)
-       Function NSSelectedItem(gadget:TNSGadget,index)
-       Function NSSelectedNode(gadget:TNSGadget)
-       ' text
-       Function NSSetText(gadget:TNSGadget,text$)
-       Function NSGetText$(gadget:TNSGadget)
-       Function NSReplaceText(gadget:TNSGadget,pos,length,text$,units)
-       Function NSAddText(gadget:TNSGadget,text$)
-       Function NSAreaText$(gadget:TNSGadget,pos,length,units)
-       Function NSAreaLen(gadget:TNSGadget,units)
-       Function NSLockText(gadget:TNSGadget)
-       Function NSUnlockText(gadget:TNSGadget)
-       Function NSSetTabs(gadget:TNSGadget,tabwidth)
-       Function NSSetMargins(gadget:TNSGadget,leftmargin)
-       Function NSSetColor(gadget:TNSGadget,r,g,b)
-       Function NSRemoveColor(gadget:TNSGadget)
-       Function NSSetAlpha(gadget:TNSGadget,alpha#)
-       Function NSSetTextColor(gadget:TNSGadget,r,g,b)
-       Function NSGetCursorPos(gadget:TNSGadget,units)
-       Function NSGetSelectionlength(gadget:TNSGadget,units)
-       Function NSSetStyle(gadget:TNSGadget,r,g,b,flags,pos,length,units)      
-       Function NSSetSelection(gadget:TNSGadget,pos,length,units)
-       Function NSCharAt(gadget:TNSGadget,line)
-       Function NSLineAt(gadget:TNSGadget,index)
-       Function NSCharX(gadget:TGadget,char)
-       Function NSCharY(gadget:TGadget,char)
-       ' prop
-       Function NSSetValue(gadget:TNSGadget,value#)
-       ' slider
-       Function NSSetSlider(gadget:TNSGadget,value:Double,small:Double,big:Double)
-       Function NSGetSlider:Double(gadget:TNSGadget)
-       ' images for panels and nodes
-       Function NSPixmapImage(image:TPixmap)
-       Function NSSetImage(gadget:TNSGadget,nsimage,flags)
-       Function NSSetIcon(gadget:TNSGadget,nsimage)
-       Function NSCountKids(gadget:TNSGadget)
-       ' html
-       Function NSRun$(gadget:TNSGadget,script$)
-       ' misc
-       Function NSRelease(nsobject)
-       ' system
-       Function NSGetUserName$()
-       Function NSGetComputerName$()
-       
-EndExtern
-
-Global GadgetMap:TMap=New TMap
-
-maxgui_driver=New TCocoaMaxGuiDriver
-
-Type TCocoaMaxGUIDriver Extends TMaxGUIDriver
-       
-       Global CocoaGuiFont:TCocoaGuiFont
-       
-       Method New()
-               NSBegin
-               atexit_ NSEnd
-               If Not CocoaGuiFont Then CocoaGuiFont = TCocoaGuiFont(LibraryFont(GUIFONT_SYSTEM))
-       End Method
-       
-       Method UserName$()
-               Return NSGetUserName$()
-       End Method
-       
-       Method ComputerName$()
-               Return NSGetComputerName$()
-       End Method
-               
-       Method CreateGadget:TGadget(internalclass,name$,x,y,w,h,group:TGadget,style)
-               Local p,hotkey
-               If internalclass=GADGET_MENUITEM
-                       name=name.Replace("&","")
-               ElseIf internalclass=GADGET_BUTTON
-                       p=name.Find("&")
-                       If p>-1
-'                              hotkey=Asc(name[p..p+1]) 'to do - convert and call SetHotKey before return
-                               name=name[..p]+name[p+1..]
-                       EndIf
-               ElseIf internalclass=GADGET_TOOLBAR
-                       Global _toolbarcount
-                       _toolbarcount:+1
-                       name="Toolbar"+_toolbarcount
-               EndIf
-               Local gadget:TNSGadget = TNSGadget.Create(internalclass,name,x,y,w,h,TNSGadget(group),style)
-               If internalclass<>GADGET_WINDOW And internalclass<>GADGET_MENUITEM And internalclass<>GADGET_DESKTOP
-                       gadget.SetLayout EDGE_CENTERED,EDGE_CENTERED,EDGE_CENTERED,EDGE_CENTERED
-               EndIf
-               If group Then gadget._SetParent group
-               gadget.SetTextColor(0,0,0)
-               gadget.LinkView
-               Return gadget   
-       End Method
-               
-       Function CreateFont:TGuiFont(handle,flags=FONT_NORMAL)
-               Local font:TGuiFont = New TCocoaGuiFont
-               font.handle = handle
-               font.name = NSFontName(handle)
-               font.size = NSFontSize(handle)
-               font.style = NSFontStyle(handle)|flags
-               Return font
-       EndFunction
-
-       Method LoadFont:TGuiFont(name$,size,flags)
-               Return CreateFont(NSLoadFont(name,Double(size),flags),flags)
-       End Method
-       
-       Method LoadFontWithDouble:TGuiFont(name$,size:Double,flags)
-               Return CreateFont(NSLoadFont(name,size,flags),flags)
-       End Method
-       
-       Method LibraryFont:TGuiFont( pFontType% = GUIFONT_SYSTEM, pFontSize:Double = 0, pFontStyle% = FONT_NORMAL )
-               If pFontType = GUIFONT_SYSTEM Then
-                       Local tmpHandle% = NSGetDefaultFont()
-                       If pFontSize <= 0 Then pFontSize = NSFontSize(tmpHandle)
-                       Return LoadFontWithDouble( NSFontName(tmpHandle), pFontSize, NSFontStyle(tmpHandle)|pFontStyle )
-               Else
-                       Return Super.LibraryFont( pFontType, pFontSize, pFontStyle )
-               EndIf
-       EndMethod
-       
-       Method LookupColor( colorindex:Int, red:Byte Var, green:Byte Var, blue:Byte Var )
-               
-               Local r, g, b
-               
-               If NSGetSysColor( colorindex, Varptr r, Varptr g, Varptr b )
-                       red = r & $FF
-                       green = g & $FF
-                       blue = b & $FF
-                       Return True
-               EndIf
-               
-               Return Super.LookupColor( colorindex, red, green, blue )
-                               
-       EndMethod
-       
-       Method RequestColor(r,g,b)
-               Return NSColorRequester(r,g,b)
-       End Method
-       
-       Method RequestFont:TGuiFont(font:TGuiFont)
-               Local   handle
-               If font handle=font.handle
-               handle=NSRequestFont(handle)
-               If handle
-                       If font And handle=font.handle Return font
-                       Return CreateFont(handle)
-               EndIf
-       End Method
-       
-       Method SetPointer(shape)
-               NSSetPointer shape
-       End Method              
-       
-       Method ActiveGadget:TGadget()
-               PollSystem()
-               Local handle = NSActiveGadget()
-               If handle Return GadgetFromHandle(handle)
-       End Method
-       
-       Method LoadIconStrip:TIconStrip(source:Object)
-               Return TCocoaIconStrip.Create(source)
-       End Method
-End Type
-
-Function GadgetFromHandle:TNSGadget( handle )
-       Return TNSGadget( GadgetMap.ValueForKey( TIntWrapper.Create(handle) ) )
-End Function
-
-Function EmitCocoaOSEvent( event:Byte Ptr,handle,gadget:Object = Null )
-       Local owner:TGadget = TGadget(gadget)
-       If Not owner Then owner = GadgetFromHandle( handle )
-       If owner Then
-               While owner.source
-                       owner = owner.source
-               Wend
-       EndIf
-       bbSystemEmitOSEvent event,Byte Ptr(handle),owner
-End Function
-
-Function EmitCocoaMouseEvent( event:Byte Ptr, handle )
-       Local gadget:TNSGadget
-'      While handle
-               gadget = GadgetFromHandle( handle )
-               If gadget Then
-                       If (gadget.sensitivity & SENSITIZE_MOUSE) Then
-                               EmitCocoaOSEvent( event, handle, gadget )
-                               Return 1
-                       EndIf
-                       Return 0
-               EndIf
-'              handle = NSSuperview(handle)
-'      Wend
-End Function
-
-Function EmitCocoaKeyEvent( event:Byte Ptr, handle )
-       Local gadget:TNSGadget
-       While handle
-               gadget = GadgetFromHandle( handle )
-               If gadget Then
-                       If (gadget.sensitivity & SENSITIZE_KEYS) Then
-                               EmitCocoaOSEvent( event, handle, gadget )
-                               Return 1
-                       EndIf
-                       Return 0
-               EndIf
-               handle = NSSuperview(handle)
-       Wend
-End Function
-
-Function PostCocoaGuiEvent( id,handle,data,mods,x,y,extra:Object )
-       
-       Local gadget:TNSGadget
-       
-       DispatchGuiEvents()
-       
-       If handle Then
-               
-               gadget = GadgetFromHandle(handle)
-               
-               If gadget Then
-                       
-                       Select gadget.internalclass
-                               Case GADGET_TREEVIEW
-                                       extra=GadgetFromHandle(data)
-                                       data = 0
-                       EndSelect
-                       
-                       Select id
-                               Case EVENT_WINDOWSIZE
-                                       If gadget.width <> x Or gadget.height <> y Then
-                                               gadget.SetRect gadget.xpos,gadget.ypos,x,y
-                                               gadget.LayoutKids
-                                       Else
-                                               Return
-                                       EndIf
-                                       
-                               Case EVENT_WINDOWMOVE
-                                       If gadget.xpos <> x Or gadget.ypos <> y Then
-                                               gadget.SetRect x,y,gadget.width,gadget.height
-                                       Else
-                                               Return
-                                       EndIf
-                                       
-                               Case EVENT_MENUACTION
-                                       extra=TNSGadget.popupextra
-                                       TNSGadget.popupextra=Null
-                                       
-                               Case EVENT_GADGETACTION
-                                       
-                                       Select gadget.internalclass
-                                               Case GADGET_SLIDER
-                                                       Local oldValue:Int = gadget.GetProp()
-                                                       If data Then
-                                                               Select (gadget.style&(SLIDER_SCROLLBAR|SLIDER_TRACKBAR|SLIDER_STEPPER))
-                                                                       Case SLIDER_SCROLLBAR
-                                                                               If data > 1 Then
-                                                                                       data = gadget.small
-                                                                               ElseIf data < -1 Then
-                                                                                       data = -gadget.small
-                                                                               EndIf
-                                                               EndSelect
-                                                               gadget.SetProp(oldValue+data)
-                                                               data=gadget.GetProp()
-                                                               If (data = oldValue) Then Return
-                                                       Else
-                                                               data=gadget.GetProp()
-                                                       EndIf
-                                               Case GADGET_LISTBOX, GADGET_COMBOBOX, GADGET_TABBER
-                                                       If (data > -1 And data < gadget.items.length) extra=gadget.ItemExtra(data)
-                                               Case GADGET_BUTTON
-                                                       Select (gadget.style&7)
-                                                               Case BUTTON_CHECKBOX
-                                                                       If ButtonState(gadget) = CHECK_INDETERMINATE Then SetButtonState(gadget, CHECK_SELECTED )
-                                                               Case BUTTON_RADIO
-                                                                       If (gadget.style&BUTTON_PUSH) Then SetButtonState(gadget,CHECK_SELECTED)
-                                                                       gadget.ExcludeOthers()
-                                                       EndSelect
-                                                       data=ButtonState(gadget)
-                                               Case GADGET_TOOLBAR
-                                                       If data>-1 Then
-                                                               extra=gadget.ItemExtra(data)
-                                                               If (gadget.ItemFlags(data)&GADGETITEM_TOGGLE) Then gadget.SelectItem(data,2)
-                                                       EndIf
-                                       EndSelect
-                                       
-                               Case EVENT_GADGETSELECT, EVENT_GADGETMENU
-                                       Select gadget.internalclass
-                                               Case GADGET_LISTBOX, GADGET_COMBOBOX, GADGET_TABBER
-                                                       If data>-1 Then extra=gadget.ItemExtra(data)
-                                       EndSelect
-                                       
-                               Case EVENT_GADGETLOSTFOCUS
-                               
-                                       QueueGuiEvent id,gadget,data,mods,x,y,extra
-                                       ScheduleEventDispatch()
-                                       Return
-                                       
-                       EndSelect
-               EndIf
-       
-       EndIf
-       
-       PostGuiEvent id,gadget,data,mods,x,y,extra
-       
-EndFunction
-
-Function FilterKeyDown( handle,key,mods )
-       Local source:TNSGadget
-       If handle
-               source=GadgetFromHandle(handle)
-       EndIf
-       If source And source.eventfilter<>Null
-               Local event:TEvent=CreateEvent(EVENT_KEYDOWN,source,key,mods)
-               Return source.eventfilter(event,source.context)
-       EndIf
-       Return 1
-End Function
-
-Function FilterChar( handle,key,mods )
-       Local source:TNSGadget
-       Select key
-               ' Return true if they are arrow key characters
-               Case 63232, 63233, 63234, 63235
-                       Return 1
-       EndSelect
-       If handle
-               source=GadgetFromHandle(handle)
-       EndIf
-       If source And source.eventfilter<>Null 'Return source.charfilter(char,mods,source.context)
-               Local event:TEvent=CreateEvent(EVENT_KEYCHAR,source,key,mods)
-               Return source.eventfilter(event,source.context)
-       EndIf
-       Return 1
-End Function
-
-Type TNSGadget Extends TGadget
-       
-       Field internalclass, origclass  'internalclass: Class the Cocoa driver uses to draw the gadget, origclass: Expected class to be returned by Class() method
-       Field handle
-       Field view, textcolor   'view: NSView handle, textcolor: NSColor handle for Objective-C code
-       Field intFontStyle      'Copy of font.style used by cocoa.macos.m to handle underlining/strikethrough etc. that isn't included in NSFont
-       Field pixmap:TPixmap
-       Field icons:TCocoaIconStrip
-       Field small, big
-       Field canvas:TGraphics
-       Field font:TCocoaGuiFont
-       Field enabled:Int = True, forceDisable:Int = False
-
-' main factory command
-
-       Function Create:TNSGadget(internalclass,text$,x,y,w,h,group:TGadget,style)
-               
-               Local gadget:TNSGadget = New TNSGadget
-               gadget.origclass = internalclass
-               gadget.internalclass = internalclass
-               
-               If Not group And internalclass<>GADGET_DESKTOP Then group = Desktop()
-               gadget.parent = group
-               
-               gadget.name = text
-               gadget.SetRect x,y,w,h  'setarea
-               gadget.style = style
-               gadget.font = TCocoaMaxGUIDriver.CocoaGUIFont
-               
-               If TNSGadget(group) Then
-                       gadget.forceDisable = Not (TNSGadget(group).enabled And Not TNSGadget(group).forceDisable)
-               EndIf
-               
-               NSInitGadget gadget
-
-               If internalclass<>GADGET_TOOLBAR 'toolbars retain name to key insertgadgetitem
-                       gadget.name = Null
-               EndIf
-               
-               GadgetMap.Insert TIntWrapper.Create(gadget.handle),gadget
-               If gadget.view And gadget.handle <> gadget.view Then
-                       GadgetMap.Insert TIntWrapper.Create(gadget.view),gadget
-               EndIf
-               
-               If internalclass=GADGET_SLIDER Then gadget.SetRange(1,10)
-               gadget.LockLayout()
-               
-               If (internalclass=GADGET_WINDOW) And (style&WINDOW_STATUS) Then
-                       If (style&WINDOW_CLIENTCOORDS) Then
-                               gadget.SetMinimumSize(25,0)
-                       Else
-                               gadget.SetMinimumSize(25,70)
-                       EndIf
-               EndIf
-               
-               If LocalizationMode() & LOCALIZATION_OVERRIDE Then LocalizeGadget(gadget,text,"")
-               
-               gadget.SetEnabled(gadget.enabled)
-               
-               Return gadget
-               
-       End Function
-       
-       Method Class()
-               Return origclass
-       EndMethod
-       
-       Function ToView:TNSGadget(value:Object)
-               Local   view:TNSGadget = TNSGadget(value)
-               If Not view Return
-               Select view.internalclass
-                       Case GADGET_DESKTOP,GADGET_WINDOW,GADGET_TOOLBAR,GADGET_LABEL,GADGET_PROGBAR,GADGET_MENUITEM,GADGET_NODE
-                               Return Null
-               End Select
-               Return view
-       End Function
-       
-       Method LinkView()
-               Local   First:TNSGadget
-               Local   prev:TNSGadget
-               Local   i,n
-
-               If Not parent Return
-               If Not ToView(Self) Return
-               n=parent.kids.count()-1
-               If n<0 Return
-' find first view in family
-               For i=0 Until  n
-                       First=ToView(parent.kids.ValueAtIndex(i))
-                       If First Exit
-               Next
-               If Not First Return
-' find last view in family
-               For i=n-1 To 0 Step -1
-                       prev=ToView(parent.kids.ValueAtIndex(i))
-                       If prev Exit
-               Next
-               If Not prev Return
-               NSSetNextView(prev,Self)
-               NSSetNextView(Self,First)
-       End Method
-       
-       Method Delete()
-               Free()
-       End Method
-       
-' generic gadget commands
-
-       Method Query(queryid)
-               Select queryid
-                       Case QUERY_NSVIEW
-                               Return handle
-                       Case QUERY_NSVIEW_CLIENT
-                               Return view
-               End Select                              
-       End Method
-
-       Method Free()
-               If handle Then
-                       
-                       If canvas Then canvas.close
-                       
-                       GadgetMap.Remove TIntWrapper.Create(handle)
-                       If view And handle <> view Then
-                               GadgetMap.Remove TIntWrapper.Create(view)
-                               view = Null
-                       EndIf
-                               
-                       If parent Then
-                               parent.kids.Remove Self
-                       End If
-                       
-                       NSFreeGadget Self
-                       font = Null
-                       
-                       handle = Null
-                       
-               EndIf
-       End Method
-
-       Method Rethink()                        'resize - was recursive
-               NSRethink( Self )
-       End Method
-               
-       Method ClientWidth()
-               Return Max(NSClientWidth(Self),0)
-       End Method
-       
-       Method ClientHeight()
-               Return Max(NSClientHeight(Self),0)
-       End Method
-       
-       Method Activate(cmd)
-               NSActivate( Self, cmd )
-       End Method
-       
-       Method State()
-               Local tmpState:Int = NSState(Self)&~STATE_DISABLED
-               If Not enabled Then tmpState:|STATE_DISABLED
-               Return tmpState
-       End Method
-       
-       Method SetShow(bool)
-               NSShow( Self, bool )
-       End Method
-
-       Method SetText(msg$)
-               If internalclass=GADGET_HTMLVIEW
-                       Local   anchor$,a
-                       a=msg.Find("#")
-                       If a<>-1 anchor=msg[a..];msg=msg[..a]
-                       If msg[0..7].ToLower()<>"http://" And msg[0..7].ToLower()<>"file://"
-                               If FileType(msg)
-                                       msg="file://"+msg
-                               Else
-                                       msg="http://"+msg
-                               EndIf
-                       EndIf
-                       msg:+anchor
-                       msg=msg.Replace(" ","%20")
-               ElseIf internalclass=GADGET_MENUITEM
-                       msg=msg.Replace("&", "")
-               EndIf
-               NSSetText Self,msg
-       End Method
-       
-       Method Run$(msg$)
-               If internalclass=GADGET_HTMLVIEW Return NSRun(Self,msg)
-       End Method
-
-       Method GetText$()
-               Return NSGetText(Self)
-       End Method
-
-       Method SetFont(pFont:TGuiFont)
-               If Not TCocoaGuiFont(pFont) Then pFont = TCocoaMaxGUIDriver.CocoaGuiFont
-               font = TCocoaGuiFont(pFont)
-               intFontStyle = font.style
-               NSSetFont( Self, font.handle )
-       End Method
-
-       Method SetColor(r,g,b)
-               NSSetColor Self,r,g,b
-       End Method
-
-       Method RemoveColor()
-               NSRemoveColor Self
-       End Method
-
-       Method SetAlpha(alpha#)
-               NSSetAlpha Self,alpha
-       End Method
-       
-       Method SetTextColor(r,g,b)
-               NSSetTextColor Self,r,g,b
-       End Method
-       
-       Method SetPixmap(pixmap:TPixmap,flags)
-               Local   nsimage, x
-               If pixmap
-                       Select pixmap.format
-                               Case PF_I8,PF_BGR888
-                                       pixmap=pixmap.Convert( PF_RGB888 )
-                               Case PF_A8,PF_BGRA8888
-                                       pixmap=pixmap.Convert( PF_RGBA8888 )
-                       End Select
-                       
-                       If AlphaBitsPerPixel[ pixmap.format ]
-                               For Local y=0 Until pixmap.height
-                                       For x=0 Until pixmap.width
-                                               Local argb=pixmap.ReadPixel( x,y )
-                                               pixmap.WritePixel x,y,premult(argb)
-                                       Next
-                               Next
-                       EndIf
-                       nsimage=NSPixmapImage(pixmap)
-               EndIf
-               NSSetImage(Self,nsimage,flags)
-       End Method
-       
-       Method SetTooltip(pTip$)
-               Select internalclass
-                       Case GADGET_WINDOW, GADGET_DESKTOP, GADGET_LISTBOX, GADGET_MENUITEM, GADGET_TOOLBAR, GADGET_TABBER, GADGET_NODE
-                       Default;Return NSSetTooltip( Self, pTip )
-               EndSelect
-       EndMethod
-       
-       Method GetTooltip$()
-               Select internalclass
-                       Case GADGET_WINDOW, GADGET_DESKTOP, GADGET_LISTBOX, GADGET_MENUITEM, GADGET_TOOLBAR, GADGET_TABBER, GADGET_NODE
-                       Default;Return NSGetTooltip( Self )
-               EndSelect
-       EndMethod
-       
-       Method ExcludeOthers()
-               For Local g:TNSGadget = EachIn parent.kids
-                       If g<>Self And g.internalclass=GADGET_BUTTON And (g.style&7)=BUTTON_RADIO
-                               NSCheck g,False
-                       EndIf
-               Next
-       End Method
-
-       Method SetSelected(bool)
-               NSCheck Self,bool
-               If internalclass=GADGET_BUTTON And (style&7)=BUTTON_RADIO And bool
-                       ExcludeOthers
-               EndIf
-       End Method
-       
-       Method SetEnabled(enable)
-               Local old:Int = enabled And Not forceDisable
-               enabled = enable
-               If Class() = GADGET_WINDOW Then
-                       NSEnable Self, enable
-               Else
-                       enable = enable And Not forceDisable
-                       NSEnable Self, enable
-                       If (enable <> old) Then
-                               For Local tmpGadget:TNSGadget = EachIn kids
-                                       tmpGadget.forceDisable = Not enable
-                                       If tmpGadget.Class() <> GADGET_WINDOW Then tmpGadget.SetEnabled(tmpGadget.enabled)
-                               Next
-                       EndIf
-               EndIf
-       End Method
-       
-       Method SetHotKey(hotkey,modifier)
-               NSSetHotKey Self,hotkey,modifier
-       End Method
-       
-' window commands
-       
-       Field _statustext$
-       
-       Method GetStatusText$()
-               Return _statustext
-       EndMethod
-       
-       Method SetStatusText(msg$)
-               Local   t,m0$,m1$,m2$
-               _statustext = msg
-               m0=msg
-               t=m0.find("~t");If t<>-1 m1=m0[t+1..];m0=m0[..t];
-               t=m1.find("~t");If t<>-1 m2=m1[t+1..];m1=m1[..t];               
-               NSSetStatus Self,m0,0
-               NSSetStatus Self,m1,1
-               NSSetStatus Self,m2,2
-       End Method
-       
-       Method GetMenu:TGadget()
-               Return Self
-       End Method
-
-       Global popupextra:Object
-       
-       Method PopupMenu(menu:TGadget,extra:Object)
-               popupextra=extra
-               NSPopupMenu Self,TNSGadget(menu)
-       End Method
-       
-       Method UpdateMenu()
-       End Method
-       
-       Method SetMinimumSize(w,h)
-               NSSetMinimumSize Self,w,h
-       End Method
-       
-       Method SetMaximumSize(w,h)
-               NSSetMaximumSize Self,w,h
-       End Method
-
-       Method SetIconStrip(iconstrip:TIconStrip)
-               icons=TCocoaIconStrip(iconstrip)
-       End Method
-
-' item handling commands
-
-       Method ClearListItems()
-               NSClearItems Self
-       End Method
-
-       Method InsertListItem(index,item$,tip$,icon,extra:Object)
-               Local   image
-               If internalclass=GADGET_TOOLBAR
-                       item=name+":"+index
-               EndIf
-               If icons And icon>=0 image=icons.images[icon]
-               NSAddItem Self,index,item,tip,image,extra
-       End Method
-       
-       Method SetListItem(index,item$,tip$,icon,extra:Object)
-               Local   image
-               If internalclass=GADGET_TOOLBAR
-                       item=name+":"+index
-               EndIf
-               If icons And icon>=0 image=icons.images[icon]
-               NSSetItem Self,index,item,tip,image,extra
-       End Method
-       
-       Method RemoveListItem(index)
-               NSRemoveItem Self,index
-       End Method
-       
-       Method SetListItemState(index,state)
-               NSSelectItem Self,index,state
-       End Method
-       
-       Method ListItemState(index)
-               Return NSSelectedItem(Self,index)
-       End Method
-       
-' treeview commands    
-
-       Method RootNode:TGadget()
-               Return Self
-       End Method
-       
-       Method SetIcon(icon)
-               Local   p:TNSGadget
-               p=Self
-               While p
-                       If p.icons Exit
-                       p=TNSGadget(p.parent)
-               Wend
-               If p
-                       If icon>-1
-                               NSSetIcon Self,p.icons.images[icon]             
-                       Else
-                               NSSetIcon Self,Null             
-                       EndIf
-               EndIf                           
-       End Method
-       
-       Method InsertNode:TGadget(index,text$,icon)
-               Local   node:TNSGadget = Create(GADGET_NODE,text,0,0,0,0,Self,index)
-               node.SetIcon icon
-               node._SetParent Self
-               Return node
-       End Method
-       
-       Method ModifyNode(text$,icon)
-               NSSetText Self,text
-               SetIcon icon
-       End Method
-
-       Method SelectedNode:TGadget()
-               Local   index = NSSelectedNode(Self)
-               If (index) Return GadgetFromHandle(index)
-       End Method
-
-       Method CountKids()
-               Return NSCountKids(Self)
-       End Method
-
-' textarea commands
-
-       Method ReplaceText(pos,length,text$,units)
-?debug
-               If pos<0 Or pos+length>AreaLen(units) Throw "Illegal Range"
-?      
-               NSReplaceText Self,pos,length,text$,units
-       End Method
-
-       Method AddText(text$)
-               NSAddText Self,text
-       End Method
-
-       Method AreaText$(pos,length,units)
-?debug
-               If pos<0 Or pos+length>AreaLen(units) Throw "Illegal Range"
-?      
-               Return NSAreaText(Self,pos,length,units)
-       End Method
-
-       Method AreaLen(units)
-               Return NSAreaLen(Self,units)
-       End Method
-
-       Method LockText()
-               NSLockText Self
-       End Method
-
-       Method UnlockText()
-               NSUnlockText Self
-       End Method
-
-       Method SetTabs(tabwidth)
-               NSSetTabs Self,tabwidth
-       End Method
-
-       Method SetMargins(leftmargin)
-               NSSetMargins Self,leftmargin
-       End Method
-
-       Method GetCursorPos(units)
-               Return NSGetCursorPos(Self,units)
-       End Method
-
-       Method GetSelectionLength(units)
-               Return NSGetSelectionLength(Self,units)
-       End Method
-
-       Method SetStyle(r,g,b,flags,pos,length,units)   
-?debug
-               If pos<0 Or pos+length>AreaLen(units) Throw "Illegal Range"
-?      
-               If length NSSetStyle Self,r,g,b,flags,pos,length,units
-       End Method
-
-       Method SetSelection(pos,length,units)
-?debug
-               If pos<0 Or pos+length>AreaLen(units) Throw "Illegal Range"
-?      
-               NSSetSelection Self,pos,length,units
-       End Method
-
-       Method CharAt(line)
-?debug
-               If line<0 Or line>AreaLen(TEXTAREA_LINES) Throw "Parameter Out Of Range"
-?      
-               Return NSCharAt(Self,line)
-       End Method
-
-       Method LineAt(index)
-?debug
-               If index<0 Or index>AreaLen(TEXTAREA_CHARS) Throw "Parameter Out Of Range"
-?      
-               Return NSLineAt(Self,index)
-       End Method
-       
-       Method CharX(char)
-               Return NSCharX(Self,char)
-       EndMethod
-       
-       Method CharY(char)
-               Return NSCharY(Self,char)
-       EndMethod
-       
-' progbar
-       
-       Method SetValue(value#)
-               NSSetValue Self,value
-       End Method
-
-' slider / scrollbar
-
-       Method SetRange(_small,_big)
-               small=_small
-               big=_big
-               NSSetSlider Self,GetProp(),small,big
-       End Method
-       
-       Method SetProp(pos)
-               NSSetSlider Self,pos,small,big
-       End Method
-
-       Method GetProp()
-               Local value:Double = NSGetSlider(Self)
-               If Not (style&(SLIDER_TRACKBAR|SLIDER_STEPPER))
-                       value:*(big-small)
-                       If value>big-small value=big-small
-               EndIf
-               Return Int(value+0.5:Double)
-       End Method
-       
-' canvas
-
-       Method AttachGraphics:TGraphics( flags )
-               canvas=brl.Graphics.AttachGraphics( Query(QUERY_NSVIEW_CLIENT),flags )
-       End Method
-       
-       Method CanvasGraphics:TGraphics()
-               Return canvas
-       End Method
-
-End Type
-
-
-Type TCocoaIconStrip Extends TIconStrip
-       
-       Field images[]
-       
-       Function IsNotBlank(pixmap:TPixmap)
-               Local y, h = pixmap.height
-               Local c = pixmap.ReadPixel(0,0)                         
-               For Local x = 0 Until h
-                       For y = 0 Until h
-                               If pixmap.ReadPixel(x,y)<>c Return True
-                       Next
-               Next
-       End Function
-               
-       Function Create:TCocoaIconStrip(source:Object)
-               Local   icons:TCocoaIconStrip
-               Local   pixmap:TPixmap,pix:TPixmap
-               Local   n,x,w,nsimage
-               pixmap=TPixmap(source)
-               If Not pixmap pixmap=LoadPixmap(source)
-               If Not pixmap Return            
-               Select pixmap.format
-               Case PF_I8,PF_BGR888
-                       pixmap=pixmap.Convert( PF_RGB888 )
-               Case PF_A8,PF_BGRA8888
-                       pixmap=pixmap.Convert( PF_RGBA8888 )
-               End Select
-               
-               If AlphaBitsPerPixel[ pixmap.format ]
-                       For Local y=0 Until pixmap.height
-                               For x=0 Until pixmap.width
-                                       Local argb=pixmap.ReadPixel( x,y )
-                                       pixmap.WritePixel x,y,premult(argb)
-                               Next
-                       Next
-               EndIf
-               
-               n=pixmap.width/pixmap.height;
-               If n=0 Return           
-               icons=New TCocoaIconStrip
-               icons.pixmap=pixmap
-               icons.count=n
-               icons.images=New Int[n]
-               w=pixmap.width/n                        
-               For x=0 Until n
-                       pix=pixmap.Window(x*w,0,w,pixmap.height)
-                       If IsNotBlank(pix) icons.images[x]=NSPixmapImage(pix)
-               Next
-               Return icons
-       EndFunction     
-       
-EndType
-
-Type TCocoaGuiFont Extends TGuiFont
-       
-       Method Delete()
-               If handle Then
-                       NSRelease(handle)
-                       handle = 0
-               EndIf
-       EndMethod
-       
-       Method CharWidth(char)
-               If handle
-                       Return NSCharWidth(handle,char)
-               EndIf
-               Return 0
-       EndMethod 
-               
-EndType
-
-Type TIntWrapper Final
-       Field value:Int
-       Function Create:TIntWrapper(value:Int)
-               Local tmpWrapper:TIntWrapper = New TIntWrapper
-               tmpWrapper.value = value
-               Return tmpWrapper
-       EndFunction
-       Method Compare( o:Object )
-               Local c:TIntWrapper = TIntWrapper(o)
-               If c Then Return (value - c.value)
-               Return Super.Compare(o)
-       EndMethod
-       Method ToString$()
-               Return value
-       EndMethod
-EndType
-
-Private
-
-Function premult(argb)
-       Local a = ((argb Shr 24) & $FF)
-       Return ((((argb&$ff00ff)*a)Shr 8)&$ff00ff)|((((argb&$ff00)*a)Shr 8)&$ff00)|(a Shl 24)
-End Function
+Strict\r
+\r
+Import MaxGUI.MaxGUI\r
+Import Pub.MacOs\r
+\r
+Import "-framework WebKit"\r
+Import "cocoa.macos_tiger.m"\r
+\r
+Extern\r
+       \r
+       Function bbSystemEmitOSEvent( nsevent:Byte Ptr,nsview:Byte Ptr,source:Object )\r
+       \r
+       Function ScheduleEventDispatch()\r
+       \r
+       Function NSBegin()\r
+       Function NSEnd()\r
+       \r
+       Function NSGetSysColor(colorindex,r:Int Ptr,g:Int Ptr, b:Int Ptr)\r
+       Function NSColorRequester(r,g,b)\r
+       Function NSSetPointer(shape)\r
+       \r
+       Function NSCharWidth(font,charcode)\r
+       ' create\r
+       Function NSInitGadget(gadget:TNSGadget)\r
+       ' generic\r
+       Function NSActiveGadget()\r
+       Function NSFreeGadget(gadget:TNSGadget)\r
+       Function NSClientWidth(gadget:TNSGadget)\r
+       Function NSClientHeight(gadget:TNSGadget)\r
+       Function NSRethink(gadget:TNSGadget)\r
+       Function NSRedraw(gadget:TNSGadget)\r
+       Function NSActivate(gadget:TNSGadget,code)\r
+       Function NSState(gadget:TNSGadget)\r
+       Function NSShow(gadget:TNSGadget,bool)\r
+       Function NSEnable(gadget:TNSGadget,bool)\r
+       Function NSCheck(gadget:TNSGadget,bool)\r
+       Function NSSetNextView(gadget:TNSGadget,nextgadget:TNSGadget)\r
+       Function NSSetHotKey(gadget:TNSGadget,hotkey,modifier)\r
+       Function NSSetTooltip(gadget:TNSGadget,tip$)\r
+       Function NSGetTooltip$(gadget:TNSGadget)\r
+       Function NSSuperview(view:Int)\r
+       ' window\r
+       Function NSSetStatus(gadget:TNSGadget,text$,pos)\r
+       Function NSSetMinimumSize(gadget:TNSGadget,width,height)\r
+       Function NSSetMaximumSize(gadget:TNSGadget,width,height)\r
+       Function NSPopupMenu(gadget:TNSGadget,menu:TNSGadget)\r
+       ' font\r
+       Function NSRequestFont(font)\r
+       Function NSLoadFont(name$,size:Double,flags)\r
+       Function NSGetDefaultFont()\r
+       Function NSSetFont(gadget:TNSGadget,font)\r
+       Function NSFontName$(font)\r
+       Function NSFontStyle(font)\r
+       Function NSFontSize:Double(font)\r
+       ' items\r
+       Function NSClearItems(gadget:TNSGadget)\r
+       Function NSAddItem(gadget:TNSGadget,index,text$,tip$,image,extra:Object)\r
+       Function NSSetItem(gadget:TNSGadget,index,text$,tip$,image,extra:Object)\r
+       Function NSRemoveItem(gadget:TNSGadget,index)\r
+       Function NSSelectItem(gadget:TNSGadget,index,state)\r
+       Function NSSelectedItem(gadget:TNSGadget,index)\r
+       Function NSSelectedNode(gadget:TNSGadget)\r
+       ' text\r
+       Function NSSetText(gadget:TNSGadget,text$)\r
+       Function NSGetText$(gadget:TNSGadget)\r
+       Function NSReplaceText(gadget:TNSGadget,pos,length,text$,units)\r
+       Function NSAddText(gadget:TNSGadget,text$)\r
+       Function NSAreaText$(gadget:TNSGadget,pos,length,units)\r
+       Function NSAreaLen(gadget:TNSGadget,units)\r
+       Function NSLockText(gadget:TNSGadget)\r
+       Function NSUnlockText(gadget:TNSGadget)\r
+       Function NSSetTabs(gadget:TNSGadget,tabwidth)\r
+       Function NSSetMargins(gadget:TNSGadget,leftmargin)\r
+       Function NSSetColor(gadget:TNSGadget,r,g,b)\r
+       Function NSRemoveColor(gadget:TNSGadget)\r
+       Function NSSetAlpha(gadget:TNSGadget,alpha#)\r
+       Function NSSetTextColor(gadget:TNSGadget,r,g,b)\r
+       Function NSGetCursorPos(gadget:TNSGadget,units)\r
+       Function NSGetSelectionlength(gadget:TNSGadget,units)\r
+       Function NSSetStyle(gadget:TNSGadget,r,g,b,flags,pos,length,units)      \r
+       Function NSSetSelection(gadget:TNSGadget,pos,length,units)\r
+       Function NSCharAt(gadget:TNSGadget,line)\r
+       Function NSLineAt(gadget:TNSGadget,index)\r
+       Function NSCharX(gadget:TGadget,char)\r
+       Function NSCharY(gadget:TGadget,char)\r
+       ' prop\r
+       Function NSSetValue(gadget:TNSGadget,value#)\r
+       ' slider\r
+       Function NSSetSlider(gadget:TNSGadget,value:Double,small:Double,big:Double)\r
+       Function NSGetSlider:Double(gadget:TNSGadget)\r
+       ' images for panels and nodes\r
+       Function NSPixmapImage(image:TPixmap)\r
+       Function NSSetImage(gadget:TNSGadget,nsimage,flags)\r
+       Function NSSetIcon(gadget:TNSGadget,nsimage)\r
+       Function NSCountKids(gadget:TNSGadget)\r
+       ' html\r
+       Function NSRun$(gadget:TNSGadget,script$)\r
+       ' misc\r
+       Function NSRelease(nsobject)\r
+       ' system\r
+       Function NSGetUserName$()\r
+       Function NSGetComputerName$()\r
+       \r
+EndExtern\r
+\r
+Global GadgetMap:TMap=New TMap\r
+\r
+maxgui_driver=New TCocoaMaxGuiDriver\r
+\r
+Type TCocoaMaxGUIDriver Extends TMaxGUIDriver\r
+       \r
+       Global CocoaGuiFont:TCocoaGuiFont\r
+       \r
+       Method New()\r
+               NSBegin\r
+               atexit_ NSEnd\r
+               If Not CocoaGuiFont Then CocoaGuiFont = TCocoaGuiFont(LibraryFont(GUIFONT_SYSTEM))\r
+       End Method\r
+       \r
+       Method UserName$()\r
+               Return NSGetUserName$()\r
+       End Method\r
+       \r
+       Method ComputerName$()\r
+               Return NSGetComputerName$()\r
+       End Method\r
+               \r
+       Method CreateGadget:TGadget(internalclass,name$,x,y,w,h,group:TGadget,style)\r
+               Local p,hotkey\r
+               If internalclass=GADGET_MENUITEM\r
+                       name=name.Replace("&","")\r
+               ElseIf internalclass=GADGET_BUTTON\r
+                       p=name.Find("&")\r
+                       If p>-1\r
+'                              hotkey=Asc(name[p..p+1]) 'to do - convert and call SetHotKey before return\r
+                               name=name[..p]+name[p+1..]\r
+                       EndIf\r
+               ElseIf internalclass=GADGET_TOOLBAR\r
+                       Global _toolbarcount\r
+                       _toolbarcount:+1\r
+                       name="Toolbar"+_toolbarcount\r
+               EndIf\r
+               Local gadget:TNSGadget = TNSGadget.Create(internalclass,name,x,y,w,h,TNSGadget(group),style)\r
+               If internalclass<>GADGET_WINDOW And internalclass<>GADGET_MENUITEM And internalclass<>GADGET_DESKTOP\r
+                       gadget.SetLayout EDGE_CENTERED,EDGE_CENTERED,EDGE_CENTERED,EDGE_CENTERED\r
+               EndIf\r
+               If group Then gadget._SetParent group\r
+               gadget.SetTextColor(0,0,0)\r
+               gadget.LinkView\r
+               Return gadget   \r
+       End Method\r
+               \r
+       Function CreateFont:TGuiFont(handle,flags=FONT_NORMAL)\r
+               Local font:TGuiFont = New TCocoaGuiFont\r
+               font.handle = handle\r
+               font.name = NSFontName(handle)\r
+               font.size = NSFontSize(handle)\r
+               font.style = NSFontStyle(handle)|flags\r
+               Return font\r
+       EndFunction\r
+\r
+       Method LoadFont:TGuiFont(name$,size,flags)\r
+               Return CreateFont(NSLoadFont(name,Double(size),flags),flags)\r
+       End Method\r
+       \r
+       Method LoadFontWithDouble:TGuiFont(name$,size:Double,flags)\r
+               Return CreateFont(NSLoadFont(name,size,flags),flags)\r
+       End Method\r
+       \r
+       Method LibraryFont:TGuiFont( pFontType% = GUIFONT_SYSTEM, pFontSize:Double = 0, pFontStyle% = FONT_NORMAL )\r
+               If pFontType = GUIFONT_SYSTEM Then\r
+                       Local tmpHandle% = NSGetDefaultFont()\r
+                       If pFontSize <= 0 Then pFontSize = NSFontSize(tmpHandle)\r
+                       Return LoadFontWithDouble( NSFontName(tmpHandle), pFontSize, NSFontStyle(tmpHandle)|pFontStyle )\r
+               Else\r
+                       Return Super.LibraryFont( pFontType, pFontSize, pFontStyle )\r
+               EndIf\r
+       EndMethod\r
+       \r
+       Method LookupColor( colorindex:Int, red:Byte Var, green:Byte Var, blue:Byte Var )\r
+               \r
+               Local r, g, b\r
+               \r
+               If NSGetSysColor( colorindex, Varptr r, Varptr g, Varptr b )\r
+                       red = r & $FF\r
+                       green = g & $FF\r
+                       blue = b & $FF\r
+                       Return True\r
+               EndIf\r
+               \r
+               Return Super.LookupColor( colorindex, red, green, blue )\r
+                               \r
+       EndMethod\r
+       \r
+       Method RequestColor(r,g,b)\r
+               Return NSColorRequester(r,g,b)\r
+       End Method\r
+       \r
+       Method RequestFont:TGuiFont(font:TGuiFont)\r
+               Local   handle\r
+               If font handle=font.handle\r
+               handle=NSRequestFont(handle)\r
+               If handle\r
+                       If font And handle=font.handle Return font\r
+                       Return CreateFont(handle)\r
+               EndIf\r
+       End Method\r
+       \r
+       Method SetPointer(shape)\r
+               NSSetPointer shape\r
+       End Method              \r
+       \r
+       Method ActiveGadget:TGadget()\r
+               PollSystem()\r
+               Local handle = NSActiveGadget()\r
+               If handle Return GadgetFromHandle(handle)\r
+       End Method\r
+       \r
+       Method LoadIconStrip:TIconStrip(source:Object)\r
+               Return TCocoaIconStrip.Create(source)\r
+       End Method\r
+End Type\r
+\r
+Function GadgetFromHandle:TNSGadget( handle )\r
+       Return TNSGadget( GadgetMap.ValueForKey( TIntWrapper.Create(handle) ) )\r
+End Function\r
+\r
+Function EmitCocoaOSEvent( event:Byte Ptr,handle,gadget:Object = Null )\r
+       Local owner:TGadget = TGadget(gadget)\r
+       If Not owner Then owner = GadgetFromHandle( handle )\r
+       If owner Then\r
+               While owner.source\r
+                       owner = owner.source\r
+               Wend\r
+       EndIf\r
+       bbSystemEmitOSEvent event,Byte Ptr(handle),owner\r
+End Function\r
+\r
+Function EmitCocoaMouseEvent( event:Byte Ptr, handle )\r
+       Local gadget:TNSGadget\r
+'      While handle\r
+               gadget = GadgetFromHandle( handle )\r
+               If gadget Then\r
+                       If (gadget.sensitivity & SENSITIZE_MOUSE) Then\r
+                               EmitCocoaOSEvent( event, handle, gadget )\r
+                               Return 1\r
+                       EndIf\r
+                       Return 0\r
+               EndIf\r
+'              handle = NSSuperview(handle)\r
+'      Wend\r
+End Function\r
+\r
+Function EmitCocoaKeyEvent( event:Byte Ptr, handle )\r
+       Local gadget:TNSGadget\r
+       While handle\r
+               gadget = GadgetFromHandle( handle )\r
+               If gadget Then\r
+                       If (gadget.sensitivity & SENSITIZE_KEYS) Then\r
+                               EmitCocoaOSEvent( event, handle, gadget )\r
+                               Return 1\r
+                       EndIf\r
+                       Return 0\r
+               EndIf\r
+               handle = NSSuperview(handle)\r
+       Wend\r
+End Function\r
+\r
+Function PostCocoaGuiEvent( id,handle,data,mods,x,y,extra:Object )\r
+       \r
+       Local gadget:TNSGadget\r
+       \r
+       DispatchGuiEvents()\r
+       \r
+       If handle Then\r
+               \r
+               gadget = GadgetFromHandle(handle)\r
+               \r
+               If gadget Then\r
+                       \r
+                       Select gadget.internalclass\r
+                               Case GADGET_TREEVIEW\r
+                                       extra=GadgetFromHandle(data)\r
+                                       data = 0\r
+                       EndSelect\r
+                       \r
+                       Select id\r
+                               Case EVENT_WINDOWSIZE\r
+                                       If gadget.width <> x Or gadget.height <> y Then\r
+                                               gadget.SetRect gadget.xpos,gadget.ypos,x,y\r
+                                               gadget.LayoutKids\r
+                                       Else\r
+                                               Return\r
+                                       EndIf\r
+                                       \r
+                               Case EVENT_WINDOWMOVE\r
+                                       If gadget.xpos <> x Or gadget.ypos <> y Then\r
+                                               gadget.SetRect x,y,gadget.width,gadget.height\r
+                                       Else\r
+                                               Return\r
+                                       EndIf\r
+                                       \r
+                               Case EVENT_MENUACTION\r
+                                       extra=TNSGadget.popupextra\r
+                                       TNSGadget.popupextra=Null\r
+                                       \r
+                               Case EVENT_GADGETACTION\r
+                                       \r
+                                       Select gadget.internalclass\r
+                                               Case GADGET_SLIDER\r
+                                                       Local oldValue:Int = gadget.GetProp()\r
+                                                       If data Then\r
+                                                               Select (gadget.style&(SLIDER_SCROLLBAR|SLIDER_TRACKBAR|SLIDER_STEPPER))\r
+                                                                       Case SLIDER_SCROLLBAR\r
+                                                                               If data > 1 Then\r
+                                                                                       data = gadget.small\r
+                                                                               ElseIf data < -1 Then\r
+                                                                                       data = -gadget.small\r
+                                                                               EndIf\r
+                                                               EndSelect\r
+                                                               gadget.SetProp(oldValue+data)\r
+                                                               data=gadget.GetProp()\r
+                                                               If (data = oldValue) Then Return\r
+                                                       Else\r
+                                                               data=gadget.GetProp()\r
+                                                       EndIf\r
+                                               Case GADGET_LISTBOX, GADGET_COMBOBOX, GADGET_TABBER\r
+                                                       If (data > -1 And data < gadget.items.length) extra=gadget.ItemExtra(data)\r
+                                               Case GADGET_BUTTON\r
+                                                       Select (gadget.style&7)\r
+                                                               Case BUTTON_CHECKBOX\r
+                                                                       If ButtonState(gadget) = CHECK_INDETERMINATE Then SetButtonState(gadget, CHECK_SELECTED )\r
+                                                               Case BUTTON_RADIO\r
+                                                                       If (gadget.style&BUTTON_PUSH) Then SetButtonState(gadget,CHECK_SELECTED)\r
+                                                                       gadget.ExcludeOthers()\r
+                                                       EndSelect\r
+                                                       data=ButtonState(gadget)\r
+                                               Case GADGET_TOOLBAR\r
+                                                       If data>-1 Then\r
+                                                               extra=gadget.ItemExtra(data)\r
+                                                               If (gadget.ItemFlags(data)&GADGETITEM_TOGGLE) Then gadget.SelectItem(data,2)\r
+                                                       EndIf\r
+                                       EndSelect\r
+                                       \r
+                               Case EVENT_GADGETSELECT, EVENT_GADGETMENU\r
+                                       Select gadget.internalclass\r
+                                               Case GADGET_LISTBOX, GADGET_COMBOBOX, GADGET_TABBER\r
+                                                       If data>-1 Then extra=gadget.ItemExtra(data)\r
+                                       EndSelect\r
+                                       \r
+                               Case EVENT_GADGETLOSTFOCUS\r
+                               \r
+                                       QueueGuiEvent id,gadget,data,mods,x,y,extra\r
+                                       ScheduleEventDispatch()\r
+                                       Return\r
+                                       \r
+                       EndSelect\r
+               EndIf\r
+       \r
+       EndIf\r
+       \r
+       PostGuiEvent id,gadget,data,mods,x,y,extra\r
+       \r
+EndFunction\r
+\r
+Function FilterKeyDown( handle,key,mods )\r
+       Local source:TNSGadget\r
+       If handle\r
+               source=GadgetFromHandle(handle)\r
+       EndIf\r
+       If source And source.eventfilter<>Null\r
+               Local event:TEvent=CreateEvent(EVENT_KEYDOWN,source,key,mods)\r
+               Return source.eventfilter(event,source.context)\r
+       EndIf\r
+       Return 1\r
+End Function\r
+\r
+Function FilterChar( handle,key,mods )\r
+       Local source:TNSGadget\r
+       Select key\r
+               ' Return true if they are arrow key characters\r
+               Case 63232, 63233, 63234, 63235\r
+                       Return 1\r
+       EndSelect\r
+       If handle\r
+               source=GadgetFromHandle(handle)\r
+       EndIf\r
+       If source And source.eventfilter<>Null 'Return source.charfilter(char,mods,source.context)\r
+               Local event:TEvent=CreateEvent(EVENT_KEYCHAR,source,key,mods)\r
+               Return source.eventfilter(event,source.context)\r
+       EndIf\r
+       Return 1\r
+End Function\r
+\r
+Type TNSGadget Extends TGadget\r
+       \r
+       Field internalclass, origclass  'internalclass: Class the Cocoa driver uses to draw the gadget, origclass: Expected class to be returned by Class() method\r
+       Field handle\r
+       Field view, textcolor   'view: NSView handle, textcolor: NSColor handle for Objective-C code\r
+       Field intFontStyle      'Copy of font.style used by cocoa.macos.m to handle underlining/strikethrough etc. that isn't included in NSFont\r
+       Field pixmap:TPixmap\r
+       Field icons:TCocoaIconStrip\r
+       Field small, big\r
+       Field canvas:TGraphics\r
+       Field font:TCocoaGuiFont\r
+       Field enabled:Int = True, forceDisable:Int = False\r
+\r
+' main factory command\r
+\r
+       Function Create:TNSGadget(internalclass,text$,x,y,w,h,group:TGadget,style)\r
+               \r
+               Local gadget:TNSGadget = New TNSGadget\r
+               gadget.origclass = internalclass\r
+               gadget.internalclass = internalclass\r
+               \r
+               If Not group And internalclass<>GADGET_DESKTOP Then group = Desktop()\r
+               gadget.parent = group\r
+               \r
+               gadget.name = text\r
+               gadget.SetRect x,y,w,h  'setarea\r
+               gadget.style = style\r
+               gadget.font = TCocoaMaxGUIDriver.CocoaGUIFont\r
+               \r
+               If TNSGadget(group) Then\r
+                       gadget.forceDisable = Not (TNSGadget(group).enabled And Not TNSGadget(group).forceDisable)\r
+               EndIf\r
+               \r
+               NSInitGadget gadget\r
+\r
+               If internalclass<>GADGET_TOOLBAR 'toolbars retain name to key insertgadgetitem\r
+                       gadget.name = Null\r
+               EndIf\r
+               \r
+               GadgetMap.Insert TIntWrapper.Create(gadget.handle),gadget\r
+               If gadget.view And gadget.handle <> gadget.view Then\r
+                       GadgetMap.Insert TIntWrapper.Create(gadget.view),gadget\r
+               EndIf\r
+               \r
+               If internalclass=GADGET_SLIDER Then gadget.SetRange(1,10)\r
+               gadget.LockLayout()\r
+               \r
+               If (internalclass=GADGET_WINDOW) And (style&WINDOW_STATUS) Then\r
+                       If (style&WINDOW_CLIENTCOORDS) Then\r
+                               gadget.SetMinimumSize(25,0)\r
+                       Else\r
+                               gadget.SetMinimumSize(25,70)\r
+                       EndIf\r
+               EndIf\r
+               \r
+               If LocalizationMode() & LOCALIZATION_OVERRIDE Then LocalizeGadget(gadget,text,"")\r
+               \r
+               gadget.SetEnabled(gadget.enabled)\r
+               \r
+               Return gadget\r
+               \r
+       End Function\r
+       \r
+       Method Class()\r
+               Return origclass\r
+       EndMethod\r
+       \r
+       Function ToView:TNSGadget(value:Object)\r
+               Local   view:TNSGadget = TNSGadget(value)\r
+               If Not view Return\r
+               Select view.internalclass\r
+                       Case GADGET_DESKTOP,GADGET_WINDOW,GADGET_TOOLBAR,GADGET_LABEL,GADGET_PROGBAR,GADGET_MENUITEM,GADGET_NODE\r
+                               Return Null\r
+               End Select\r
+               Return view\r
+       End Function\r
+       \r
+       Method LinkView()\r
+               Local   First:TNSGadget\r
+               Local   prev:TNSGadget\r
+               Local   i,n\r
+\r
+               If Not parent Return\r
+               If Not ToView(Self) Return\r
+               n=parent.kids.count()-1\r
+               If n<0 Return\r
+' find first view in family\r
+               For i=0 Until  n\r
+                       First=ToView(parent.kids.ValueAtIndex(i))\r
+                       If First Exit\r
+               Next\r
+               If Not First Return\r
+' find last view in family\r
+               For i=n-1 To 0 Step -1\r
+                       prev=ToView(parent.kids.ValueAtIndex(i))\r
+                       If prev Exit\r
+               Next\r
+               If Not prev Return\r
+               NSSetNextView(prev,Self)\r
+               NSSetNextView(Self,First)\r
+       End Method\r
+       \r
+       Method Delete()\r
+               Free()\r
+       End Method\r
+       \r
+' generic gadget commands\r
+\r
+       Method Query(queryid)\r
+               Select queryid\r
+                       Case QUERY_NSVIEW\r
+                               Return handle\r
+                       Case QUERY_NSVIEW_CLIENT\r
+                               Return view\r
+               End Select                              \r
+       End Method\r
+\r
+       Method Free()\r
+               If handle Then\r
+                       \r
+                       If canvas Then canvas.close\r
+                       \r
+                       GadgetMap.Remove TIntWrapper.Create(handle)\r
+                       If view And handle <> view Then\r
+                               GadgetMap.Remove TIntWrapper.Create(view)\r
+                               view = Null\r
+                       EndIf\r
+                               \r
+                       If parent Then\r
+                               parent.kids.Remove Self\r
+                       End If\r
+                       \r
+                       NSFreeGadget Self\r
+                       font = Null\r
+                       \r
+                       handle = Null\r
+                       \r
+               EndIf\r
+       End Method\r
+\r
+       Method Rethink()                        'resize - was recursive\r
+               NSRethink( Self )\r
+       End Method\r
+               \r
+       Method ClientWidth()\r
+               Return Max(NSClientWidth(Self),0)\r
+       End Method\r
+       \r
+       Method ClientHeight()\r
+               Return Max(NSClientHeight(Self),0)\r
+       End Method\r
+       \r
+       Method Activate(cmd)\r
+               NSActivate( Self, cmd )\r
+       End Method\r
+       \r
+       Method State()\r
+               Local tmpState:Int = NSState(Self)&~STATE_DISABLED\r
+               If Not enabled Then tmpState:|STATE_DISABLED\r
+               Return tmpState\r
+       End Method\r
+       \r
+       Method SetShow(bool)\r
+               NSShow( Self, bool )\r
+       End Method\r
+\r
+       Method SetText(msg$)\r
+               If internalclass=GADGET_HTMLVIEW\r
+                       Local   anchor$,a\r
+                       a=msg.Find("#")\r
+                       If a<>-1 anchor=msg[a..];msg=msg[..a]\r
+                       If msg[0..7].ToLower()<>"http://" And msg[0..7].ToLower()<>"file://"\r
+                               If FileType(msg)\r
+                                       msg="file://"+msg\r
+                               Else\r
+                                       msg="http://"+msg\r
+                               EndIf\r
+                       EndIf\r
+                       msg:+anchor\r
+                       msg=msg.Replace(" ","%20")\r
+               ElseIf internalclass=GADGET_MENUITEM\r
+                       msg=msg.Replace("&", "")\r
+               EndIf\r
+               NSSetText Self,msg\r
+       End Method\r
+       \r
+       Method Run$(msg$)\r
+               If internalclass=GADGET_HTMLVIEW Return NSRun(Self,msg)\r
+       End Method\r
+\r
+       Method GetText$()\r
+               Return NSGetText(Self)\r
+       End Method\r
+\r
+       Method SetFont(pFont:TGuiFont)\r
+               If Not TCocoaGuiFont(pFont) Then pFont = TCocoaMaxGUIDriver.CocoaGuiFont\r
+               font = TCocoaGuiFont(pFont)\r
+               intFontStyle = font.style\r
+               NSSetFont( Self, font.handle )\r
+       End Method\r
+\r
+       Method SetColor(r,g,b)\r
+               NSSetColor Self,r,g,b\r
+       End Method\r
+\r
+       Method RemoveColor()\r
+               NSRemoveColor Self\r
+       End Method\r
+\r
+       Method SetAlpha(alpha#)\r
+               NSSetAlpha Self,alpha\r
+       End Method\r
+       \r
+       Method SetTextColor(r,g,b)\r
+               NSSetTextColor Self,r,g,b\r
+       End Method\r
+       \r
+       Method SetPixmap(pixmap:TPixmap,flags)\r
+               Local   nsimage, x\r
+               If pixmap\r
+                       Select pixmap.format\r
+                               Case PF_I8,PF_BGR888\r
+                                       pixmap=pixmap.Convert( PF_RGB888 )\r
+                               Case PF_A8,PF_BGRA8888\r
+                                       pixmap=pixmap.Convert( PF_RGBA8888 )\r
+                       End Select\r
+                       \r
+                       If AlphaBitsPerPixel[ pixmap.format ]\r
+                               For Local y=0 Until pixmap.height\r
+                                       For x=0 Until pixmap.width\r
+                                               Local argb=pixmap.ReadPixel( x,y )\r
+                                               pixmap.WritePixel x,y,premult(argb)\r
+                                       Next\r
+                               Next\r
+                       EndIf\r
+                       nsimage=NSPixmapImage(pixmap)\r
+               EndIf\r
+               NSSetImage(Self,nsimage,flags)\r
+       End Method\r
+       \r
+       Method SetTooltip(pTip$)\r
+               Select internalclass\r
+                       Case GADGET_WINDOW, GADGET_DESKTOP, GADGET_LISTBOX, GADGET_MENUITEM, GADGET_TOOLBAR, GADGET_TABBER, GADGET_NODE\r
+                       Default;Return NSSetTooltip( Self, pTip )\r
+               EndSelect\r
+       EndMethod\r
+       \r
+       Method GetTooltip$()\r
+               Select internalclass\r
+                       Case GADGET_WINDOW, GADGET_DESKTOP, GADGET_LISTBOX, GADGET_MENUITEM, GADGET_TOOLBAR, GADGET_TABBER, GADGET_NODE\r
+                       Default;Return NSGetTooltip( Self )\r
+               EndSelect\r
+       EndMethod\r
+       \r
+       Method ExcludeOthers()\r
+               For Local g:TNSGadget = EachIn parent.kids\r
+                       If g<>Self And g.internalclass=GADGET_BUTTON And (g.style&7)=BUTTON_RADIO\r
+                               NSCheck g,False\r
+                       EndIf\r
+               Next\r
+       End Method\r
+\r
+       Method SetSelected(bool)\r
+               NSCheck Self,bool\r
+               If internalclass=GADGET_BUTTON And (style&7)=BUTTON_RADIO And bool\r
+                       ExcludeOthers\r
+               EndIf\r
+       End Method\r
+       \r
+       Method SetEnabled(enable)\r
+               Local old:Int = enabled And Not forceDisable\r
+               enabled = enable\r
+               If Class() = GADGET_WINDOW Then\r
+                       NSEnable Self, enable\r
+               Else\r
+                       enable = enable And Not forceDisable\r
+                       NSEnable Self, enable\r
+                       If (enable <> old) Then\r
+                               For Local tmpGadget:TNSGadget = EachIn kids\r
+                                       tmpGadget.forceDisable = Not enable\r
+                                       If tmpGadget.Class() <> GADGET_WINDOW Then tmpGadget.SetEnabled(tmpGadget.enabled)\r
+                               Next\r
+                       EndIf\r
+               EndIf\r
+       End Method\r
+       \r
+       Method SetHotKey(hotkey,modifier)\r
+               NSSetHotKey Self,hotkey,modifier\r
+       End Method\r
+       \r
+' window commands\r
+       \r
+       Field _statustext$\r
+       \r
+       Method GetStatusText$()\r
+               Return _statustext\r
+       EndMethod\r
+       \r
+       Method SetStatusText(msg$)\r
+               Local   t,m0$,m1$,m2$\r
+               _statustext = msg\r
+               m0=msg\r
+               t=m0.find("~t");If t<>-1 m1=m0[t+1..];m0=m0[..t];\r
+               t=m1.find("~t");If t<>-1 m2=m1[t+1..];m1=m1[..t];               \r
+               NSSetStatus Self,m0,0\r
+               NSSetStatus Self,m1,1\r
+               NSSetStatus Self,m2,2\r
+       End Method\r
+       \r
+       Method GetMenu:TGadget()\r
+               Return Self\r
+       End Method\r
+\r
+       Global popupextra:Object\r
+       \r
+       Method PopupMenu(menu:TGadget,extra:Object)\r
+               popupextra=extra\r
+               NSPopupMenu Self,TNSGadget(menu)\r
+       End Method\r
+       \r
+       Method UpdateMenu()\r
+       End Method\r
+       \r
+       Method SetMinimumSize(w,h)\r
+               NSSetMinimumSize Self,w,h\r
+       End Method\r
+       \r
+       Method SetMaximumSize(w,h)\r
+               NSSetMaximumSize Self,w,h\r
+       End Method\r
+\r
+       Method SetIconStrip(iconstrip:TIconStrip)\r
+               icons=TCocoaIconStrip(iconstrip)\r
+       End Method\r
+\r
+' item handling commands\r
+\r
+       Method ClearListItems()\r
+               NSClearItems Self\r
+       End Method\r
+\r
+       Method InsertListItem(index,item$,tip$,icon,extra:Object)\r
+               Local   image\r
+               If internalclass=GADGET_TOOLBAR\r
+                       item=name+":"+index\r
+               EndIf\r
+               If icons And icon>=0 image=icons.images[icon]\r
+               NSAddItem Self,index,item,tip,image,extra\r
+       End Method\r
+       \r
+       Method SetListItem(index,item$,tip$,icon,extra:Object)\r
+               Local   image\r
+               If internalclass=GADGET_TOOLBAR\r
+                       item=name+":"+index\r
+               EndIf\r
+               If icons And icon>=0 image=icons.images[icon]\r
+               NSSetItem Self,index,item,tip,image,extra\r
+       End Method\r
+       \r
+       Method RemoveListItem(index)\r
+               NSRemoveItem Self,index\r
+       End Method\r
+       \r
+       Method SetListItemState(index,state)\r
+               NSSelectItem Self,index,state\r
+       End Method\r
+       \r
+       Method ListItemState(index)\r
+               Return NSSelectedItem(Self,index)\r
+       End Method\r
+       \r
+' treeview commands    \r
+\r
+       Method RootNode:TGadget()\r
+               Return Self\r
+       End Method\r
+       \r
+       Method SetIcon(icon)\r
+               Local   p:TNSGadget\r
+               p=Self\r
+               While p\r
+                       If p.icons Exit\r
+                       p=TNSGadget(p.parent)\r
+               Wend\r
+               If p\r
+                       If icon>-1\r
+                               NSSetIcon Self,p.icons.images[icon]             \r
+                       Else\r
+                               NSSetIcon Self,Null             \r
+                       EndIf\r
+               EndIf                           \r
+       End Method\r
+       \r
+       Method InsertNode:TGadget(index,text$,icon)\r
+               Local   node:TNSGadget = Create(GADGET_NODE,text,0,0,0,0,Self,index)\r
+               node.SetIcon icon\r
+               node._SetParent Self\r
+               Return node\r
+       End Method\r
+       \r
+       Method ModifyNode(text$,icon)\r
+               NSSetText Self,text\r
+               SetIcon icon\r
+       End Method\r
+\r
+       Method SelectedNode:TGadget()\r
+               Local   index = NSSelectedNode(Self)\r
+               If (index) Return GadgetFromHandle(index)\r
+       End Method\r
+\r
+       Method CountKids()\r
+               Return NSCountKids(Self)\r
+       End Method\r
+\r
+' textarea commands\r
+\r
+       Method ReplaceText(pos,length,text$,units)\r
+?debug\r
+               If pos<0 Or pos+length>AreaLen(units) Throw "Illegal Range"\r
+?      \r
+               NSReplaceText Self,pos,length,text$,units\r
+       End Method\r
+\r
+       Method AddText(text$)\r
+               NSAddText Self,text\r
+       End Method\r
+\r
+       Method AreaText$(pos,length,units)\r
+?debug\r
+               If pos<0 Or pos+length>AreaLen(units) Throw "Illegal Range"\r
+?      \r
+               Return NSAreaText(Self,pos,length,units)\r
+       End Method\r
+\r
+       Method AreaLen(units)\r
+               Return NSAreaLen(Self,units)\r
+       End Method\r
+\r
+       Method LockText()\r
+               NSLockText Self\r
+       End Method\r
+\r
+       Method UnlockText()\r
+               NSUnlockText Self\r
+       End Method\r
+\r
+       Method SetTabs(tabwidth)\r
+               NSSetTabs Self,tabwidth\r
+       End Method\r
+\r
+       Method SetMargins(leftmargin)\r
+               NSSetMargins Self,leftmargin\r
+       End Method\r
+\r
+       Method GetCursorPos(units)\r
+               Return NSGetCursorPos(Self,units)\r
+       End Method\r
+\r
+       Method GetSelectionLength(units)\r
+               Return NSGetSelectionLength(Self,units)\r
+       End Method\r
+\r
+       Method SetStyle(r,g,b,flags,pos,length,units)   \r
+?debug\r
+               If pos<0 Or pos+length>AreaLen(units) Throw "Illegal Range"\r
+?      \r
+               If length NSSetStyle Self,r,g,b,flags,pos,length,units\r
+       End Method\r
+\r
+       Method SetSelection(pos,length,units)\r
+?debug\r
+               If pos<0 Or pos+length>AreaLen(units) Throw "Illegal Range"\r
+?      \r
+               NSSetSelection Self,pos,length,units\r
+       End Method\r
+\r
+       Method CharAt(line)\r
+?debug\r
+               If line<0 Or line>AreaLen(TEXTAREA_LINES) Throw "Parameter Out Of Range"\r
+?      \r
+               Return NSCharAt(Self,line)\r
+       End Method\r
+\r
+       Method LineAt(index)\r
+?debug\r
+               If index<0 Or index>AreaLen(TEXTAREA_CHARS) Throw "Parameter Out Of Range"\r
+?      \r
+               Return NSLineAt(Self,index)\r
+       End Method\r
+       \r
+       Method CharX(char)\r
+               Return NSCharX(Self,char)\r
+       EndMethod\r
+       \r
+       Method CharY(char)\r
+               Return NSCharY(Self,char)\r
+       EndMethod\r
+       \r
+' progbar\r
+       \r
+       Method SetValue(value#)\r
+               NSSetValue Self,value\r
+       End Method\r
+\r
+' slider / scrollbar\r
+\r
+       Method SetRange(_small,_big)\r
+               small=_small\r
+               big=_big\r
+               NSSetSlider Self,GetProp(),small,big\r
+       End Method\r
+       \r
+       Method SetProp(pos)\r
+               NSSetSlider Self,pos,small,big\r
+       End Method\r
+\r
+       Method GetProp()\r
+               Local value:Double = NSGetSlider(Self)\r
+               If Not (style&(SLIDER_TRACKBAR|SLIDER_STEPPER))\r
+                       value:*(big-small)\r
+                       If value>big-small value=big-small\r
+               EndIf\r
+               Return Int(value+0.5:Double)\r
+       End Method\r
+       \r
+' canvas\r
+\r
+       Method AttachGraphics:TGraphics( flags )\r
+               canvas=brl.Graphics.AttachGraphics( Query(QUERY_NSVIEW_CLIENT),flags )\r
+       End Method\r
+       \r
+       Method CanvasGraphics:TGraphics()\r
+               Return canvas\r
+       End Method\r
+\r
+End Type\r
+\r
+\r
+Type TCocoaIconStrip Extends TIconStrip\r
+       \r
+       Field images[]\r
+       \r
+       Function IsNotBlank(pixmap:TPixmap)\r
+               Local y, h = pixmap.height\r
+               Local c = pixmap.ReadPixel(0,0)                         \r
+               For Local x = 0 Until h\r
+                       For y = 0 Until h\r
+                               If pixmap.ReadPixel(x,y)<>c Return True\r
+                       Next\r
+               Next\r
+       End Function\r
+               \r
+       Function Create:TCocoaIconStrip(source:Object)\r
+               Local   icons:TCocoaIconStrip\r
+               Local   pixmap:TPixmap,pix:TPixmap\r
+               Local   n,x,w,nsimage\r
+               pixmap=TPixmap(source)\r
+               If Not pixmap pixmap=LoadPixmap(source)\r
+               If Not pixmap Return            \r
+               Select pixmap.format\r
+               Case PF_I8,PF_BGR888\r
+                       pixmap=pixmap.Convert( PF_RGB888 )\r
+               Case PF_A8,PF_BGRA8888\r
+                       pixmap=pixmap.Convert( PF_RGBA8888 )\r
+               End Select\r
+               \r
+               If AlphaBitsPerPixel[ pixmap.format ]\r
+                       For Local y=0 Until pixmap.height\r
+                               For x=0 Until pixmap.width\r
+                                       Local argb=pixmap.ReadPixel( x,y )\r
+                                       pixmap.WritePixel x,y,premult(argb)\r
+                               Next\r
+                       Next\r
+               EndIf\r
+               \r
+               n=pixmap.width/pixmap.height;\r
+               If n=0 Return           \r
+               icons=New TCocoaIconStrip\r
+               icons.pixmap=pixmap\r
+               icons.count=n\r
+               icons.images=New Int[n]\r
+               w=pixmap.width/n                        \r
+               For x=0 Until n\r
+                       pix=pixmap.Window(x*w,0,w,pixmap.height)\r
+                       If IsNotBlank(pix) icons.images[x]=NSPixmapImage(pix)\r
+               Next\r
+               Return icons\r
+       EndFunction     \r
+       \r
+EndType\r
+\r
+Type TCocoaGuiFont Extends TGuiFont\r
+       \r
+       Method Delete()\r
+               If handle Then\r
+                       NSRelease(handle)\r
+                       handle = 0\r
+               EndIf\r
+       EndMethod\r
+       \r
+       Method CharWidth(char)\r
+               If handle\r
+                       Return NSCharWidth(handle,char)\r
+               EndIf\r
+               Return 0\r
+       EndMethod \r
+               \r
+EndType\r
+\r
+Type TIntWrapper Final\r
+       Field value:Int\r
+       Function Create:TIntWrapper(value:Int)\r
+               Local tmpWrapper:TIntWrapper = New TIntWrapper\r
+               tmpWrapper.value = value\r
+               Return tmpWrapper\r
+       EndFunction\r
+       Method Compare( o:Object )\r
+               Local c:TIntWrapper = TIntWrapper(o)\r
+               If c Then Return (value - c.value)\r
+               Return Super.Compare(o)\r
+       EndMethod\r
+       Method ToString$()\r
+               Return value\r
+       EndMethod\r
+EndType\r
+\r
+Private\r
+\r
+Function premult(argb)\r
+       Local a = ((argb Shr 24) & $FF)\r
+       Return ((((argb&$ff00ff)*a)Shr 8)&$ff00ff)|((((argb&$ff00)*a)Shr 8)&$ff00)|(a Shl 24)\r
+End Function\r