Search Results

Search found 22 results on 1 pages for 'nsevent'.

Page 1/1 | 1 

  • How to get the current eventNumber for creating an event with NSEvent

    - by Chris
    Hello I'm creating an os x application for which I try to add a remote interface. For this I need to be able to send mouse down and mouse up commands to the window of my application. I found code with which I can successfully do this, it looks as follows: int mask = 0x100; NSEvent* eventMouseDown = [NSEvent mouseEventWithType:NSLeftMouseDown location:p modifierFlags:mask timestamp:[NSDate timeIntervalSinceSystemStartup] windowNumber:[w windowNumber] context:[NSGraphicsContext graphicsContextWithWindow:w] eventNumber:++eventCounter +42599 clickCount:1 pressure:0]; NSLog(@"Mouse down event: %@", eventMouseDown); [[NSApplication sharedApplication] sendEvent:eventMouseDown]; I have only one problem with this code thought and this is the eventNumer parameter. As far as I found out it is a number which get increased with each event. But I cannot find a way to find the current number from where on I need to increase. The number I use there currently is just try and error and also does not seam to work always.

    Read the article

  • How to store (and use) the current mouse position?

    - by Ben Packard
    What is the best way to store the current mouse position (system-wide) and then (later) put the mouse at that stored point? [NSEvent mouseLocation] gets me the position, and I can move the mouse with a CGEventMouseMoved, but they each use a different co-ordinates system (I believe y=0 is the top for NSEvent and the bottom for a CGEvent). I'm worried about the robustness of capturing the screen height and using it to convert between the two - or is this the best approach?

    Read the article

  • keyUp event heard?: Overridden NSView method

    - by Old McStopher
    UPDATED: I'm now overriding the NSView keyUp method from a NSView subclass set to first responder like below, but am still not seeing evidence that it is being called. @implementation svsView - (BOOL)acceptsFirstResponder { return YES; } - (void)keyUp:(NSEvent *)event { //--do key up stuff-- NSLog(@"key up'd!"); } @end --ORIGINAL POST-- I'm new to Cocoa and Obj-C and am trying to do a (void)keyUp: from within the implementation of my controller class (which itself is of type NSController). I'm not sure if this is the right place to put it, though. I have a series of like buttons each set to a unique key equivalent (IB button attribute) and each calls my (IBAction)keyInput method which then passes the identity of each key onto another object. This runs just fine, but I also want to track when each key is released. --ORIGINAL [bad] EXAMPLE-- @implementation svsController //init //IBActions - (IBAction)keyInput:(id)sender { //--do key down stuff-- } - (void)keyUp:(NSEvent *)event { //--do key up stuff-- } @end Upon fail, I also tried the keyUp as an IBAction (instead of void), like the user-defined keyInput is, and hooked it up to the appropriate buttons in Interface Builder, but then keyUp was only called when the keys were down and not when released. (Which I kind of figured would happen.) Pardon my noobery, but should I be putting this method in another class or doing something differently? Wherever it is, though, I need it be able to access objects owned by the controller class. Thanks for any insight you may have.

    Read the article

  • How may I monitor all gestures of the entire system

    - by Jiulong Zhao
    I can make a view to accept touch event and receive detailed gesture event like this: [self setAcceptsTouchEvents:YES]; // NSSet *touches = [event touchesMatchingPhase:NSTouchPhaseBegan inView:self]; I can also receive global event by crate a monitor in this way: NSUInteger eventMasks = NSEventTypeBeginGesture | NSEventTypeEndGesture | NSEventMaskGesture; [NSEvent addGlobalMonitorForEventsMatchingMask:eventMasks handler:^(NSEvent *theevent) {//do something}]; But I can NOT get the detailed event from monitor by -touchesMatchingPhase How may I monitor all gestures of the entire system.

    Read the article

  • Update NSView in function of events

    - by Forchita
    Hi everyone! I have a main view (subclass of NSView) and as i'm new to cocoa, i'd like to know how to update the view in function of events. I know there are many methods that take events such as -(void)mouseMoved:(NSEvent*)event or - (void)mouseClicked:(NSEvent*)event My algorithm to determine what to do is ready. I want to know where I should update the main view: is it in the -(void)mouseMoved:(NSEvent*)event or in the - (void)drawRect:(NSRect)dirtyRect. And if it is in drawRect, then how should i pass the information to it? Thanks in advance!

    Read the article

  • Cocoa nextEventMatchingMask not receiving NSMouseMoved event

    - by Jonny
    Hello, I created a local event loop and showed up a borderless window (derived from NSPanel), I found in the event loop there's no NSMouseMoved event received, although I can receive Mouse button down/up events. What should I do to get the NSMouseMoved events? I found making the float window as key window can receive the NSMouseMoved events, but I don't want to change key window. And it appears this is possible, because I found after clicking the test App Icon in System Dock Bar, I can receive the mousemoved events, and the key window/mainwindow are unchanged. Here's the my test code: (Create a Cocoa App project names FloatWindowTest, and put a button to link it with the onClick: IBAction). Thanks in advance! -Jonny #import "FloatWindowTestAppDelegate.h" @interface FloatWindow : NSPanel @end @interface FloatWindowContentView : NSView @end @implementation FloatWindowTestAppDelegate @synthesize window; - (void)delayedAction:(id)sender { // What does this function do? // 1. create a float window // 2. create a local event loop // 3. print out the events got from nextEventMatchingMask. // 4. send it to float window. // What is the problem? // In local event loop, althrough the event mask has set NSMouseMovedMask // there's no mouse moved messages received. // FloatWindow* floatWindow = [[FloatWindow alloc] init]; NSEvent* event = [NSApp currentEvent]; NSPoint screenOrigin = [[self window] convertBaseToScreen:[event locationInWindow]]; [floatWindow setFrameTopLeftPoint:screenOrigin]; [floatWindow orderFront:nil]; //Making the float window as Key window will work, however //change active window is not anticipated. //[floatWindow makeKeyAndOrderFront:nil]; BOOL done = NO; while (!done) { NSAutoreleasePool* pool = [NSAutoreleasePool new]; NSUInteger eventMask = NSLeftMouseDownMask| NSLeftMouseUpMask| NSMouseMovedMask| NSMouseEnteredMask| NSMouseExitedMask| NSLeftMouseDraggedMask; NSEvent* event = [NSApp nextEventMatchingMask:eventMask untilDate:[NSDate distantFuture] inMode:NSDefaultRunLoopMode dequeue:YES]; //why I cannot get NSMouseMoved event?? NSLog(@"new event %@", [event description]); [floatWindow sendEvent:event]; [pool drain]; } [floatWindow release]; return; } -(IBAction)onClick:(id)sender { //Tried to postpone the local event loop //after return from button's mouse tracking loop. //but not fixes this problem. [[NSRunLoop currentRunLoop] performSelector:@selector(delayedAction:) target:self argument:nil order:0 modes:[NSArray arrayWithObject:NSDefaultRunLoopMode]]; } @end @implementation FloatWindow - (id)init { NSRect contentRect = NSMakeRect(200,300,200,300); self = [super initWithContentRect:contentRect styleMask:NSTitledWindowMask backing:NSBackingStoreBuffered defer:YES]; if (self) { [self setLevel:NSFloatingWindowLevel]; NSRect frameRect = [self frameRectForContentRect:contentRect]; NSView* view = [[[FloatWindowContentView alloc] initWithFrame:frameRect] autorelease]; [self setContentView:view]; [self setAcceptsMouseMovedEvents:YES]; [self setIgnoresMouseEvents:NO]; } return self; } - (BOOL)becomesKeyOnlyIfNeeded { return YES; } - (void)becomeMainWindow { NSLog(@"becomeMainWindow"); [super becomeMainWindow]; } - (void)becomeKeyWindow { NSLog(@"becomeKeyWindow"); [super becomeKeyWindow]; } @end @implementation FloatWindowContentView - (BOOL)acceptsFirstMouse:(NSEvent *)theEvent { return YES; } - (BOOL)acceptsFirstResponder { return YES; } - (id)initWithFrame:(NSRect)frameRect { self = [super initWithFrame:frameRect]; if (self) { NSTrackingArea* area; area = [[NSTrackingArea alloc] initWithRect:frameRect options:NSTrackingActiveAlways| NSTrackingMouseMoved| NSTrackingMouseEnteredAndExited owner:self userInfo:nil]; [self addTrackingArea:area]; [area release]; } return self; } - (void)drawRect:(NSRect)rect { [[NSColor redColor] set]; NSRectFill([self bounds]); } - (BOOL)becomeFirstResponder { NSLog(@"becomeFirstResponder"); return [super becomeFirstResponder]; } @end

    Read the article

  • NSCollectionView subclass doesn't call drawRect during drag session despite setNeedsDisplay

    - by Alain Vitry
    Greetings, I am puzzled as to how and when drawRect is supposed to be called in a NSCollectionView subclass. I implement drag and drop operation in order to move NSCollectionViewItems within the collection, and would like to draw a visual indication of where the drop would end. The subclass does not call drawRect during the drag session. (It does during scroll) Is this the intended operation ? Any hint on how to implement this behavior properly are welcome. A full xcode project of the following code is available at: http://babouk.ovh.org/dload/MyCollectionView.zip Best regards Code sample: @interface CollectionViewAppDelegate : NSObject <NSApplicationDelegate> { NSWindow *window; NSMutableArray *collectionContent; } /* properties declaration */ /* KVC compliance declarations */ @end @interface MyCollectionView : NSCollectionView @end @interface ItemModel { NSString *name; } @property (copy) NSString *name; @end @implementation MyCollectionView - (void)drawRect:(NSRect)rect { NSLog(@"DrawRect"); } - (void)mouseDragged:(NSEvent *)aEvent { NSPoint localPoint = [self convertPoint:[aEvent locationInWindow] fromView:nil]; [self dragImage:[NSImage imageNamed:@"Move.png"] at:localPoint offset:NSZeroSize event:aEvent pasteboard:nil source:self slideBack:NO]; } - (BOOL)prepareForDragOperation:(id < NSDraggingInfo >)sender { return YES; } - (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender { return NSDragOperationEvery; } - (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)sender { [self setNeedsDisplay:YES]; return NSDragOperationEvery; } - (NSDragOperation)draggingSourceOperationMaskForLocal:(BOOL)isLocal { return NSDragOperationEvery; } - (void)mouseDown:(NSEvent *)theEvent { } @end @implementation CollectionViewAppDelegate @synthesize window, collectionContent, collectionView; - (void)applicationDidFinishLaunching:(NSNotification *)aNotification { NSMutableArray *data = [[NSMutableArray alloc] init]; /* Fill in data */ [self setCollectionContent:data]; [data release]; } /* dealloc */ /* KVC implementation */ @end @implementation ItemModel @synthesize name; /* dealloc */ @end

    Read the article

  • Getting Custom NSCell with NSButtonCell instance to handle mouse click/mouse events

    - by sidha
    OK I'm really stumped on this one. I want to make a checkbox with a NSTextFieldCell combined together. It's important that the checkbox goes ON if the mouse hits the box, NOT the text. I've accomplished this, more or less, but the issue is receiving the mouse event because I click one checkbox in a row, but ALL of them turn to NSOnState. I will show what I've done and my various failed attempts in order to get this to work. So this is how I've done it so far: header: @interface MyCheckboxCellToo : NSTextFieldCell { NSButtonCell *_checkboxCell; } implementation: - (NSUInteger)hitTestForEvent:(NSEvent *)event inRect:(NSRect)cellFrame ofView:(NSView *)controlView { NSPoint point = [controlView convertPoint:[event locationInWindow] fromView:nil]; NSLog(@"%@", NSStringFromPoint(point)); NSRect checkFrame; NSDivideRect(cellFrame, &checkFrame, &cellFrame, cellFrame.size.height/*3 + [[_checkboxCell image] size].width*/, NSMinXEdge); if (NSMouseInRect(point, checkFrame, [controlView isFlipped])) { // the checkbox, or the small region around it, was hit. so let's flip the state NSCellStateValue checkState = ([_checkboxCell state] == NSOnState) ? NSOffState:NSOnState; [self setState:checkState]; [_checkboxCell setState:checkState]; [controlView setNeedsDisplay:YES]; return NSCellHitTrackableArea; } return [super hitTestForEvent:event inRect:cellFrame ofView:controlView]; } I know I probably shouldn't be doing: [self setState:checkState]; [_checkboxCell setState:checkState]; [controlView setNeedsDisplay:YES]; in there... because the result is that EVERY checkbox in every goes to NSOnState. Is this because cells are re-used? How come the ImageAndTextCell can have different images in the same tableview? How do I handle the mouse event? I have tried: - (BOOL)trackMouse:(NSEvent *)theEvent inRect:(NSRect)cellFrame ofView:(NSView *)controlView untilMouseUp:(BOOL)untilMouseUp { NSLog(@"%s %@", _cmd, theEvent); return [_checkboxCell trackMouse:theEvent inRect:cellFrame ofView:controlView untilMouseUp:untilMouseUp]; // return YES; // return [super trackMouse:theEvent inRect:cellFrame ofView:controlView untilMouseUp:untilMouseUp]; } - (BOOL)startTrackingAt:(NSPoint)startPoint inView:(NSView *)controlView { NSLog(@"%s %@", _cmd, NSStringFromPoint(startPoint)); return [super startTrackingAt:startPoint inView:controlView]; } - (BOOL)continueTracking:(NSPoint)lastPoint at:(NSPoint)currentPoint inView:(NSView *)controlView { NSLog(@"%s %@", _cmd, NSStringFromPoint(currentPoint)); return [super continueTracking:lastPoint at:currentPoint inView:controlView]; } - (void)stopTracking:(NSPoint)lastPoint at:(NSPoint)stopPoint inView:(NSView *)controlView mouseIsUp:(BOOL)flag { NSLog(@"%s %d %@", _cmd, flag, NSStringFromPoint(stopPoint)); } trackMouse: ... DOES gets called but startTrackingAt:..., continueTracking:..., and stopTracking:.... DO NOT get called when I click on the checkbox "hit area" in trackMouse:... I have tried return [_checkboxCell trackMouse:theEvent inRect:cellFrame ofView:controlView untilMouseUp:untilMouseUp]; and return [super trackMouse:theEvent inRect:cellFrame ofView:controlView untilMouseUp:untilMouseUp]; and neither seems to result in the mouse event being handled by the checkbox. How do I get that single checkbox to go NSOnState? I know I'm pretty close but after a lot of doc reading and google searching I haven't been successful at solving this. suggestions and comments welcome.. OK here is a bit more to show creation and destruction of the object.. - (id)init { if ((self = [super init])) { _checkboxCell = [[NSButtonCell alloc] init]; [_checkboxCell setButtonType:NSSwitchButton]; [_checkboxCell setTitle:@""]; [_checkboxCell setTarget:self]; [_checkboxCell setImagePosition:NSImageLeft]; [_checkboxCell setControlSize:NSRegularControlSize]; } return self; } - copyWithZone:(NSZone *)zone { MyCheckboxCellToo *cell = (MyCheckboxCellToo *)[super copyWithZone:zone]; cell->_checkboxCell = [_checkboxCell copyWithZone:zone]; return cell; } - (void)dealloc { [_checkboxCell release]; [super dealloc]; }

    Read the article

  • [Cocoa] NSImage transparency

    - by ndg
    I'm trying to set a custom drag icon for use in an NSTableView. Everything seems to work but I've run into a problem due to my inexperience with Quartz. - (NSImage *)dragImageForRowsWithIndexes:(NSIndexSet *)dragRows tableColumns:(NSArray *)tableColumns event:(NSEvent *)dragEvent offset:(NSPointPointer)dragImageOffset { NSImage *dragImage = [NSImage imageNamed:@"icon.png"]; NSString *count = [NSString stringWithFormat:@"%d", [dragRows count]]; [dragImage lockFocus]; [dragImage compositeToPoint:NSZeroPoint fromRect:NSZeroRect operation:NSCompositeSourceOver fraction:0.5]; [count drawAtPoint:NSZeroPoint withAttributes:nil]; [dragImage unlockFocus]; return dragImage; } Essentially what I'm looking to do is render my icon.png file with 50% opacity along with an NSString which shows the number of rows currently being dragged. The issue I'm seeing is that my NSString renders with a low opacity, but not my icon.

    Read the article

  • Objective C memory leaking

    - by Jakub Lédl
    Hi everyone, I'm creating one Cocoa application for myself and I found a problem. I have two NSTextFields and they're connected to each other as nextKeyViews. When I run this app with memory leaks detection tool and tab through those 2 textboxes for a while, enter some text etc., I start to leak memory. It shows me that the AppKit library is responsible, the leaked objects are NSCFStrings and the responsible frames are [NSEvent charactersIgnoringModifiers] and [NSApplication nextEventMatchingMask:untilDate:inMode:dequeue:]. I know this is quite a brief and incomplete description, but does anyone have any ideas what could be the problem? Also, I don't use GC, so I release my instance variables in the controllers dealloc. What about the outlets? Since IBOutlet is just a mark for Interface Builder and doesn't actually mean anything, should I release them too?

    Read the article

  • Command line tool (PDF Workflow) in OSX that detects if key is down

    - by kroko
    Hello! I'm writing a OSX PDF Workflow in ObjC and C. A single executable ("UNIX Tool" as named in the Apple reference), that reads in the spooled PDF file, does some parsing. I'd like to give more functionality by enabling a key-down event handling, meaning - when user opens print dialog in an application - and chooses to left-mouse-click on the custom made pdf workflow to run it - depending on if a keyboard key is down (i.e. option key, but "any key down" would be enough for me) when running that workflow - a decision is made in the code. I have read NSEvent and Carbon Event Manager reference and it seems that in this case (a plain unix executable + not run as root) it's not possible. Or is it? Many thanks in advance, Kroko

    Read the article

  • NSMenu doesn't start tracking

    - by Measunny
    Hey, I have a little cocoa app which usually operates in the background (as agent). Sometimes I'd like to be able to popup a contextmenu (no window or s.th. visible at this time). As I'm only targetting Snow Leopard I tried this: if (windows) { NSMenu *theMenu = [[[NSMenu alloc] initWithTitle:@"test"] autorelease]; [theMenu setShowsStateColumn:NO]; [theMenu setAutoenablesItems:NO]; for (id item in windows) { NSString *labelText = @"some text"; NSMenuItem *theMenuItem = [[[NSMenuItem alloc] initWithTitle:labelText action:@selector(menuItemSelected:) keyEquivalent:@""] autorelease]; [theMenuItem setTarget:self]; [theMenuItem setRepresentedObject:item]; [theMenuItem setEnabled:YES]; [theMenuItem setImage:icon]; [theMenu addItem:theMenuItem]; } [theMenu popUpMenuPositioningItem:nil atLocation:[NSEvent mouseLocation] inView:nil]; } The menu popsup perfectly but if I hover the items with the mouse cursor they don't highlight and I can't click them. The menuItemSelected: method looks just like this: -(IBAction)menuItemSelected:(id)sender { } Any idea what I'm doing wrong?

    Read the article

  • Bring a subview to the top on mouseDown: AND keep receiving events (for dragging)

    - by d11wtq
    Ok, basically I have a view with a series of slightly overlapping subviews. When a subview is clicked, it moves to the top (among other things), by a really simple two-liner: -(void)mouseDown:(NSEvent *)theEvent { if (_selected) { // Don't do anything this subview is already in the foreground return; } NSView *superview = [self superview]; [self removeFromSuperview]; [superview addSubview:self position:NSWindowAbove relativeTo:nil]; } This works fine and seems to be the "normal" way to do this. The problem is that I'm now introducing some drag logic to the view, so I need to respond to -mouseDragged:. Unfortunately, since the view is removed from the view hierarchy and re-added in the process, I can have the view come to the foreground and be dragged in the same mouse action. It only drags if I leave go of the mouse and click on the view again, since the second click doesn't do any view hierarchy juggling. Is there anything I can do that will allow the view to move to the foreground like this, AND continue to receive the subsequent -mouseDragged: and -mouseUp: events that follow? I started along the lines of thinking of overriding -hitTest: in the superview and intercepting the mouseDown event in order to bring the view to the foreground before it actually receives the event. The problem here is, from within -hitTest:, how do I distinguish what type of event I'm actually performing the hit test for? I wouldn't want to move the subview to the foreground for other mouse events, such as mouseMoved etc.

    Read the article

  • Getting around IBActions limited scope

    - by Septih
    Hello, I have an NSCollectionView and the view is an NSBox with a label and an NSButton. I want a double click or a click of the NSButton to tell the controller to perform an action with the represented object of the NSCollectionViewItem. The Item View is has been subclassed, the code is as follows: #import <Cocoa/Cocoa.h> #import "WizardItem.h" @interface WizardItemView : NSBox { id delegate; IBOutlet NSCollectionViewItem * viewItem; WizardItem * wizardItem; } @property(readwrite,retain) WizardItem * wizardItem; @property(readwrite,retain) id delegate; -(IBAction)start:(id)sender; @end #import "WizardItemView.h" @implementation WizardItemView @synthesize wizardItem, delegate; -(void)awakeFromNib { [self bind:@"wizardItem" toObject:viewItem withKeyPath:@"representedObject" options:nil]; } -(void)mouseDown:(NSEvent *)event { [super mouseDown:event]; if([event clickCount] > 1) { [delegate performAction:[wizardItem action]]; } } -(IBAction)start:(id)sender { [delegate performAction:[wizardItem action]]; } @end The problem I've run into is that as an IBAction, the only things in the scope of -start are the things that have been bound in IB, so delegate and viewItem. This means that I cannot get at the represented object to send it to the delegate. Is there a way around this limited scope or a better way or getting hold of the represented object? Thanks.

    Read the article

  • My cocoa app won't capture key events

    - by Oscar
    Hi, i usually develop for iPhone. But now trying to make a pong game in Cocoa desktop application. Working out pretty well, but i can't find a way to capture key events. Here's my code: #import "PongAppDelegate.h" #define GameStateRunning 1 #define GameStatePause 2 #define BallSpeedX 10 #define BallSpeedY 15 @implementation PongAppDelegate @synthesize window, leftPaddle, rightPaddle, ball; - (void)applicationDidFinishLaunching:(NSNotification *)aNotification { gameState = GameStateRunning; ballVelocity = CGPointMake(BallSpeedX, BallSpeedY); [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(gameLoop) userInfo:nil repeats:YES]; } - (void)gameLoop { if(gameState == GameStateRunning) { [ball setFrameOrigin:CGPointMake(ball.frame.origin.x + ballVelocity.x, ball.frame.origin.y + ballVelocity.y)]; if(ball.frame.origin.x + 15 > window.frame.size.width || ball.frame.origin.x < 0) { ballVelocity.x =- ballVelocity.x; } if(ball.frame.origin.y + 35 > window.frame.size.height || ball.frame.origin.y < 0) { ballVelocity.y =- ballVelocity.y; } } } - (void)keyDown:(NSEvent *)theEvent { NSLog(@"habba"); // Arrow keys are associated with the numeric keypad if ([theEvent modifierFlags] & NSNumericPadKeyMask) { [window interpretKeyEvents:[NSArray arrayWithObject:theEvent]]; } else { [window keyDown:theEvent]; } } - (void)dealloc { [ball release]; [rightPaddle release]; [leftPaddle release]; [super dealloc]; } @end

    Read the article

  • MAAttachedWindow hide

    - by Montecorte
    I had the same problem that The-Kenny at this post but I fixed it adding the windowDidResignKey: method on the MAAttachedWindow.m, but now my problem is that when I click outside the StatusBar item keeps blue background and when I click another time on the status item it goes normally and I have to click a second time on it to show the window. I tried to add a method in the CustomView (the view of the status item) that do the same thing that te mouseDown method: - (void)mouseDown:(NSEvent *)event { NSRect frame = [[self window] frame]; NSPoint pt = NSMakePoint(NSMidX(frame), NSMidY(frame)); NSLog(@"%g,%g",pt.x,pt.y); clicked = !clicked; [controller toggleAttachedWindowAtPoint:pt]; [self setNeedsDisplay:YES];} my method is: - (void)windowDidResignKey { NSLog(@"Resigned"); NSRect frame = [[self window] frame]; NSPoint pt = NSMakePoint(NSMidX(frame), NSMidY(frame)); NSLog(@"%g,%g",pt.x,pt.y); clicked = !clicked; [controller toggleAttachedWindowAtPoint:pt]; [self setNeedsDisplay:YES];} I call this method in the windowDidResignKey that I have defined on MAAttachedWindow.m, but this method dont call correctly the toggleAttachedWindowAtPoint method, I dont know exactly why, it's only called when I click another time over the status item If anybody knows how to do that any help would be fine. Thank you so much :)

    Read the article

  • OSX: Programmatically added subviews not responding to mouse down events

    - by BigCola
    I have 3 subclasses: a Block class, a Row class and a Table class. All are subclasses of NSView. I have a Table added with IB which programmatically displays 8 rows, each of which displays 8 blocks. I overrode the mouseDown: method in Block to change the background color to red, but it doesn't work. Still if I add a block directly on top of the Table with IB it does work so I can't understand why it won't work in the first case. Here's the implementation code for Block and Row (Table's implementation works the same way as Row's): //block.m - (void)drawRect:(NSRect)dirtyRect { [color set]; [NSBezierPath fillRect:dirtyRect]; } -(void)mouseDown:(NSEvent *)theEvent { color = [NSColor redColor]; checked = YES; [self setNeedsDisplay:YES]; } //row.m - (void)drawRect:(NSRect)dirtyRect { [[NSColor blueColor] set]; [NSBezierPath fillRect:dirtyRect]; int x; for(x=0; x<8; x++){ int margin = x*2; NSRect rect = NSMakeRect(0, 50*x+margin, 50, 50); Block *block = [[Block alloc] initWithFrame:rect]; [self addSubview:block]; } }

    Read the article

  • Custom NSView in NSMenuItem not receiving mouse events

    - by Dennis
    I have an NSMenu popping out of an NSStatusItem using popUpStatusItemMenu. These NSMenuItems show a bunch of different links, and each one is connected with setAction: to the openLink: method of a target. This arrangement has been working fine for a long time. The user chooses a link from the menu and the openLink: method then deals with it. Unfortunately, I recently decided to experiment with using NSMenuItem's setView: method to provide a nicer/slicker interface. Basically, I just stopped setting the title, created the NSMenuItem, and then used setView: to display a custom view. This works perfectly, the menu items look great and my custom view is displayed. However, when the user chooses a menu item and releases the mouse, the action no longer works (i.e., openLink: isn't called). If I just simply comment out the setView: call, then the actions work again (of course, the menu items are blank, but the action is executed properly). My first question, then, is why setting a view breaks the NSMenuItem's action. No problem, I thought, I'll fix it by detecting the mouseUp event in my custom view and calling my action method from there. I added this method to my custom view: - (void)mouseUp:(NSEvent *)theEvent { NSLog(@"in mouseUp"); } No dice! This method is never called. I can set tracking rects and receive mouseEntered: events, though. I put a few tests in my mouseEntered routine, as follows: if ([[self window] ignoresMouseEvents]) { NSLog(@"ignoring mouse events"); } else { NSLog(@"not ignoring mouse events"); } if ([[self window] canBecomeKeyWindow]) { dNSLog((@"canBecomeKeyWindow")); } else { NSLog(@"not canBecomeKeyWindow"); } if ([[self window] isKeyWindow]) { dNSLog((@"isKeyWindow")); } else { NSLog(@"not isKeyWindow"); } And got the following responses: not ignoring mouse events canBecomeKeyWindow not isKeyWindow Is this the problem? "not isKeyWindow"? Presumably this isn't good because Apple's docs say "If the user clicks a view that isn’t in the key window, by default the window is brought forward and made key, but the mouse event is not dispatched." But there must be a way do detect these events. HOW? Adding: [[self window] makeKeyWindow]; has no effect, despite the fact that canBecomeKeyWindow is YES.

    Read the article

  • Cocoa QuickLook initiated by NSTableView Cell

    - by Tristan Seifert
    I have an NSTableView that contains 2 different Columns - one is an NSImageCell that shows a file icon, and the second is a custom subclass of NSTextFieldCell that contains a quick look button on the right of the text. When I click the Quick Look button, the following code is invoked: [[QLPreviewPanel sharedPreviewPanel] makeKeyAndOrderFront:nil]; This does it's job and shows the blank Quick Look panel saying "No Items Selected." After I did a bit of research on the internet, I implemented a custom NSTableView subclass to be the Delegate and Data Source for the Quick Look panel. I get the notification that Quick Look asks if I want to be the delegate, and I respond with return YES. Even though I implement all methods in both QLPreviewPanelDataSource and QLPreviewPanelDelegate, at runtime I get this error on the console: 2010-12-24 15:32:17.235 BackMeUp[4763:80f] clicked: ~/Desktop/HUDTape.mov 2010-12-24 15:32:17.489 BackMeUp[4763:80f] [QL] QLError(): -[QLPreviewPanel setDelegate:] called while the panel has no controller - Fix this or this will raise soon. See comments in QLPreviewPanel.h for -acceptsPreviewPanelControl:/-beginPreviewPanelControl:/-endPreviewPanelControl:. 2010-12-24 15:32:17.490 BackMeUp[4763:80f] [QL] QLError(): -[QLPreviewPanel setDataSource:] called while the panel has no controller - Fix this or this will raise soon. See comments in QLPreviewPanel.h for -acceptsPreviewPanelControl:/-beginPreviewPanelControl:/-endPreviewPanelControl:. 2010-12-24 15:32:17.491 BackMeUp[4763:80f] We can now receive QL Events. 2010-12-24 15:32:18.291 BackMeUp[4763:80f] -[NSPathStore2 stringValue]: unrecognized selector sent to instance 0x5ecb10 2010-12-24 15:32:18.292 BackMeUp[4763:80f] -[NSPathStore2 stringValue]: unrecognized selector sent to instance 0x5ecb10 And the Quick Look panel does not show up, which I find rather odd. The first line above is just that I know the cell has been clicked. Anyways, here is the .m file of the custom table view subclass: // // BackupListTableView.m // BackMeUp // // Created by Tristan Seifert on 12/24/10. // Copyright 2010 24/7 Server. All rights reserved. // #import "BackupListTableView.h" @implementation BackupListTableView - (void) awakeFromNib { } // Quick Look Delegates - (BOOL)acceptsPreviewPanelControl:(QLPreviewPanel *)panel; { [QLPreviewPanel sharedPreviewPanel].delegate = self; [QLPreviewPanel sharedPreviewPanel].dataSource = self; NSLog(@"We can now receive QL Events."); return YES; } - (void)beginPreviewPanelControl:(QLPreviewPanel *)panel { // This document is now responsible of the preview panel // It is allowed to set the delegate, data source and refresh panel. [QLPreviewPanel sharedPreviewPanel].delegate = self; [QLPreviewPanel sharedPreviewPanel].dataSource = self; } - (void)endPreviewPanelControl:(QLPreviewPanel *)panel { // This document loses its responsisibility on the preview panel // Until the next call to -beginPreviewPanelControl: it must not // change the panel's delegate, data source or refresh it. return; } // Quick Look panel data source - (NSInteger)numberOfPreviewItemsInPreviewPanel:(QLPreviewPanel *)panel { return 1; } - (id <QLPreviewItem>)previewPanel:(QLPreviewPanel *)panel previewItemAtIndex:(NSInteger)index { int selectedRow = [self selectedRow]; return [NSURL URLWithString:[[[self dataSource] tableView:self objectValueForTableColumn:fileColumn row:selectedRow] stringValue]]; } // Quick Look panel delegate - (BOOL)previewPanel:(QLPreviewPanel *)panel handleEvent:(NSEvent *)event { // redirect all key down events to the table view return NO; } // This delegate method provides the rect on screen from which the panel will zoom. - (NSRect)previewPanel:(QLPreviewPanel *)panel sourceFrameOnScreenForPreviewItem:(id <QLPreviewItem>)item { NSRect iconRect = [self rectOfColumn:1]; /* // check that the icon rect is visible on screen NSRect visibleRect = [self visibleRect]; // convert icon rect to screen coordinates iconRect = [self convertRectToBase:iconRect]; iconRect.origin = [[self window] convertBaseToScreen:iconRect.origin]; */ return iconRect; } // This delegate method provides a transition image between the table view and the preview panel - (id)previewPanel:(QLPreviewPanel *)panel transitionImageForPreviewItem:(id <QLPreviewItem>)item contentRect:(NSRect *)contentRect { int selectedRow = [self selectedRow]; NSImage *fileIcon = [[NSWorkspace sharedWorkspace] iconForFile:[[[self dataSource] tableView:self objectValueForTableColumn:fileColumn row:selectedRow] stringValue]]; return fileIcon; } @end Thanks for any help.

    Read the article

  • Different cursor formats in IOFrameBufferShared

    - by Thomi
    Hi, I'm reading the moust cursor pixmap data from the StdFBShmem_t structure, as defined in the IOFrameBufferShared API. Everything works fine, 90% of the time. However, I have noticed that some applications on the mac set a cursor in a different format. According to the documentation for the data structures, the cursor pixmap format should always be in the same format as the frame buffer. My frame buffer is 32BPP. I expect the pixmap data to be in the format 0xAARRGGBB, which is it. However, in some cases, I'm reading data that looks like a mask. Specifically, the pixel will either be 0x00FFFFFF or `0x00000000. This looks to me to be a mask for separate pixel data stored somewhere else. As far as I can tell, the only application that uses this cursor pixel format is Qt Creator, but I need to work with all applications, so I'd like to sort this out. The code I'm using to read the cursor pixmap data is: NSAutoreleasePool *autoReleasePool = [[NSAutoreleasePool alloc] init]; NSPoint mouseLocation = [NSEvent mouseLocation]; NSArray *allScreens = [NSScreen screens]; NSEnumerator *screensEnum = [allScreens objectEnumerator]; NSScreen *screen; NSDictionary *screenDesc = nil; while ((screen = [screensEnum nextObject])) { NSRect screenFrame = [screen frame]; screenDesc = [screen deviceDescription]; if (NSMouseInRect(mouseLocation, screenFrame, NO)) break; } if (screen) { kern_return_t err; CGDirectDisplayID displayID = (CGDirectDisplayID) [[screenDesc objectForKey:@"NSScreenNumber"] pointerValue]; task_port_t taskPort = mach_task_self(); io_service_t displayServicePort = CGDisplayIOServicePort(displayID); io_connect_t displayConnection =0; err = IOFramebufferOpen(displayServicePort, taskPort, kIOFBSharedConnectType, &displayConnection); if (KERN_SUCCESS == err) { union { vm_address_t vm_ptr; StdFBShmem_t *fbshmem; } cursorInfo; vm_size_t size; err = IOConnectMapMemory(displayConnection, kIOFBCursorMemory, taskPort, &cursorInfo.vm_ptr, &size, kIOMapAnywhere | kIOMapDefaultCache | kIOMapReadOnly); if (KERN_SUCCESS == err) { // for some reason, cursor data is not always in the same format as the frame buffer. For this reason, we need // some way to detect which structure we should be reading. QByteArray pixData((const char*)cursorInfo.fbshmem->cursor.rgb24.image[currentFrame], m_mouseInfo.currentSize.width() * m_mouseInfo.currentSize.height() * 4); IOConnectUnmapMemory(displayConnection, kIOFBCursorMemory, taskPort, cursorInfo.vm_ptr); } // IOConnectMapMemory else qDebug() << "IOConnectMapMemory Failed:" << err; IOServiceClose(displayConnection); } // IOServiceOpen else qDebug() << "IOFramebufferOpen Failed:" << err; }// if screen [autoReleasePool release]; My question is: How can I detect if the cursor is a different format from the framebuffer? Where can I read the actual pixel data? the bm18Cursor structure contains a mask section, but it's not in the right place for me to be reading it using the code above. Cheers,

    Read the article

  • keyDown works but i get beeps

    - by Oscar
    I just got my keydown method to work. But i get system beep everytime i press key. i have no idea whats wrong. Googled for hours and all people say is that if you have your keyDown method you should also implement the acceptsFirstResponder. did that to and it still doesn't work. #import <Cocoa/Cocoa.h> #import "PaddleView.h" #import "BallView.h" @interface GameController : NSView { PaddleView *leftPaddle; PaddleView *rightPaddle; BallView * ball; CGPoint ballVelocity; int gameState; int player1Score; int player2Score; } @property (retain) IBOutlet PaddleView *leftPaddle; @property (retain) IBOutlet PaddleView *rightPaddle; @property (retain) IBOutlet BallView *ball; - (void)reset:(BOOL)newGame; @end #import "GameController.h" #define GameStateRunning 1 #define GameStatePause 2 #define BallSpeedX 0.2 #define BallSpeedY 0.3 #define CompMoveSpeed 15 #define ScoreToWin 5 @implementation GameController @synthesize leftPaddle, rightPaddle, ball; - (id)initWithCoder:(NSCoder *)aDecoder { self = [super initWithCoder:aDecoder]; if(self) { gameState = GameStatePause; ballVelocity = CGPointMake(BallSpeedX, BallSpeedY); [NSTimer scheduledTimerWithTimeInterval:0.001 target:self selector:@selector(gameLoop) userInfo:nil repeats:YES]; } return self; } - (void)gameLoop { if(gameState == GameStateRunning) { [ball setFrameOrigin:CGPointMake(ball.frame.origin.x + ballVelocity.x, ball.frame.origin.y + ballVelocity.y)]; if(ball.frame.origin.x + 15 > self.frame.size.width || ball.frame.origin.x < 0) { ballVelocity.x =- ballVelocity.x; } if(ball.frame.origin.y + 35 > self.frame.size.height || ball.frame.origin.y < 0) { ballVelocity.y =- ballVelocity.y; } } if(CGRectIntersectsRect(ball.frame, leftPaddle.frame)) { if(ball.frame.origin.x > leftPaddle.frame.origin.x) { ballVelocity.x =- ballVelocity.x; } } if(CGRectIntersectsRect(ball.frame, rightPaddle.frame)) { if(ball.frame.origin.x +15 > rightPaddle.frame.origin.x) { ballVelocity.x =- ballVelocity.x; } } if(ball.frame.origin.x <= self.frame.size.width / 2) { if(ball.frame.origin.y < leftPaddle.frame.origin.y + 75 && leftPaddle.frame.origin.y > 0) { [leftPaddle setFrameOrigin:CGPointMake(leftPaddle.frame.origin.x, leftPaddle.frame.origin.y - CompMoveSpeed)]; } if(ball.frame.origin.y > leftPaddle.frame.origin.y +75 && leftPaddle.frame.origin.y < 700 - leftPaddle.frame.size.height ) { [leftPaddle setFrameOrigin:CGPointMake(leftPaddle.frame.origin.x, leftPaddle.frame.origin.y + CompMoveSpeed)]; } } if(ball.frame.origin.x <= 0) { player2Score++; [self reset:(player2Score >= ScoreToWin)]; } if(ball.frame.origin.x + 15 > self.frame.size.width) { player1Score++; [self reset:(player1Score >= ScoreToWin)]; } } - (void)reset:(BOOL)newGame { gameState = GameStatePause; [ball setFrameOrigin:CGPointMake((self.frame.size.width + 7.5) / 2, (self.frame.size.height + 7.5)/2)]; if(newGame) { if(player1Score > player2Score) { NSLog(@"Player 1 Wins!"); } else { NSLog(@"Player 2 Wins!"); } player1Score = 0; player2Score = 0; } else { NSLog(@"Press key to serve"); } NSLog(@"Player 1: %d",player1Score); NSLog(@"Player 2: %d",player2Score); } - (void)moveRightPaddleUp { if(rightPaddle.frame.origin.y < 700 - rightPaddle.frame.size.height) { [rightPaddle setFrameOrigin:CGPointMake(rightPaddle.frame.origin.x, rightPaddle.frame.origin.y + 20)]; } } - (void)moveRightPaddleDown { if(rightPaddle.frame.origin.y > 0) { [rightPaddle setFrameOrigin:CGPointMake(rightPaddle.frame.origin.x, rightPaddle.frame.origin.y - 20)]; } } - (BOOL)acceptsFirstResponder { return YES; } - (void)keyDown:(NSEvent *)theEvent { if ([theEvent modifierFlags] & NSNumericPadKeyMask) { NSString *theArrow = [theEvent charactersIgnoringModifiers]; unichar keyChar = 0; if ( [theArrow length] == 0 ) { return; // reject dead keys } if ( [theArrow length] == 1 ) { keyChar = [theArrow characterAtIndex:0]; if ( keyChar == NSLeftArrowFunctionKey ) { gameState = GameStateRunning; } if ( keyChar == NSRightArrowFunctionKey ) { } if ( keyChar == NSUpArrowFunctionKey ) { [self moveRightPaddleUp]; } if ( keyChar == NSDownArrowFunctionKey ) { [self moveRightPaddleDown]; } [super keyDown:theEvent]; } } else { [super keyDown:theEvent]; } } - (void)drawRect:(NSRect)dirtyRect { } - (void)dealloc { [ball release]; [rightPaddle release]; [leftPaddle release]; [super dealloc]; } @end

    Read the article

1