supernova: allocators - fix construct method
[supercollider.git] / editors / scapp / SCCocoaView.M
blob1ef45b29516cd37dc12932078f7b0e1220602127
1 /*
2 SCCocoaView.M
4 Created by falkenst on Tue Feb 08 2005.
5 Copyright (c) 2005 jan truetzschler. All rights reserved.
7 SuperCollider real time audio synthesis system
8 Copyright (c) 2002 James McCartney. All rights reserved.
9 http://www.audiosynth.com
11 This program is free software; you can redistribute it and/or modify
12 it under the terms of the GNU General Public License as published by
13 the Free Software Foundation; either version 2 of the License, or
14 (at your option) any later version.
16 This program is distributed in the hope that it will be useful,
17 but WITHOUT ANY WARRANTY; without even the implied warranty of
18 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 GNU General Public License for more details.
21 You should have received a copy of the GNU General Public License
22 along with this program; if not, write to the Free Software
23 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
27 #include <Cocoa/Cocoa.h>
28 #include <Carbon/Carbon.h>
29 #include <pthread.h>
30 #import "SCBase.h"
31 #import "PyrSymbol.h"
32 #include "PyrPrimitive.h"
33 #include "PyrObject.h"
34 #include "PyrKernel.h"
35 #include "GC.h"
36 #include "VMGlobals.h"
37 #include "SC_RGen.h"
38 #include "SC_BoundsMacros.h"
39 #include "SC_InlineBinaryOp.h"
40 #include "PyrListPrim.h"
43 #include "SCCocoaView.h"
44 #include "QTKit/QTKit.h"
45 #import "HTMLRenderer.h"
46 #import "MyDocument.h"
47 #import "SCImage.h"
50 extern pthread_mutex_t gLangMutex;
51 extern bool compiledOK;
53 // SCImage support
54 extern PyrSymbol *s_scimage; // class symbol
55 extern PyrObject* newPyrSCImage(VMGlobals* g); // class creation func
57 void SyntaxColorize(NSTextView* textView);
59 static NSString *sSCObjType = @"SuperCollider object address";
60 extern PyrSymbol *s_scview;
62 @implementation SCCocoaTextViewResponder
64 - (struct PyrObject*)getSCObject
66 return mSCViewObject->GetSCObj();
68 - (void)textDidEndEditing:(NSNotification *)aNotification
70 // post("endEditing");
72 - (void)textDidBeginEditing:(NSNotification *)aNotification
76 - (void)setSCView: (struct SCCocoaTextView*)inObject
78 mSCViewObject = inObject;
82 - (IBAction) executeSelection: (id) sender
84 if(enterExecutesSelection)
85 [self sendSelection: "interpretPrintCmdLine" ];
88 - (void)sendSelection: (char*) methodName
90 if (!compiledOK) {
91 return;
94 NSRange selectedRange;
95 SCTextView * txtView = mSCViewObject->getTextView();
96 NSString* selection = [txtView currentlySelectedTextOrLine: &selectedRange];
97 const char *text = [selection UTF8String];
98 int textlength = strlen(text);
100 [[SCVirtualMachine sharedInstance] setCmdLine: text length: textlength];
102 NSRange newSelectedRange = NSMakeRange(selectedRange.location + selectedRange.length, 0);
103 [txtView setSelectedRange: newSelectedRange];
105 pthread_mutex_lock(&gLangMutex);
106 runLibrary(getsym(methodName));
107 pthread_mutex_unlock(&gLangMutex);
111 //- (void) keyDown: (NSEvent*) event
112 //- (BOOL)textView:(NSTextView *)textView shouldChangeTextInRanges:(NSArray *)affectedRanges replacementStrings:(NSArray *)characters
113 - (BOOL) handleKeyDown: (NSEvent*) event;
116 // for some reason modifiers becomes 256 on my machine with no keys pressed. So need to mask against known keys.
117 if(usesTabToFocusNextView && ([event type] == NSKeyDown)){
118 NSString *characters = [event characters];
119 unsigned int modifiers = [event modifierFlags];
120 uint32 allKnownModifiers = NSAlphaShiftKeyMask | NSShiftKeyMask | NSControlKeyMask | NSCommandKeyMask
121 | NSAlternateKeyMask | NSHelpKeyMask | NSFunctionKeyMask;
122 unichar character = 0;
123 if([characters length] > 0) {
124 character = [characters characterAtIndex: 0];
126 if(character == 9 && ((modifiers & allKnownModifiers) == 0)) {
127 mSCViewObject->tabPrevFocus();
128 return YES;
129 } else if (character == 25 && ((modifiers & allKnownModifiers) == NSShiftKeyMask)) { // check above for tab
130 //NSLog(@"backtab");
131 /////[mSCViewObject->getTextView() resignFirstResponder];
132 mSCViewObject->tabNextFocus();
133 return YES;
134 } // other tab keys avail for user
136 return NO;
139 //- (BOOL) handleKeyDown: (NSEvent*) event;
141 // //NSLog(@"keyDown");
142 // // for some reason modifiers becomes 256 on my machine with no keys pressed. So need to mask against known keys.
143 // if(usesTabToFocusNextView){
144 // NSString *characters = [event characters];
145 // unsigned int modifiers = [event modifierFlags];
146 // uint32 allKnownModifiers = NSAlphaShiftKeyMask | NSShiftKeyMask | NSControlKeyMask | NSCommandKeyMask
147 // | NSAlternateKeyMask | NSHelpKeyMask | NSFunctionKeyMask;
148 // unichar character = 0;
149 // if([characters length] > 0) {
150 // character = [characters characterAtIndex: 0];
151 // //NSLog(@"char %i", character);
152 // }
153 // if (character == 25 && ((modifiers & allKnownModifiers) == NSShiftKeyMask)) { // check above for tab
154 // //NSLog(@"backtab");
155 // /////[mSCViewObject->getTextView() resignFirstResponder];
156 // mSCViewObject->tabNextFocus();
157 // return YES;
158 // } // other tab keys avail for user
159 // }
160 // return NO;
162 - (void) keyUp: (NSEvent*) event
166 - (void) mouseDown: (NSEvent*) event
168 mSCViewObject->makeFocus(true);
171 - (void) setUsesTabToFocusNextView: (BOOL) flag
173 usesTabToFocusNextView = flag;
176 - (void) setEnterExecutesSelection: (BOOL) flag
178 enterExecutesSelection = flag;
181 - (BOOL) textView: (NSTextView *) textView
182 clickedOnLink: (id) link
183 atIndex: (unsigned) charIndex
185 bool loadLinkInView = mSCViewObject->getLoadLinkInView();
186 NSDocumentController* docctl = [NSDocumentController sharedDocumentController];
187 if (!docctl && !loadLinkInView) return YES;
189 NSURL *desiredURL;
191 // is it a NSURL link or a NSString link?
192 if ([link isKindOfClass: [NSString class]])
194 if([link hasPrefix:@"SC://"] || [link hasPrefix:@"sc://"]) { // this means search immediately
195 NSString *helpPath = pathOfHelpFileFor([[[link substringFromIndex:5] stringByDeletingPathExtension] stringByDeletingPathExtension]);
196 if(!helpPath) {
197 post("WARNING:\nInvalid hyperlink: '%s' Please repair this.\n", [link cString]);
198 return YES;
200 desiredURL = [NSURL URLWithString: helpPath];
201 } else desiredURL = [NSURL URLWithString: [link stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding] relativeToURL: mSCViewObject->getLastURL()];
203 } else if ([link isKindOfClass: [NSURL class]])
205 // check for schemes which we'll handle
206 if([[link scheme] isEqualToString: @"SC"] || [[link scheme] isEqualToString:@"sc"]) { // this means search immediately
207 NSString *helpPath = pathOfHelpFileFor([[[[link relativeString] substringFromIndex:5] stringByDeletingPathExtension] stringByDeletingPathExtension]);
208 if(!helpPath) {
209 post("WARNING:\nInvalid hyperlink: '%s' Please repair this.\n", [[link relativeString] cString]);
210 return YES;
212 desiredURL = [NSURL fileURLWithPath: helpPath];
213 } else if (![link scheme]) { // NULL could be a regular file link that's been edited
214 if([[link relativePath] hasPrefix: @"/"]) {
215 desiredURL = [NSURL fileURLWithPath: [link relativeString]];
216 } else {
217 desiredURL = [NSURL URLWithString: [[link relativeString] stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding] relativeToURL: mSCViewObject->getLastURL()];
219 } else if(![[link scheme] isEqualToString: @"file"]) {
220 return NO; // it's http, etc. so pass it on to Safari or whatever
221 } else {
222 desiredURL = link; // it's a regular file:// URL
224 } else return NO;
226 // try the link action first then use default
227 if(mSCViewObject->linkAction([desiredURL absoluteString])) return YES;
229 MyDocument *doc = nil;
230 int result = 0;
232 if([[NSFileManager defaultManager] fileExistsAtPath: [desiredURL path]]) {
233 if(!loadLinkInView) doc = (MyDocument*)[docctl documentForURL: [desiredURL absoluteURL]];
234 } else NSLog(@"file doesn't exist at path");
235 if (!doc) {
236 if(!loadLinkInView) {
237 doc = [docctl openDocumentWithContentsOfURL: desiredURL display: true];
238 } else {
239 result = mSCViewObject->open([desiredURL path]);
241 if (!doc && result) {
242 // it's a bad file:// URL, post a warning and search
243 post("WARNING:\nInvalid hyperlink: '%s' Please repair this.\nSearching help directories for alternative.\n", [[desiredURL path] cString]);
244 // delete extension twice in case something.help.rtf
245 NSString *desiredHelpName = [[[[desiredURL path] lastPathComponent] stringByDeletingPathExtension] stringByDeletingPathExtension];
246 NSString *helpPath = pathOfHelpFileFor(desiredHelpName);
247 if(!helpPath) {
248 post("Can't find Help File Document for: '%s'\n", [desiredHelpName cString]);
249 return YES;
251 desiredURL = [NSURL fileURLWithPath: helpPath];
252 if([[NSFileManager defaultManager] fileExistsAtPath: [desiredURL path]]) {
253 if(!loadLinkInView) {
254 doc = (MyDocument*)[docctl documentForURL: [desiredURL absoluteURL]];
256 } else post("file doesn't exist at path: '%s'\n", [[desiredURL path] cString]);
257 if (!doc) {
258 if(!loadLinkInView) {
259 doc = [docctl openDocumentWithContentsOfURL: desiredURL display: true];
260 } else {
261 result = mSCViewObject->open(helpPath);
263 if(!doc && result) {
264 post("Can't open Help File Document: '%s'\n", [[desiredURL path] cString]);
265 return YES;
270 if(!loadLinkInView) {
271 NSWindow *window = [[[doc windowControllers] objectAtIndex: 0] window];
272 if (!window) {
273 post("!! window controller returns nil ? failed to open help file window\n");
274 return YES;
276 [window makeKeyAndOrderFront: nil];
278 return YES;
281 - (void) loadHTMLToTextView:(NSURL *)url
283 if (!url) return;
284 SCTextView *textView = mSCViewObject->getTextView();
285 NSTextStorage* text = [textView textStorage];
286 [text beginEditing]; // Bracket with begin/end editing for efficiency
288 NSAttributedString *htmlAttributedString = [HTMLRenderer attributedStringWithURL:url];
290 if(htmlAttributedString)
292 [text setAttributedString:htmlAttributedString];
293 [textView setDefaultTabsTo: 28.0f];
296 [text endEditing];
297 [url release];
300 // for compatibility with Document
301 - (void)setActiveTextView:(SCTextView*)aTextView
304 @end
307 @implementation SCTextFieldResponder
309 //- (id)initWithFrame:(NSRect)frameRect
311 // backGroundColor = [[NSColor whiteColor] retain];
312 // return [super initWithFrame:frameRect];
315 //- (void)dealloc
317 // [backGroundColor release];
318 // [super dealloc];
321 //- (void)setBackgroundColor:(NSColor *)aColor
323 // [aColor retain];
324 // [backGroundColor release];
325 // backGroundColor = aColor;
328 //- (void)drawRect:(NSRect)aRect
330 // // draw a background
331 // CGContextRef cgc = (CGContextRef)[[NSGraphicsContext currentContext] graphicsPort];
332 // CGContextSaveGState(cgc);
333 // CGContextSetRGBFillColor(cgc, 1.0, 0.0, 0.0, 0.5);
334 // CGContextFillRect(cgc, (*(CGRect *)&(aRect)));
335 // CGContextRestoreGState(cgc);
337 // [super drawRect:aRect]; // call superclass here for everything else
340 - (struct PyrObject*)getSCObject
342 return mSCViewObject->GetSCObj();
345 //- (void)controlTextDidEndEditing:(NSNotification *)aNotification
347 // if(textReallyChanged){
348 // pthread_mutex_lock (&gLangMutex);
349 // PyrSymbol *method = getsym("doAction");
350 // PyrObject *mObj;
351 // if (mObj = mSCViewObject->GetSCObj()) {
352 // VMGlobals *g = gMainVMGlobals;
353 // g->canCallOS = true;
354 // ++g->sp; SetObject(g->sp, mObj);
355 // runInterpreter(g, method, 1);
356 // g->canCallOS = false;
357 // }
358 // pthread_mutex_unlock (&gLangMutex);
359 // textReallyChanged = false;
360 // }
364 //- (BOOL)textShouldBeginEditing:(NSText *)fieldEditor
366 // post("foo\n");
367 // if(mSCViewObject->isFocus()) return YES;
369 // return NO;
372 //- (BOOL)control:(NSControl *)control textShouldBeginEditing:(NSText *)fieldEditor
374 // //[(SCFieldEditor*)fieldEditor setCurrentTextField:self];
375 // post("ctsbe\n");
376 // return YES;
379 //- (BOOL)control:(NSControl *)control textShouldEndEditing:(NSText *)fieldEditor
381 // //[(SCFieldEditor*)fieldEditor setCurrentTextField:nil];
382 // return YES;
386 //- (void)mouseDown:(NSEvent *)theEvent
389 // mSCViewObject->makeFocus(true);
390 // unsigned int modifiers = [theEvent modifierFlags];
391 // //control tab/escape doesn't get passed here at all ?
392 // if(modifiers & NSCommandKeyMask) {
393 // [self selectText:self]; // exit editing and select all for a drag
394 // [self display];
395 // } else [super mouseDown:theEvent];
398 //- (void)drawRect:(NSRect)aRect
400 // [backGroundColor setFill];
401 // NSRectFill(aRect);
402 // [super drawRect:aRect];
405 -(void)rightMouseDown:(NSEvent*)theEvent { [self mouseDown:theEvent]; }
406 -(void)otherMouseDown:(NSEvent*)theEvent { [self mouseDown:theEvent]; }
407 - (void)mouseDown:(NSEvent *)theEvent
409 //NSLog(@"SCGraphView MOUSEDOWN");
410 //[[self window] makeFirstResponder:self]; // there may be an active field editor
411 BOOL keepOn = YES;
412 //BOOL isInside = YES;
413 NSPoint mouseLoc;
414 //NSLog(@"Click count: %i", [theEvent clickCount]);
415 //if([theEvent clickCount] == 2) return;
416 //if (!mTopView) return;
417 unsigned int modifiers = [theEvent modifierFlags];
418 mouseLoc = [self convertPoint:[theEvent locationInWindow] fromView:nil];
419 SCPoint scpoint = SCMakePoint(mouseLoc.x, mouseLoc.y);
420 SCTopView *mTopView = mSCViewObject->getTop();
421 if (mSCViewObject) {
422 mDragStarted = NO;
423 bool mouseMoved = NO;
424 //mMenuView = 0;
425 mSCViewObject->makeFocus(true);
426 // force focus ring into drawing even if we're already in focus
427 SEL sel = @selector(setNeedsDisplay:);
428 NSMethodSignature *sig = [NSView instanceMethodSignatureForSelector: sel];
429 NSInvocation *anInvocation = [NSInvocation invocationWithMethodSignature: sig];
430 SCVirtualMachine* scvm = [SCVirtualMachine sharedInstance];
431 [anInvocation setTarget: [self superview]];
432 [anInvocation setSelector: sel];
433 BOOL flag = YES;
434 [anInvocation setArgument: &flag atIndex: 2];
435 [scvm defer: anInvocation];
437 [self setEditingInactive:NO]; // in this way we know that editing was started by a mouse click rather than a key down
439 bool constructionmode = mTopView->ConstructionMode();
440 if(!constructionmode)
442 mSCViewObject->mouseDownAction(scpoint, modifiers,theEvent);
443 mSCViewObject->mouseBeginTrack(scpoint, modifiers,theEvent);
444 }else
445 mSCViewObject->setConstructionModeFromPoint(scpoint);
447 [self displayIfNeeded];
449 while (keepOn && !mDragStarted) {
450 theEvent = [[self window] nextEventMatchingMask: NSLeftMouseUpMask |NSRightMouseUp | NSOtherMouseUp |
451 NSLeftMouseDraggedMask | NSRightMouseDragged | NSOtherMouseDragged
452 | NSKeyDownMask | NSKeyUpMask
454 modifiers = [theEvent modifierFlags]; // added
455 mouseLoc = [self convertPoint:[theEvent locationInWindow] fromView:nil];
456 //isInside = [self mouse:mouseLoc inRect:[self bounds]];
457 scpoint = SCMakePoint(mouseLoc.x, mouseLoc.y);
458 int evtype = [theEvent type];
459 switch ([theEvent type]) {
460 case NSLeftMouseDown:
461 case NSRightMouseDown:
462 if(constructionmode)
464 mSCViewObject->doConstructionMove(scpoint);
465 mTopView->refresh();
466 }else
467 mSCViewObject->mouseDownAction(scpoint, modifiers,theEvent);
468 // post("down \n");
469 break;
470 case NSLeftMouseDragged:
471 case NSRightMouseDragged:
472 case NSOtherMouseDragged:
473 if(constructionmode)
475 mSCViewObject->doConstructionMove(scpoint);
476 mTopView->refresh();
477 }else
478 mSCViewObject->mouseTrack(scpoint, modifiers,theEvent);
479 mSCViewObject->mouseMoveAction(scpoint, modifiers,theEvent);
480 mouseMoved = YES;
481 // post("drag \n");
482 break;
483 case NSLeftMouseUp:
484 case NSRightMouseUp:
485 case NSOtherMouseUp:
486 if(constructionmode)
488 // view->doConstructionMove(scpoint);
489 mTopView->refresh();
490 }else
492 if(mouseMoved) { // check if this was just a mouse down or also a drag; if the latter end editing
493 [[self window] endEditingFor:self];
494 [self setEditingInactive:YES];
495 //[[self window] makeFirstResponder:[self superview]];
496 // trick focus ring into drawing
497 SEL sel = @selector(setNeedsDisplay:);
498 NSMethodSignature *sig = [NSView instanceMethodSignatureForSelector: sel];
499 NSInvocation *anInvocation = [NSInvocation invocationWithMethodSignature: sig];
500 SCVirtualMachine* scvm = [SCVirtualMachine sharedInstance];
501 [anInvocation setTarget: [self superview]];
502 [anInvocation setSelector: sel];
503 BOOL flag = YES;
504 [anInvocation setArgument: &flag atIndex: 2];
505 [scvm defer: anInvocation];
507 // if(!view.GetSCObj()) break;
508 mSCViewObject->mouseUpAction(scpoint, modifiers,theEvent);
509 mSCViewObject->mouseEndTrack(scpoint, modifiers,theEvent);
511 keepOn = NO;
512 break;
513 case NSKeyDown:
514 if(!constructionmode)
516 [self keyDown:theEvent];
518 break;
519 case NSKeyUp:
520 if(!constructionmode)
522 [self keyUp:theEvent];
524 break;
525 default:
526 post("evtype %d %4.4s\n", evtype, (char*)&evtype);
527 /* Ignore any other kind of event. */
528 break;
530 // display:
531 [self displayIfNeeded];
532 flushPostBuf();
535 //mMenuView = 0;
536 return;
539 -(void)mouseMoved:(NSEvent*)theEvent
541 NSPoint mouseLoc;
542 unsigned int modifiers = [theEvent modifierFlags];
543 mouseLoc = [self convertPoint:[theEvent locationInWindow] fromView:nil];
544 SCPoint scpoint = SCMakePoint(mouseLoc.x, mouseLoc.y);
545 if (mSCViewObject) {
546 mDragStarted = NO;
547 // view->makeFocus(true);
548 mSCViewObject->mouseOver(scpoint, modifiers, theEvent);
552 const int circDiam = 20;
554 - (NSImage*) makeDragImage: (PyrSlot*)slot label: (NSString*)label
557 if (!slot) return 0;
559 NSString *nsstring;
560 if(label) {
561 nsstring = label;
562 } else if (slot) {
563 PyrClass *classobj = classOfSlot(slot);
564 nsstring = [NSString stringWithCString: slotRawSymbol(&classobj->name)->name];
565 if (!nsstring) return 0;
566 } else {
567 nsstring = @"No Data!";
570 NSMutableDictionary *dict = [NSMutableDictionary dictionary];
571 NSFont *font = [NSFont fontWithName: @"Helvetica" size: 12];
572 if (!font) return 0;
573 [dict setObject: font forKey: NSFontAttributeName ];
575 NSSize strSize = [nsstring sizeWithAttributes: dict];
576 NSRect strRect = NSMakeRect(circDiam, 0, circDiam + strSize.width, strSize.height);
578 NSSize size = NSMakeSize(circDiam+strSize.width, sc_max(circDiam, strSize.height));
580 NSImage *image = [[NSImage alloc] initWithSize: size];
581 if (!image) return 0;
583 [image autorelease];
585 float alpha = 0.6;
586 NSColor *colorClear = [NSColor colorWithCalibratedRed: 0
587 green: 0
588 blue: 0
589 alpha: 0];
590 NSColor *colorTransBlack = [NSColor colorWithCalibratedRed: 0
591 green: 0
592 blue: 0
593 alpha: alpha];
594 NSColor *colorTransBlue = [NSColor colorWithCalibratedRed: 0
595 green: 0
596 blue: 1
597 alpha: alpha];
598 /*NSColor *colorTransLtBlue = [NSColor colorWithCalibratedRed: 0.8
599 green: 0.8
600 blue: 1
601 alpha: alpha];*/
602 NSColor *colorTransWhite = [NSColor colorWithCalibratedRed: 1
603 green: 1
604 blue: 1
605 alpha: alpha];
606 NSColor *colorCaptionBackgnd = [NSColor colorWithCalibratedRed: 0
607 green: 0
608 blue: 0
609 alpha: 0.4];
610 NSColor *colorWhite = [NSColor colorWithCalibratedRed: 1
611 green: 1
612 blue: 1
613 alpha: 1];
615 [dict setObject: colorWhite forKey: NSForegroundColorAttributeName ];
617 [image lockFocus];
618 [colorClear set];
619 [NSBezierPath fillRect: NSMakeRect(0,0,size.width,size.height)];
620 NSBezierPath *path = [NSBezierPath bezierPathWithOvalInRect: NSMakeRect(1,1,circDiam-2,circDiam-2)];
622 [path setLineWidth: 1.5];
623 [colorTransBlue set];
624 [path fill];
626 NSBezierPath *hilite = [NSBezierPath bezierPathWithOvalInRect:
627 NSMakeRect(circDiam*0.3, circDiam*0.7, circDiam*0.4, circDiam*0.15)];
629 [colorTransWhite set];
630 [hilite fill];
632 [colorTransBlack set];
633 [path stroke];
635 [colorCaptionBackgnd set];
636 [NSBezierPath fillRect: strRect];
638 [nsstring drawInRect: strRect withAttributes: dict];
640 [image unlockFocus];
642 return image;
646 - (void) beginDragFrom: (NSPoint)where of: (PyrSlot*)slot string:(NSString*) string label:(NSString*) label
648 NSImage *image = [self makeDragImage: slot label: label];
650 NSPasteboard *pboard = [NSPasteboard pasteboardWithName: NSDragPboard];
651 [pboard declareTypes: [NSArray arrayWithObjects: sSCObjType, NSStringPboardType, nil] owner: self];
653 int fakeData;
654 NSData *data = [NSData dataWithBytes: &fakeData length: sizeof(int)];
656 [pboard setData: data forType: sSCObjType];
657 [pboard setString: string forType: NSStringPboardType];
659 NSSize imageSize = [image size];
660 where.x -= circDiam / 2;
661 where.y += circDiam / 4;
663 NSSize dragOffset = NSMakeSize(0.0, 0.0);
664 mDragStarted = YES;
665 [self dragImage: image at: where offset: dragOffset event: [NSApp currentEvent]
666 pasteboard: pboard source: self slideBack: YES];
669 //- (void)mouseDragged:(NSEvent *)theEvent
671 // NSSize dragOffset = NSMakeSize(0.0, 0.0);
672 // NSPasteboard *pboard;
674 // pboard = [NSPasteboard pasteboardWithName:NSDragPboard];
675 // [pboard declareTypes:[NSArray arrayWithObjects:sSCObjType, NSStringPboardType, nil] owner:self];
677 // int fakeData;
678 // NSData *data = [NSData dataWithBytes: &fakeData length: sizeof(int)];
680 // [pboard setData: data forType: sSCObjType];
681 // [pboard setString: [self stringValue] forType: NSStringPboardType];
683 // [self dragImage:[[[self window] fieldEditor:NO forObject:self] dragImageForSelectionWithEvent:NSMakePoint(0.0, 0.0)] at:[self imageLocation] offset:dragOffset
684 // event:theEvent pasteboard:pboard source:self slideBack:YES];
686 // return;
689 - (void)setSCView: (struct SCTextField*)inObject
691 mSCViewObject = inObject;
694 -(BOOL) acceptsFirstResponder
696 return mAcceptsFirstResponder;
699 -(void) setAcceptsFirstResponder: (BOOL) flag
701 mAcceptsFirstResponder = flag;
705 // TEST: For tab-index
706 //- (BOOL)becomeFirstResponder
708 // if(!mSCViewObject->isFocus()){
709 // [self resignFirstResponder];
710 // [mSCViewObject->getTop()->focusView()->focusResponder() becomeFirstResponder];
711 // return NO;
712 // } else return [super becomeFirstResponder];
714 //-(BOOL) acceptsFirstResponder
716 // return YES;
719 //- (BOOL)resignFirstResponder
721 // post("resignFirstResponder\n");
722 // [[self window] endEditingFor:self];
723 // return YES;
726 // this for keyDowns. KeyUps come in keyUp below.
727 - (BOOL)textView:(NSTextView *)aTextView shouldChangeTextInRange:(NSRange)affectedCharRange replacementString:(NSString *)replacementString
729 //post("sctir\n");
730 NSEvent* event = [NSApp currentEvent];
731 NSString *characters = [event characters];
732 unsigned int modifiers = [event modifierFlags];
733 unichar character = 0;
734 if([characters length] > 0) {
735 character = [characters characterAtIndex: 0];
737 if ([event keyCode] == 53){ //escape key breaks from modal or fullscreen windows
738 [[self window] keyDown:event];
740 mSCViewObject->keyDown(character, modifiers,[event keyCode]);
741 return YES;
744 // handle tabs and enter
745 - (BOOL)textView:(NSTextView *)aTextView doCommandBySelector:(SEL)aSelector
747 //post("dcbs\n");
748 //NSLog(@"sel: %@", NSStringFromSelector(aSelector));
749 if (aSelector == @selector(insertTab:)){
750 mSCViewObject->tabPrevFocus();
751 return YES;
752 } else if (aSelector == @selector(insertBacktab:)){
753 mSCViewObject->tabNextFocus();
754 return YES;
755 } else if (aSelector == @selector(insertNewline:)){
756 [[self window] endEditingFor:self];
757 // fire the action
758 pthread_mutex_lock (&gLangMutex);
759 PyrSymbol *method = getsym("doAction");
760 PyrObject *mObj;
761 if (mObj = mSCViewObject->GetSCObj()) {
762 VMGlobals *g = gMainVMGlobals;
763 g->canCallOS = true;
764 ++g->sp; SetObject(g->sp, mObj);
765 runInterpreter(g, method, 1);
766 g->canCallOS = false;
768 pthread_mutex_unlock (&gLangMutex);
769 //NSLog(@"sv: %@", [self superview]);
770 [self setEditingInactive:YES];
771 [[self window] makeFirstResponder:[self superview]];
772 //NSLog(@"firstresp: %@", [[self window] firstResponder]);
773 return NO; // this will let the field editor end editing
774 } else if (aSelector == @selector(moveUp:) || aSelector == @selector(moveDown:)){ // stop editing and forward key event (for numbox)
775 NSEvent* event = [NSApp currentEvent];
776 NSString *characters = [event characters];
777 unsigned int modifiers = [event modifierFlags];
778 unichar character = 0;
779 if([characters length] > 0) {
780 character = [characters characterAtIndex: 0];
782 [[self window] endEditingFor:self];
783 [self setEditingInactive:YES];
784 [[self window] makeFirstResponder:[self superview]];
785 mSCViewObject->keyDown(character, modifiers,[event keyCode]);
786 return YES;
788 return NO;
792 - (NSDragOperation)draggingEntered:(id < NSDraggingInfo >)dragInfo {
793 NSPasteboard* pboard = [dragInfo draggingPasteboard];
794 if ([[pboard types] containsObject: sSCObjType]) {
795 return mSCViewObject->draggingEntered();
796 } else if ([[pboard types] containsObject: NSStringPboardType]) {
797 NSString *nsstring = [pboard stringForType: NSStringPboardType];
798 if (!nsstring) return NSDragOperationNone;
800 pthread_mutex_lock (&gLangMutex);
801 VMGlobals *g = gMainVMGlobals;
802 PyrString* pstrobj = newPyrString(g->gc, [nsstring UTF8String], 0, true);
803 int classVarIndex = slotRawInt(&getsym("SCView")->u.classobj->classVarIndex);
804 SetObject(&g->classvars->slots[classVarIndex+0], pstrobj);
805 g->gc->GCWrite(g->classvars, pstrobj);
806 //PyrSymbol *method = getsym("importDrag");
807 //g->canCallOS = true;
808 ++g->sp; SetObject(g->sp, s_scview->u.classobj);
809 //runInterpreter(g, method, 1);
810 //g->canCallOS = false;
812 pthread_mutex_unlock (&gLangMutex);
814 int fakeData;
815 NSData *data = [NSData dataWithBytes: &fakeData length: sizeof(int)];
816 [pboard setData: data forType: sSCObjType];
818 } else if ([[pboard types] containsObject: NSFilenamesPboardType]) {
819 NSArray *files = [pboard propertyListForType: NSFilenamesPboardType];
820 if (!files) return NSDragOperationNone;
821 pthread_mutex_lock (&gLangMutex);
822 VMGlobals *g = gMainVMGlobals;
823 int size = [files count];
824 PyrObject* array = newPyrArray(g->gc, size, 0, true);
826 for (int i=0; i<size; ++i) {
827 NSString *path = [files objectAtIndex: i];
828 PyrString *string = newPyrString(g->gc, [path UTF8String], 0, true);
829 SetObject(array->slots + array->size, string);
830 array->size++;
831 g->gc->GCWrite(array, string);
834 int classVarIndex = slotRawInt(&getsym("SCView")->u.classobj->classVarIndex);
835 SetObject(&g->classvars->slots[classVarIndex+0], array);
836 g->gc->GCWrite(g->classvars, array);
838 pthread_mutex_unlock (&gLangMutex);
840 int fakeData;
841 NSData *data = [NSData dataWithBytes: &fakeData length: sizeof(int)];
842 [pboard setData: data forType: sSCObjType];
844 } else {
845 return NSDragOperationNone;
850 - (BOOL)performDragOperation:(id <NSDraggingInfo>)sender {
852 return mSCViewObject->performDrag();
855 - (void)keyUp:(NSEvent*)event
858 //post("doKeyUpAction\n");
859 NSString *characters = [event characters];
860 unsigned int modifiers = [event modifierFlags];
861 unichar character = 0;
862 if([characters length] > 0) {
863 character = [characters characterAtIndex: 0];
865 mSCViewObject->keyUp(character, modifiers,[event keyCode]);
869 void QDDrawBevelRect(CGContextRef cgc, CGRect bounds, float width, bool inout);
870 - (void)drawRect:(NSRect)aRect
872 [super drawRect:aRect];
874 CGContextRef cgc = (CGContextRef)[[NSGraphicsContext currentContext] graphicsPort];
875 CGContextSaveGState(cgc);
876 #if (MAC_OS_X_VERSION_MIN_REQUIRED <= MAC_OS_X_VERSION_10_4)
877 QDDrawBevelRect(cgc, (*(CGRect *)&([self bounds])), 1, true);
878 #else
879 QDDrawBevelRect(cgc, NSRectToCGRect([self bounds]), 1, true);
880 #endif
881 CGContextRestoreGState(cgc);
885 // doing this here keeps C++ classes much simpler
886 - (void) addNumberFormatter
888 [NSNumberFormatter setDefaultFormatterBehavior:NSNumberFormatterBehavior10_4];
889 mFormatter = [[[NSNumberFormatter alloc] init] autorelease];
890 [mFormatter setNumberStyle: NSNumberFormatterDecimalStyle];
891 [mFormatter setAlwaysShowsDecimalSeparator:NO];
892 [mFormatter setExponentSymbol:@"e"];
893 [mFormatter setMaximumFractionDigits:20];
894 [mFormatter setDecimalSeparator:@"."];
895 [mFormatter setUsesGroupingSeparator:NO];
896 [[self cell] setFormatter:mFormatter];
899 // with these two methods we can check in C++ keyDown methods to see if editing is active
900 // if not, we start it and replace the string in the field editor
901 - (void) setEditingInactive: (BOOL)flag
903 mEditingInactive = flag;
906 - (BOOL) editingInactive
908 return mEditingInactive;
910 @end
912 @implementation SCNSMenuItem
914 - (void)setSCObject: (struct PyrObject*)inObject
916 mMenuItemObj = inObject;
919 - (struct PyrObject*)getSCObject
921 return mMenuItemObj;
924 - (void)doAction: (id)sender
926 // post("doAction \n");
927 pthread_mutex_lock (&gLangMutex);
928 PyrObject * pobj = [self getSCObject];
929 if(compiledOK && pobj){
930 PyrSymbol *method = getsym("doAction");
931 VMGlobals *g = gMainVMGlobals;
932 g->canCallOS = true;
933 ++g->sp; SetObject(g->sp, pobj);
934 ++g->sp; SetInt(g->sp, 1);
935 runInterpreter(g, method, 2);
936 g->canCallOS = false;
938 pthread_mutex_unlock (&gLangMutex);
941 @end
943 @implementation SCNSLevelIndicator
945 - (void)drawRect:(NSRect)aRect
947 if(drawPeak) { // make warning and critical show for peak not value if peak is drawn
948 if(criticalAboveWarning) {
949 if(peakValue >= critical) {
950 [self setCriticalValue: value];
951 [self setWarningValue: value - 0.1];
952 } else if (peakValue >= warning) {
953 [self setWarningValue: value];
954 [self setCriticalValue: value + 0.1];
955 } else {
956 [self setWarningValue: 1.1];
957 [self setCriticalValue: 1.1];
959 } else {
960 if(peakValue <= critical) {
961 [self setCriticalValue: value];
962 [self setWarningValue: value + 0.1];
963 } else if (peakValue <= warning) {
964 [self setWarningValue: value];
965 [self setCriticalValue: value - 0.1];
966 } else {
967 [self setWarningValue: -0.1];
968 [self setCriticalValue: -0.1];
972 [super drawRect:aRect];
974 CGContextRef cgc = (CGContextRef)[[NSGraphicsContext currentContext] graphicsPort];
975 CGContextSaveGState(cgc);
976 CGContextSetRGBFillColor(cgc, 1.0, 1.0, 0.0, 0.6);
977 CGRect peakRect;
978 //peakRect = CGRectMake(peakLevel, aRect.origin.y + peakSubtract, 3.f, aRect.size.height - peakSubtract);
979 peakRect = CGRectMake(peakLevel, peakY, 3.f, peakHeight);
980 CGContextFillRect(cgc, peakRect);
981 CGContextRestoreGState(cgc);
982 } else {
983 [super drawRect:aRect];
987 - (id)initWithFrame:(NSRect)frameRect
989 if (![super initWithFrame:frameRect])
990 return nil;
991 drawPeak = NO;
992 isVertical = NO;
993 peakSubtract = 0.f;
994 peakLevel = 0.f;
995 value = peakValue = 0.0;
996 critical = warning = 1.1;
997 criticalAboveWarning = YES;
998 [self prepPeakBounds];
999 return self;
1002 - (void)setFrame:(NSRect)frameRect
1004 [super setFrame:frameRect];
1005 [self prepPeakBounds];
1006 [self setNeedsDisplay:YES];
1009 - (void)setDrawPeak:(BOOL)flag
1011 drawPeak = flag;
1012 if(!flag) {
1013 [self setWarningValue: warning];
1014 [self setCriticalValue: critical];
1016 [self prepPeakBounds];
1017 [self setNeedsDisplay:YES];
1020 - (void)setDoubleValue:(double)val
1022 [super setDoubleValue:val];
1023 value = val;
1026 - (void)setMaxValue:(double)maxVal
1028 peakValue = (peakValue / [self maxValue]) * maxVal;
1029 [super setMaxValue:maxVal];
1032 - (void)setIsVertical:(BOOL)flag
1034 isVertical = flag;
1035 [self prepPeakBounds];
1036 [self setNeedsDisplay:YES];
1039 - (void)setPeakSubtract:(float)val
1041 peakSubtract = val;
1042 [self prepPeakBounds];
1043 [self setNeedsDisplay:YES];
1046 - (void)setPeakLevel:(float)val
1048 peakValue = val * [self maxValue];
1049 peakLevel = val * ([self bounds].size.width - 3);
1050 //NSLog(@"peakLevel %f", peakLevel);
1051 [self setNeedsDisplay:YES];
1054 - (void)prepPeakBounds
1056 NSRect bounds = [self bounds];
1057 peakY = bounds.origin.y + peakSubtract;
1058 peakHeight = bounds.size.height - peakSubtract;
1061 - (void)setUpWarning:(double)val
1063 warning = nextafter(val, val + 1.0);
1064 if(critical > warning) {
1065 criticalAboveWarning = YES;
1066 } else {
1067 criticalAboveWarning = NO;
1069 [self setWarningValue:warning];
1072 - (void)setUpCritical:(double)val
1074 critical = nextafter(val, val + 1.0);
1075 if(critical > warning) {
1076 criticalAboveWarning = YES;
1077 } else {
1078 criticalAboveWarning = NO;
1080 [self setCriticalValue:critical];
1083 @end
1085 @implementation SCNSFlippedView
1087 - (BOOL)isFlipped { return YES; }
1089 @end
1092 @implementation SCNSWebView
1094 -(void)initVars {
1095 loadCount=0;
1096 handleLinks = true;
1097 enterExecutesSelection = YES;
1100 - (void)setSCObject: (struct SCWebView*)inObject
1102 mSCWebView = inObject;
1105 - (struct SCWebView*)getSCObject
1107 return mSCWebView;
1110 - (void)setHandleLinks: (bool)handle
1112 handleLinks = handle;
1115 - (void)resetLoadCount
1117 loadCount = 0;
1120 - (BOOL)shouldCloseWithWindow {
1121 mSCWebView = nil;
1122 [[SCVirtualMachine sharedInstance] removeDeferredOperationsFor:self];
1123 return YES;
1126 // delegate methods
1127 - (void)webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame
1129 loadCount = loadCount - 1;
1130 if (loadCount <= 0 && mSCWebView) {
1131 loadCount = 0;
1132 SEL selector = @selector(doLoadAction);
1133 NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:
1134 [sender methodSignatureForSelector: selector]];
1135 [invocation setTarget:sender];
1136 [invocation setSelector: selector];
1138 [[SCVirtualMachine sharedInstance] defer: invocation];
1142 - (void)webView:(WebView *)sender didStartProvisionalLoadForFrame:(WebFrame *)frame
1144 loadCount = loadCount + 1;
1147 - (void)webView:(WebView *)sender didFailProvisionalLoadWithError:(NSError *)error forFrame:(WebFrame *)frame
1149 NSLog(@"didFailProvisionalLoadWithError: %@",[error localizedDescription]);
1150 if ([error code] == NSURLErrorCancelled) return; // this is Error -999
1151 if (mSCWebView) {
1152 post("SCWebView load request failed: '%s'\n", [[error localizedDescription] cString]);
1153 SEL selector = @selector(doFailAction);
1154 NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:
1155 [sender methodSignatureForSelector: selector]];
1156 [invocation setTarget:sender];
1157 [invocation setSelector: selector];
1159 [[SCVirtualMachine sharedInstance] defer: invocation];
1163 - (void)doFailAction
1165 if (mSCWebView) {
1166 mSCWebView->doLoadFailedAction();
1170 - (void)doLoadAction
1172 if (mSCWebView) {
1173 mSCWebView->doOnLoadAction();
1177 - (void)webView:(WebView *)sender didFailLoadWithError:(NSError *)error
1179 NSLog(@"didFailLoadWithError: %@",[error localizedDescription]);
1180 if ([error code] == NSURLErrorCancelled) return; // this is Error -999
1181 if (mSCWebView) {
1182 post("SCWebView load request failed: '%s'\n", [[error localizedDescription] cString]);
1183 SEL selector = @selector(doFailAction);
1184 NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:
1185 [sender methodSignatureForSelector: selector]];
1186 [invocation setTarget:sender];
1187 [invocation setSelector: selector];
1189 [[SCVirtualMachine sharedInstance] defer: invocation];
1193 // call link action if set, otherwise proceed
1194 - (void)webView:(WebView *)webView decidePolicyForNavigationAction:(NSDictionary *)actionInformation request:(NSURLRequest *)request frame:(WebFrame *)frame decisionListener:(id )listener
1196 //NSLog(@"decide policy");
1197 int actionKey = [[actionInformation objectForKey:WebActionNavigationTypeKey] intValue];
1198 if(actionKey == WebNavigationTypeLinkClicked) {
1199 //NSLog(@"link clicked");
1200 if(handleLinks) {
1201 loadCount = 0;
1202 //NSLog(@"handle link");
1203 [listener use];
1204 } else {
1205 //NSLog(@"fire action");
1206 [listener ignore];
1207 NSString *urlString = [[[request URL] absoluteString] retain];
1209 SEL selector = @selector(doLinkAction:);
1210 NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:
1211 [webView methodSignatureForSelector: selector]];
1212 [invocation setTarget:webView];
1213 [invocation setSelector: selector];
1214 [invocation setArgument:&urlString atIndex:2];
1216 [[SCVirtualMachine sharedInstance] defer: invocation];
1218 } else {
1219 [listener use];
1220 //NSLog(@"link not clicked");
1225 // handle error
1226 - (void)webView:(WebView *)webView unableToImplementPolicyWithError:(NSError *)error frame:(WebFrame *)frame
1228 NSLog(@"unableToImplementPolicyWithError: %@",[error localizedDescription]);
1231 - (void)doLinkAction:(NSString *)urlString
1233 VMGlobals *g = gMainVMGlobals;
1234 const char * cstr = [urlString UTF8String];
1235 PyrString *string = newPyrString(g->gc, cstr, 0, true);
1236 mSCWebView->doLinkClickedAction(string);
1237 [urlString release];
1240 - (BOOL)webView:(WebView *)webView shouldInsertText:(NSString *)insertText replacingDOMRange:(DOMRange *)range givenAction:(WebViewInsertAction)action
1242 //post("sctir\n");
1243 NSEvent* event = [NSApp currentEvent];
1244 NSString *characters = [event characters];
1245 unsigned int modifiers = [event modifierFlags];
1246 unichar character = 0;
1247 if([characters length] > 0) {
1248 character = [characters characterAtIndex: 0];
1250 if ([event keyCode] == 53){ //escape key breaks from modal or fullscreen windows
1251 [[self window] keyDown:event];
1253 mSCWebView->keyDown(character, modifiers,[event keyCode]);
1254 if ([characters isEqual: @"\03"] ||
1255 (([characters isEqual: @"\n"] || [characters isEqual: @"\r"]) && ([event modifierFlags] & (NSControlKeyMask | NSShiftKeyMask)))) {
1256 [self executeSelection: self];
1257 return NO;
1260 return YES;
1263 - (void)keyDown:(NSEvent *)event
1265 NSString *characters = [event characters];
1266 unsigned int modifiers = [event modifierFlags];
1267 unichar character = 0;
1268 if([characters length] > 0) {
1269 character = [characters characterAtIndex: 0];
1271 if ([event keyCode] == 53){ //escape key breaks from modal or fullscreen windows
1272 [[self window] keyDown:event];
1274 mSCWebView->keyDown(character, modifiers,[event keyCode]);
1275 if ([characters isEqual: @"\03"] ||
1276 (([characters isEqual: @"\n"] || [characters isEqual: @"\r"]) && ([event modifierFlags] & (NSControlKeyMask | NSShiftKeyMask)))) {
1277 [self executeSelection: self];
1278 } else {
1279 [super keyDown:event];
1284 - (void) setEnterExecutesSelection: (BOOL) flag
1286 enterExecutesSelection = flag;
1289 - (void)sendSelection: (char*) methodName
1291 if (!compiledOK) {
1292 return;
1295 [self setSelection];
1297 pthread_mutex_lock(&gLangMutex);
1298 runLibrary(getsym(methodName));
1299 pthread_mutex_unlock(&gLangMutex);
1303 - (void)setSelection;
1305 NSString* selection = [self stringByEvaluatingJavaScriptFromString:@"(function (){selectLine(); selObj = window.getSelection(); string = selObj.toString(); selObj.collapseToEnd(); return string })();"];
1306 const char *text = [selection UTF8String];
1307 int textlength = strlen(text);
1309 [[SCVirtualMachine sharedInstance] setCmdLine: text length: textlength];
1312 - (IBAction)openCode:(id)sender
1314 [self sendSelection: "openCodeFile"];
1317 - (IBAction) showHelpFor: (id) sender
1319 [self sendSelection: "showHelp"];
1322 - (IBAction)showHelpSearch:(id)sender {
1323 [self sendSelection: "showHelpSearch"];
1326 - (IBAction)methodTemplates: (id)sender
1328 [self sendSelection: "methodTemplates"];
1331 - (IBAction)methodReferences: (id)sender
1333 [self sendSelection: "methodReferences"];
1336 - (IBAction)executeSelection: (id) sender
1338 if(enterExecutesSelection)
1339 [self sendSelection: "interpretPrintCmdLine" ];
1342 // workaround for plaintext copy
1343 - (BOOL)webView:(WebView *)webView doCommandBySelector:(SEL)command
1345 if (command == @selector(copy:)) {
1346 NSString *markup = [[self selectedDOMRange] markupString];
1347 NSData *data = [markup dataUsingEncoding: NSUTF8StringEncoding];
1348 NSNumber *n = [NSNumber numberWithUnsignedInteger: NSUTF8StringEncoding];
1349 NSDictionary *options = [NSDictionary dictionaryWithObject:n forKey: NSCharacterEncodingDocumentOption];
1350 NSAttributedString *as = [[NSAttributedString alloc] initWithHTML:data options:options documentAttributes: NULL];
1351 NSString *selectedString = [as string];
1352 [as autorelease];
1354 NSPasteboard *pasteboard = [NSPasteboard generalPasteboard];
1355 [pasteboard clearContents];
1356 NSArray *objectsToCopy = [NSArray arrayWithObject: selectedString];
1357 [pasteboard writeObjects:objectsToCopy];
1358 return YES;
1360 return NO;
1363 - (void)cmdF:(id)sender {
1364 [self keyDown:[NSApp currentEvent]];
1366 @end
1368 NSRect SCtoNSRect(SCRect screct);
1370 SCView* NewSCCocoaTextView(SCContainerView *inParent, PyrObject* inObj, SCRect inBounds)
1372 return new SCCocoaTextView(inParent, inObj, inBounds);
1375 SCCocoaTextView::SCCocoaTextView(SCContainerView *inParent, PyrObject* inObj, SCRect inBounds)
1376 : SCView(inParent, inObj, inBounds)
1379 mLoadLinkInView = true;
1380 mLastURL = nil;
1381 NSRect matrect = SCtoNSRect(getDrawBounds());
1382 mTextView = [[SCTextView alloc] initWithFrame:matrect];
1383 NSView *view = mTop->GetNSView();
1384 mCocoaToLangAction = [SCCocoaTextViewResponder alloc];
1385 [mCocoaToLangAction setSCView: this];
1386 [mTextView setAutoresizingMask: 63];
1387 [[mTextView textContainer] setWidthTracksTextView: YES];
1388 [mTextView setAllowsUndo: YES];
1389 [mTextView setRichText: YES];
1390 [mTextView setSmartInsertDeleteEnabled: NO];
1391 [mTextView setImportsGraphics: YES];
1392 [mTextView setFont: [NSFont fontWithName: @"Monaco" size: 9]];
1393 [mTextView setSelectedRange: NSMakeRange(0,0)];
1394 [mTextView setLangClassToCall:@"SCView"
1395 withKeyDownActionIndex:1 withKeyUpActionIndex:2];
1396 [mTextView setObjectKeyDownActionIndex:4 setObjectKeyUpActionIndex:5];
1397 mScrollView = [[NSScrollView alloc] initWithFrame: matrect];
1398 [mScrollView setDocumentView: mTextView];
1399 [mTextView setDelegate: mCocoaToLangAction];
1400 [view addSubview: mScrollView];
1401 [[mTextView textContainer] setContainerSize:NSMakeSize([mScrollView contentSize].width, FLT_MAX)];
1402 //This is a hack, otherwise the mTextView always has focus even if makeFirstResponder: view is called...
1403 [mTextView setAcceptsFirstResponder:NO];
1404 [mScrollView setDrawsBackground:YES];
1405 [mCocoaToLangAction setUsesTabToFocusNextView:YES];
1406 [mCocoaToLangAction setEnterExecutesSelection:YES];
1407 // [mTextView autorelease];
1408 // [mScrollView autorelease];
1410 setVisibleFromParent();
1413 SCCocoaTextView::~SCCocoaTextView()
1415 [mScrollView removeFromSuperview];
1416 [mCocoaToLangAction release];
1417 [mTextView release];
1418 [mScrollView release];
1419 [mLastURL release];
1422 void SCCocoaTextView::tabPrevFocus()
1424 mTop->tabPrevFocus();
1426 void SCCocoaTextView::tabNextFocus()
1428 //post("next focus\n");
1429 mTop->tabNextFocus();
1431 void SCCocoaTextView::makeFocus(bool focus)
1433 if (focus) {
1434 if (canFocus() && !isFocus()) {
1435 [mTextView setAcceptsFirstResponder:YES];
1436 //[[mTextView window] makeFirstResponder: mTextView];
1438 } else {
1439 if (isFocus()) {
1440 [mTextView setAcceptsFirstResponder:NO];
1443 SCView::makeFocus(focus);
1447 int slotGetSCRect(PyrSlot* a, SCRect *r);
1448 extern PyrSymbol *s_font;
1449 int slotBackgroundVal(PyrSlot *slot, DrawBackground **ioPtr);
1451 void SCCocoaTextView::setBounds(SCRect inBounds)
1453 mBounds = inBounds;
1454 [[mScrollView superview] setNeedsDisplayInRect:[mScrollView frame]];
1455 if(!(mParent->isSubViewScroller())){
1456 SCRect pbounds = mParent->getLayout().bounds;
1457 mLayout.bounds.x = mBounds.x + pbounds.x;
1458 mLayout.bounds.y = mBounds.y + pbounds.y;
1459 mLayout.bounds.width = mBounds.width;
1460 mLayout.bounds.height = mBounds.height;
1461 } else {
1462 mLayout.bounds = mBounds;
1464 [mScrollView setFrame: SCtoNSRect(mLayout.bounds)];
1465 //[mTextView setFrame: SCtoNSRect(mLayout.bounds)]; // not needed - br
1467 // [mScrollView setBounds: SCtoNSRect(mBounds)];
1468 // [mTextView setBounds: SCtoNSRect(mBounds)];
1469 // [mScrollView setNeedsDisplay: YES]; // not needed - br
1470 // [mTextView setNeedsDisplay: YES]; // not needed - br
1473 void SCCocoaTextView::keyDown(int character, int modifiers, unsigned short keycode)
1477 void SCCocoaTextView::keyUp(int character, int modifiers, unsigned short keycode)
1482 int slotColorVal(PyrSlot *slot, SCColor *sccolor);
1483 int setSlotColor(PyrSlot *slot, SCColor *sccolor);
1485 int SCCocoaTextView::setProperty(PyrSymbol *symbol, PyrSlot *slot)
1487 int err;
1488 char *name = symbol->name;
1490 if (strcmp(name, "visible")==0) {
1491 bool visible = IsTrue(slot);
1492 mVisible = visible;
1493 setVisibleFromParent();
1494 return errNone;
1497 if (strcmp(name, "usesTabToFocusNextView")==0) {
1498 if(IsTrue(slot))[mCocoaToLangAction setUsesTabToFocusNextView:YES];
1499 else [mCocoaToLangAction setUsesTabToFocusNextView:NO];
1500 return errNone;
1502 if (strcmp(name, "enterExecutesSelection")==0) {
1503 if(IsTrue(slot))[mCocoaToLangAction setEnterExecutesSelection:YES];
1504 else [mCocoaToLangAction setEnterExecutesSelection:NO];
1505 return errNone;
1507 if (strcmp(name, "setScrollersSize")==0) {
1508 if(IsTrue(slot)) [[mScrollView verticalScroller] setControlSize: NSMiniControlSize];
1509 else [mScrollView setAutohidesScrollers:NO];
1510 [mScrollView setNeedsDisplay: YES];
1511 return errNone;
1515 if (strcmp(name, "setAutohidesScrollers")==0) {
1516 if(IsTrue(slot)) [mScrollView setAutohidesScrollers:YES];
1517 else [mScrollView setAutohidesScrollers:NO];
1518 [mScrollView setNeedsDisplay: YES];
1519 return errNone;
1523 if (strcmp(name, "setHasHorizontalScroller")==0) {
1524 if(IsTrue(slot)) [mScrollView setHasHorizontalScroller:YES];
1525 else [mScrollView setHasHorizontalScroller:NO];
1526 [mScrollView setNeedsDisplay: YES];
1527 return errNone;
1531 if (strcmp(name, "setHasVerticalScroller")==0) {
1532 if(IsTrue(slot)) [mScrollView setHasVerticalScroller:YES];
1533 else [mScrollView setHasVerticalScroller:NO];
1534 [mScrollView setNeedsDisplay: YES];
1535 return errNone;
1537 if (strcmp(name, "setEditable")==0) {
1538 if(IsTrue(slot)) [mTextView setEditable:YES];
1539 else [mTextView setEditable:NO];
1540 return errNone;
1542 if (strcmp(name, "bounds")==0) {
1543 SCRect screct;
1544 //add avariable to choos if this should resize the textview too
1545 err = slotGetSCRect(slot, &screct);
1546 if (err) return err;
1548 setBounds(screct);
1550 return errNone;
1553 if (strcmp(name, "textBounds")==0) {
1554 SCRect screct;
1555 err = slotGetSCRect(slot, &screct);
1556 if (err) return err;
1557 [[mScrollView superview] setNeedsDisplayInRect:[mScrollView frame]];
1558 //mBounds = screct;
1560 [mTextView setFrame: SCtoNSRect(screct)];
1562 // [mScrollView setBounds: SCtoNSRect(mBounds)];
1563 // [mTextView setBounds: SCtoNSRect(mBounds)];
1564 [mScrollView setNeedsDisplay: YES];
1565 [mTextView setNeedsDisplay: YES];
1567 return errNone;
1569 if (strcmp(name, "selectedString")==0) {
1570 if(!isKindOfSlot(slot, class_string)) return errWrongType;
1571 PyrString* pstring = slotRawString(slot);
1572 if(!pstring) return errNone;
1573 NSRange selectedRange = [mTextView selectedRange];
1574 NSString *string = [[NSString alloc] initWithCString: pstring->s length: pstring->size];
1575 if ([mTextView shouldChangeTextInRange: selectedRange replacementString: string]) {
1576 [mTextView replaceCharactersInRange: selectedRange withString: string];
1577 [mTextView didChangeText];
1579 [string release];
1580 return errNone;
1583 if (strcmp(name, "open")==0) {
1584 if(!isKindOfSlot(slot, class_string)) return errWrongType;
1585 PyrString* pstring = slotRawString(slot);
1586 if(!pstring) return errNone;
1587 NSRange selectedRange = [mTextView selectedRange];
1588 NSString *path = [[NSString alloc] initWithCString: pstring->s length: pstring->size];
1590 int result = open(path);
1592 [path release];
1593 return result;
1596 if (strcmp(name, "background")==0) {
1597 err = slotBackgroundVal(slot, &mBackground);
1598 if (err) return err;
1599 SCColor rgb;
1600 err = slotColorVal(slot, &rgb);
1601 if (err) return err;
1602 NSColor *color = [NSColor colorWithCalibratedRed: rgb.red
1603 green: rgb.green
1604 blue: rgb.blue
1605 alpha: rgb.alpha];
1606 [mTextView setBackgroundColor: color];
1607 [mScrollView setBackgroundColor: color];
1608 return errNone;
1611 if (strcmp(name, "setTextColor")==0) {
1612 if(!isKindOfSlot(slot, class_array)) return errWrongType;
1613 PyrSlot *slots = slotRawObject(slot)->slots;
1614 SCColor rgb;
1615 int rangeStart, rangeSize;
1616 err = slotColorVal(slots+0, &rgb);
1617 if (err) return err;
1618 err = slotIntVal(slots+1, &rangeStart);
1619 if (err) return err;
1620 err = slotIntVal(slots+2, &rangeSize);
1621 if (err) return err;
1624 NSColor *color = [NSColor colorWithCalibratedRed: rgb.red
1625 green: rgb.green
1626 blue: rgb.blue
1627 alpha: rgb.alpha];
1629 //[[doc textView] setBackgroundColor: color];
1631 if(rangeStart < 0){
1632 [mTextView setTextColor: color];
1633 [mTextView didChangeText];
1634 return errNone;
1636 int length = [[mTextView string] length];
1637 if(rangeStart >= length) rangeStart = length - 1 ;
1638 if(rangeStart + rangeSize >= length) rangeSize = length - rangeStart;
1639 NSRange selectedRange = NSMakeRange(rangeStart, rangeSize);
1642 [mTextView setTextColor: color range: selectedRange];
1643 [mTextView didChangeText];
1644 return errNone;
1647 if (strcmp(name, "setFont")==0) {
1648 if(!isKindOfSlot(slot, class_array)) return errWrongType;
1649 PyrSlot *slots =slotRawObject(slot)->slots;
1650 PyrSlot *fontSlot = slots+0;
1651 if (IsNil(fontSlot)) return errNone; // use default font
1652 if (!(isKindOfSlot(fontSlot, s_font->u.classobj))) return errWrongType;
1653 PyrSlot *nameSlot = slotRawObject(fontSlot)->slots+0;
1654 PyrSlot *sizeSlot = slotRawObject(fontSlot)->slots+1;
1655 float size;
1656 int err = slotFloatVal(sizeSlot, &size);
1657 if (err) return err;
1659 PyrString *pstring = slotRawString(nameSlot);
1660 NSString *fontName = [NSString stringWithCString: pstring->s length: pstring->size];
1661 if (!fontName) return errFailed;
1662 NSFont *font = [NSFont fontWithName: fontName size: size];
1663 if (!font) return errFailed;
1665 int rangeStart, rangeSize;
1666 err = slotIntVal(slots+1, &rangeStart); //if -1 do not use range
1667 if (err) return err;
1668 err = slotIntVal(slots+2, &rangeSize);
1669 if (err) return err;
1671 if(rangeStart < 0){
1672 [mTextView setFont: font];
1673 return errNone;
1675 NSString* string = [mTextView string];
1676 int length = [string length];
1677 if(length < 1) return errFailed;
1678 if(rangeStart >= length) rangeStart = length - 1 ;
1679 if(rangeStart + rangeSize >= length) rangeSize = length - rangeStart;
1680 NSRange selectedRange = NSMakeRange(rangeStart, rangeSize);
1682 [mTextView setFont: font range: selectedRange];
1683 return errNone;
1686 // if (strcmp(name, "insertString")==0) {
1687 // if (!(isKindOfSlot(slot, class_string))) return errWrongType;
1688 // PyrString* string = slotRawString(slot);
1689 //// [doc insertText: string->s length: string->size];
1690 // return errNone;
1691 // }
1692 if (strcmp(name, "insertStringInRange")==0) {
1693 if(!isKindOfSlot(slot, class_array)) return errWrongType;
1694 PyrSlot *slots =slotRawObject(slot)->slots;
1695 PyrSlot *stringSlot = slots+0;
1696 if (!(isKindOfSlot(stringSlot, class_string))) return errWrongType;
1698 int rangeStart, rangeSize;
1699 int err = slotIntVal(slots+1, &rangeStart); //if -1 do not use range
1700 if (err) return err;
1701 err = slotIntVal(slots+2, &rangeSize);
1702 if (err) return err;
1704 PyrString* pstring = slotRawString(stringSlot);
1705 NSRange selectedRange;
1706 int length = [[mTextView string] length];
1708 if(rangeSize < 0) rangeSize = length - 1;
1709 if(rangeStart >= length) rangeStart = length - 1 ;
1710 if(rangeStart + rangeSize >= length) rangeSize = length - rangeStart;
1712 if(rangeStart<0) selectedRange = NSMakeRange(0, length);
1713 else selectedRange = NSMakeRange(rangeStart, rangeSize);
1715 NSString *string = [[NSString alloc] initWithCString: pstring->s length: pstring->size];
1716 BOOL editable = [mTextView isEditable];
1717 if(!editable) [mTextView setEditable:YES]; //always allow programmatic editing
1719 if ([mTextView shouldChangeTextInRange: selectedRange replacementString: string]) {
1720 [mTextView replaceCharactersInRange: selectedRange withString: string];
1721 [mTextView didChangeText];
1724 if(!editable) [mTextView setEditable:NO];
1726 [string release];
1728 return errNone;
1731 if (strcmp(name, "setSyntaxColors")==0) {
1732 SyntaxColorize(mTextView);
1733 return errNone;
1736 if (strcmp(name, "setUsesAutoInOutdent")==0) {
1737 bool uses = IsTrue(slot);
1738 [mTextView setUsesAutoInOutdent: uses];
1739 return errNone;
1742 return SCView::setProperty(symbol, slot);
1745 int SCCocoaTextView::getProperty(PyrSymbol *symbol, PyrSlot *slot)
1747 char *name = symbol->name;
1748 VMGlobals *g = gMainVMGlobals;
1750 if (strcmp(name, "string")==0) {
1751 NSString* str = [mTextView string];
1752 const char * cstr = [str UTF8String];
1753 PyrString *string = newPyrString(g->gc, cstr, 0, true);
1754 SetObject(slot, string);
1755 return errNone;
1758 if (strcmp(name, "selectedString")==0) {
1759 NSString* str = [mTextView currentlySelectedTextOrLine:NULL];
1760 const char * cstr = [str UTF8String];
1761 PyrString *string = newPyrString(g->gc, cstr, 0, true);
1762 SetObject(slot, string);
1763 return errNone;
1766 if (strcmp(name, "selectedRange")==0) {
1767 NSRange range = [mTextView selectedRange];
1768 SetInt(slot, range.length);
1769 return errNone;
1772 if (strcmp(name, "selectedRangeLocation")==0) {
1773 NSRange range = [mTextView selectedRange];
1774 SetInt(slot, range.location);
1775 return errNone;
1778 if (strcmp(name, "path")==0) {
1779 if(mLastURL) {
1780 const char * cstr = [[mLastURL path] UTF8String];
1781 PyrString *string = newPyrString(g->gc, cstr, 0, true);
1782 SetObject(slot, string);
1783 } else SetNil(slot);
1784 return errNone;
1787 return SCView::getProperty(symbol, slot);
1790 int SCCocoaTextView::open(NSString *path)
1792 NSURL *url = [[NSURL alloc] initWithString: path];
1793 if(!url) return errFailed;
1795 NSTextStorage* text = [mTextView textStorage];
1797 NSString* extension = [path pathExtension];
1799 if ([extension isEqualToString: @"html"] || [extension isEqualToString: @"htm"]) {
1801 SEL sel = @selector(loadHTMLToTextView:);
1802 NSMethodSignature *sig = [SCCocoaTextViewResponder instanceMethodSignatureForSelector: sel];
1803 SCVirtualMachine* scvm = [SCVirtualMachine sharedInstance];
1805 NSInvocation *anInvocation = [NSInvocation invocationWithMethodSignature: sig];
1806 [anInvocation setTarget: mCocoaToLangAction];
1807 [anInvocation setSelector: sel];
1808 [anInvocation setArgument:&url atIndex:2];
1809 [scvm defer: anInvocation];
1810 return errNone;
1812 else {
1813 [text beginEditing]; // Bracket with begin/end editing for efficiency
1814 [[text mutableString] setString:@""]; // Empty the document
1816 NSError *error;
1817 BOOL success = [text readFromURL:url options:nil documentAttributes:nil error:&error];
1818 if(!success) {
1819 NSLog(@"Error opening file: %@", error);
1820 [text endEditing];
1821 [url release];
1822 return errFailed;
1826 if ([extension isEqualToString: @"sc"] || [extension isEqualToString: @"scd"]) {
1827 [mTextView setFont: [NSFont fontWithName: @"Monaco" size: 9]];
1828 SyntaxColorize(mTextView);
1830 [mTextView scrollPoint:NSMakePoint(0, 0)];
1831 [text endEditing];
1832 [mLastURL release];
1833 mLastURL = url;
1834 return errNone;
1837 void SCCocoaTextView::setVisibleFromParent()
1839 if(mVisible && mParent->isVisible()) {
1840 [mScrollView setHidden:NO];
1841 [mTextView setHidden:NO];
1842 return;
1843 } else {
1844 [mScrollView setHidden:YES];
1845 [mTextView setHidden:YES];
1850 extern int ivxSCTextView_linkAction;
1852 bool SCCocoaTextView::linkAction(NSString *url)
1854 if(NotNil(mObj->slots + ivxSCTextView_linkAction)){
1855 pthread_mutex_lock (&gLangMutex);
1856 PyrSymbol *method = getsym("doLinkAction");
1857 if (mObj) {
1858 VMGlobals *g = gMainVMGlobals;
1859 g->canCallOS = true;
1860 const char * cstr = [url UTF8String];
1861 PyrString *string = newPyrString(g->gc, cstr, 0, true);
1862 ++g->sp; SetObject(g->sp, mObj);
1863 ++g->sp; SetObject(g->sp, string);
1864 ++g->sp; SetObject(g->sp, string);
1865 runInterpreter(g, method, 3);
1866 g->canCallOS = false;
1868 pthread_mutex_unlock (&gLangMutex);
1869 return true;
1870 } else return false; // handle the link in the responder
1876 ////////////////////
1877 SCView* NewSCMovieView(SCContainerView *inParent, PyrObject* inObj, SCRect inBounds)
1879 return new SCMovieView(inParent, inObj, inBounds);
1882 SCMovieView::SCMovieView(SCContainerView *inParent, PyrObject* inObj, SCRect inBounds)
1883 : SCView(inParent, inObj, inBounds)
1885 NSRect matrect = SCtoNSRect(getDrawBounds());
1886 mMovieView = [[QTMovieView alloc] initWithFrame:matrect];
1887 [mMovieView setStepButtonsVisible:YES];
1888 [mMovieView setTranslateButtonVisible:YES];
1889 NSView *view = mTop->GetNSView();
1890 [view addSubview: mMovieView];
1892 setVisibleFromParent();
1895 SCMovieView::~SCMovieView()
1897 [mMovieView removeFromSuperview];
1898 [mMovieView release];
1901 void SCMovieView::setBounds(SCRect screct)
1903 [[mMovieView superview] setNeedsDisplayInRect:[mMovieView frame]];
1904 mBounds = screct;
1905 if(!(mParent->isSubViewScroller())){
1906 SCRect pbounds = mParent->getLayout().bounds;
1907 mLayout.bounds.x = mBounds.x + pbounds.x;
1908 mLayout.bounds.y = mBounds.y + pbounds.y;
1909 mLayout.bounds.width = mBounds.width;
1910 mLayout.bounds.height = mBounds.height;
1911 } else {
1912 mLayout.bounds = mBounds;
1915 [mMovieView setFrame: SCtoNSRect(mLayout.bounds)];
1916 [mMovieView setBounds: SCtoNSRect(mBounds)]; //?
1917 [mMovieView setNeedsDisplay: YES];
1920 int SCMovieView::setProperty(PyrSymbol *symbol, PyrSlot *slot)
1922 int err;
1923 char *name = symbol->name;
1925 if (strcmp(name, "visible")==0) {
1926 bool visible = IsTrue(slot);
1927 mVisible = visible;
1928 setVisibleFromParent();
1929 return errNone;
1932 if (strcmp(name, "stop")==0) {
1933 [mMovie stop];
1934 return errNone;
1937 if (strcmp(name, "start")==0) {
1938 [mMovie play];
1939 return errNone;
1941 if (strcmp(name, "stepForward")==0) {
1942 [mMovie stepForward];
1943 return errNone;
1945 if (strcmp(name, "stepBack")==0) {
1946 [mMovie stepBackward];
1947 return errNone;
1950 if (strcmp(name, "resizeWithMagnification")==0) {
1951 float mag;
1952 err = slotFloatVal(slot, &mag);
1953 if(err) return err;
1954 [mMovieView resizeWithMagnification: mag];
1955 NSSize size = [mMovieView sizeForMagnification: mag];
1956 mBounds.width = size.width;
1957 mBounds.height = size.height;
1958 return errNone;
1961 if (strcmp(name, "bounds")==0) {
1962 SCRect screct;
1963 err = slotGetSCRect(slot, &screct);
1964 if (err) return err;
1965 setBounds(screct);
1966 return errNone;
1969 if (strcmp(name, "setMovie")==0) {
1970 if(!isKindOfSlot(slot, class_string)) return errWrongType;
1971 PyrString* pstring = slotRawString(slot);
1972 if(!pstring) return errNone;
1973 NSString *string = [[NSString alloc] initWithCString: pstring->s length: pstring->size];
1974 NSURL * url = [[NSURL alloc] initFileURLWithPath: string];
1975 QTMovie *movie = [[QTMovie alloc] initWithURL: url error:nil];
1976 if(!movie) return errFailed;
1977 //check for current movie:
1978 QTMovie *old_movie = [mMovieView movie];
1979 [mMovieView setMovie: movie];
1980 if(old_movie){
1981 [old_movie release];
1983 [string release];
1984 [url release];
1985 /* QT: */
1986 mMovie = movie;
1987 mTime = [movie currentTime];
1989 return errNone;
1992 if (strcmp(name, "setMuted")==0) {
1993 if(IsTrue(slot))[mMovie setMuted: YES];
1994 else [mMovie setMuted: NO];
1995 return errNone;
1998 if (strcmp(name, "setEditable")==0) {
1999 if(IsTrue(slot))[mMovieView setEditable: YES];
2000 else [mMovieView setEditable: NO];
2001 return errNone;
2004 if (strcmp(name, "setPlaysSelectionOnly")==0) {
2005 [mMovie setAttribute:[NSNumber numberWithBool:IsTrue(slot)] forKey:QTMoviePlaysSelectionOnlyAttribute];
2006 return errNone;
2009 if (strcmp(name, "setRate")==0) {
2010 float rate;
2011 err = slotFloatVal(slot, &rate);
2012 if(err) return err;
2013 [mMovie setRate:rate];
2014 return errNone;
2016 if (strcmp(name, "setVolume")==0) {
2017 float vol;
2018 err = slotFloatVal(slot, &vol);
2019 if(err) return err;
2020 [mMovie setVolume:vol];
2021 return errNone;
2023 if (strcmp(name, "setLoopMode")==0) {
2024 int mode;
2025 err = slotIntVal(slot, &mode);
2026 if(err) return err;
2027 NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithBool:NO], QTMovieLoopsBackAndForthAttribute, [NSNumber numberWithBool:NO], QTMovieLoopsAttribute, nil];
2028 switch(mode)
2030 case 0: [dict setObject:[NSNumber numberWithBool:YES] forKey:QTMovieLoopsBackAndForthAttribute]; break;
2031 case 1: [dict setObject:[NSNumber numberWithBool:YES] forKey:QTMovieLoopsAttribute]; break;
2032 case 2:
2033 default: break;
2035 [mMovie setMovieAttributes:dict];
2036 return errNone;
2038 if (strcmp(name, "gotoEnd")==0) {
2039 [mMovie gotoEnd];
2040 return errNone;
2043 if (strcmp(name, "gotoBeginning")==0) {
2044 [mMovie gotoBeginning];
2045 return errNone;
2048 if (strcmp(name, "showControllerAndAdjustSize")==0) {
2049 if(!isKindOfSlot(slot, class_array)) return errWrongType;
2050 PyrSlot *slots = slotRawObject(slot)->slots;
2051 BOOL showC, adjust;
2052 if(IsTrue(slots+0)) showC=YES;
2053 else showC = NO;
2054 if(IsTrue(slots+1)) adjust=YES;
2055 else adjust = NO;
2056 [mMovieView setControllerVisible:showC];
2057 //[mMovieView showController: showC adjustingSize: adjust];
2058 return errNone;
2061 if (strcmp(name, "copy")==0) {
2062 [mMovieView copy: NULL];
2063 return errNone;
2065 if (strcmp(name, "clear")==0) {
2066 [mMovieView delete: NULL];
2067 return errNone;
2069 if (strcmp(name, "cut")==0) {
2070 [mMovieView cut: NULL];
2071 return errNone;
2073 if (strcmp(name, "paste")==0) {
2074 [mMovieView paste: NULL];
2075 return errNone;
2078 if (strcmp(name, "setCurrentTime")==0) {
2079 float time;
2080 err = slotFloatVal(slot, &time);
2081 if(err) return err;
2082 QTTime qttime = mTime;
2083 qttime.timeValue = time * qttime.timeScale;
2084 [mMovie setCurrentTime:qttime];
2085 return errNone;
2088 return SCView::setProperty(symbol, slot);
2091 int SCMovieView::getProperty(PyrSymbol *symbol, PyrSlot *slot)
2093 char *name = symbol->name;
2094 //GetMovieDuration([[mMovieView movie] QTMovie]);
2095 if (strcmp(name, "getCurrentTime")==0) {
2096 float time;
2097 //post("timescale: %d \n", mTimeRecord.scale);
2098 QTTime qt_time = [mMovie currentTime];
2099 time = (float) ((float)qt_time.timeValue / qt_time.timeScale);
2100 SetFloat(slot, time);
2101 return errNone;
2103 return SCView::getProperty(symbol, slot);
2106 void SCMovieView::setVisibleFromParent()
2108 if(mVisible && mParent->isVisible()) {
2109 [mMovieView setHidden:NO];
2110 } else {
2111 [mMovieView setHidden:YES];
2113 [mMovieView setNeedsDisplay:YES];
2114 NSRect frame = [mMovieView frame];
2115 [mMovieView setFrame: NSInsetRect(frame,1,1)];
2116 [mMovieView setFrame: frame];
2117 mTop->resetFocus();
2118 refresh();
2121 extern PyrSymbol *s_proto, *s_parent;
2122 extern int ivxIdentDict_array, ivxIdentDict_size, ivxIdentDict_parent, ivxIdentDict_proto, ivxIdentDict_know;
2123 int identDictPut(struct VMGlobals *g, PyrObject *dict, PyrSlot *key, PyrSlot *value);
2124 extern PyrClass *class_identdict;
2125 ///////////
2127 SCQuartzComposerView by Scott Wilson
2128 Copyright (c) 2007 Scott Wilson. All rights reserved.
2129 Development funded in part by the Arts and Humanites Research Council http://www.ahrc.ac.uk/
2132 SCView* NewSCQuartzComposerView(SCContainerView *inParent, PyrObject* inObj, SCRect inBounds)
2134 return new SCQuartzComposerView(inParent, inObj, inBounds);
2137 SCQuartzComposerView::SCQuartzComposerView(SCContainerView *inParent, PyrObject* inObj, SCRect inBounds)
2138 : SCView(inParent, inObj, inBounds)
2140 NSRect matrect = SCtoNSRect(getDrawBounds());
2141 mQCView = [[QCView alloc] initWithFrame:matrect];
2142 [mQCView setEventForwardingMask: NSAnyEventMask];
2143 NSView *view = mTop->GetNSView();
2144 [view addSubview: mQCView];
2146 setVisibleFromParent();
2149 SCQuartzComposerView::~SCQuartzComposerView()
2151 [mQCView removeFromSuperview];
2152 [mQCView release];
2156 void SCQuartzComposerView::setBounds(SCRect screct)
2158 [[mQCView superview] setNeedsDisplayInRect:[mQCView frame]];
2159 mBounds = screct;
2160 if(!(mParent->isSubViewScroller())){
2161 SCRect pbounds = mParent->getLayout().bounds;
2162 mLayout.bounds.x = mBounds.x + pbounds.x;
2163 mLayout.bounds.y = mBounds.y + pbounds.y;
2164 mLayout.bounds.width = mBounds.width;
2165 mLayout.bounds.height = mBounds.height;
2166 } else {
2167 mLayout.bounds = mBounds;
2169 [mQCView setFrame: SCtoNSRect(mLayout.bounds)];
2170 [mQCView setNeedsDisplay: YES];
2175 int SCQuartzComposerView::setProperty(PyrSymbol *symbol, PyrSlot *slot)
2177 char *name = symbol->name;
2179 if (strcmp(name, "visible")==0) {
2180 bool visible = IsTrue(slot);
2181 // if(visible && mParent->isVisible())
2182 // {
2183 // [mQCView setHidden:NO];
2184 // }
2185 // else
2186 // {
2187 // [mQCView setHidden:YES];
2188 // mTop->resetFocus();
2189 // }
2190 mVisible = visible;
2191 setVisibleFromParent();
2192 return errNone;
2195 if (strcmp(name, "bounds")==0) {
2196 SCRect screct;
2197 int err = slotGetSCRect(slot, &screct);
2198 if (err) return err;
2199 mBounds = screct;
2200 setBounds(screct);
2201 return errNone;
2204 if (strcmp(name, "loadCompositionFromFile")==0) {
2205 if(!isKindOfSlot(slot, class_string)) return errWrongType;
2206 PyrString* pstring = slotRawString(slot);
2207 if(!pstring) return errNone;
2208 NSString *string = [[NSString alloc] initWithCString: pstring->s length: pstring->size];
2209 BOOL success = [mQCView loadCompositionFromFile: string];
2210 if(!success) return errFailed;
2211 [string release];
2212 return errNone;
2215 if (strcmp(name, "stop")==0) {
2216 [mQCView stopRendering];
2217 return errNone;
2220 if (strcmp(name, "start")==0) {
2221 BOOL success = [mQCView startRendering];
2222 if(!success) return errFailed;
2223 return errNone;
2226 //// doesn't seem to work ; fix later
2227 // if (strcmp(name, "erase")==0) {
2228 // [mQCView erase];
2229 // return errNone;
2230 // }
2232 // if (strcmp(name, "eraseColor")==0) {
2233 // SCColor rgb;
2234 // int err = slotColorVal(slot, &rgb);
2235 // if (err) return err;
2236 // NSColor *color = [NSColor colorWithCalibratedRed: rgb.red green: rgb.green blue: rgb.blue alpha: rgb.alpha];
2237 // //NSLog(@"color: %@", color);
2238 // //NSColor *color = [NSColor blueColor];
2239 // [mQCView setEraseColor: color];
2240 // [mQCView erase];
2241 // return errNone;
2242 // }
2244 if (strcmp(name, "setMaxRenderingFrameRate")==0) {
2245 float rate;
2246 int err = slotFloatVal(slot, &rate);
2247 if (err) return err;
2248 [mQCView setMaxRenderingFrameRate: rate];
2249 return errNone;
2252 if (strcmp(name, "setInputValue")==0) {
2253 if(!isKindOfSlot(slot, class_array)) return errWrongType;
2254 PyrSlot *slots = slotRawObject(slot)->slots;
2255 PyrSymbol *keysymbol;
2256 int err = slotSymbolVal(slots + 0, &keysymbol);
2257 if (err) return err;
2259 NSString *key = [[NSString alloc] initWithCString: keysymbol->name encoding: NSASCIIStringEncoding];
2260 if(![[mQCView inputKeys] containsObject: key]) {
2261 [key release];
2262 //post("There is no port with key \"%s\".\n\n", [key cString]);
2263 return errFailed;
2266 id nsObject = getNSObjectForSCObject(slots + 1, &err);
2267 if(!nsObject) {[key release]; return err;}
2268 BOOL success = [mQCView setValue: nsObject forInputKey: key];
2269 [key release];
2270 if(!success) return errFailed;
2271 return errNone;
2275 return SCView::setProperty(symbol, slot);
2278 id SCQuartzComposerView::getNSObjectForSCObject(PyrSlot *scobject, int *returnErr) {
2280 int err;
2281 // find the value type and set appropriately
2282 if(IsFloat(scobject)) { // it's a float
2283 float val;
2284 err = slotFloatVal(scobject, &val);
2285 if (err) {returnErr = &err; return NULL;}
2286 NSNumber *returnObject = [NSNumber numberWithFloat: val];
2287 if(!returnObject) { err = errFailed; returnErr = &err; return NULL;}
2288 return returnObject;
2289 } else if(IsInt(scobject)) { // it's an int
2290 int val;
2291 err = slotIntVal(scobject, &val);
2292 if (err) {returnErr = &err; return NULL;}
2293 NSNumber *returnObject = [NSNumber numberWithInt: val];
2294 if(!returnObject) { err = errFailed; returnErr = &err; return NULL;}
2295 return returnObject;
2296 } else if(IsTrue(scobject)) { // it's bool true
2297 NSNumber *returnObject = [NSNumber numberWithBool: YES];
2298 if(!returnObject) { err = errFailed; returnErr = &err; return NULL;}
2299 return returnObject;
2300 } else if(IsFalse(scobject)) { // it's bool false
2301 NSNumber *returnObject = [NSNumber numberWithBool: NO];
2302 if(!returnObject) { err = errFailed; returnErr = &err; return NULL;}
2303 return returnObject;
2304 } else if(isKindOfSlot(scobject, s_string->u.classobj)) { // it's a string
2305 PyrString *string = slotRawString(scobject);
2306 if(string->size == 0) { err = errFailed; returnErr = &err; return NULL;}
2307 NSString *returnObject = [NSString stringWithCString: string->s length: string->size];
2308 if(!returnObject) { err = errFailed; returnErr = &err; return NULL;}
2309 return returnObject;
2310 } else if(isKindOfSlot(scobject, s_color->u.classobj)) { // it's a color
2311 SCColor rgb;
2312 err = slotColorVal(scobject, &rgb);
2313 if (err) {returnErr = &err; return NULL;}
2314 NSColor *returnObject = [NSColor colorWithCalibratedRed: rgb.red green: rgb.green blue: rgb.blue alpha: rgb.alpha];
2315 if(!returnObject) { err = errFailed; returnErr = &err; return NULL;}
2316 return returnObject;
2317 } else if(isKindOfSlot(scobject, s_identitydictionary->u.classobj)) { // it's a structure (dict)
2318 PyrObject *array;
2319 array = slotRawObject(&(slotRawObject(scobject)->slots[ivxIdentDict_array]));
2320 if (!isKindOf((PyrObject*)array, class_array)) { err = errFailed; returnErr = &err; return NULL;}
2321 NSMutableDictionary *structure = [NSMutableDictionary dictionary];
2322 int len = array->size;
2324 for(int i=0; i<len; i=i+2){
2325 PyrSlot *element = array->slots+i;
2326 if(!IsNil(element)) {
2327 PyrSymbol *keysymbol;
2328 err = slotSymbolVal(element, &keysymbol);
2329 if (err) {returnErr = &err; return NULL;}
2330 NSString *key = [[NSString alloc] initWithCString: keysymbol->name encoding: NSASCIIStringEncoding];
2331 int innerErr;
2332 id innerSCObject = getNSObjectForSCObject(element + 1, &innerErr);
2333 if(!innerSCObject) { returnErr = &innerErr; return NULL;}
2334 [structure setObject: innerSCObject forKey: key];
2337 err = errNone;
2338 returnErr = &err;
2339 return structure;
2340 } else if(isKindOfSlot(scobject, class_array)) { // it's a structure (array)
2341 PyrSlot *array = scobject;
2342 int len = slotRawObject(array)->size;
2343 NSMutableArray *structure = [NSMutableArray arrayWithCapacity: (unsigned)len];
2345 for(int i =0; i<len; i++){
2346 PyrSlot *element = slotRawObject(array)->slots+i;
2347 int innerErr;
2348 id innerSCObject = getNSObjectForSCObject(element, &innerErr);
2349 if(!innerSCObject) { returnErr = &innerErr; return NULL;}
2350 [structure addObject: innerSCObject];
2353 err = errNone;
2354 returnErr = &err;
2355 return structure;
2356 } else if(isKindOfSlot(scobject, s_scimage->u.classobj)) { // it's an SCImage : )
2357 SCImage *scimage = (SCImage *)slotRawPtr(slotRawObject(scobject)->slots);
2358 if(scimage) {
2359 if([scimage isAccelerated])
2360 return [scimage ciimage];
2361 else
2362 return [scimage nsimage];
2364 else {
2365 post("SCQuartzComposerView: invalid SCImage as input port !");
2366 err = errWrongType;
2367 returnErr = &err;
2368 return NULL;
2370 } else {
2371 err = errWrongType; // it's something else...
2372 returnErr = &err;
2373 return NULL;
2378 int SCQuartzComposerView::getProperty(PyrSymbol *symbol, PyrSlot *slot)
2380 char *name = symbol->name;
2381 if (strcmp(name, "getOutputValue")==0) {
2382 PyrSymbol *keysymbol;
2383 int err = slotSymbolVal(slot, &keysymbol);
2384 if (err) return err;
2386 NSString *key = [[NSString alloc] initWithCString: keysymbol->name encoding: NSASCIIStringEncoding];
2387 if(![[mQCView outputKeys] containsObject: key]) {
2388 [key release];
2389 //post("There is no port with key \"%s\".\n\n", [key cString]);
2390 return errFailed;
2393 NSDictionary *outputAttributes = [[mQCView attributes] objectForKey: key];
2394 NSString *type = [outputAttributes objectForKey:QCPortAttributeTypeKey];
2396 id nsObject = [mQCView valueForOutputKey: key];
2397 [key release];
2398 err = getSCObjectForNSObject(slot, nsObject, type);
2399 if (err) return err;
2400 return errNone;
2402 } else if(strcmp(name, "getInputValue")==0) {
2403 PyrSymbol *keysymbol;
2404 int err = slotSymbolVal(slot, &keysymbol);
2405 if (err) return err;
2407 NSString *key = [[NSString alloc] initWithCString: keysymbol->name encoding: NSASCIIStringEncoding];
2408 if(![[mQCView inputKeys] containsObject: key]) {
2409 [key release];
2410 //post("There is no port with key \"%s\".\n\n", [key cString]);
2411 return errFailed;
2414 NSDictionary *inputAttributes = [[mQCView attributes] objectForKey: key];
2415 NSString *type = [inputAttributes objectForKey:QCPortAttributeTypeKey];
2417 id nsObject = [mQCView valueForInputKey: key];
2418 [key release];
2419 err = getSCObjectForNSObject(slot, nsObject, type);
2420 if (err) return err;
2421 return errNone;
2423 } else if(strcmp(name, "getInputKeys")==0) {
2424 NSArray* inputKeys = [mQCView inputKeys];
2425 int size = [inputKeys count];
2426 VMGlobals *g = gMainVMGlobals;
2427 PyrObject* array = newPyrArray(g->gc, size, 0, true);
2428 SetObject(slot, array);
2430 for (int i=0; i<size; ++i) {
2431 NSString *name = [inputKeys objectAtIndex: i];
2432 PyrString *string = newPyrString(g->gc, [name UTF8String], 0, true);
2433 SetObject(array->slots + array->size, string);
2434 array->size++;
2435 g->gc->GCWrite(array, string);
2438 return errNone;
2440 } else if(strcmp(name, "getOutputKeys")==0) {
2441 NSArray* inputKeys = [mQCView outputKeys];
2442 int size = [inputKeys count];
2443 VMGlobals *g = gMainVMGlobals;
2444 PyrObject* array = newPyrArray(g->gc, size, 0, true);
2445 SetObject(slot, array);
2447 for (int i=0; i<size; ++i) {
2448 NSString *name = [inputKeys objectAtIndex: i];
2449 PyrString *string = newPyrString(g->gc, [name UTF8String], 0, true);
2450 SetObject(array->slots + array->size, string);
2451 array->size++;
2452 g->gc->GCWrite(array, string);
2455 return errNone;
2458 return SCView::getProperty(symbol, slot);
2461 int SCQuartzComposerView::getSCObjectForNSObject(PyrSlot *slot, id nsObject, NSString *type)
2463 if([type isEqualToString:QCPortTypeBoolean]) {
2464 SetBool(slot, [nsObject boolValue]);
2465 return errNone;
2466 } else if([type isEqualToString:QCPortTypeIndex]) {
2467 SetInt(slot, [nsObject intValue]);
2468 return errNone;
2469 } else if([type isEqualToString:QCPortTypeNumber]) {
2470 SetFloat(slot, [nsObject floatValue]);
2471 return errNone;
2472 } else if([type isEqualToString:QCPortTypeString]) {
2473 const char * cstr = [nsObject UTF8String];
2474 VMGlobals *g = gMainVMGlobals;
2475 PyrString *string = newPyrString(g->gc, cstr, 0, true);
2476 SetObject(slot, string);
2477 return errNone;
2478 } else if([type isEqualToString:QCPortTypeColor]) {
2480 VMGlobals *g = gMainVMGlobals;
2481 PyrObject* colorObj = instantiateObject(g->gc, s_color->u.classobj, 0, false, true);
2482 SCColor rgb = SCMakeColor([nsObject redComponent], [nsObject greenComponent], [nsObject blueComponent], [nsObject alphaComponent]);
2483 SetObject(slot, colorObj);
2484 int err = setSlotColor(slot, &rgb);
2485 if (err) { return err;}
2486 return errNone;
2487 } else if([type isEqualToString:QCPortTypeStructure]) {
2488 //NSLog(@"QCPortTypeStructure");
2489 //NSLog(@"class: %@", [nsObject class]);
2491 // for the moment QC seems to deal with all internal structures as NSCFDictionary
2492 // but check here to be safe
2493 if([nsObject isKindOfClass: [NSDictionary class]]){
2494 //NSLog(@"it's a dict");
2495 PyrObject *dict, *array;
2496 VMGlobals *g = gMainVMGlobals;
2498 dict = instantiateObject(g->gc, class_identdict, 5, true, false);
2499 array = newPyrArray(g->gc, 4, 0, false);
2500 array->size = 4;
2501 nilSlots(array->slots, array->size);
2502 SetObject(dict->slots + ivxIdentDict_array, array);
2503 g->gc->GCWrite(dict, array);
2504 SetObject(slot, dict);
2506 NSEnumerator *enumerator = [nsObject keyEnumerator];
2507 id key;
2509 while ((key = [enumerator nextObject])) {
2510 //NSLog(@"key class: %@", [key class]);
2511 id innerNSObject = [nsObject objectForKey: key];
2512 //NSLog(@"innerNSObject: %@", innerNSObject);
2513 PyrSlot innerSlot;
2514 NSString *innerType;
2516 if([innerNSObject isKindOfClass: [NSNumber class]]){
2517 //NSLog(@"objCType: %s", [innerNSObject objCType]);
2518 if(!strcmp([innerNSObject objCType], @encode(BOOL))) {
2519 //NSLog(@"Number");
2520 innerType = QCPortTypeBoolean;
2521 } else if(!strcmp([innerNSObject objCType], @encode(int))) {
2522 innerType = QCPortTypeIndex;
2523 } else innerType = QCPortTypeNumber;
2524 } else if([innerNSObject isKindOfClass: [NSColor class]]){
2525 //NSLog(@"Color");
2526 innerType = QCPortTypeColor;
2527 } else if([innerNSObject isKindOfClass: [NSString class]]){
2528 //NSLog(@"String");
2529 innerType = QCPortTypeString;
2530 } else if([innerNSObject isKindOfClass: [NSArray class]] || [innerNSObject isKindOfClass: [NSDictionary class]]){
2531 //NSLog(@"Structure");
2532 innerType = QCPortTypeStructure;
2533 } else return errWrongType; // it's something else
2535 //NSLog(@"innerObject Class: %@", [innerNSObject class]);
2536 int err = getSCObjectForNSObject(&innerSlot, innerNSObject, innerType);
2537 if(err) return err;
2539 PyrSlot outKey;
2540 SetSymbol(&outKey, getsym([key cString]));
2541 err = identDictPut(g, dict, &outKey, &innerSlot);
2542 if(err) return err;
2546 return errNone;
2550 else if([type isEqualToString:QCPortTypeImage]) { // SCImage
2551 NSImage *nsimage = (NSImage*)nsObject;
2552 if(!nsimage)
2553 post("SCQuartzComposerView: bad return value as QCPortTypeImage");
2555 SCImage *scimage = [[SCImage alloc]initWithNSImage:nsimage];
2556 if(scimage) {
2557 VMGlobals *g = gMainVMGlobals;
2558 PyrObject *object = newPyrSCImage(g); // should be garbage collected
2559 if(object) {
2560 PyrSlot *slots = object->slots;
2561 SetObject(slot, object);
2562 SetPtr(slots + 0, scimage);
2563 SetFloat(slots + 1, (float)[scimage width]);
2564 SetFloat(slots + 2, (float)[scimage height]);
2565 return errNone;
2568 else {
2569 post("SCQuartzComposerView: failed NSImage to SCImage conversion !");
2572 return errWrongType; // it's something else
2577 void SCQuartzComposerView::setVisibleFromParent()
2579 if(mVisible && mParent->isVisible()) {
2580 [mQCView setHidden:NO];
2581 return;
2582 } else {
2583 [mQCView setHidden:YES];
2585 mTop->resetFocus();
2589 ////////////////////
2590 SCView* NewSCWebView(SCContainerView *inParent, PyrObject* inObj, SCRect inBounds)
2592 return new SCWebView(inParent, inObj, inBounds);
2595 SCWebView::SCWebView(SCContainerView *inParent, PyrObject* inObj, SCRect inBounds)
2596 : SCView(inParent, inObj, inBounds)
2598 NSRect matrect = SCtoNSRect(getDrawBounds());
2599 //NSLog(@"bounds %@", NSStringFromRect(matrect));
2600 mWebView = [[SCNSWebView alloc] initWithFrame:matrect frameName:nil groupName: nil];
2601 [mWebView initVars];
2602 NSView *view = mTop->GetNSView();
2603 flipView = [[view window] contentView];
2604 if (![flipView isKindOfClass: [SCNSFlippedView class]] ) {
2605 flipView = [[SCNSFlippedView alloc] initWithFrame:[view frame]]; // a wrapper view hack to get coords right
2606 [view retain];
2607 [view setAutoresizingMask: 63];
2608 [flipView setAutoresizesSubviews:YES];
2609 [[view window] setContentView:flipView];
2610 [flipView addSubview:view];
2611 } else {
2612 [flipView retain]; // increment the retain count
2614 [view addSubview:mWebView];
2616 [mWebView setEditingDelegate:mWebView];
2617 [mWebView setFrameLoadDelegate:mWebView];
2618 [mWebView setPolicyDelegate:mWebView];
2619 //[mWebView setUIDelegate:mWebView];
2621 [mWebView setSCObject: this];
2623 [mWebView setFocusRingType:NSFocusRingTypeNone];
2624 [mWebView setEnterExecutesSelection:YES];
2625 [mWebView setPreferencesIdentifier:@"SuperCollider"];
2627 setVisibleFromParent();
2630 SCWebView::~SCWebView()
2632 [mWebView removeFromSuperview];
2633 [mWebView close];
2634 [[SCVirtualMachine sharedInstance] removeDeferredOperationsFor:mWebView];
2635 [mWebView release];
2636 if ([flipView retainCount] == 1) { // if nobody else needs this wrapperView, clean it up
2637 NSView *view = mTop->GetNSView();
2638 [[view window] setContentView:view];
2639 [view release];
2640 [flipView removeFromSuperview];
2641 [flipView release];
2642 } else {
2643 [flipView release]; // otherwise just decrement the retain count
2648 void SCWebView::setBounds(SCRect screct)
2651 mBounds.x == screct.x &&
2652 mBounds.x == screct.y &&
2653 mBounds.width == screct.width &&
2654 mBounds.height == screct.height
2655 ) { // in case - prevent a refresh if the bounds are the same
2656 return;
2659 mBounds = screct;
2660 if(!(mParent->isSubViewScroller())){
2661 SCRect pbounds = mParent->getLayout().bounds;
2662 mLayout.bounds.x = mBounds.x + pbounds.x;
2663 mLayout.bounds.y = mBounds.y + pbounds.y;
2664 mLayout.bounds.width = mBounds.width;
2665 mLayout.bounds.height = mBounds.height;
2666 } else {
2667 mLayout.bounds = mBounds;
2670 [mWebView setFrame: SCtoNSRect(mLayout.bounds)];
2673 void SCWebView::doOnLoadAction()
2675 pthread_mutex_lock (&gLangMutex);
2676 if(compiledOK){
2677 PyrSymbol *method = getsym("didLoad");
2678 VMGlobals *g = gMainVMGlobals;
2679 g->canCallOS = true;
2680 ++g->sp; SetObject(g->sp, mObj);
2681 runInterpreter(g, method, 1);
2682 g->canCallOS = false;
2684 pthread_mutex_unlock (&gLangMutex);
2687 void SCWebView::doLoadFailedAction()
2689 pthread_mutex_lock (&gLangMutex);
2690 if(compiledOK){
2691 PyrSymbol *method = getsym("didFail");
2692 VMGlobals *g = gMainVMGlobals;
2693 g->canCallOS = true;
2694 ++g->sp; SetObject(g->sp, mObj);
2695 runInterpreter(g, method, 1);
2696 g->canCallOS = false;
2698 pthread_mutex_unlock (&gLangMutex);
2701 void SCWebView::doLinkClickedAction(PyrString* pstring)
2703 pthread_mutex_lock (&gLangMutex);
2704 if(compiledOK){
2705 PyrSymbol *method = getsym("linkActivated");
2706 VMGlobals *g = gMainVMGlobals;
2707 g->canCallOS = true;
2708 ++g->sp; SetObject(g->sp, mObj);
2709 ++g->sp; SetObject(g->sp, pstring);
2710 runInterpreter(g, method, 2);
2711 g->canCallOS = false;
2713 pthread_mutex_unlock (&gLangMutex);
2716 int SCWebView::setProperty(PyrSymbol *symbol, PyrSlot *slot)
2718 int err;
2719 char *name = symbol->name;
2721 if (strcmp(name, "url")==0) {
2722 if(!isKindOfSlot(slot, class_string)) return errWrongType;
2723 PyrString* pstring = slotRawString(slot);
2724 if(!pstring) return errFailed;
2725 [mWebView resetLoadCount];
2726 NSString *path = [[NSString alloc] initWithCString: pstring->s length: pstring->size];
2727 [[mWebView mainFrame] loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:path]]];
2728 return errNone;
2731 if (strcmp(name, "visible")==0) {
2732 bool visible = IsTrue(slot);
2733 mVisible = visible;
2734 setVisibleFromParent();
2735 return errNone;
2738 if (strcmp(name, "bounds")==0) {
2739 SCRect screct;
2740 err = slotGetSCRect(slot, &screct);
2741 if (err) return err;
2742 setBounds(screct);
2743 return errNone;
2746 if (strcmp(name, "back")==0) {
2747 if([mWebView canGoBack]) {
2748 [mWebView resetLoadCount];
2749 SEL selector = @selector(goBack);
2750 NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:
2751 [mWebView methodSignatureForSelector: selector]];
2752 [invocation setTarget:mWebView];
2753 [invocation setSelector: selector];
2755 [[SCVirtualMachine sharedInstance] defer: invocation];
2757 return errNone;
2760 if (strcmp(name, "forward")==0) {
2761 if([mWebView canGoForward]) {
2762 [mWebView resetLoadCount];
2763 SEL selector = @selector(goForward);
2764 NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:
2765 [mWebView methodSignatureForSelector: selector]];
2766 [invocation setTarget:mWebView];
2767 [invocation setSelector: selector];
2769 [[SCVirtualMachine sharedInstance] defer: invocation];
2771 return errNone;
2774 if (strcmp(name, "reload")==0) {
2775 [mWebView resetLoadCount];
2776 SEL selector = @selector(reload:);
2777 NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:
2778 [mWebView methodSignatureForSelector: selector]];
2779 [invocation setTarget:mWebView];
2780 [invocation setSelector: selector];
2781 [invocation setArgument:&mWebView atIndex:2];
2783 [[SCVirtualMachine sharedInstance] defer: invocation];
2784 return errNone;
2787 if (strcmp(name, "html")==0) {
2788 if(!isKindOfSlot(slot, class_string)) return errWrongType;
2789 PyrString* pstring = slotRawString(slot);
2790 if(!pstring) return errFailed;
2791 [mWebView resetLoadCount];
2792 NSString *html = [[NSString alloc] initWithCString: pstring->s length: pstring->size];
2793 [[mWebView mainFrame] loadHTMLString:html baseURL:nil];
2794 return errNone;
2797 if (strcmp(name, "handleLinks")==0) {
2798 bool handleLinks = IsTrue(slot);
2799 [mWebView setHandleLinks: handleLinks];
2800 return errNone;
2803 if (strcmp(name, "editable")==0) {
2804 bool editable = IsTrue(slot);
2805 [mWebView setEditable: editable];
2806 return errNone;
2809 if (strcmp(name, "findText")==0) {
2810 if(!isKindOfSlot(slot, class_array)) return errWrongType;
2811 PyrSlot *slots =slotRawObject(slot)->slots;
2812 PyrSlot *stringSlot = slots+0;
2813 if(!isKindOfSlot(stringSlot, class_string)) return errWrongType;
2814 PyrString* pstring = slotRawString(stringSlot);
2815 if(!pstring) return errFailed;
2816 NSString *searchText = [[NSString alloc] initWithCString: pstring->s length: pstring->size];
2818 PyrSlot *dir = slots+1;
2819 bool goesForward = IsFalse(dir);
2821 [mWebView searchFor:searchText direction:goesForward caseSensitive:NO wrap:YES];
2822 return errNone;
2825 if (strcmp(name, "enterExecutesSelection")==0) {
2826 if(IsTrue(slot))[mWebView setEnterExecutesSelection:YES];
2827 else [mWebView setEnterExecutesSelection:NO];
2828 return errNone;
2831 if (strcmp(name, "fontFamily")==0) {
2832 if(!isKindOfSlot(slot, class_array)) return errWrongType;
2833 PyrSlot *slots = slotRawObject(slot)->slots;
2834 if(!IsSym(slots+0)) return errWrongType;
2835 PyrString* pstring = slotRawString(slots+1);
2836 if(!pstring) return errFailed;
2838 PyrSymbol *genericFont = slotRawSymbol(slots+0);
2839 NSString *specificFont = [[NSString alloc] initWithCString: pstring->s length: pstring->size];
2841 if (genericFont == getsym("standard"))
2842 [[mWebView preferences] setStandardFontFamily: specificFont];
2843 else if (genericFont == getsym("fixed"))
2844 [[mWebView preferences] setFixedFontFamily: specificFont];
2845 else if (genericFont == getsym("serif"))
2846 [[mWebView preferences] setSerifFontFamily: specificFont];
2847 else if (genericFont == getsym("sansSerif"))
2848 [[mWebView preferences] setSansSerifFontFamily: specificFont];
2849 else if (genericFont == getsym("cursive"))
2850 [[mWebView preferences] setCursiveFontFamily: specificFont];
2851 else if (genericFont == getsym("fantasy"))
2852 [[mWebView preferences] setFantasyFontFamily: specificFont];
2854 [specificFont release];
2856 return errNone;
2859 return SCView::setProperty(symbol, slot);
2863 int SCWebView::getProperty(PyrSymbol *symbol, PyrSlot *slot)
2865 char *name = symbol->name;
2866 VMGlobals *g = gMainVMGlobals;
2868 if (strcmp(name, "url")==0) {
2869 NSString *rawLocationString = [mWebView stringByEvaluatingJavaScriptFromString:@"location.href;"];
2870 const char * cstr = [rawLocationString UTF8String];
2871 PyrString *string = newPyrString(g->gc, cstr, 0, true);
2872 SetObject(slot, string);
2873 return errNone;
2876 if (strcmp(name, "html")==0) {
2877 NSString *html = [mWebView stringByEvaluatingJavaScriptFromString:@"document.documentElement.outerHTML"];
2878 const char * cstr = [html UTF8String];
2879 PyrString *string = newPyrString(g->gc, cstr, 0, true);
2880 SetObject(slot, string);
2881 return errNone;
2884 if (strcmp(name, "plainText")==0) {
2885 NSString *plainText = [mWebView stringByEvaluatingJavaScriptFromString:@"document.body.innerText"];
2886 const char * cstr = [plainText UTF8String];
2887 PyrString *string = newPyrString(g->gc, cstr, 0, true);
2888 SetObject(slot, string);
2889 return errNone;
2892 if (strcmp(name, "selectedText")==0) {
2893 NSString *selectedText = [mWebView stringByEvaluatingJavaScriptFromString:@"(function (){return window.getSelection().toString();})();"];
2894 const char * cstr = [selectedText UTF8String];
2895 PyrString *string = newPyrString(g->gc, cstr, 0, true);
2896 SetObject(slot, string);
2897 return errNone;
2900 if (strcmp(name, "title")==0) {
2901 NSString *rawLocationString = [mWebView mainFrameTitle];
2902 const char * cstr = [rawLocationString UTF8String];
2903 PyrString *string = newPyrString(g->gc, cstr, 0, true);
2904 SetObject(slot, string);
2905 return errNone;
2908 return SCView::getProperty(symbol, slot);
2912 void SCWebView::setVisibleFromParent()
2914 if(mVisible && mParent->isVisible()) {
2915 [mWebView setHidden:NO];
2916 } else {
2917 [mWebView setHidden:YES];
2919 [mWebView setNeedsDisplay:YES];
2920 NSRect frame = [mWebView frame];
2921 [mWebView setFrame: frame];
2922 mTop->resetFocus();
2923 refresh();
2927 void SCWebView::tabPrevFocus()
2929 mTop->tabPrevFocus();
2931 void SCWebView::tabNextFocus()
2933 //post("next focus\n");
2934 mTop->tabNextFocus();
2937 void SCWebView::mouseTrack(SCPoint where, int modifiers, NSEvent *theEvent)
2939 if (modifiers & NSCommandKeyMask) {
2940 beginDrag(where);
2945 ////////////////////
2947 ////////////////////
2948 SCView* NewSCTextField(SCContainerView *inParent, PyrObject* inObj, SCRect inBounds)
2950 return new SCTextField(inParent, inObj, inBounds);
2953 SCTextField::SCTextField(SCContainerView *inParent, PyrObject* inObj, SCRect inBounds)
2954 : SCView(inParent, inObj, inBounds)
2955 //: SCStaticText(inParent, inObj, inBounds)
2957 NSRect matrect = SCtoNSRect(getDrawBounds());
2958 mTextField = [[SCTextFieldResponder alloc] initWithFrame:matrect];
2959 NSView *view = mTop->GetNSView();
2960 [view addSubview: mTextField];
2962 [mTextField setFocusRingType:NSFocusRingTypeNone];
2963 //NSLog(@"SCTextField init\n");
2965 //mCocoaToLangAction = [SCTextFieldResponder alloc];
2966 [mTextField setSCView: this];
2967 [mTextField setDelegate: mTextField];
2968 [mTextField setEditingInactive:NO];
2970 [mTextField setBordered:NO]; // for some reason, if we don't set this we can't have transparency
2971 [mTextField setDrawsBackground:NO]; // SCView will draw for us. This also allows 0 < alpha < 1
2973 [[mTextField cell] setScrollable:YES];
2975 mBackground = new SolidColorBackground(SCMakeColor(1.0,1.0,1.0, 1.0)); // default is white
2977 [mTextField registerForDraggedTypes: [NSArray arrayWithObjects: sSCObjType, NSStringPboardType, NSFilenamesPboardType, nil]];
2978 //This is a hack, otherwise the mTextField always has focus even if makeFirstResponder: view is called...
2979 [mTextField setAcceptsFirstResponder:NO];
2980 setVisibleFromParent();
2983 SCTextField::~SCTextField()
2985 [mTextField removeFromSuperview];
2986 [mTextField release];
2989 void SCTextField::setBounds(SCRect screct)
2992 mBounds.x == screct.x &&
2993 mBounds.x == screct.y &&
2994 mBounds.width == screct.width &&
2995 mBounds.height == screct.height
2996 ) { // in case - prevent a refresh if the bounds are the same
2997 return;
3000 //[[mTextField superview] setNeedsDisplayInRect:[mTextField frame]];
3001 mBounds = screct;
3002 if(!(mParent->isSubViewScroller())){
3003 SCRect pbounds = mParent->getLayout().bounds;
3004 mLayout.bounds.x = mBounds.x + pbounds.x;
3005 mLayout.bounds.y = mBounds.y + pbounds.y;
3006 mLayout.bounds.width = mBounds.width;
3007 mLayout.bounds.height = mBounds.height;
3008 } else {
3009 mLayout.bounds = mBounds;
3012 [mTextField setFrame: SCtoNSRect(mLayout.bounds)];
3013 //[mTextField setNeedsDisplay: YES];
3016 int SCTextField::setProperty(PyrSymbol *symbol, PyrSlot *slot)
3018 int err;
3019 char *name = symbol->name;
3021 if (strcmp(name, "string")==0) {
3022 if(!isKindOfSlot(slot, class_string)) return errWrongType;
3023 PyrString* pstring = slotRawString(slot);
3024 if(!pstring) return errNone;
3025 NSString *string = [[NSString alloc] initWithCString: pstring->s length: pstring->size];
3026 [mTextField setStringValue: string];
3027 [string release];
3028 return errNone;
3031 if (strcmp(name, "visible")==0) {
3032 bool visible = IsTrue(slot);
3033 mVisible = visible;
3034 setVisibleFromParent();
3035 return errNone;
3038 if (strcmp(name, "font")==0) {
3039 NSFont *font;
3040 if (IsNil(slot)){
3042 font = [NSFont controlContentFontOfSize: 0.0 ];
3044 }else{
3046 if (!(isKindOfSlot(slot, s_font->u.classobj))) return errWrongType;
3047 PyrSlot *nameSlot = slotRawObject(slot)->slots+0;
3048 PyrSlot *sizeSlot = slotRawObject(slot)->slots+1;
3049 float size;
3050 if (IsNil(sizeSlot)){
3051 size = [[mTextField font] pointSize];
3052 }else{
3053 int err = slotFloatVal(sizeSlot, &size);
3054 if (err) return err;
3057 PyrString *pstring = slotRawString(nameSlot);
3058 NSString *fontName = [NSString stringWithCString: pstring->s length: pstring->size];
3059 if (!fontName) return errFailed;
3060 font = [NSFont fontWithName: fontName size: size];
3061 if (!font) return errFailed;
3064 [mTextField setFont: font];
3065 return errNone;
3068 if (strcmp(name, "stringColor")==0) {
3069 err = slotColorVal(slot, &mStringColor);
3070 if (err) return err;
3071 NSColor *color = [NSColor colorWithCalibratedRed: mStringColor.red
3072 green: mStringColor.green
3073 blue: mStringColor.blue
3074 alpha: mStringColor.alpha];
3075 [mTextField setTextColor: color];
3076 refresh();
3077 return errNone;
3080 if (strcmp(name, "bounds")==0) {
3081 SCRect screct;
3082 err = slotGetSCRect(slot, &screct);
3083 if (err) return err;
3084 setBounds(screct);
3085 return errNone;
3088 if (strcmp(name, "align")==0) {
3089 int align;
3090 if (IsSym(slot)) {
3091 [[mTextField window] endEditingFor:mTextField];
3092 if (slotRawSymbol(slot)->name[0] == 'l') [mTextField setAlignment: NSLeftTextAlignment];
3093 else if (slotRawSymbol(slot)->name[0] == 'r') [mTextField setAlignment: NSRightTextAlignment];
3094 else if (slotRawSymbol(slot)->name[0] == 'c') [mTextField setAlignment: NSCenterTextAlignment];
3095 else return errFailed;
3097 //[mTextField display];
3098 }/* else {
3099 err = slotIntVal(slot, &align);
3100 if (err) return err;
3101 mAlignment = align;
3102 } */
3103 refresh();
3104 return errNone;
3107 if (strcmp(name, "enabled")==0) {
3108 bool enabled = IsTrue(slot);
3109 if (mEnabled != enabled) {
3110 mEnabled = enabled;
3111 [mTextField setEnabled:(BOOL)enabled];
3112 if (!mEnabled) mTop->resetFocus();
3113 refresh();
3115 return errNone;
3118 //return SCStaticText::setProperty(symbol, slot);
3119 return SCView::setProperty(symbol, slot);
3123 int SCTextField::getProperty(PyrSymbol *symbol, PyrSlot *slot)
3125 char *name = symbol->name;
3126 VMGlobals *g = gMainVMGlobals;
3128 if (strcmp(name, "string")==0) {
3129 NSString* str = [mTextField stringValue];
3130 const char * cstr = [str UTF8String];
3131 PyrString *string = newPyrString(g->gc, cstr, 0, true);
3132 SetObject(slot, string);
3133 return errNone;
3135 if (strcmp(name, "boxColor")==0) {
3136 return setSlotColor(slot, &mBoxColor);
3138 if (strcmp(name, "stringColor")==0) {
3139 return setSlotColor(slot, &mStringColor);
3142 //return SCStaticText::getProperty(symbol, slot);
3143 return SCView::getProperty(symbol, slot);
3147 void SCTextField::setVisibleFromParent()
3149 if(mVisible && mParent->isVisible()) {
3150 [mTextField setHidden:NO];
3151 } else {
3152 [mTextField setHidden:YES];
3154 [mTextField setNeedsDisplay:YES];
3155 NSRect frame = [mTextField frame];
3156 [mTextField setFrame: NSInsetRect(frame,1,1)];
3157 [mTextField setFrame: frame];
3158 mTop->resetFocus();
3159 refresh();
3162 void SCTextField::makeFocus(bool focus)
3164 if (focus) {
3165 if (canFocus() && !isFocus()) {
3166 [mTextField setAcceptsFirstResponder:YES];
3168 // trick focus ring into drawing
3169 SEL sel = @selector(setNeedsDisplay:);
3170 NSMethodSignature *sig = [NSView instanceMethodSignatureForSelector: sel];
3171 NSInvocation *anInvocation = [NSInvocation invocationWithMethodSignature: sig];
3172 SCVirtualMachine* scvm = [SCVirtualMachine sharedInstance];
3173 [anInvocation setTarget: [mTextField superview]];
3174 [anInvocation setSelector: sel];
3175 BOOL flag = YES;
3176 [anInvocation setArgument: &flag atIndex: 2];
3177 [scvm defer: anInvocation];
3179 } else {
3180 if (isFocus()) {
3181 [mTextField setAcceptsFirstResponder:NO];
3184 SCView::makeFocus(focus);
3187 void SCTextField::tabPrevFocus()
3189 mTop->tabPrevFocus();
3191 void SCTextField::tabNextFocus()
3193 //post("next focus\n");
3194 mTop->tabNextFocus();
3197 void SCTextField::keyDown(int character, int modifiers, unsigned short keycode)
3199 // when enter was pressed firstResponder was passed to the parent SCGraphView
3200 // this checks if keyDown was passed from there and if so starts to edit using the key pressed
3201 // We access the field editor as that's the receiving object while editing is active
3202 if([mTextField editingInactive] && (character != 13 || character !=3)) {
3203 //post("keydownEP\n");
3204 [[mTextField window] makeFirstResponder:mTextField];
3205 unichar charVal = (unichar)character;
3206 NSString *charstring = [[NSString alloc] initWithCharacters: &charVal length: 1];
3207 NSText *fieldEditor = [[mTextField window] fieldEditor:YES forObject:mTextField];
3208 [fieldEditor setString:charstring];
3209 [charstring release];
3210 [mTextField setEditingInactive:NO];
3212 SCView::keyDown(character, modifiers, keycode);
3215 extern PyrSymbol* s_canReceiveDrag;
3217 bool SCTextField::canReceiveDrag()
3219 PyrSlot result;
3220 sendMessage(s_canReceiveDrag, 0, 0, &result);
3221 return IsTrue(&result);
3224 NSDragOperation SCTextField::draggingEntered()
3226 bool flag = canReceiveDrag();
3227 mTop->setDragView(flag ? this : 0);
3228 [mTextField displayIfNeeded];
3229 return flag ? NSDragOperationEvery : NSDragOperationNone;
3232 extern PyrSymbol* s_receiveDrag;
3234 BOOL SCTextField::performDrag()
3236 bool flag = canReceiveDrag();
3237 if (flag) {
3238 mTop->setDragView(this);
3239 sendMessage(s_receiveDrag, 0, 0, 0);
3240 mTop->setDragView(0);
3241 } else {
3242 mTop->setDragView(0);
3244 [mTextField displayIfNeeded];
3245 return flag ? YES : NO;
3248 void SCTextField::mouseTrack(SCPoint where, int modifiers, NSEvent *theEvent)
3250 if (modifiers & NSCommandKeyMask) {
3251 beginDrag(where);
3255 extern PyrSymbol *s_beginDrag;
3257 void SCTextField::beginDrag(SCPoint where)
3259 sendMessage(s_beginDrag, 0, 0, 0);
3261 PyrSlot slot;
3262 PyrSlot stringSlot;
3263 NSString *string = 0;
3264 NSString *label = 0;
3265 pthread_mutex_lock (&gLangMutex);
3266 if (mObj) {
3267 VMGlobals *g = gMainVMGlobals;
3268 int classVarIndex = slotRawInt(&getsym("SCView")->u.classobj->classVarIndex);
3269 slotCopy(&slot, &g->classvars->slots[classVarIndex]);
3270 slotCopy(&stringSlot, &g->classvars->slots[classVarIndex+1]);
3271 if (isKindOfSlot(&stringSlot, class_string)) {
3272 string = [NSString stringWithCString: slotRawString(&stringSlot)->s length: slotRawString(&stringSlot)->size];
3274 if(mDragLabel) label = mDragLabel;
3276 pthread_mutex_unlock (&gLangMutex);
3278 //mTop->beginDragCallback(where, &slot, string, label);
3279 NSPoint point = NSMakePoint(where.x, where.y);
3280 [mTextField beginDragFrom: point of: &slot string: string label: label];
3283 ////////////////////
3284 SCView* NewSCNumberBox(SCContainerView *inParent, PyrObject* inObj, SCRect inBounds)
3286 return new SCNumberBox(inParent, inObj, inBounds);
3289 SCNumberBox::SCNumberBox(SCContainerView *inParent, PyrObject* inObj, SCRect inBounds)
3290 : SCTextField(inParent, inObj, inBounds)
3291 //: SCStaticText(inParent, inObj, inBounds)
3293 [mTextField addNumberFormatter];
3296 SCNumberBox::~SCNumberBox()
3300 int SCNumberBox::setProperty(PyrSymbol *symbol, PyrSlot *slot)
3302 int err;
3303 char *name = symbol->name;
3305 if (strcmp(name, "value")==0) {
3306 double value;
3307 err = slotDoubleVal(slot, &value);
3308 if (err) return err;
3309 [mTextField setDoubleValue:value];
3310 return errNone;
3313 // if (strcmp(name, "clipLo")==0) {
3314 // double value;
3315 // err = slotDoubleVal(slot, &value);
3316 // if (err) return err;
3317 // [[mTextField formatter] setMinimum:[NSNumber numberWithDouble:value]];
3318 // return errNone;
3319 // }
3321 // if (strcmp(name, "clipHi")==0) {
3322 // double value;
3323 // err = slotDoubleVal(slot, &value);
3324 // if (err) return err;
3325 // [[mTextField formatter] setMaximum:[NSNumber numberWithDouble:value]];
3326 // return errNone;
3327 // }
3329 return SCTextField::setProperty(symbol, slot);
3332 int SCNumberBox::getProperty(PyrSymbol *symbol, PyrSlot *slot)
3334 char *name = symbol->name;
3336 if (strcmp(name, "value")==0) {
3337 double val = [mTextField doubleValue];
3338 SetFloat(slot, val);
3339 return errNone;
3342 return SCTextField::getProperty(symbol, slot);
3345 void SCNumberBox::keyDown(int character, int modifiers, unsigned short keycode)
3347 // test for arrows enter and return
3348 if([mTextField editingInactive] && (character == 63232 || character == 63233 || character == 63234 || character == 63235 || character == 3 || character == 13)){
3349 SCView::keyDown(character, modifiers, keycode);
3350 } else {
3351 SCTextField::keyDown(character, modifiers, keycode);
3355 ////////////////////
3356 SCView* NewSCLevelIndicator(SCContainerView *inParent, PyrObject* inObj, SCRect inBounds)
3358 return new SCLevelIndicator(inParent, inObj, inBounds);
3361 SCLevelIndicator::SCLevelIndicator(SCContainerView *inParent, PyrObject* inObj, SCRect inBounds)
3362 : SCView(inParent, inObj, inBounds)
3364 NSRect matrect = SCtoNSRect(getDrawBounds());
3365 mLevelIndicator = [[SCNSLevelIndicator alloc] initWithFrame:matrect];
3366 NSView *view = mTop->GetNSView();
3367 [view addSubview: mLevelIndicator];
3369 [[mLevelIndicator cell] setLevelIndicatorStyle:NSContinuousCapacityLevelIndicatorStyle];
3370 [mLevelIndicator setMinValue:0.0];
3371 [mLevelIndicator setMaxValue:1.0];
3372 mStyle = 1;
3373 mNumSteps = 1;
3374 if(matrect.size.height > matrect.size.width) {
3375 [mLevelIndicator setBoundsRotation: 90.0]; // vertical
3376 [mLevelIndicator setIsVertical:YES];
3377 [mLevelIndicator setNeedsDisplay: YES];
3378 mIsVertical = true;
3379 } else mIsVertical = false;
3381 mWarning = 0.0;
3382 mCritical = 0.0;
3383 mTickHeight = 0.f;
3385 mImage = [[NSImage imageNamed:@"NSApplicationIcon"] retain];
3386 setImage();
3388 setVisibleFromParent();
3391 SCLevelIndicator::~SCLevelIndicator()
3393 [mLevelIndicator removeFromSuperview];
3394 [mLevelIndicator release];
3395 [mImage release];
3398 void SCLevelIndicator::setBounds(SCRect screct)
3400 mBounds = screct;
3401 if(!(mParent->isSubViewScroller())){
3402 SCRect pbounds = mParent->getLayout().bounds;
3403 mLayout.bounds.x = mBounds.x + pbounds.x;
3404 mLayout.bounds.y = mBounds.y + pbounds.y;
3405 mLayout.bounds.width = mBounds.width;
3406 mLayout.bounds.height = mBounds.height;
3407 } else {
3408 mLayout.bounds = mBounds;
3411 if(mBounds.height > mBounds.width) {
3412 [mLevelIndicator setBoundsRotation: 90.0]; // vertical
3413 mIsVertical = true;
3414 [mLevelIndicator setIsVertical:YES];
3415 } else {
3416 [mLevelIndicator setBoundsRotation: 0.0]; // horizontal
3417 mIsVertical = false;
3418 [mLevelIndicator setIsVertical:NO];
3421 if([mLevelIndicator numberOfTickMarks] > 0)
3422 mTickHeight = [mLevelIndicator rectOfTickMarkAtIndex:0].size.height; // 0 will be major if there are any
3423 else
3424 mTickHeight = 0.f;
3426 [mLevelIndicator setPeakSubtract:mTickHeight];
3428 setImage();
3429 [mLevelIndicator setFrame: SCtoNSRect(mLayout.bounds)];
3430 [mLevelIndicator setNeedsDisplay: YES];
3433 void SCLevelIndicator::setImage()
3435 NSImage* newImage = nil;
3437 NSSize imageSize = [mImage size];
3438 float width = imageSize.width;
3439 float height = imageSize.height;
3441 SCRect bounds = getDrawBounds();
3442 NSSize targetSize;
3443 if(mIsVertical) {
3444 targetSize = NSMakeSize(bounds.height / mNumSteps, bounds.width - mTickHeight);
3445 } else {
3446 targetSize = NSMakeSize(bounds.width / mNumSteps, bounds.height - mTickHeight);
3449 float targetWidth = targetSize.width;
3450 float targetHeight = targetSize.height;
3452 float scaleFactor = 0.0;
3453 float scaledWidth = targetWidth;
3454 float scaledHeight = targetHeight;
3456 NSPoint newPoint = NSMakePoint(0,0);
3458 if ( NSEqualSizes( imageSize, targetSize ) == NO )
3460 float widthFactor, heightFactor;
3461 if(mIsVertical){
3462 widthFactor = targetHeight / width;
3463 heightFactor = targetWidth / height;
3464 } else {
3465 widthFactor = targetWidth / width;
3466 heightFactor = targetHeight / height;
3469 if ( widthFactor < heightFactor)
3470 scaleFactor = widthFactor;
3471 else
3472 scaleFactor = heightFactor;
3474 scaledWidth = width * scaleFactor;
3475 scaledHeight = height * scaleFactor;
3477 if(mIsVertical) {
3478 if ( widthFactor < heightFactor)
3479 newPoint.y = (targetWidth - scaledHeight) * 0.5;
3480 else if ( widthFactor > heightFactor )
3481 newPoint.x = (targetHeight - scaledWidth) * 0.5;
3482 } else {
3483 if ( widthFactor < heightFactor)
3484 newPoint.y = (targetHeight - scaledHeight) * 0.5;
3485 else if ( widthFactor > heightFactor )
3486 newPoint.x = (targetWidth - scaledWidth) * 0.5;
3490 //NSLog(@"targetSize: %@", NSStringFromSize(targetSize));
3492 // create a new image to draw into
3493 newImage = [[NSImage alloc] initWithSize:targetSize];
3495 [newImage lockFocus];
3497 NSRect newRect;
3498 newRect.origin = newPoint;
3499 newRect.size.width = scaledWidth;
3500 newRect.size.height = scaledHeight;
3502 //NSLog(@"newPoint: %@", NSStringFromRect(newRect));
3504 if(mIsVertical) {
3506 NSAffineTransform *rotateTF = [NSAffineTransform transform];
3507 NSPoint centerPoint = NSMakePoint(targetSize.width / 2, targetSize.height / 2);
3509 [rotateTF translateXBy: centerPoint.x yBy: centerPoint.y];
3510 [rotateTF rotateByDegrees: - 90];
3511 [rotateTF translateXBy: -centerPoint.y yBy: -centerPoint.x];
3512 [rotateTF concat];
3515 [mImage drawInRect: newRect fromRect: NSZeroRect operation: NSCompositeSourceOver fraction: 1.0];
3517 [newImage unlockFocus];
3519 [[mLevelIndicator cell] setImage:newImage];
3521 [newImage autorelease];
3523 void SCLevelIndicator::resetParams()
3525 if(mStyle >= 2) {
3526 [mLevelIndicator setUpWarning:mWarning * mNumSteps];
3527 [mLevelIndicator setUpCritical:mCritical * mNumSteps];
3528 [mLevelIndicator setMaxValue: mNumSteps];
3529 } else {
3530 [mLevelIndicator setUpWarning:mWarning];
3531 [mLevelIndicator setUpCritical:mCritical];
3532 [mLevelIndicator setMaxValue: 1.0];
3534 [mLevelIndicator setNeedsDisplay:YES];
3537 int SCLevelIndicator::setProperty(PyrSymbol *symbol, PyrSlot *slot)
3539 int err;
3540 char *name = symbol->name;
3542 if (strcmp(name, "value")==0) {
3543 double value;
3544 err = slotDoubleVal(slot, &value);
3545 if (err) return err;
3546 if(mStyle >= 2) value = value * mNumSteps;
3547 [mLevelIndicator setDoubleValue:value];
3548 return errNone;
3551 if (strcmp(name, "warning")==0) {
3552 double value;
3553 err = slotDoubleVal(slot, &value);
3554 if (err) return err;
3555 mWarning = value;
3556 resetParams();
3557 return errNone;
3560 if (strcmp(name, "critical")==0) {
3561 double value;
3562 err = slotDoubleVal(slot, &value);
3563 if (err) return err;
3564 mCritical = value;
3565 resetParams();
3566 return errNone;
3569 if (strcmp(name, "visible")==0) {
3570 bool visible = IsTrue(slot);
3571 mVisible = visible;
3572 setVisibleFromParent();
3573 return errNone;
3576 if (strcmp(name, "bounds")==0) {
3577 SCRect screct;
3578 err = slotGetSCRect(slot, &screct);
3579 if (err) return err;
3580 setBounds(screct);
3581 return errNone;
3584 if (strcmp(name, "enabled")==0) {
3585 bool enabled = IsTrue(slot);
3586 if (mEnabled != enabled) {
3587 mEnabled = enabled;
3588 [mLevelIndicator setEnabled:(BOOL)enabled];
3589 if (!mEnabled) mTop->resetFocus();
3590 refresh();
3592 return errNone;
3595 if (strcmp(name, "style")==0) {
3596 int style;
3597 err = slotIntVal(slot, &style);
3598 if (err) return err;
3599 if(style <= 0) {
3600 [[mLevelIndicator cell] setLevelIndicatorStyle:NSContinuousCapacityLevelIndicatorStyle];
3601 mStyle = 0;
3602 } else if(style == 1) {
3603 [[mLevelIndicator cell] setLevelIndicatorStyle:NSRelevancyLevelIndicatorStyle];
3604 mStyle = 1;
3605 } else if(style == 2) {
3606 [[mLevelIndicator cell] setLevelIndicatorStyle:NSDiscreteCapacityLevelIndicatorStyle];
3607 mStyle = 2;
3608 } else {
3609 [[mLevelIndicator cell] setLevelIndicatorStyle:NSRatingLevelIndicatorStyle];
3610 mStyle = 3;
3611 setImage();
3613 resetParams();
3614 return errNone;
3617 if (strcmp(name, "numSteps")==0) {
3618 int numSteps;
3619 err = slotIntVal(slot, &numSteps);
3620 if (err) return err;
3621 mNumSteps = numSteps >= 1 ? (double)numSteps : 1.0;
3622 resetParams();
3623 setImage();
3624 return errNone;
3627 if (strcmp(name, "numTicks")==0) {
3628 int numTicks;
3629 err = slotIntVal(slot, &numTicks);
3630 if (err) return err;
3631 [mLevelIndicator setNumberOfTickMarks:numTicks];
3632 if(numTicks > 0)
3633 mTickHeight = [mLevelIndicator rectOfTickMarkAtIndex:0].size.height; // 0 will be major if there are any
3634 else
3635 mTickHeight = 0.f;
3636 [mLevelIndicator setPeakSubtract:mTickHeight];
3637 setImage();
3638 return errNone;
3641 if (strcmp(name, "numMajorTicks")==0) {
3642 int numTicks;
3643 err = slotIntVal(slot, &numTicks);
3644 if (err) return err;
3645 [mLevelIndicator setNumberOfMajorTickMarks:numTicks];
3646 if([mLevelIndicator numberOfTickMarks] > 0)
3647 mTickHeight = [mLevelIndicator rectOfTickMarkAtIndex:0].size.height; // 0 will be major if there are any
3648 else
3649 mTickHeight = 0.f;
3650 [mLevelIndicator setPeakSubtract:mTickHeight];
3651 setImage();
3652 return errNone;
3655 if (strcmp(name, "image")==0) {
3656 if(isKindOfSlot(slot, s_scimage->u.classobj)) { // it's an SCImage : )
3657 SCImage *scimage = (SCImage *)slotRawPtr(slotRawObject(slot)->slots);
3658 if(scimage) {
3659 NSImage *oldImage = mImage;
3660 mImage = [[scimage nsimage] retain];
3661 setImage();
3662 [oldImage release];
3663 return errNone;
3665 else {
3666 post("Invalid Image");
3667 return errWrongType;
3669 } else {
3670 return errWrongType;
3674 if (strcmp(name, "drawsPeak")==0) {
3675 bool drawsPeak = IsTrue(slot);
3676 [mLevelIndicator setDrawPeak:drawsPeak];
3677 return errNone;
3680 if (strcmp(name, "peakLevel")==0) {
3681 float value;
3682 err = slotFloatVal(slot, &value);
3683 if (err) return err;
3684 [mLevelIndicator setPeakLevel:sc_clip(value, 0.f, 1.f)];
3685 return errNone;
3688 return SCView::setProperty(symbol, slot);
3692 int SCLevelIndicator::getProperty(PyrSymbol *symbol, PyrSlot *slot)
3694 char *name = symbol->name;
3696 if (strcmp(name, "value")==0) {
3697 double value = [mLevelIndicator doubleValue];
3698 SetFloat(slot, value);
3699 return errNone;
3702 return SCView::getProperty(symbol, slot);
3706 void SCLevelIndicator::setVisibleFromParent()
3708 if(mVisible && mParent->isVisible()) {
3709 [mLevelIndicator setHidden:NO];
3710 } else {
3711 [mLevelIndicator setHidden:YES];
3713 [mLevelIndicator setNeedsDisplay:YES];
3714 mTop->resetFocus();
3715 refresh();
3718 void SCLevelIndicator::tabPrevFocus()
3720 mTop->tabPrevFocus();
3722 void SCLevelIndicator::tabNextFocus()
3724 //post("next focus\n");
3725 mTop->tabNextFocus();