void XBMCHelper::CaptureAllInput() { // Take keyboard focus away from FrontRow and native screen saver if (g_sysinfo.IsAppleTV()) { ProcessSerialNumber psn = {0, kCurrentProcess}; SetFrontProcess(&psn); EnableSecureEventInput(); } }
void screeninit(void) { int fmt; int dx, dy; ProcessSerialNumber psn = { 0, kCurrentProcess }; TransformProcessType(&psn, kProcessTransformToForegroundApplication); SetFrontProcess(&psn); fmt = XBGR32; //XRGB32; devRect = max_bounds(); dx = devRect.size.width; dy = devRect.size.height; gscreen = allocmemimage(Rect(0,0,dx,dy), fmt); dataProviderRef = CGDataProviderCreateWithData(0, gscreen->data->bdata, dx * dy * 4, 0); fullScreenImage = CGImageCreate(dx, dy, 8, 32, dx * 4, CGColorSpaceCreateDeviceRGB(), kCGImageAlphaNoneSkipLast, dataProviderRef, 0, 0, kCGRenderingIntentDefault); devRect = CGDisplayBounds(CGMainDisplayID()); kproc("osxscreen", winproc, nil, 0); kproc("osxflush", flushproc, nil, 0); Sleep(&rend, isready, nil); }
bool Window::configInitAGLFullscreen() { AGLContext context = getAGLContext(); if( !context ) { setError( ERROR_AGLWINDOW_NO_CONTEXT ); return false; } Global::enterCarbon(); aglEnable( context, AGL_FS_CAPTURE_SINGLE ); const eq::Pipe* pipe = getPipe(); const PixelViewport& pipePVP = pipe->getPixelViewport(); const PixelViewport& windowPVP = getWindow()->getPixelViewport(); const PixelViewport& pvp = pipePVP.isValid() ? pipePVP : windowPVP; if( !aglSetFullScreen( context, pvp.w, pvp.h, 0, 0 )) LBWARN << "aglSetFullScreen to " << pvp << " failed: " << AGLERROR << std::endl; // Do focus hell ProcessSerialNumber selfProcess = { 0, kCurrentProcess }; SetFrontProcess( &selfProcess ); Global::leaveCarbon(); getWindow()->setPixelViewport( pvp ); if( getIAttribute( eq::Window::IATTR_HINT_DRAWABLE ) != OFF ) initEventHandler(); return true; }
void CBOINCGUIApp::ShowApplication(bool bShow) { if (bShow) { SetFrontProcess(&m_psnCurrentProcess); } else { ShowHideProcess(&m_psnCurrentProcess, false); } }
short wxApp::MacHandleAEPDoc(const WXEVENTREF event , WXEVENTREF WXUNUSED(reply)) { AEDescList docList; AEKeyword keywd; DescType returnedType; Size actualSize; long itemsInList; OSErr err; short i; err = AEGetParamDesc((AppleEvent *)event, keyDirectObject, typeAEList,&docList); if (err != noErr) return err; err = AECountItems(&docList, &itemsInList); if (err != noErr) return err; ProcessSerialNumber PSN ; PSN.highLongOfPSN = 0 ; PSN.lowLongOfPSN = kCurrentProcess ; SetFrontProcess( &PSN ) ; for (i = 1; i <= itemsInList; i++) { wxString fName ; FSRef theRef ; AEGetNthPtr(&docList, i, typeFSRef, &keywd, &returnedType, (Ptr) & theRef, sizeof(theRef), &actualSize); fName = wxMacFSRefToPath( &theRef ) ; MacPrintFile(fName); } return noErr; }
Qt::Native::Status sendNativeKeyEventToProcess_Quartz(const QNativeKeyEvent &event, int pid) { ProcessSerialNumber psn; GetProcessForPID(pid, &psn); CGEventRef e = CGEventCreateKeyboardEvent(0, (uint)event.nativeKeyCode, event.press); setModifiersFromQNativeEvent(e, event); SetFrontProcess(&psn); CGEventPostToPSN(&psn, e); CFRelease(e); return Qt::Native::Success; }
// Using 32-bit background server correspondence to achieve the same result void openMovSettingsPopup(TPropertyGroup *props, bool unused) { QLocalSocket socket; if (!tipc::startSlaveConnection(&socket, t32bitsrv::srvName(), 3000, t32bitsrv::srvCmdline(), "_main")) return; // Send the appropriate commands to the server tipc::Stream stream(&socket); tipc::Message msg; // We'll communicate through temporary files. stream << (msg << QString("$tmpfile_request") << QString("openMovSets")); QString res(tipc::readMessage(stream, msg)); QString fp; msg >> fp; assert(res == "ok" && !fp.isEmpty()); TFilePath tfp(fp.toStdWString()); { // Save the input props to the temporary file TOStream os(tfp); props->saveData(os); } // Invoke the settings popup stream << (msg << tipc::clr << QString("$openMovSettingsPopup") << fp); res = tipc::readMessageNB(stream, msg, -1, QEventLoop::ExcludeUserInputEvents); assert(res == "ok"); #ifdef MACOSX // Bring this application back to front ProcessSerialNumber psn = {0, kCurrentProcess}; SetFrontProcess(&psn); #endif // MACOSX props->clear(); { // Save the input props to the temporary file TIStream is(tfp); props->loadData(is); } // Release the temporary file stream << (msg << tipc::clr << QString("$tmpfile_release") << QString("openMovSets")); res = tipc::readMessage(stream, msg); assert(res == "ok"); }
bool Sys_CreateWindow(const char *title, unsigned int w, unsigned int h, bool fs) { OSErr result; ProcessSerialNumber psn; windowRect.top = 100; windowRect.left = 100; windowRect.bottom = windowRect.top + h; windowRect.right = windowRect.left + w; g_Window.height = h; g_Window.width = w; g_Window.fs = fs; result = CreateNewWindow(kDocumentWindowClass, (kWindowStandardDocumentAttributes | kWindowInWindowMenuAttribute | kWindowStandardHandlerAttribute) & ~kWindowResizableAttribute, &windowRect, &g_Window.window); if (result != noErr) return false; SetWindowTitleWithCFString( g_Window.window, CFStringCreateWithCString(0, title, CFStringGetSystemEncoding()) ); result = GetCurrentProcess(&psn); if (result == noErr) { TransformProcessType(&psn, kProcessTransformToForegroundApplication); SetFrontProcess(&psn); } ShowWindow(g_Window.window); SelectWindow(g_Window.window); g_Window.glctx = createContext(g_Window.window); if (!g_Window.glctx) return false; /* static EventTypeSpec suspendResume[2] = {{kEventClassApplication, kEventAppActivated}, {kEventClassApplication, kEventAppDeactivated}}; InstallApplicationEventHandler(NewEventHandlerUPP(suspendResumeHandler), 2, suspendResume, &g_Window.window, NULL); */ AEInstallEventHandler(kCoreEventClass, kAEQuitApplication, NewAEEventHandlerUPP(quitEventHandler), 0, false); return true; }
/** This chunk of code is heavily based off SDL_macosx.m from SDL. * The CPSEnableForegroundOperation that was here before is private * and should not be used. * Replaced by a call to the 10.3+ TransformProcessType. */ void osx_foreground_hack(void) { #if !defined (CONFIG_MACOSX_FINDER) || !defined (CONFIG_SDL) ProcessSerialNumber myProc, frProc; Boolean sameProc; if (GetFrontProcess(&frProc) == noErr && GetCurrentProcess(&myProc) == noErr) { if (SameProcess(&frProc, &myProc, &sameProc) == noErr && !sameProc) { TransformProcessType(&myProc, kProcessTransformToForegroundApplication); } SetFrontProcess(&myProc); } #endif }
//#################### EVENT HANDLERS #################### bool Application::OnInit() { #ifdef __WXMAC__ // Make mast into a foreground application on Mac OS X and bring it to the front. ProcessSerialNumber PSN; GetCurrentProcess(&PSN); TransformProcessType(&PSN, kProcessTransformToForegroundApplication); SetFrontProcess(&PSN); #endif HelpController::instance().initialize(); MainWindow *window = new MainWindow("MAST - Millipede Automatic Segmentation Tool"); window->Show(); return true; }
/// /// Detect if another instance of this application is running. // Returns true if there is, otherwise false /// bool CBOINCGUIApp::DetectDuplicateInstance() { #ifdef __WXMSW__ if (CTaskBarIcon::FireAppRestore()) { return true; } #endif #ifdef __WXMAC__ ProcessSerialNumber PSN; int iInstanceID = wxGetApp().IsAnotherInstanceRunning(); if (iInstanceID) { // Bring other instance to the front and exit this instance OSStatus err = GetProcessForPID(iInstanceID, &PSN); if (!err) SetFrontProcess(&PSN); return true; } #endif return false; }
//! This method is called right at the beginning and opens a frame for us. // bool MyApp::OnInit() { #ifdef __WXMAC__ // this hack enables to have a GUI on Mac OSX even if the // program was called from the command line (and isn't a bundle) ProcessSerialNumber psn; GetCurrentProcess( &psn ); CPSEnableForegroundOperation( &psn ); SetFrontProcess( &psn ); #endif wxPLplotwindow<wxFrame> *frame = new wxPLplotwindow<wxFrame>(); frame->Create( NULL, wxID_ANY, wxT( "wxPLplotDemo" ) ); frame->SetIcon( wxIcon( graph ) ); frame->Show(); Plot( frame ); return true; }
boolean getyesno(char default_answer) { extern FILE *logfile; short alertid,i,large,err; char dfault[8], ndfault[8]; ProcessSerialNumber psn; if (batchmode) return(default_answer == 'y' ? TRUE : FALSE); if (strlen(Yes_No_Message)<72) large=0; else large=100; strcpy(dfault,default_answer == 'y' ? LANG("y") : LANG("n")); strcpy(ndfault,default_answer == 'n' ? LANG("y") : LANG("n")); for(i=0;i<strlen(Yes_No_Message);i++) if (Yes_No_Message[i]<' ' && Yes_No_Message[i]>=0) Yes_No_Message[i]=' '; /* It's a signed char! */ InitCursor(); alertid=(default_answer == 'n' ? 211+large : 212+large); c2pstr(Yes_No_Message); ParamText((uchar *)Yes_No_Message,(uchar *)"", \ (uchar *)"",(uchar *)""); if (AEProcessing) { if (gHasProcessManager) GetFrontProcess(&psn); if(MyInteractWithUser()) return default_answer; if (gHasProcessManager) SetFrontProcess(&psn); } if (CautionAlert(alertid,nil)==1){ p2cstr((uchar *)Yes_No_Message); fputs(strcat(Yes_No_Message,dfault),stderr); fputc('\n',stderr); fflush(stderr); return(default_answer == 'y' ? TRUE : FALSE); } p2cstr((uchar *)Yes_No_Message); fputs(strcat(Yes_No_Message,ndfault),stderr); fputc('\n',stderr); fflush(stderr); return(default_answer == 'n' ? TRUE : FALSE); }
short wxApp::MacHandleAEGURL(const WXEVENTREF event, WXEVENTREF WXUNUSED(reply)) { DescType returnedType; Size actualSize; char url[255]; OSErr err = AEGetParamPtr((AppleEvent *)event, keyDirectObject, typeChar, &returnedType, url, sizeof(url)-1, &actualSize); if (err != noErr) return err; url[actualSize] = '\0'; // Terminate the C string ProcessSerialNumber PSN ; PSN.highLongOfPSN = 0 ; PSN.lowLongOfPSN = kCurrentProcess ; SetFrontProcess( &PSN ) ; MacOpenURL(wxString(url, wxConvUTF8)); return noErr; }
bool RubyApp::OnInit() { wxApp::OnInit(); #ifdef __WXMAC__ ProcessSerialNumber psn; GetCurrentProcess( &psn ); CPSEnableForegroundOperation( &psn ); SetFrontProcess( &psn ); #endif RubyWX::Color::define_const(); RubyWX::Font::define_const(); RubyWX::Brush::define_const(); RubyWX::Pen::define_const(); #if wxUSE_INTL wxLocale::CreateLanguagesDB(); mLocale = new wxLocale(wxLANGUAGE_DEFAULT); mLocale->AddCatalog("wxstd"); #ifdef __LINUX__ mLocale->AddCatalog("fileutils"); #endif #endif #if wxUSE_PROPGRID wxPropertyGrid::RegisterAdditionalEditors(); #endif this->Bind(wxEVT_ASYNC_METHOD_CALL,AppAfter()); ruby_app_inited = true; bool result = RTEST(rb_funcall(mRuby, rb_intern("on_init"), 0)); if(rb_block_given_p()) rb_obj_instance_eval(0, 0, mRuby); return result; }
void ProcessHelper::SetActiveProcess(const QString& path) { #ifdef Q_OS_DARWIN ProcessSerialNumber psn; if (ProcessHelper::GetProcessPSN(path, psn)) SetFrontProcess(&psn); #elif defined Q_OS_WIN quint32 pid = 0; HWND hWnd = 0; if (GetProcessID(path, pid)) { ENUMINFO EnumInfo; // set the search parameters EnumInfo.PId = pid; // set the return parameters to default values EnumInfo.hWnd = NULL; EnumInfo.hEmptyWnd = NULL; EnumInfo.hInvisibleWnd = NULL; EnumInfo.hEmptyInvisibleWnd = NULL; // do the search among the top level windows ::EnumWindows((WNDENUMPROC)EnumWindowsProc, (LPARAM)&EnumInfo); // return the one found if any if (EnumInfo.hWnd != NULL) hWnd = EnumInfo.hWnd; else if (EnumInfo.hEmptyWnd != NULL) hWnd = EnumInfo.hEmptyWnd; else if (EnumInfo.hInvisibleWnd != NULL) hWnd = EnumInfo.hInvisibleWnd; else hWnd = EnumInfo.hEmptyInvisibleWnd; } if (hWnd) ::SetForegroundWindow(hWnd); #endif }
static PyObject * MacOS_WMAvailable(PyObject *self, PyObject *args) { static PyObject *rv = NULL; if (!PyArg_ParseTuple(args, "")) return NULL; if (!rv) { ProcessSerialNumber psn; /* ** This is a fairly innocuous call to make if we don't have a window ** manager, or if we have no permission to talk to it. It will print ** a message on stderr, but at least it won't abort the process. ** It appears the function caches the result itself, and it's cheap, so ** no need for us to cache. */ #ifdef kCGNullDirectDisplay /* On 10.1 CGMainDisplayID() isn't available, and ** kCGNullDirectDisplay isn't defined. */ if (CGMainDisplayID() == 0) { rv = Py_False; } else { #else { #endif if (GetCurrentProcess(&psn) < 0 || SetFrontProcess(&psn) < 0) { rv = Py_False; } else { rv = Py_True; } } } Py_INCREF(rv); return rv; } static char GetTicks_doc[] = "Return number of ticks since bootup"; static PyObject * MacOS_GetTicks(PyObject *self, PyObject *args) { return Py_BuildValue("i", (int)TickCount()); } static char openrf_doc[] = "Open resource fork of a file"; static PyObject * MacOS_openrf(PyObject *self, PyObject *args) { OSErr err; char *mode = "r"; FSRef ref; SInt8 permission = fsRdPerm; rfobject *fp; HFSUniStr255 name; if (!PyArg_ParseTuple(args, "O&|s", PyMac_GetFSRef, &ref, &mode)) return NULL; while (*mode) { switch (*mode++) { case '*': break; case 'r': permission = fsRdPerm; break; case 'w': permission = fsWrPerm; break; case 'b': break; default: PyErr_BadArgument(); return NULL; } } err = FSGetResourceForkName(&name); if (err != noErr) { PyMac_Error(err); return NULL; } if ( (fp = newrfobject()) == NULL ) return NULL; err = FSOpenFork(&ref, name.length, name.unicode, permission, &fp->fRefNum); if (err != noErr) { Py_DECREF(fp); PyMac_Error(err); return NULL; } fp->isclosed = 0; return (PyObject *)fp; }
GHOST_WindowCarbon::GHOST_WindowCarbon( const STR_String& title, GHOST_TInt32 left, GHOST_TInt32 top, GHOST_TUns32 width, GHOST_TUns32 height, GHOST_TWindowState state, GHOST_TDrawingContextType type, const bool stereoVisual, const GHOST_TUns16 numOfAASamples ) : GHOST_Window(width, height, state, GHOST_kDrawingContextTypeNone), m_windowRef(0), m_grafPtr(0), m_aglCtx(0), m_customCursor(0), m_fullScreenDirty(false) { Str255 title255; OSStatus err; //fprintf(stderr," main screen top %i left %i height %i width %i\n", top, left, height, width); if (state >= GHOST_kWindowState8Normal ) { if(state == GHOST_kWindowState8Normal) state= GHOST_kWindowStateNormal; else if(state == GHOST_kWindowState8Maximized) state= GHOST_kWindowStateMaximized; else if(state == GHOST_kWindowState8Minimized) state= GHOST_kWindowStateMinimized; else if(state == GHOST_kWindowState8FullScreen) state= GHOST_kWindowStateFullScreen; // state = state - 8; this was the simple version of above code, doesnt work in gcc 4.0 setMac_windowState(1); } else setMac_windowState(0); if (state != GHOST_kWindowStateFullScreen) { Rect bnds = { top, left, top+height, left+width }; // Boolean visible = (state == GHOST_kWindowStateNormal) || (state == GHOST_kWindowStateMaximized); /*unused*/ gen2mac(title, title255); err = ::CreateNewWindow( kDocumentWindowClass, kWindowStandardDocumentAttributes+kWindowLiveResizeAttribute, &bnds, &m_windowRef); if ( err != noErr) { fprintf(stderr," error creating window %i \n",(int)err); } else { ::SetWRefCon(m_windowRef,(SInt32)this); setTitle(title); err = InstallWindowEventHandler (m_windowRef, myWEventHandlerProc, GetEventTypeCount(kWEvents), kWEvents,NULL,NULL); if ( err != noErr) { fprintf(stderr," error creating handler %i \n",(int)err); } else { // ::TransitionWindow (m_windowRef,kWindowZoomTransitionEffect,kWindowShowTransitionAction,NULL); ::ShowWindow(m_windowRef); ::MoveWindow (m_windowRef, left, top,true); } } if (m_windowRef) { m_grafPtr = ::GetWindowPort(m_windowRef); setDrawingContextType(type); updateDrawingContext(); activateDrawingContext(); } if(ugly_hack==NULL) { ugly_hack= m_windowRef; // when started from commandline, window remains in the back... also for play anim ProcessSerialNumber psn; GetCurrentProcess(&psn); SetFrontProcess(&psn); } } else { /* Rect bnds = { top, left, top+height, left+width }; gen2mac("", title255); m_windowRef = ::NewCWindow( nil, // Storage &bnds, // Bounding rectangle of the window title255, // Title of the window 0, // Window initially visible plainDBox, // procID (WindowRef)-1L, // Put window before all other windows 0, // Window has minimize box (SInt32)this); // Store a pointer to the class in the refCon */ //GHOST_PRINT("GHOST_WindowCarbon::GHOST_WindowCarbon(): creating full-screen OpenGL context\n"); setDrawingContextType(GHOST_kDrawingContextTypeOpenGL);;installDrawingContext(GHOST_kDrawingContextTypeOpenGL); updateDrawingContext(); activateDrawingContext(); m_tablet.Active = GHOST_kTabletModeNone; } }
//------------------------------------------------------------ void ofAppGlutWindow::display(void){ //-------------------------------- // when I had "glutFullScreen()" // in the initOpenGl, I was gettings a "heap" allocation error // when debugging via visual studio. putting it here, changes that. // maybe it's voodoo, or I am getting rid of the problem // by removing something unrelated, but everything seems // to work if I put fullscreen on the first frame of display. if (windowMode != OF_GAME_MODE){ if ( bNewScreenMode ){ if( windowMode == OF_FULLSCREEN){ //---------------------------------------------------- // before we go fullscreen, take a snapshot of where we are: nonFullScreenX = glutGet(GLUT_WINDOW_X); nonFullScreenY = glutGet(GLUT_WINDOW_Y); //---------------------------------------------------- glutFullScreen(); #if 0 #ifdef TARGET_OSX SetSystemUIMode(kUIModeAllHidden,NULL); #ifdef MAC_OS_X_VERSION_10_7 //needed for Lion as when the machine reboots the app is not at front level if( nFrameCount <= 10 ){ //is this long enough? too long? ProcessSerialNumber psn; OSErr err = GetCurrentProcess( &psn ); if ( err == noErr ){ SetFrontProcess( &psn ); } } #endif #endif #endif }else if( windowMode == OF_WINDOW ){ glutReshapeWindow(requestedWidth, requestedHeight); //---------------------------------------------------- // if we have recorded the screen posion, put it there // if not, better to let the system do it (and put it where it wants) if (nFrameCount > 0){ glutPositionWindow(nonFullScreenX,nonFullScreenY); } //---------------------------------------------------- #if 0 #ifdef TARGET_OSX SetSystemUIMode(kUIModeNormal,NULL); #endif #endif } bNewScreenMode = false; } } // set viewport, clear the screen ofViewport(0, 0, glutGet(GLUT_WINDOW_WIDTH), glutGet(GLUT_WINDOW_HEIGHT)); // used to be glViewport( 0, 0, width, height ); float * bgPtr = ofBgColorPtr(); bool bClearAuto = ofbClearBg(); // to do non auto clear on PC for now - we do something like "single" buffering -- // it's not that pretty but it work for the most part #ifdef TARGET_WIN32 if (bClearAuto == false){ glDrawBuffer (GL_FRONT); } #endif if ( bClearAuto == true || nFrameCount < 3){ ofClear(bgPtr[0]*255,bgPtr[1]*255,bgPtr[2]*255, bgPtr[3]*255); } if( bEnableSetupScreen )ofSetupScreen(); ofNotifyDraw(); #ifdef TARGET_WIN32 if (bClearAuto == false){ // on a PC resizing a window with this method of accumulation (essentially single buffering) // is BAD, so we clear on resize events. if (nFramesSinceWindowResized < 3){ ofClear(bgPtr[0]*255,bgPtr[1]*255,bgPtr[2]*255, bgPtr[3]*255); } else { if ( (nFrameCount < 3 || nFramesSinceWindowResized < 3) && bDoubleBuffered) glutSwapBuffers(); else glFlush(); } } else { if(bDoubleBuffered){ glutSwapBuffers(); } else{ glFlush(); } } #else if (bClearAuto == false){ // in accum mode resizing a window is BAD, so we clear on resize events. if (nFramesSinceWindowResized < 3){ ofClear(bgPtr[0]*255,bgPtr[1]*255,bgPtr[2]*255, bgPtr[3]*255); } } if(bDoubleBuffered){ glutSwapBuffers(); } else{ glFlush(); } #endif nFramesSinceWindowResized++; //fps calculation moved to idle_cb as we were having fps speedups when heavy drawing was occuring //wasn't reflecting on the actual app fps which was in reality slower. //could be caused by some sort of deferred drawing? nFrameCount++; // increase the overall frame count //setFrameNum(nFrameCount); // get this info to ofUtils for people to access }
int _glfwPlatformOpenWindow( int width, int height, const _GLFWwndconfig *wndconfig, const _GLFWfbconfig *fbconfig ) { OSStatus error; unsigned int windowAttributes; ProcessSerialNumber psn; // TODO: Break up this function! _glfwWin.windowUPP = NULL; _glfwWin.mouseUPP = NULL; _glfwWin.keyboardUPP = NULL; _glfwWin.commandUPP = NULL; _glfwWin.window = NULL; _glfwWin.aglContext = NULL; _glfwWin.aglPixelFormat = NULL; _glfwWin.cglContext = NULL; _glfwWin.cglPixelFormat = NULL; _glfwWin.refreshRate = wndconfig->refreshRate; // Fail if OpenGL 3.0 or above was requested if( wndconfig->glMajor > 2 ) { fprintf( stderr, "OpenGL 3.0+ is not yet supported on Mac OS X\n" ); _glfwPlatformCloseWindow(); return GL_FALSE; } if( _glfwLibrary.Unbundled ) { if( GetCurrentProcess( &psn ) != noErr ) { fprintf( stderr, "Failed to get the process serial number\n" ); _glfwPlatformCloseWindow(); return GL_FALSE; } if( TransformProcessType( &psn, kProcessTransformToForegroundApplication ) != noErr ) { fprintf( stderr, "Failed to become a foreground application\n" ); _glfwPlatformCloseWindow(); return GL_FALSE; } if( wndconfig->mode == GLFW_FULLSCREEN ) { if( SetFrontProcess( &psn ) != noErr ) { fprintf( stderr, "Failed to become the front process\n" ); _glfwPlatformCloseWindow(); return GL_FALSE; } } } if( !installEventHandlers() ) { fprintf( stderr, "Failed to install Carbon application event handlers\n" ); _glfwPlatformTerminate(); return GL_FALSE; } // Windowed or fullscreen; AGL or CGL? Quite the mess... // AGL appears to be the only choice for attaching OpenGL contexts to // Carbon windows, but it leaves the user no control over fullscreen // mode stretching. Solution: AGL for windowed, CGL for fullscreen. if( wndconfig->mode == GLFW_WINDOW ) { // create AGL pixel format attribute list GLint AGLpixelFormatAttributes[256]; int numAGLAttrs = 0; AGLpixelFormatAttributes[numAGLAttrs++] = AGL_RGBA; AGLpixelFormatAttributes[numAGLAttrs++] = AGL_DOUBLEBUFFER; AGLpixelFormatAttributes[numAGLAttrs++] = AGL_CLOSEST_POLICY; if( fbconfig->stereo ) { AGLpixelFormatAttributes[numAGLAttrs++] = AGL_STEREO; } _setAGLAttribute( AGL_AUX_BUFFERS, fbconfig->auxBuffers); _setAGLAttribute( AGL_RED_SIZE, fbconfig->redBits ); _setAGLAttribute( AGL_GREEN_SIZE, fbconfig->greenBits ); _setAGLAttribute( AGL_BLUE_SIZE, fbconfig->blueBits ); _setAGLAttribute( AGL_ALPHA_SIZE, fbconfig->alphaBits ); _setAGLAttribute( AGL_DEPTH_SIZE, fbconfig->depthBits ); _setAGLAttribute( AGL_STENCIL_SIZE, fbconfig->stencilBits ); _setAGLAttribute( AGL_ACCUM_RED_SIZE, fbconfig->accumRedBits ); _setAGLAttribute( AGL_ACCUM_GREEN_SIZE, fbconfig->accumGreenBits ); _setAGLAttribute( AGL_ACCUM_BLUE_SIZE, fbconfig->accumBlueBits ); _setAGLAttribute( AGL_ACCUM_ALPHA_SIZE, fbconfig->accumAlphaBits ); if( fbconfig->samples > 1 ) { _setAGLAttribute( AGL_SAMPLE_BUFFERS_ARB, 1 ); _setAGLAttribute( AGL_SAMPLES_ARB, fbconfig->samples ); AGLpixelFormatAttributes[numAGLAttrs++] = AGL_NO_RECOVERY; } AGLpixelFormatAttributes[numAGLAttrs++] = AGL_NONE; // create pixel format descriptor AGLDevice mainMonitor = GetMainDevice(); _glfwWin.aglPixelFormat = aglChoosePixelFormat( &mainMonitor, 1, AGLpixelFormatAttributes ); if( _glfwWin.aglPixelFormat == NULL ) { fprintf( stderr, "Failed to choose AGL pixel format: %s\n", aglErrorString( aglGetError() ) ); _glfwPlatformCloseWindow(); return GL_FALSE; } // create AGL context _glfwWin.aglContext = aglCreateContext( _glfwWin.aglPixelFormat, NULL ); if( _glfwWin.aglContext == NULL ) { fprintf( stderr, "Failed to create AGL context: %s\n", aglErrorString( aglGetError() ) ); _glfwPlatformCloseWindow(); return GL_FALSE; } // create window Rect windowContentBounds; windowContentBounds.left = 0; windowContentBounds.top = 0; windowContentBounds.right = width; windowContentBounds.bottom = height; windowAttributes = ( kWindowCloseBoxAttribute | kWindowCollapseBoxAttribute | kWindowStandardHandlerAttribute ); if( wndconfig->windowNoResize ) { windowAttributes |= kWindowLiveResizeAttribute; } else { windowAttributes |= ( kWindowFullZoomAttribute | kWindowResizableAttribute ); } error = CreateNewWindow( kDocumentWindowClass, windowAttributes, &windowContentBounds, &( _glfwWin.window ) ); if( ( error != noErr ) || ( _glfwWin.window == NULL ) ) { fprintf( stderr, "Failed to create Carbon window\n" ); _glfwPlatformCloseWindow(); return GL_FALSE; } _glfwWin.windowUPP = NewEventHandlerUPP( windowEventHandler ); error = InstallWindowEventHandler( _glfwWin.window, _glfwWin.windowUPP, GetEventTypeCount( GLFW_WINDOW_EVENT_TYPES ), GLFW_WINDOW_EVENT_TYPES, NULL, NULL ); if( error != noErr ) { fprintf( stderr, "Failed to install Carbon window event handler\n" ); _glfwPlatformCloseWindow(); return GL_FALSE; } // Don't care if we fail here (void)SetWindowTitleWithCFString( _glfwWin.window, CFSTR( "GLFW Window" ) ); (void)RepositionWindow( _glfwWin.window, NULL, kWindowCenterOnMainScreen ); if( !aglSetDrawable( _glfwWin.aglContext, GetWindowPort( _glfwWin.window ) ) ) { fprintf( stderr, "Failed to set the AGL context as the Carbon window drawable: %s\n", aglErrorString( aglGetError() ) ); _glfwPlatformCloseWindow(); return GL_FALSE; } // Make OpenGL context current if( !aglSetCurrentContext( _glfwWin.aglContext ) ) { fprintf( stderr, "Failed to make AGL context current: %s\n", aglErrorString( aglGetError() ) ); _glfwPlatformCloseWindow(); return GL_FALSE; } ShowWindow( _glfwWin.window ); } else { CGDisplayErr cgErr; CGLError cglErr; CFDictionaryRef optimalMode; GLint numCGLvs = 0; CGLPixelFormatAttribute CGLpixelFormatAttributes[64]; int numCGLAttrs = 0; // variables for enumerating color depths GLint rgbColorDepth; // CGL pixel format attributes _setCGLAttribute( kCGLPFADisplayMask, CGDisplayIDToOpenGLDisplayMask( kCGDirectMainDisplay ) ); if( fbconfig->stereo ) { CGLpixelFormatAttributes[ numCGLAttrs++ ] = kCGLPFAStereo; } if( fbconfig->samples > 1 ) { _setCGLAttribute( kCGLPFASamples, (CGLPixelFormatAttribute)fbconfig->samples ); _setCGLAttribute( kCGLPFASampleBuffers, (CGLPixelFormatAttribute)1 ); CGLpixelFormatAttributes[ numCGLAttrs++ ] = kCGLPFANoRecovery; } CGLpixelFormatAttributes[ numCGLAttrs++ ] = kCGLPFAFullScreen; CGLpixelFormatAttributes[ numCGLAttrs++ ] = kCGLPFADoubleBuffer; CGLpixelFormatAttributes[ numCGLAttrs++ ] = kCGLPFAAccelerated; CGLpixelFormatAttributes[ numCGLAttrs++ ] = kCGLPFANoRecovery; CGLpixelFormatAttributes[ numCGLAttrs++ ] = kCGLPFAMinimumPolicy; _setCGLAttribute( kCGLPFAAccumSize, (CGLPixelFormatAttribute)( fbconfig->accumRedBits \ + fbconfig->accumGreenBits \ + fbconfig->accumBlueBits \ + fbconfig->accumAlphaBits ) ); _setCGLAttribute( kCGLPFAAlphaSize, (CGLPixelFormatAttribute)fbconfig->alphaBits ); _setCGLAttribute( kCGLPFADepthSize, (CGLPixelFormatAttribute)fbconfig->depthBits ); _setCGLAttribute( kCGLPFAStencilSize, (CGLPixelFormatAttribute)fbconfig->stencilBits ); _setCGLAttribute( kCGLPFAAuxBuffers, (CGLPixelFormatAttribute)fbconfig->auxBuffers ); CGLpixelFormatAttributes[ numCGLAttrs++ ] = (CGLPixelFormatAttribute)NULL; // create a suitable pixel format with above attributes.. cglErr = CGLChoosePixelFormat( CGLpixelFormatAttributes, &_glfwWin.cglPixelFormat, &numCGLvs ); if( cglErr != kCGLNoError ) { fprintf( stderr, "Failed to choose CGL pixel format: %s\n", CGLErrorString( cglErr ) ); _glfwPlatformCloseWindow(); return GL_FALSE; } // ..and create a rendering context using that pixel format cglErr = CGLCreateContext( _glfwWin.cglPixelFormat, NULL, &_glfwWin.cglContext ); if( cglErr != kCGLNoError ) { fprintf( stderr, "Failed to create CGL context: %s\n", CGLErrorString( cglErr ) ); _glfwPlatformCloseWindow(); return GL_FALSE; } // enumerate depth of RGB channels - unlike AGL, CGL works with // a single parameter reflecting the full depth of the frame buffer (void)CGLDescribePixelFormat( _glfwWin.cglPixelFormat, 0, kCGLPFAColorSize, &rgbColorDepth ); // capture the display for our application cgErr = CGCaptureAllDisplays(); if( cgErr != kCGErrorSuccess ) { fprintf( stderr, "Failed to capture Core Graphics displays\n"); _glfwPlatformCloseWindow(); return GL_FALSE; } // find closest matching NON-STRETCHED display mode.. optimalMode = CGDisplayBestModeForParametersAndRefreshRateWithProperty( kCGDirectMainDisplay, rgbColorDepth, width, height, wndconfig->refreshRate, NULL, NULL ); if( optimalMode == NULL ) { fprintf( stderr, "Failed to retrieve Core Graphics display mode\n"); _glfwPlatformCloseWindow(); return GL_FALSE; } // ..and switch to that mode cgErr = CGDisplaySwitchToMode( kCGDirectMainDisplay, optimalMode ); if( cgErr != kCGErrorSuccess ) { fprintf( stderr, "Failed to switch to Core Graphics display mode\n"); _glfwPlatformCloseWindow(); return GL_FALSE; } // switch to our OpenGL context, and bring it up fullscreen cglErr = CGLSetCurrentContext( _glfwWin.cglContext ); if( cglErr != kCGLNoError ) { fprintf( stderr, "Failed to make CGL context current: %s\n", CGLErrorString( cglErr ) ); _glfwPlatformCloseWindow(); return GL_FALSE; } cglErr = CGLSetFullScreen( _glfwWin.cglContext ); if( cglErr != kCGLNoError ) { fprintf( stderr, "Failed to set CGL fullscreen mode: %s\n", CGLErrorString( cglErr ) ); _glfwPlatformCloseWindow(); return GL_FALSE; } } return GL_TRUE; }
CV_IMPL int cvNamedWindow( const char* name, int flags ) { int result = 0; CV_FUNCNAME( "cvNamedWindow" ); if (!wasInitialized) cvInitSystem(0, NULL); // to be able to display a window, we need to be a 'faceful' application // http://lists.apple.com/archives/carbon-dev/2005/Jun/msg01414.html static bool switched_to_faceful = false; if (! switched_to_faceful) { ProcessSerialNumber psn = { 0, kCurrentProcess }; OSStatus ret = TransformProcessType (&psn, kProcessTransformToForegroundApplication ); if (ret == noErr) { SetFrontProcess( &psn ); switched_to_faceful = true; } else { fprintf(stderr, "Failed to tranform process type: %d\n", (int) ret); fflush (stderr); } } __BEGIN__; WindowRef outWindow = NULL; OSStatus err = noErr; Rect contentBounds = {100,100,320,440}; CvWindow* window; UInt wAttributes = 0; int len; const EventTypeSpec genericWindowEventHandler[] = { { kEventClassMouse, kEventMouseMoved}, { kEventClassMouse, kEventMouseUp}, { kEventClassMouse, kEventMouseDown}, { kEventClassWindow, kEventWindowClose }, { kEventClassWindow, kEventWindowBoundsChanged }//FD }; if( !name ) CV_ERROR( CV_StsNullPtr, "NULL name string" ); if( icvFindWindowByName( name ) != 0 ){ result = 1; EXIT; } len = strlen(name); CV_CALL( window = (CvWindow*)cvAlloc(sizeof(CvWindow) + len + 1)); memset( window, 0, sizeof(*window)); window->name = (char*)(window + 1); memcpy( window->name, name, len + 1 ); window->flags = flags; window->signature = CV_WINDOW_MAGIC_VAL; window->image = 0; window->last_key = 0; window->on_mouse = 0; window->on_mouse_param = 0; window->next = hg_windows; window->prev = 0; if( hg_windows ) hg_windows->prev = window; hg_windows = window; wAttributes = kWindowStandardDocumentAttributes | kWindowStandardHandlerAttribute | kWindowLiveResizeAttribute; err = CreateNewWindow ( kDocumentWindowClass,wAttributes,&contentBounds,&outWindow); if (err != noErr) fprintf(stderr,"Erreur while creating the window\n"); SetWindowTitleWithCFString(outWindow,CFStringCreateWithCString(NULL,name,kCFStringEncodingASCII)); if (err != noErr) fprintf(stdout,"Erreur SetWindowTitleWithCFString\n"); window->window = outWindow; err = InstallWindowEventHandler(outWindow, NewEventHandlerUPP(windowEventHandler), GetEventTypeCount(genericWindowEventHandler), genericWindowEventHandler, outWindow, NULL); ShowWindow( outWindow ); result = 1; __END__; return result; }
bool VisualizerApp::init( int argc, char** argv ) { ROS_INFO( "rviz version %s", get_version().c_str() ); ROS_INFO( "compiled against Qt version " QT_VERSION_STR ); ROS_INFO( "compiled against OGRE version %d.%d.%d%s (%s)", OGRE_VERSION_MAJOR, OGRE_VERSION_MINOR, OGRE_VERSION_PATCH, OGRE_VERSION_SUFFIX, OGRE_VERSION_NAME ); #ifdef Q_OS_MAC ProcessSerialNumber PSN; GetCurrentProcess(&PSN); TransformProcessType(&PSN,kProcessTransformToForegroundApplication); SetFrontProcess(&PSN); #endif #if CATCH_EXCEPTIONS try { #endif ros::init( argc, argv, "rviz", ros::init_options::AnonymousName ); startContinueChecker(); po::options_description options; options.add_options() ("help,h", "Produce this help message") ("splash-screen,s", po::value<std::string>(), "A custom splash-screen image to display") ("help-file", po::value<std::string>(), "A custom html file to show as the help screen") ("display-config,d", po::value<std::string>(), "A display config file (.rviz) to load") ("fixed-frame,f", po::value<std::string>(), "Set the fixed frame") ("ogre-log,l", "Enable the Ogre.log file (output in cwd) and console output.") ("in-mc-wrapper", "Signal that this is running inside a master-chooser wrapper") ("opengl", po::value<int>(), "Force OpenGL version (use '--opengl 210' for OpenGL 2.1 compatibility mode)") ("disable-anti-aliasing", "Prevent rviz from trying to use anti-aliasing when rendering.") ("no-stereo", "Disable the use of stereo rendering.") ("verbose,v", "Enable debug visualizations") ("log-level-debug", "Sets the ROS logger level to debug."); po::variables_map vm; std::string display_config, fixed_frame, splash_path, help_path; bool enable_ogre_log = false; bool in_mc_wrapper = false; bool verbose = false; int force_gl_version = 0; bool disable_anti_aliasing = false; bool disable_stereo = false; try { po::store( po::parse_command_line( argc, argv, options ), vm ); po::notify( vm ); if( vm.count( "help" )) { std::cout << "rviz command line options:\n" << options; return false; } if( vm.count( "in-mc-wrapper" )) { in_mc_wrapper = true; } if (vm.count("display-config")) { display_config = vm["display-config"].as<std::string>(); if( display_config.substr( display_config.size() - 4, 4 ) == ".vcg" ) { std::cerr << "ERROR: the config file '" << display_config << "' is a .vcg file, which is the old rviz config format." << std::endl; std::cerr << " New config files have a .rviz extension and use YAML formatting. The format changed" << std::endl; std::cerr << " between Fuerte and Groovy. There is not (yet) an automated conversion program." << std::endl; return false; } } if (vm.count("splash-screen")) { splash_path = vm["splash-screen"].as<std::string>(); } if (vm.count("help-file")) { help_path = vm["help-file"].as<std::string>(); } if (vm.count("fixed-frame")) { fixed_frame = vm["fixed-frame"].as<std::string>(); } if (vm.count("ogre-log")) { enable_ogre_log = true; } if (vm.count("no-stereo")) { disable_stereo = true; } if (vm.count("opengl")) { //std::cout << vm["opengl"].as<std::string>() << std::endl; force_gl_version = vm["opengl"].as<int>(); } if (vm.count("disable-anti-aliasing")) { disable_anti_aliasing = true; } if (vm.count("verbose")) { verbose = true; } if (vm.count("log-level-debug")) { if( ros::console::set_logger_level(ROSCONSOLE_DEFAULT_NAME, ros::console::levels::Debug) ) { ros::console::notifyLoggerLevelsChanged(); } } } catch (std::exception& e) { ROS_ERROR("Error parsing command line: %s", e.what()); return false; } if( !ros::master::check() ) { WaitForMasterDialog* dialog = new WaitForMasterDialog; if( dialog->exec() != QDialog::Accepted ) { return false; } } nh_.reset( new ros::NodeHandle ); if( enable_ogre_log ) { OgreLogging::useRosLog(); } if ( force_gl_version ) { RenderSystem::forceGlVersion( force_gl_version ); } if (disable_anti_aliasing) { RenderSystem::disableAntiAliasing(); } if ( disable_stereo ) { RenderSystem::forceNoStereo(); } frame_ = new VisualizationFrame(); frame_->setApp( this->app_ ); if( help_path != "" ) { frame_->setHelpPath( QString::fromStdString( help_path )); } frame_->setShowChooseNewMaster( in_mc_wrapper ); if( splash_path != "" ) { frame_->setSplashPath( QString::fromStdString( splash_path )); } frame_->initialize( QString::fromStdString( display_config )); if( !fixed_frame.empty() ) { frame_->getManager()->setFixedFrame( QString::fromStdString( fixed_frame )); } frame_->getManager()->getSelectionManager()->setDebugMode( verbose ); frame_->show(); ros::NodeHandle private_nh("~"); reload_shaders_service_ = private_nh.advertiseService("reload_shaders", reloadShaders); #if CATCH_EXCEPTIONS } catch (std::exception& e) { ROS_ERROR("Caught exception while loading: %s", e.what()); return false; } #endif return true; }
static int ioSetFullScreenActual(int fullScreen) { Rect screen; int width, height, maxWidth, maxHeight; int oldWidth, oldHeight; static Rect rememberOldLocation = {0,0,0,0}; GDHandle dominantGDevice; windowDescriptorBlock * targetWindowBlock = windowBlockFromIndex(1); extern Boolean gSqueakBrowserWasHeadlessButMadeFullScreen; extern Boolean gSqueakBrowserSubProcess; if (browserActiveAndDrawingContextOk()) { if (!gSqueakBrowserWasHeadlessButMadeFullScreen) { gSqueakBrowserWasHeadlessButMadeFullScreen = true; SetUpMenus(); AdjustMenus(); } sqShowWindowActual(1); if (targetWindowBlock->context) //Set context to NULL, if screen is same size as fullscreen we wouldn't get new context QDEndCGContext(GetWindowPort(targetWindowBlock->handle),&targetWindowBlock->context); targetWindowBlock->context = NULL; } if ((targetWindowBlock == NULL) || (fullScreen && getFullScreenFlag() && !targetWindowBlock->isInvisible)) return 0; dominantGDevice = getThatDominateGDevice(targetWindowBlock->handle); if (dominantGDevice == null) { success(false); return 0; } screen = (**dominantGDevice).gdRect; if (fullScreen) { GetPortBounds(GetWindowPort(targetWindowBlock->handle),&rememberOldLocation); oldWidth = rememberOldLocation.right - rememberOldLocation.left; oldHeight = rememberOldLocation.bottom - rememberOldLocation.top; if (targetWindowBlock->isInvisible) { rememberOldLocation.top = 44; rememberOldLocation.left = 8; } QDLocalToGlobalRect(GetWindowPort(targetWindowBlock->handle),&rememberOldLocation); if (gSqueakBrowserSubProcess) { ProcessSerialNumber psn = { 0, kCurrentProcess }; ProcessInfoRec info; info.processName = NULL; info.processAppSpec = NULL; info.processInfoLength = sizeof(ProcessInfoRec); GetProcessInformation(&psn,&info); SetFrontProcess(&psn); } MenuBarHide(); width = screen.right - screen.left; height = (screen.bottom - screen.top); MoveWindow(targetWindowBlock->handle, screen.left, screen.top, true); SizeWindow(targetWindowBlock->handle, width, height, true); setFullScreenFlag(true); } else { MenuBarRestore(); if (gSqueakBrowserWasHeadlessButMadeFullScreen) { HideWindow(targetWindowBlock->handle); { ProcessSerialNumber psn; pid_t parent; OSStatus err; parent = getppid(); if (parent != 1) { err = GetProcessForPID(parent,&psn); if(err == 0) SetFrontProcess(&psn); } } } if (EmptyRect(&rememberOldLocation)) { /* get old window size */ width = (unsigned) getSavedWindowSize() >> 16; height = getSavedWindowSize() & 0xFFFF; /* minimum size is 1 x 1 */ width = (width > 0) ? width : 64; height = (height > 0) ? height : 64; /* maximum size is screen size inset slightly */ maxWidth = (screen.right - screen.left) - 16; maxHeight = (screen.bottom - screen.top) - 52; width = (width <= maxWidth) ? width : maxWidth; height = (height <= maxHeight) ? height : maxHeight; MoveWindow(targetWindowBlock->handle, 8, 44, true); SizeWindow(targetWindowBlock->handle, width, height, true); } else {
IO_stat MCDispatch::startup(void) { IO_stat stat; MCStack *sptr; // set up image cache before the first stack is opened MCCachedImageRep::init(); startdir = MCS_getcurdir(); enginedir = strclone(MCcmd); char *eptr; eptr = strrchr(enginedir, PATH_SEPARATOR); if (eptr != NULL) *eptr = '\0'; else *enginedir = '\0'; MCExecPoint ep; ep . setstaticbytes(MCstartupstack, MCstartupstack_length); MCDecompress::do_decompress(ep, 0, 0); IO_handle stream = MCS_fakeopen(ep . getsvalue()); if ((stat = MCdispatcher -> readfile(NULL, NULL, stream, sptr)) != IO_NORMAL) { MCS_close(stream); return stat; } MCS_close(stream); memset((void *)ep . getsvalue() . getstring(), 0, ep . getsvalue() . getlength()); ep . clear(); // Temporary fix to make sure environment stack doesn't get lost behind everything. #if defined(_MACOSX) ProcessSerialNumber t_psn = { 0, kCurrentProcess }; SetFrontProcess(&t_psn); #elif defined(_WINDOWS) SetForegroundWindow(((MCScreenDC *)MCscreen) -> getinvisiblewindow()); #endif MCenvironmentactive = True; sptr -> setfilename(strclone(MCcmd)); MCdefaultstackptr = MCstaticdefaultstackptr = stacks; { MCdefaultstackptr -> setextendedstate(true, ECS_DURING_STARTUP); MCdefaultstackptr -> message(MCM_start_up, nil, False, True); MCdefaultstackptr -> setextendedstate(false, ECS_DURING_STARTUP); } if (!MCquit) { MCresult -> fetch(ep); ep . appendchar('\0'); if (ep . getsvalue() . getlength() == 1) { sptr -> open(); MCImage::init(); X_main_loop(); MCresult -> fetch(ep); ep . appendchar('\0'); if (ep . getsvalue() . getlength() == 1) return IO_NORMAL; } if (sptr -> getscript() != NULL) memset(sptr -> getscript(), 0, strlen(sptr -> getscript())); destroystack(sptr, True); MCtopstackptr = NULL; MCquit = False; MCenvironmentactive = False; send_relaunch(); sptr = findstackname(ep . getsvalue() . getstring()); if (sptr == NULL && (stat = loadfile(ep . getsvalue() . getstring(), sptr)) != IO_NORMAL) return stat; } if (!MCquit) { // OK-2007-11-13 : Bug 5525, after opening the IDE engine, the allowInterrupts should always default to false, // regardless of what the environment stack may have set it to. MCallowinterrupts = true; sptr -> setparent(this); MCdefaultstackptr = MCstaticdefaultstackptr = stacks; send_startup_message(false); if (!MCquit) sptr -> open(); } return IO_NORMAL; }
bool Window::configInitAGLWindow() { AGLContext context = getAGLContext(); if( !context ) { sendError( ERROR_AGLWINDOW_NO_CONTEXT ); return false; } // window const bool decoration = getIAttribute(WindowSettings::IATTR_HINT_DECORATION) != OFF; WindowAttributes winAttributes = ( decoration ? kWindowStandardDocumentAttributes : kWindowNoTitleBarAttribute | kWindowNoShadowAttribute | kWindowResizableAttribute ) | kWindowStandardHandlerAttribute | kWindowInWindowMenuAttribute; // top, left, bottom, right const PixelViewport& pvp = getPixelViewport(); const int32_t menuHeight = decoration ? EQ_AGL_MENUBARHEIGHT : 0 ; Rect windowRect = { short( pvp.y + menuHeight ), short( pvp.x ), short( pvp.getYEnd() + menuHeight ), short( pvp.getXEnd( )) }; WindowRef windowRef; Global::enterCarbon(); const OSStatus status = CreateNewWindow( kDocumentWindowClass, winAttributes, &windowRect, &windowRef ); if( status != noErr ) { sendError( ERROR_AGLWINDOW_CREATEWINDOW_FAILED ) << lexical_cast< std::string >( status ); Global::leaveCarbon(); return false; } // window title const std::string& name = getName(); std::stringstream windowTitle; if( name.empty( )) { windowTitle << "Equalizer"; #ifndef NDEBUG windowTitle << " (" << getpid() << ")"; #endif } else windowTitle << name; CFStringRef title = CFStringCreateWithCString( kCFAllocatorDefault, windowTitle.str().c_str(), kCFStringEncodingMacRoman ); SetWindowTitleWithCFString( windowRef, title ); CFRelease( title ); if( !aglSetWindowRef( context, windowRef )) { sendError( ERROR_AGLWINDOW_SETWINDOW_FAILED ) << aglError(); Global::leaveCarbon(); return false; } // show ShowWindow( windowRef ); // Do focus hell ProcessSerialNumber selfProcess = { 0, kCurrentProcess }; SetFrontProcess( &selfProcess ); Global::leaveCarbon(); setCarbonWindow( windowRef ); return true; }
int main(int argc, char **argv) #endif { ll_init_apr(); // Set up llerror logging { LLError::initForApplication("."); LLError::setDefaultLevel(LLError::LEVEL_INFO); // LLError::setTagLevel("Plugin", LLError::LEVEL_DEBUG); // LLError::logToFile("slplugin.log"); } #if LL_WINDOWS if( strlen( lpCmdLine ) == 0 ) { LL_ERRS("slplugin") << "usage: " << "SLPlugin" << " launcher_port" << LL_ENDL; }; U32 port = 0; if(!LLStringUtil::convertToU32(lpCmdLine, port)) { LL_ERRS("slplugin") << "port number must be numeric" << LL_ENDL; }; // Insert our exception handler into the system so this plugin doesn't // display a crash message if something bad happens. The host app will // see the missing heartbeat and log appropriately. initExceptionHandler(); #elif LL_DARWIN || LL_LINUX if(argc < 2) { LL_ERRS("slplugin") << "usage: " << argv[0] << " launcher_port" << LL_ENDL; } U32 port = 0; if(!LLStringUtil::convertToU32(argv[1], port)) { LL_ERRS("slplugin") << "port number must be numeric" << LL_ENDL; } // Catch signals that most kinds of crashes will generate, and exit cleanly so the system crash dialog isn't shown. signal(SIGILL, &crash_handler); // illegal instruction # if LL_DARWIN signal(SIGEMT, &crash_handler); // emulate instruction executed # endif // LL_DARWIN signal(SIGFPE, &crash_handler); // floating-point exception signal(SIGBUS, &crash_handler); // bus error signal(SIGSEGV, &crash_handler); // segmentation violation signal(SIGSYS, &crash_handler); // non-existent system call invoked #endif #if LL_DARWIN setupCocoa(); createAutoReleasePool(); #endif LLPluginProcessChild *plugin = new LLPluginProcessChild(); plugin->init(port); #if LL_DARWIN deleteAutoReleasePool(); #endif LLTimer timer; timer.start(); #if LL_WINDOWS checkExceptionHandler(); #endif #if LL_DARWIN // If the plugin opens a new window (such as the Flash plugin's fullscreen player), we may need to bring this plugin process to the foreground. // Use this to track the current frontmost window and bring this process to the front if it changes. WindowRef front_window = NULL; WindowGroupRef layer_group = NULL; int window_hack_state = 0; CreateWindowGroup(kWindowGroupAttrFixedLevel, &layer_group); if(layer_group) { // Start out with a window layer that's way out in front (fixes the problem with the menubar not getting hidden on first switch to fullscreen youtube) SetWindowGroupName(layer_group, CFSTR("SLPlugin Layer")); SetWindowGroupLevel(layer_group, kCGOverlayWindowLevel); } #endif #if LL_DARWIN EventTargetRef event_target = GetEventDispatcherTarget(); #endif while(!plugin->isDone()) { #if LL_DARWIN createAutoReleasePool(); #endif timer.reset(); plugin->idle(); #if LL_DARWIN { // Some plugins (webkit at least) will want an event loop. This qualifies. EventRef event; if(ReceiveNextEvent(0, 0, kEventDurationNoWait, true, &event) == noErr) { SendEventToEventTarget (event, event_target); ReleaseEvent(event); } // Check for a change in this process's frontmost window. if(FrontWindow() != front_window) { ProcessSerialNumber self = { 0, kCurrentProcess }; ProcessSerialNumber parent = { 0, kNoProcess }; ProcessSerialNumber front = { 0, kNoProcess }; Boolean this_is_front_process = false; Boolean parent_is_front_process = false; { // Get this process's parent ProcessInfoRec info; info.processInfoLength = sizeof(ProcessInfoRec); info.processName = NULL; info.processAppSpec = NULL; if(GetProcessInformation( &self, &info ) == noErr) { parent = info.processLauncher; } // and figure out whether this process or its parent are currently frontmost if(GetFrontProcess(&front) == noErr) { (void) SameProcess(&self, &front, &this_is_front_process); (void) SameProcess(&parent, &front, &parent_is_front_process); } } if((FrontWindow() != NULL) && (front_window == NULL)) { // Opening the first window if(window_hack_state == 0) { // Next time through the event loop, lower the window group layer window_hack_state = 1; } if(layer_group) { SetWindowGroup(FrontWindow(), layer_group); } if(parent_is_front_process) { // Bring this process's windows to the front. (void) SetFrontProcess( &self ); } ActivateWindow(FrontWindow(), true); } else if((FrontWindow() == NULL) && (front_window != NULL)) { // Closing the last window if(this_is_front_process) { // Try to bring this process's parent to the front (void) SetFrontProcess(&parent); } } else if(window_hack_state == 1) { if(layer_group) { // Set the window group level back to something less extreme SetWindowGroupLevel(layer_group, kCGNormalWindowLevel); } window_hack_state = 2; } front_window = FrontWindow(); } } #endif F64 elapsed = timer.getElapsedTimeF64(); F64 remaining = plugin->getSleepTime() - elapsed; if(remaining <= 0.0f) { // We've already used our full allotment. // LL_INFOS("slplugin") << "elapsed = " << elapsed * 1000.0f << " ms, remaining = " << remaining * 1000.0f << " ms, not sleeping" << LL_ENDL; // Still need to service the network... plugin->pump(); } else { // LL_INFOS("slplugin") << "elapsed = " << elapsed * 1000.0f << " ms, remaining = " << remaining * 1000.0f << " ms, sleeping for " << remaining * 1000.0f << " ms" << LL_ENDL; // timer.reset(); // This also services the network as needed. plugin->sleep(remaining); // LL_INFOS("slplugin") << "slept for "<< timer.getElapsedTimeF64() * 1000.0f << " ms" << LL_ENDL; } #if LL_WINDOWS // More agressive checking of interfering exception handlers. // Doesn't appear to be required so far - even for plugins // that do crash with a single call to the intercept // exception handler such as QuickTime. //checkExceptionHandler(); #endif #if LL_DARWIN deleteAutoReleasePool(); #endif } delete plugin; ll_cleanup_apr(); return 0; }
// Note that this function has to be called once. To recreate textures, call the renewTex() member function. int appleMultiContext::init(struct sageDisplayConfig &cfg) { // Make this a "faceful app" that can receive input events: ProcessSerialNumber psn; OSStatus s; s = GetCurrentProcess(&psn); assert(s == noErr); s = TransformProcessType(&psn,kProcessTransformToForegroundApplication); assert(s == noErr); s = SetFrontProcess(&psn); assert(s == noErr); singleContext = false; configStruct = cfg; tileNum = cfg.dimX * cfg.dimY; if (tileNum > MAX_TILES_PER_NODE) { sage::printLog("displayContext::init() : The tile number exceeds the maximum"); return -1; } if (!winCreatFlag) { // // Set up us the OpenGL: // Choose global pixel format: static GLint agl_fmt_list[] = { AGL_RGBA, AGL_RED_SIZE, 8, AGL_GREEN_SIZE, 8, AGL_BLUE_SIZE, 8, AGL_ALPHA_SIZE, 8, AGL_DEPTH_SIZE, 24, AGL_DOUBLEBUFFER, AGL_NONE }; agl_fmt = aglChoosePixelFormat(0,0,agl_fmt_list); if (agl_fmt == 0) { fprintf(stderr,"failed to choose OpenGL pixel format\n"); abort(); } // The critical region object MPCreateCriticalRegion(&cr); // Install event handlers // EventTargetRef target = GetApplicationEventTarget(); EventTypeSpec eventTypes[] = { { kEventClassKeyboard, kEventRawKeyDown } }; InstallEventHandler(target,NewEventHandlerUPP(keyboard_handler), sizeof(eventTypes) / sizeof(EventTypeSpec),eventTypes, 0,0); // Create Windows for (int k = 0; k < tileNum; k++) { int tileX = (k % cfg.dimX) * cfg.tileRect[k].width; int tileY = (k / cfg.dimX) * cfg.tileRect[k].height; Rect wrect; wrect.left = tileX; // cfg.tileRect[k].x; wrect.top = tileY; // cfg.tileRect[k].y; wrect.right = wrect.left + cfg.tileRect[k].width; wrect.bottom = wrect.top + cfg.tileRect[k].height; //fprintf(stderr,"Create window %d at %i,%i,%i,%i\n",k, wrect.left,wrect.top,wrect.right,wrect.bottom); windows[k] = new Window(wrect, configStruct.fullScreenFlag); windows[k]->beginGL(); glEnable(GL_DEPTH_TEST); glEnable(GL_TEXTURE_2D); } winCreatFlag = true; } return 0; } // End of appleMultiContext::init()
OP_STATUS MacOpPluginAdapter::ProcessMessage(const OpTypedMessage* message) { switch (message->GetType()) { case OpPeerConnectedMessage::Type: if (m_plugin_window) // Send initial top-level window coordinates. m_plugin_window->OnDesktopWindowMoved(NULL); break; case OpPeerDisconnectedMessage::Type: m_plugin_channel = NULL; break; case OpMacPluginUpdateViewMessage::Type: if (m_plugin_window) m_plugin_window->UpdatePluginView(); break; case OpMacPluginFullscreenMessage::Type: { SystemUIMode outMode; SystemUIOptions outOptions; GetSystemUIMode(&outMode, &outOptions); ProcessSerialNumber psn; if (OpMacPluginFullscreenMessage::Cast(message)->GetFullscreen()) { // Hide menu and dock SetSystemUIMode(kUIModeAllHidden, outOptions); // Set the plugin as the front process psn.highLongOfPSN = OpMacPluginFullscreenMessage::Cast(message)->GetHighLongOfPSN(); psn.lowLongOfPSN = OpMacPluginFullscreenMessage::Cast(message)->GetLowLongOfPSN(); SetFrontProcess(&psn); } else { // Set Opera as the front process GetCurrentProcess(&psn); SetFrontProcess(&psn); // Show menu and dock SetSystemUIMode(kUIModeNormal, outOptions); } } break; case OpMacPluginWindowShownMessage::Type: { ProcessSerialNumber psn; if (OpMacPluginWindowShownMessage::Cast(message)->GetShow()) { // Set the plugin as the front process psn.highLongOfPSN = OpMacPluginWindowShownMessage::Cast(message)->GetHighLongOfPSN(); psn.lowLongOfPSN = OpMacPluginWindowShownMessage::Cast(message)->GetLowLongOfPSN(); SetFrontProcess(&psn); } else { // Set Opera as the front process GetCurrentProcess(&psn); SetFrontProcess(&psn); } } break; case OpMacPluginInfoMessage::Type: return message->Reply(OpMacPluginInfoResponseMessage::Create(CommandLineManager::GetInstance()->GetArgument(CommandLineManager::DisableCoreAnimation) ? TRUE : FALSE, CommandLineManager::GetInstance()->GetArgument(CommandLineManager::DisableInvalidatingCoreAnimation) ? TRUE : FALSE)); case OpMacPluginCursorShownMessage::Type: { if (OpMacPluginCursorShownMessage::Cast(message)->GetShow()) { CGDisplayShowCursor(CGMainDisplayID()); } else { CGDisplayHideCursor(CGMainDisplayID()); } } break; case OpMacPluginContextMenuShownMessage::Type: { gHandlingContextMenu = OpMacPluginContextMenuShownMessage::Cast(message)->GetShow(); } break; } return OpStatus::OK; }
int main(int argc, char *argv[]) { AGLPixelFormat format; /* OpenGL pixel format */ WindowPtr window; /* Window */ int winattrs; /* Window attributes */ Str255 title; /* Title of window */ Rect rect; /* Rectangle definition */ EventHandlerUPP handler; /* Event handler */ EventLoopTimerUPP thandler; /* Timer handler */ EventLoopTimerRef timer; /* Timer for animating the window */ ProcessSerialNumber psn; /* Process serial number */ static EventTypeSpec events[] = /* Events we are interested in... */ { { kEventClassMouse, kEventMouseDown }, { kEventClassMouse, kEventMouseUp }, { kEventClassMouse, kEventMouseMoved }, { kEventClassMouse, kEventMouseDragged }, { kEventClassWindow, kEventWindowDrawContent }, { kEventClassWindow, kEventWindowShown }, { kEventClassWindow, kEventWindowHidden }, { kEventClassWindow, kEventWindowActivated }, { kEventClassWindow, kEventWindowDeactivated }, { kEventClassWindow, kEventWindowClose }, { kEventClassWindow, kEventWindowBoundsChanged }, { kCoreEventClass, kAEOpenApplication } }; static GLint attributes[] = /* OpenGL attributes */ { AGL_RGBA, AGL_GREEN_SIZE, 1, AGL_DOUBLEBUFFER, AGL_DEPTH_SIZE, 16, AGL_NONE }; //Set initial values for window const int origWinHeight = 628; const int origWinWidth = 850; const int origWinXOffset = 50; const int origWinYOffset = 50; // Create the window... aglContext = 0; WindowVisible = 0; SetRect(&rect, origWinXOffset, origWinYOffset, origWinWidth, origWinHeight); winattrs = kWindowStandardHandlerAttribute | kWindowCloseBoxAttribute | kWindowCollapseBoxAttribute | kWindowFullZoomAttribute | kWindowResizableAttribute | kWindowLiveResizeAttribute; winattrs &= GetAvailableWindowAttributes(kDocumentWindowClass); strcpy((char *)(title + 1), "Rigid Body Dynamics"); title[0] = strlen((char *)(title + 1)); CreateNewWindow(kDocumentWindowClass, winattrs, &rect, &window); SetWTitle(window, title); handler = NewEventHandlerUPP(EventHandler); InstallWindowEventHandler(window, handler, sizeof(events) / sizeof(events[0]), events, NULL, 0L); thandler = NewEventLoopTimerUPP((void (*)(EventLoopTimerRef, void *))IdleFunc); InstallEventLoopTimer(GetMainEventLoop(), 0, 0, thandler, 0, &timer); GetCurrentProcess(&psn); SetFrontProcess(&psn); DrawGrowIcon(window); ShowWindow(window); // Create the OpenGL context and bind it to the window... format = aglChoosePixelFormat(NULL, 0, attributes); aglContext = aglCreateContext(format, NULL); aglSetCurrentContext(aglContext); if (aglContext == NULL) { printf("Unable to create OpenGL context.\n"); return 1; } aglDestroyPixelFormat(format); aglSetDrawable(aglContext, GetWindowPort(window)); // Set the initial size of the cube altEngine.init((void *)&window, (void *)&aglContext); altEngine.resize(origWinWidth - origWinXOffset, origWinHeight - origWinYOffset); for (;;) { if (WindowVisible) SetEventLoopTimerNextFireTime(timer, 0.05); RunApplicationEventLoop(); if (WindowVisible) { altEngine.step(); //render frame, must pass a message to event handler altEngine.render(); } } }
// A magic method that allows applications to react to events even // when they are not organized in a bundle static void osx_AllowForeground(void) { ProcessSerialNumber psn = { 0, kCurrentProcess }; TransformProcessType(&psn, kProcessTransformToForegroundApplication); SetFrontProcess(&psn); }