NSOpenGLView toggle to fullscreen from within the view - cocoa

I'm trying to create a method that will toggle between fullscreen and a window. I'm trying to do this from within a class inherited from NSOpenGLView, essentially following this blogpost. That works once, going from windowed to fullscreen; trying to go back fails in various ways: the window screen doesn't get updated, or I don't even manage switch to the window but the fullscreen just blanks out. Trying to go back and forth a few times anyway (mapped it to the 'f' key), the program often locks up, and in a worst case, I have to restart my computer.
I've attached the code for the method below; for debugging purposes, I've set the full frame rectangle much smaller, so that if things freeze, the application is never at full screen.
The fullscreen example in the Apple developer examples suggest using a controller, and does not go fullscreen from within the inherited NSOpenGLView.
My questions:
should I use a controller instead, and from there switch between windowed and fullscreen (creating a separate fullscreen view each time)? Or should both methods work?
If both methods should work, which one is preferred?
If both methods can work, what am I doing wrong in the current way of implementing this?
or, is there a third, better, method?
Note that for both references, I'll have to assume that things haven't changed for 10.8 (both references seem to apply to 10.6).
Code follows:
#implementation MyOpenGLView
[...]
- (void)toggleFullscreen
{
mainWindow = [self window];
if (isFullscreen) {
[fullscreenWindow close];
[mainWindow setAcceptsMouseMovedEvents:YES];
[mainWindow setContentView: self];
[mainWindow makeKeyAndOrderFront: self];
[mainWindow makeFirstResponder: self];
isFullscreen = false;
} else {
[mainWindow setAcceptsMouseMovedEvents:NO];
//NSRect fullscreenFrame = [[NSScreen mainScreen] frame];
NSRect fullscreenFrame = { {300, 300}, {300, 300} };
fullscreenWindow = [[NSWindow alloc] initWithContentRect:fullscreenFrame
styleMask:NSBorderlessWindowMask
backing:NSBackingStoreBuffered
defer:NO];
if (fullscreenWindow) {
[fullscreenWindow setAcceptsMouseMovedEvents:YES];
[fullscreenWindow setTitle:#"Full screen"];
[fullscreenWindow setReleasedWhenClosed: YES];
[fullscreenWindow setContentView: self];
[fullscreenWindow makeKeyAndOrderFront: self];
//[fullscreenWindow setOpaque:YES];
//[fullscreenWindow setHidesOnDeactivate:YES];
// Set the window level to be just above the menu bar
//[fullScreenWindow setLevel:NSMainMenuWindowLevel+1];
// Set the window level to be just below the screen saver
[fullscreenWindow setLevel:NSScreenSaverWindowLevel-1];
[fullscreenWindow makeFirstResponder:self];
isFullscreen = true;
} else {
NSLog(#"Error: could not switch to full screen.");
}
}
}
[...]
#end

I now think this can't be done, and should not be done. When windowed, the rendering context is a window, which is a different beast than a screen, when rendering fullscreen.
Thus, when switching between, things have to re-setup everytime you switch.
It is possible to simply use the native fullscreen option that is in the newest OS X variants. This will (presumably) enlarge the containg window to full screen size while removing the frame, borders and buttons. Thus, you're still rendering to a window, though it looks fullscreen.
I'm not sure if this option makes things slower: there's a window layer in between, which could make it a slower than rendering directly to a screen.
For the curious, implementing the native fullscreen is ridiculously easy (at least in 10.8 and 10.9): In XCode, select the .xib file, select the (main) window in the editor's sidebar, then select the attributes selector on the right. You can find a "Full Screen" selection between Unsupported, Primary Window or Auxiliary Window. That will automatically add the full screen toggle to the window.
Even neater, now select the main menu -> view menu in the sidebar, find the "Full Screen Menu Item" in the inspector at the bottom (there's a search bar for it), drag it into the View menu in the editor, and voilà, it will have a shortcut and automatically connect to the full screen option for the window (select the new View menu item and look at the Connections inspector to it's already connected for you).
A nice way to test all this is to grab the full screen example I linked in my question, and edit it as suggested above. Using the default control-command F shortcut to toggle back and forth between fullscreen will show the opengl view and the frame with text below it in a full screen. Using the fullscreen option as coded in the example will toggle the openglview to use the fullscreen, without any extra (Cocoa) frames, buttons or text.

I'm curious about this too- specifically your first two bullet point questions.
This doesn't address those questions, but your third one about the bug, I think you can get away with just changing the properties of the same window (works for me):
- (void)toggleFullscreen
{
if (isFullscreen) {
NSRect windowFrame = [[NSScreen mainScreen] visibleFrame];
[mainWindow setStyleMask:NSTitledWindowMask | NSClosableWindowMask |
NSMiniaturizableWindowMask | NSResizableWindowMask ];
[mainWindow setFrame:windowFrame display:true];
[mainWindow setAcceptsMouseMovedEvents:YES];
[mainWindow setLevel:NSNormalWindowLevel];
[mainWindow setTitle:#"SimpleOculus"];
[mainWindow makeKeyAndOrderFront:self];
[mainWindow makeFirstResponder:self];
isFullscreen = false;
}
else {
NSRect fullscreenFrame = [[NSScreen mainScreen] frame];
[mainWindow setStyleMask:NSBorderlessWindowMask];
[mainWindow setFrame:fullscreenFrame display:true];
[mainWindow setAcceptsMouseMovedEvents:YES];
[mainWindow setLevel:NSScreenSaverWindowLevel-1];
[mainWindow makeKeyAndOrderFront:self];
[mainWindow makeFirstResponder:self];
isFullscreen = true;
}
}

Related

NSTextField Drawing on Top of Sub View

I have created a secondary NSViewController to create a progress indicator "popup". The reason for this is that the software has to interact with some hardware and some of the functions take the device a few seconds to respond. So being thoughtful of the end user I have a NSViewController that has a NSView (that is black and semi-transparent) and then a message/progress bar on top. This is added to the window using addSubView.
Everything works great except when the screen has a NSTextField in it. The popup shows but the NSTextField is drawn on top. What is this?
The view code I used for drawing semi-transparent:
#implementation ConnectingView
- (id)initWithFrame:(NSRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code here.
}
return self;
}
- (void)drawRect:(NSRect)dirtyRect
{
[super drawRect:dirtyRect];
// Drawing code here.
CGContextRef context = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
CGContextSetRGBFillColor(context, 0.227,0.251,0.337,0.8);
CGContextFillRect(context, NSRectToCGRect(dirtyRect));
}
#end
The code I use to show the progress view
-(void) showProgressWithMessage:(NSString *) message andIsIndet:(BOOL) indet
{
connectingView = [[ConnectingViewController alloc] init];
[self.view.window.contentView addSubview:connectingView.view];
connectingView.view.frame = ((NSView*)self.view.window.contentView).bounds;
[connectingView changeProgressLabel:message];
if (indet)
[connectingView makeProgressBar:NO];
}
Is there a better way to add the subview or to tell the NSTextFields I don't want them to be drawn on top?
Thanks!
So Setting [self setWantsLayer] to my custom NSViews sort of worked however there are a lot of redraw issues (white borders, and backgrounds). A NSPopover may be better in some instances however I was going for "locked down" approach where the interface is unreachable until it finishes (or times out).
What worked for me was to go to the instance of my NSView, select the window in Interface Builder, then go to layers (far right on properties view) and select my view under "Core Animation Layer".

How to repaint window after hide or show control

I have a NSTextField control on the bottom of the window.
I need to show them or hide according to some condition.
In the initial state the control is hidden.
The window shows the blank space on the control's position.
When in runtime the control should become visible
mpTxtCtrl.hidden = NO;
it does not happen.
The tasks:
1 Display/Hide control.
2 Resize the main window according to the control's state.
I can't find any tutorials how to manage layouts in the cocoa.
I would be grateful for any help!
When in runtime the control should become visible
mpTxtCtrl.hidden = NO;
it does not happen.
Make sure you connected the mpTxtCtrl outlet to the text field in your nib. Having forgotten to connect your outlet to anything is a leading cause of nothing happening.
I can't find any tutorials how to manage layouts in the cocoa.
Switch to the File Inspector while editing the nib and turn “Use Auto Layout” on. Xcode will create constraints whenever you place views along Aqua guides (the blue lines that appear when you place and size views correctly), and Cocoa will enforce these constraints as the sizes of views and the window change.
More info:
Cocoa Auto Layout Guide
WWDC 2012 videos — include several sessions on Auto Layout
OS X Human Interface Guidelines — Aqua guide lines appear to indicate conformance to the HIG
Check this code, if you will find some useful stuffs here:
-(void)awakeFromNib{
[self.label setHidden:YES];
}
- (IBAction)showHide:(id)sender {
NSLog(#"%#",[sender title]);
if ([[sender title] isEqualToString:#"Hide"]) {
[self.label setHidden:YES];
[sender setTitle:#"Show"];
}
else if ([[sender title] isEqualToString:#"Show"]){
[self.label setHidden:NO];
[sender setTitle:#"Hide"];
}
}
- (IBAction)maximize:(id)sender {
NSArray *screens = [NSScreen screens];
NSRect screenRect;
for (NSInteger index=0; index < [screens count]; index++) {
NSScreen *screen = screens[index];
screenRect = [screen visibleFrame];
}
[self.window setFrame:screenRect display:YES];
}

Lion compound animations for full screen

I'm transitioning a window to full screen mode (the new Lion kind of full screen mode). While I do the transition, I'd like to also slide one of the views in my NSWindow to a new position.
So, in my NSWindowDelegate, I've tried returning the window and implementing the custom animation:
- (NSArray *)customWindowsToEnterFullScreenForWindow:(NSWindow *)window
{
return [NSArray arrayWithObject: window];
}
- (void)window:(NSWindow *)_window startCustomAnimationToEnterFullScreenWithDuration:(NSTimeInterval)duration
{
// book is NSView *ivar
[[book animator] setFrame: NSMakeRect(/*computed rect*/)];
}
But this completely kills the default animation of going to full-screen mode and my window suddenly doesn't paint correctly.
Is there some way to compound these while still using the default animation? I'm pretty new to core animation beyond [view animator] level stuff, So I'm sure I'm screwing up something quite simple.
You have to write something like this in order to have the two animations in sync:
- (void)window:(NSWindow *)_window startCustomAnimationToEnterFullScreenWithDuration:(NSTimeInterval)duration
{
// book is NSView *ivar
[[NSAnimationContext currentContext] setDuration:duration];
[[book animator] setFrame: NSMakeRect(/*computed rect*/)];
}

How to create an OSD-like window with Cocoa on Mac OSX?

Please keep in mind that I'm a really newbie Cocoa developer
Scenario: I've a search the when reaches the end of document restarts from begin, a so called "wrap around".
When I do the wrap I want to show a window that flashes on screen for some time (one second??) like and OSD (On Screen Display) control window, TextWrangler and XCode do that when text search restarts from the begin.
How can I implement a similar window?
Implementing a view to do this would be relatively simple. The following code in an NSView subclass would display a partially transparent rounded rect which ignores events when placed in a window.
- (void)drawRect:(NSRect)dirtyRect {
[[NSColor colorWithDeviceWhite:0 alpha:.7] set];
[[NSBezierPath bezierPathWithRoundedRect:self.bounds xRadius:10 yRadius:10] fill];
//Additional drawing
}
- (NSView *)hitTest:(NSPoint)aPoint {
return nil;
}
- (BOOL)acceptsFirstResponder {
return NO;
}
- (BOOL)isOpaque {
return NO;
}
If you do want to do this in a window, you will need to create a borderless, non-opaque window and set this as the content view. Also, you will need to have the view fill it's bounds with a clear color at the start of the drawRect: method.
//Create and display window
NSPanel *panel = [[NSPanel alloc] initWithFrame:NSMakeRect(0,0,300,200) styleMask:NSBorderlessWindowMask|NSNonactivatingPanelMask backing:NSBackingStoreBuffered defer:YES];
[panel setOpaque:NO];
MyViewSubview *view = [MyViewSubview new];
[panel setContentView:view];
[view release];
[p setLevel:NSScreenSaverWindowLevel];
[p orderFront:nil];
//Add these two lines to the beginning of the drawRect: method
[[NSColor clearColor set];
NSRectFill(self.bounds);
However, this window will intercept events and I have not been able to disable this using standard methods.
To fade the view, check out NSViewAnimation, or use an NSTimer object and do it manually.

How to implement HUD-style window like Address Book's "Show in Large Type"

Several apps, including the built-in Address Book use a HUD window that is semi-transparent, with large shadowed text. I'd like to implement a similar window in my Cocoa Mac app.
Is there a free implementation of this kind of window somewhere?
If not, what is the best way to implement it?
Here's a sample project that shows how to do it:
http://github.com/NSGod/BlackBorderlessWindow
Basically, you need to create a borderless NSWindow subclass. The easiest way to do this is to set your window size and arrangement in the nib file, and then set its class to be your custom subclass. So while it will still look like a normal window in Interface Builder, at runtime it will appear as you need it to.
#implementation MDBorderlessWindow
- (id)initWithContentRect:(NSRect)contentRect
styleMask:(NSUInteger)windowStyle
backing:(NSBackingStoreType)bufferingType
defer:(BOOL)deferCreation {
if (self = [super initWithContentRect:contentRect
styleMask:NSBorderlessWindowMask
backing:NSBackingStoreBuffered defer:deferCreation]) {
[self setAlphaValue:0.75];
[self setOpaque:NO];
[self setExcludedFromWindowsMenu:NO];
}
return self;
}
The alpha value will make the window semi-transparent.
Also, you can create a custom NSView subclass that will draw a round rectangle:
#implementation MDBlackTransparentView
- (id)initWithFrame:(NSRect)frame {
if (self = [super initWithFrame:frame]) {
}
return self;
}
- (void)drawRect:(NSRect)frame {
NSBezierPath *path = [NSBezierPath bezierPathWithRoundedRect:frame
xRadius:6.0 yRadius:6.0];
[[NSColor blackColor] set];
[path fill];
}
#end
Like with the window, you simply set the class of the window's contentView to be your custom NSView subclass. (Use outline view mode and click the disclosure triangle to show the nested NSView inside the icon of the window in the nib file). Again, while the view will look ordinary in Interface Builder, it will look okay at runtime.
Then just place an NSTextField on top of view and set the text accordingly.
Note that, in general, borderless windows aren't easy to work with (for example, if you want to be able to drag the window around, you'll need to add that functionality back yourself). Apple has some sample code on how to allow dragging, for instance.
Thank you for sharing this code. Helped me a lot!
You may add the following line...
[self setBackgroundColor:[NSColor clearColor]];
to the init function of the window. This removes the white corners.

Resources