void MacOpMessageLoop::DispatchAllPostedMessagesNow()
{
#ifdef USE_UNTESTED_DISPATCH_CODE
	OpVector<EventRef> eventList;
	OSStatus err;
	EventRef nextEvent;

	do
	{
		nextEvent = FindSpecificEventInQueue(gMainEventQueue, OperaEventComparatorProc, NULL);
		if(nextEvent)
		{
			if(noErr == RemoveEventFromQueue(gMainEventQueue, nextEvent))
			{
				eventList.Add(&nextEvent);
			}
		}
	} while(nextEvent);


	if(eventList.GetCount() > 0)
	{
		for(int i = 0; i < eventList.GetCount(); i++)
		{
			nextEvent = *eventList.Get(i);
			err = SendEventToEventTarget(nextEvent, GetEventDispatcherTarget());
			ReleaseEvent(nextEvent);
		}
	}
#endif
}
Example #2
0
OSStatus
TkMacOSXReceiveAndProcessEvent()
{
    static EventTargetRef targetRef = NULL;
    EventRef eventRef;
    OSStatus err;

    /*
     * This is a poll, since we have already counted the events coming
     * into this routine, and are guaranteed to have one waiting.
     */
     
    err = ReceiveNextEvent(0, NULL, kEventDurationNoWait, true, &eventRef);
    if (err == noErr) {
        if (!targetRef) {
            targetRef = GetEventDispatcherTarget();
        }
        TkMacOSXStartTclEventLoopCarbonTimer();
        err = SendEventToEventTarget(eventRef,targetRef);
        TkMacOSXStopTclEventLoopCarbonTimer();
#ifdef TK_MAC_DEBUG
        if (err != noErr && err != eventLoopTimedOutErr
                && err != eventNotHandledErr
        ) {
            char buf [256];
            fprintf(stderr,
                    "RCNE SendEventToEventTarget (%s) failed, %d\n",
                    CarbonEventToAscii(eventRef, buf), (int)err);
        }
#endif
        ReleaseEvent(eventRef);
    }
    return err;
}
Example #3
0
void MessagePump::dispatchAll()
{
    _initReceiverQueue();

    while( true )
    {
        EventRef       event;

        if( _needGlobalLock )
            Global::enterCarbon(); 
        const OSStatus status = ReceiveNextEvent( 0, 0, 0.0, true, &event );

        if( status == eventLoopTimedOutErr )
            break;

        if( status != noErr )
        {
            EQWARN << "ReceiveNextEvent failed: " << status << std::endl;
            break;
        }

        EQVERB << "Dispatch Carbon event " << event << std::endl;

        if( !_needGlobalLock )
            Global::enterCarbon();
        const EventTargetRef target = GetEventDispatcherTarget();
        SendEventToEventTarget( event, target );
        Global::leaveCarbon();

        ReleaseEvent( event );
    }

    if( _needGlobalLock )
        Global::leaveCarbon();
}
Example #4
0
MODULE_SCOPE void
TkMacOSXInitCarbonEvents(
    Tcl_Interp *interp)
{
    const EventTypeSpec dispatcherEventTypes[] = {
	{kEventClassKeyboard,	 kEventRawKeyDown},
	{kEventClassKeyboard,	 kEventRawKeyRepeat},
	{kEventClassKeyboard,	 kEventRawKeyUp},
	{kEventClassKeyboard,	 kEventRawKeyModifiersChanged},
	{kEventClassKeyboard,	 kEventRawKeyRepeat},
    };
    const EventTypeSpec applicationEventTypes[] = {
	{kEventClassMenu,	 kEventMenuBeginTracking},
	{kEventClassMenu,	 kEventMenuEndTracking},
	{kEventClassMenu,	 kEventMenuOpening},
	{kEventClassMenu,	 kEventMenuTargetItem},
	{kEventClassCommand,	 kEventCommandProcess},
	{kEventClassCommand,	 kEventCommandUpdateStatus},
	{kEventClassApplication, kEventAppActivated},
	{kEventClassApplication, kEventAppDeactivated},
	{kEventClassApplication, kEventAppQuit},
	{kEventClassApplication, kEventAppHidden},
	{kEventClassApplication, kEventAppShown},
	{kEventClassApplication, kEventAppAvailableWindowBoundsChanged},
	{kEventClassAppearance,	 kEventAppearanceScrollBarVariantChanged},
	{kEventClassFont,	 kEventFontPanelClosed},
	{kEventClassFont,	 kEventFontSelection},
    };

    carbonEventHandlerUPP = NewEventHandlerUPP(CarbonEventHandlerProc);
    carbonEventInterp = interp;
    ChkErr(InstallStandardApplicationEventHandler);
    ChkErr(InstallEventHandler, GetEventDispatcherTarget(),
	    carbonEventHandlerUPP, GetEventTypeCount(dispatcherEventTypes),
	    dispatcherEventTypes, (void *) carbonEventInterp, NULL);
    ChkErr(InstallEventHandler, GetApplicationEventTarget(),
	    carbonEventHandlerUPP, GetEventTypeCount(applicationEventTypes),
	    applicationEventTypes, (void *) carbonEventInterp, NULL);

#ifdef TK_MAC_DEBUG_CARBON_EVENTS
    TkMacOSXInitNamedSymbol(HIToolbox, void, DebugTraceEvent, OSType, UInt32,
	    Boolean);
    if (DebugTraceEvent) {
	unsigned int i;
	const EventTypeSpec *e;

	for (i = 0, e = dispatcherEventTypes;
		i < GetEventTypeCount(dispatcherEventTypes); i++, e++) {
	    DebugTraceEvent(e->eventClass, e->eventKind, 1);
	}
	for (i = 0, e = applicationEventTypes;
		i < GetEventTypeCount(applicationEventTypes); i++, e++) {
	    DebugTraceEvent(e->eventClass, e->eventKind, 1);
	}
	DebugTraceEvent = NULL; /* Only enable tracing once. */
    }
#endif /* TK_MAC_DEBUG_CARBON_EVENTS */
}
//--------------------------------------------------------------------------------//
void WindowEventUtilities::messagePump()
{
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
	// Windows Message Loop (NULL means check all HWNDs belonging to this context)
	MSG  msg;
	while( PeekMessage( &msg, NULL, 0U, 0U, PM_REMOVE ) )
	{
		TranslateMessage( &msg );
		DispatchMessage( &msg );
	}
#elif OGRE_PLATFORM == OGRE_PLATFORM_LINUX
	//GLX Message Pump
	RenderWindowList::iterator win = _msWindows.begin();
	RenderWindowList::iterator end = _msWindows.end();

	Display* xDisplay = 0; // same for all windows
	
	for (; win != end; win++)
	{
	    XID xid;
	    XEvent event;

	    if (!xDisplay)
		(*win)->getCustomAttribute("XDISPLAY", &xDisplay);

	    (*win)->getCustomAttribute("WINDOW", &xid);

	    while (XCheckWindowEvent (xDisplay, xid, StructureNotifyMask | VisibilityChangeMask | FocusChangeMask, &event))
	    {
		GLXProc(*win, event);
	    }

	    // The ClientMessage event does not appear under any Event Mask
	    while (XCheckTypedWindowEvent (xDisplay, xid, ClientMessage, &event))
	    {
		GLXProc(*win, event);
	    }
	}
#elif OGRE_PLATFORM == OGRE_PLATFORM_APPLE && !defined __OBJC__ && !defined __LP64__
	// OSX Message Pump
	EventRef event = NULL;
	EventTargetRef targetWindow;
	targetWindow = GetEventDispatcherTarget();
    
    // If we are unable to get the target then we no longer care about events.
    if( !targetWindow ) return;
    
    // Grab the next event, process it if it is a window event
	while( ReceiveNextEvent( 0, NULL, kEventDurationNoWait, true, &event ) == noErr )
	{
        // Dispatch the event
		SendEventToEventTarget( event, targetWindow );
   		ReleaseEvent( event );
	}
#endif
}
Example #6
0
void QuartzWindow::check_carbon_events() {
  BlockGlueFlag f(quartz_semaphore);

  for (;;) {
    EventRef evt;
    ReceiveNextEvent(0, NULL, kEventDurationNoWait, true, &evt);
    if (!evt) return;
    SendEventToEventTarget(evt, GetEventDispatcherTarget());
  }
}
Example #7
0
void _glfwPlatformPollEvents( void )
{
    EventRef event;
    EventTargetRef eventDispatcher = GetEventDispatcherTarget();

    while ( ReceiveNextEvent( 0, NULL, 0.0, TRUE, &event ) == noErr )
    {
        SendEventToEventTarget( event, eventDispatcher );
        ReleaseEvent( event );
    }
}
void appleMultiContext::checkEvent() 
{
   // Event management for Apple
   EventRef theEvent;
   EventTargetRef theTarget;
   theTarget = GetEventDispatcherTarget();
   while (ReceiveNextEvent(0, NULL,kEventDurationNoWait,true, &theEvent) == noErr) {
      SendEventToEventTarget (theEvent, theTarget);
      ReleaseEvent(theEvent);
   }
}
Example #9
0
static void DispatchAndReleaseEvent(EventRef theEvent)
{
    if ( wxTheApp )
        wxTheApp->MacSetCurrentEvent( theEvent, NULL );

    OSStatus status = SendEventToEventTarget(theEvent, GetEventDispatcherTarget());
    if (status == eventNotHandledErr && wxTheApp)
        wxTheApp->MacHandleUnhandledEvent(theEvent);

    ReleaseEvent( theEvent );
}
Example #10
0
void wxApp::MacHandleOneEvent( WXEVENTREF evr )
{
    EventTargetRef theTarget;
    theTarget = GetEventDispatcherTarget();
    m_macCurrentEvent = evr ;
    OSStatus status = SendEventToEventTarget ((EventRef) evr , theTarget);
    if(status == eventNotHandledErr)
    {
        MacHandleUnhandledEvent(evr);
    }
    wxMacProcessNotifierAndPendingEvents() ;
#if wxUSE_THREADS
    wxMutexGuiLeaveOrEnter();
#endif // wxUSE_THREADS
}
Example #11
0
/** 
  Process one event if it is there and return immediately. 
*/
int
R_carbonReceiveNextEvent()
{
  EventRef ev;
  OSStatus status;
  status = ReciveNextEvent(0, NULL, kEventDurationNoWait, true, &ev);
  EventTargetRef target = GetEventDispatcherTarget();

  if (err == noErr) {
      (void) SendEventToEventTarget(ev, target);
      ReleaseEvent(ev);
      return(1);
  }

  return(0);
}
CL_DisplayWindow_OpenGL::CL_DisplayWindow_OpenGL() :
	left_ctrl_down(false), left_alt_down(false), left_shift_down(false),
	right_ctrl_down(false), right_alt_down(false), right_shift_down(false),
	fullscreen(false), fullscreen_width(0), fullscreen_height(0),
	saved_position(0, 0, 0, 0),
	context(0), win_context(0),
	fs_context(0), window_ref(0)
{
	static bool first_call = true;
	if (first_call)
	{
		// Enable key-up:
		SetEventMask(everyEvent);
		target_ref = GetEventDispatcherTarget();
		first_call = false;
	}

	gc = CL_GraphicContext(new CL_GraphicContext_OpenGL(this));
}
OP_STATUS MacOpMessageLoop::RunSlice()
{
	//	You can try this one if the other code doesn't work. This one will handle all sorts of things waiting,
	//	including idle events, until 10 milliseconds have passed. You can of course change the value,
	//	but be warned that it WILL spend all this time, even if there isn't anything to do.

//	RunCurrentEventLoop(10 * kEventDurationMillisecond);


	// This will only handle system events, not timeouts (such as delayed messages or plugin idler).
	// Note that, like the Windows version, it may deadlock.
	EventRef 			nextEvent;
	while (noErr == ::ReceiveNextEvent(0, NULL, kEventDurationNoWait, true, &nextEvent))
	{
		::SendEventToEventTarget(nextEvent, GetEventDispatcherTarget());
		::ReleaseEvent(nextEvent);
	}
	return OpStatus::OK;
}
Example #14
0
static int
ReceiveAndProcessEvent()
{
    TkMacOSXEvent       macEvent;
    MacEventStatus   eventStatus;
    int              err;
    char             buf [ 256 ];

    /*
     * This is a poll, since we have already counted the events coming
     * into this routine, and are guaranteed to have one waiting.
     */
     
    err = ReceiveNextEvent(0, NULL, kEventDurationNoWait, 
            true, &macEvent.eventRef);
    if (err != noErr) {
        return err;
    } else {
        macEvent.eClass = GetEventClass(macEvent.eventRef);
        macEvent.eKind = GetEventKind(macEvent.eventRef);
        bzero(&eventStatus, sizeof(eventStatus));
        TkMacOSXProcessEvent(&macEvent,&eventStatus);
        if (!eventStatus.stopProcessing) {
            if (!targetRef) {
                targetRef = GetEventDispatcherTarget();
            }
            
            err = SendEventToEventTarget(macEvent.eventRef,targetRef);
            if (err != noErr
#if !TK_MAC_DEBUG
                    && err != eventNotHandledErr
#endif
                ) {
                fprintf(stderr,
                        "RCNE SendEventToEventTarget (%s) failed, %d\n",
                        CarbonEventToAscii(macEvent.eventRef, buf),err);
            }
         }
         ReleaseEvent(macEvent.eventRef);
         return 0;
     }
}
Example #15
0
void MacOSXLoop::run()
{
    // Main event loop
    while( !m_exit )
    {
        EventRef pEvent;
        OSStatus err = ReceiveNextEvent( 0, NULL, kEventDurationForever, true,
                                         &pEvent );
        if( err != noErr )
        {
            // Get the event type
            UInt32 evClass = GetEventClass( pEvent );

            switch( evClass )
            {
            case kEventClassMouse:
            {
                break;
            }

            case kEventClassKeyboard:
            {
                break;
            }

            case kEventClassWindow:
            {
                handleWindowEvent( pEvent );
                break;
            }

            default:
            {
                EventTargetRef pTarget;
                pTarget = GetEventDispatcherTarget();
                SendEventToEventTarget( pEvent, pTarget );
                ReleaseEvent( pEvent );
            }
            }
        }
    }
}
Example #16
0
gii_event_mask GII_quartz_eventpoll(gii_input *inp, void *arg)
{
	gii_event_mask mask = 0;

	EventRef theEvent;
	EventTargetRef theTarget;
	OSStatus theErr;


	/* Get event */
	theTarget = GetEventDispatcherTarget();
	theErr = ReceiveNextEvent(0,0, kEventDurationNoWait, TRUE, &theEvent);
	if (theErr == noErr && theEvent != NULL) {
		mask = transEvent2Mask(theEvent);
		SendEventToEventTarget(theEvent, theTarget);
		ReleaseEvent(theEvent);
	}	/* if */

	return mask;
}	/* GII_quartz_eventpoll */
Example #17
0
void MessagePump::dispatchOne( const uint32_t timeout )
{
    _initReceiverQueue();
    _clock.reset();

    for( int64_t timeLeft = timeout; timeleft >= 0;
         timeleft = timeout - _clock.getTime64( ))
    {
        if( _needGlobalLock )
            Global::enterCarbon();

        EventRef event;
        const float wait = EQ_MIN( float( timeLeft ) * .001f, .05f /* 50ms */ );
        const OSStatus status = ReceiveNextEvent( 0, 0, wait, true, &event );
        if( status == noErr )
        {
            LBVERB << "Dispatch Carbon event " << event << std::endl;

            if( !_needGlobalLock )
                Global::enterCarbon();
            const EventTargetRef target = GetEventDispatcherTarget();
            SendEventToEventTarget( event, target );
            Global::leaveCarbon();

            ReleaseEvent( event );
            return;
        }

        if( _needGlobalLock )
            Global::leaveCarbon();

        if( status != eventLoopTimedOutErr )
        {
            LBWARN << "ReceiveNextEvent failed: " << status << std::endl;
            return;
        }
    }
}
Example #18
0
//-----------------------------------------------------------------------------
void PluginGUIEditor::doIdleStuff ()
{
	// get the current time
	uint32_t currentTicks = getTicks ();

	// YG TEST idle ();
	if (currentTicks < lLastTicks)
	{
		#if (MAC && TARGET_API_MAC_CARBON)
		RunCurrentEventLoop (kEventDurationMillisecond * kIdleRateMin);
		#else
		wait (kIdleRateMin);
		#endif
		currentTicks += kIdleRateMin;
		if (currentTicks < lLastTicks - kIdleRate2)
			return;
	}
	idle (); // TEST

	#if WINDOWS
	struct tagMSG windowsMessage;
	if (PeekMessage (&windowsMessage, NULL, WM_PAINT, WM_PAINT, PM_REMOVE))
		DispatchMessage (&windowsMessage);

	#elif MAC && !__LP64__
	EventRef event;
	EventTypeSpec eventTypes[] = { {kEventClassWindow, kEventWindowUpdate}, {kEventClassWindow, kEventWindowDrawContent} };
	if (ReceiveNextEvent (GetEventTypeCount (eventTypes), eventTypes, kEventDurationNoWait, true, &event) == noErr)
	{
		SendEventToEventTarget (event, GetEventDispatcherTarget ());
		ReleaseEvent (event);
	}
	#endif

	// save the next time
 	lLastTicks = currentTicks + kIdleRate;
}
void CSMNativeWindow::carbonMainLoop(void)
{
    EventRef       pEvent;
    EventTargetRef pTarget = GetEventDispatcherTarget();

    while(_bRun == true)
    {
        while(ReceiveNextEvent(0, 
                               NULL, 
                               0, //kEventDurationForever, 
                               true, 
                               &pEvent) == noErr)
        {
            SendEventToEventTarget(pEvent, pTarget);
            ReleaseEvent          (pEvent         );
        }
        
        ComplexSceneManager::the()->frame();
        
        Thread::getCurrentChangeList()->commitChangesAndClear();
    }

    ComplexSceneManager::the()->terminate();
}
Example #20
0
void
COSXScreen::handleSystemEvent(const CEvent& event, void*)
{
	EventRef* carbonEvent = reinterpret_cast<EventRef*>(event.getData());
	assert(carbonEvent != NULL);

	UInt32 eventClass = GetEventClass(*carbonEvent);

	switch (eventClass) {
	case kEventClassMouse:
		switch (GetEventKind(*carbonEvent)) {
		case kSynergyEventMouseScroll:
		{
			OSStatus r;
			long xScroll;
			long yScroll;

			// get scroll amount
			r = GetEventParameter(*carbonEvent,
					kSynergyMouseScrollAxisX,
					typeLongInteger,
					NULL,
					sizeof(xScroll),
					NULL,
					&xScroll);
			if (r != noErr) {
				xScroll = 0;
			}
			r = GetEventParameter(*carbonEvent,
					kSynergyMouseScrollAxisY,
					typeLongInteger,
					NULL,
					sizeof(yScroll),
					NULL,
					&yScroll);
			if (r != noErr) {
				yScroll = 0;
			}

			if (xScroll != 0 || yScroll != 0) {
				onMouseWheel(-mapScrollWheelToSynergy(xScroll),
								mapScrollWheelToSynergy(yScroll));
			}
		}
		}
		break;

	case kEventClassKeyboard: 
			switch (GetEventKind(*carbonEvent)) {
				case kEventHotKeyPressed:
				case kEventHotKeyReleased:
					onHotKey(*carbonEvent);
					break;
			}
			
			break;
			
	case kEventClassWindow:
		SendEventToWindow(*carbonEvent, m_userInputWindow);
		switch (GetEventKind(*carbonEvent)) {
		case kEventWindowActivated:
			LOG((CLOG_DEBUG1 "window activated"));
			break;

		case kEventWindowDeactivated:
			LOG((CLOG_DEBUG1 "window deactivated"));
			break;

		case kEventWindowFocusAcquired:
			LOG((CLOG_DEBUG1 "focus acquired"));
			break;

		case kEventWindowFocusRelinquish:
			LOG((CLOG_DEBUG1 "focus released"));
			break;
		}
		break;

	default:
		SendEventToEventTarget(*carbonEvent, GetEventDispatcherTarget());
		break;
	}
}
Example #21
0
void
COSXScreen::handleSystemEvent(const CEvent& event, void*)
{
	EventRef* carbonEvent = reinterpret_cast<EventRef*>(event.getData());
	assert(carbonEvent != NULL);

	UInt32 eventClass = GetEventClass(*carbonEvent);

	switch (eventClass) {
	case kEventClassMouse:
		switch (GetEventKind(*carbonEvent)) {
		case kEventMouseDown:
		{
			UInt16 myButton;
			GetEventParameter(*carbonEvent,
					kEventParamMouseButton,
					typeMouseButton,
					NULL,
					sizeof(myButton),
					NULL,
					&myButton);
			onMouseButton(true, myButton);
			break;
		}

		case kEventMouseUp:
		{
			UInt16 myButton;
			GetEventParameter(*carbonEvent,
					kEventParamMouseButton,
					typeMouseButton,
					NULL,
					sizeof(myButton),
					NULL,
					&myButton);
			onMouseButton(false, myButton);
			break;
		}

		case kEventMouseDragged:
		case kEventMouseMoved:
		{
			HIPoint point;
			GetEventParameter(*carbonEvent,
					kEventParamMouseLocation,
					typeHIPoint,
					NULL,
					sizeof(point),
					NULL,
					&point);
			onMouseMove((SInt32)point.x, (SInt32)point.y);
			break;
		}

		case kEventMouseWheelMoved:
		{
			EventMouseWheelAxis axis;
			SInt32 delta;
			GetEventParameter(*carbonEvent,
					kEventParamMouseWheelAxis,
					typeMouseWheelAxis,
					NULL,
					sizeof(axis),
					NULL,
					&axis);
			if (axis == kEventMouseWheelAxisX ||
				axis == kEventMouseWheelAxisY) {
				GetEventParameter(*carbonEvent,
					kEventParamMouseWheelDelta,
					typeLongInteger,
					NULL,
					sizeof(delta),
					NULL,
					&delta);
				if (axis == kEventMouseWheelAxisX) {
					onMouseWheel(-mapScrollWheelToSynergy((SInt32)delta), 0);
				}
				else {
					onMouseWheel(0, mapScrollWheelToSynergy((SInt32)delta));
				}
			}
			break;
		}

		case kSynergyEventMouseScroll:
		{
			OSStatus r;
			long xScroll;
			long yScroll;

			// get scroll amount
			r = GetEventParameter(*carbonEvent,
					kSynergyMouseScrollAxisX,
					typeLongInteger,
					NULL,
					sizeof(xScroll),
					NULL,
					&xScroll);
			if (r != noErr) {
				xScroll = 0;
			}
			r = GetEventParameter(*carbonEvent,
					kSynergyMouseScrollAxisY,
					typeLongInteger,
					NULL,
					sizeof(yScroll),
					NULL,
					&yScroll);
			if (r != noErr) {
				yScroll = 0;
			}

			if (xScroll != 0 || yScroll != 0) {
				onMouseWheel(-mapScrollWheelToSynergy(xScroll),
								mapScrollWheelToSynergy(yScroll));
			}
		}
		}
		break;

	case kEventClassKeyboard: 
		switch (GetEventKind(*carbonEvent)) {
		case kEventRawKeyUp:
		case kEventRawKeyDown:
		case kEventRawKeyRepeat:
		case kEventRawKeyModifiersChanged:
			onKey(*carbonEvent);
			break;

		case kEventHotKeyPressed:
		case kEventHotKeyReleased:
			onHotKey(*carbonEvent);
			break;
		}

		break;

	case kEventClassWindow:
		SendEventToWindow(*carbonEvent, m_userInputWindow);
		switch (GetEventKind(*carbonEvent)) {
		case kEventWindowActivated:
			LOG((CLOG_DEBUG1 "window activated"));
			break;

		case kEventWindowDeactivated:
			LOG((CLOG_DEBUG1 "window deactivated"));
			break;

		case kEventWindowFocusAcquired:
			LOG((CLOG_DEBUG1 "focus acquired"));
			break;

		case kEventWindowFocusRelinquish:
			LOG((CLOG_DEBUG1 "focus released"));
			break;
		}
		break;

	default:
		SendEventToEventTarget(*carbonEvent, GetEventDispatcherTarget());
		break;
	}
}
Example #22
0
void Sys_SendKeyEvents(void)
{
	EventRef theEvent;
	EventTargetRef theTarget;

	// Start by processing the asynchronous events we received since the previous frame
	VID_ProcessPendingAsyncEvents();

	theTarget = GetEventDispatcherTarget();
	while (ReceiveNextEvent(0, NULL, kEventDurationNoWait, true, &theEvent) == noErr)
	{
		UInt32 eventClass = GetEventClass(theEvent);
		UInt32 eventKind = GetEventKind(theEvent);

		switch (eventClass)
		{
			case kEventClassMouse:
			{
				EventMouseButton theButton;
				int key;

				switch (eventKind)
				{
					case kEventMouseDown:
					case kEventMouseUp:
						GetEventParameter(theEvent, kEventParamMouseButton, typeMouseButton, NULL, sizeof(theButton), NULL, &theButton);
						switch (theButton)
						{
							default:
							case kEventMouseButtonPrimary:
								key = K_MOUSE1;
								break;
							case kEventMouseButtonSecondary:
								key = K_MOUSE2;
								break;
							case kEventMouseButtonTertiary:
								key = K_MOUSE3;
								break;
						}
						Key_Event(key, '\0', eventKind == kEventMouseDown);
						break;

					// Note: These two events are mutual exclusives
					// Treat MouseDragged in the same statement, so we don't block MouseMoved while a mousebutton is held
					case kEventMouseMoved:
					case kEventMouseDragged:
					{
						HIPoint deltaPos;
						HIPoint windowPos;

						GetEventParameter(theEvent, kEventParamMouseDelta, typeHIPoint, NULL, sizeof(deltaPos), NULL, &deltaPos);
						GetEventParameter(theEvent, kEventParamWindowMouseLocation, typeHIPoint, NULL, sizeof(windowPos), NULL, &windowPos);

						if (vid_usingmouse)
						{
							in_mouse_x += deltaPos.x;
							in_mouse_y += deltaPos.y;
						}

						in_windowmouse_x = windowPos.x;
						in_windowmouse_y = windowPos.y;
						break;
					}

					case kEventMouseWheelMoved:
					{
						SInt32 delta;
						unsigned int wheelEvent;

						GetEventParameter(theEvent, kEventParamMouseWheelDelta, typeSInt32, NULL, sizeof(delta), NULL, &delta);

						wheelEvent = (delta > 0) ? K_MWHEELUP : K_MWHEELDOWN;
						Key_Event(wheelEvent, 0, true);
						Key_Event(wheelEvent, 0, false);
						break;
					}

					default:
						Con_Printf (">> kEventClassMouse (UNKNOWN eventKind: %u) <<\n", (unsigned)eventKind);
						break;
				}
			}

			case kEventClassKeyboard:
			{
				char charcode;
				UInt32 keycode;

				switch (eventKind)
				{
					case kEventRawKeyDown:
						GetEventParameter(theEvent, kEventParamKeyMacCharCodes, typeChar, NULL, sizeof(charcode), NULL, &charcode);
						GetEventParameter(theEvent, kEventParamKeyCode, typeUInt32, NULL, sizeof(keycode), NULL, &keycode);
						Handle_Key(charcode, keycode, true);
						break;

					case kEventRawKeyRepeat:
						break;

					case kEventRawKeyUp:
						GetEventParameter(theEvent, kEventParamKeyMacCharCodes, typeChar, NULL, sizeof(charcode), NULL, &charcode);
						GetEventParameter(theEvent, kEventParamKeyCode, typeUInt32, NULL, sizeof(keycode), NULL, &keycode);
						Handle_Key(charcode, keycode, false);
						break;

					case kEventRawKeyModifiersChanged:
					{
						UInt32 keymod = 0;
						GetEventParameter(theEvent, kEventParamKeyModifiers, typeUInt32, NULL, sizeof(keymod), NULL, &keymod);
						Handle_KeyMod(keymod);
						break;
					}

					case kEventHotKeyPressed:
						break;

					case kEventHotKeyReleased:
						break;

					case kEventMouseWheelMoved:
						break;

					default:
						Con_Printf (">> kEventClassKeyboard (UNKNOWN eventKind: %u) <<\n", (unsigned)eventKind);
						break;
				}
				break;
			}

			case kEventClassTextInput:
				Con_Printf(">> kEventClassTextInput (%d) <<\n", (int)eventKind);
				break;

			case kEventClassApplication:
				switch (eventKind)
				{
					case kEventAppActivated :
						VID_AppFocusChanged(true);
						break;
					case kEventAppDeactivated:
						VID_AppFocusChanged(false);
						break;
					case kEventAppQuit:
						Sys_Quit(0);
						break;
					case kEventAppActiveWindowChanged:
						break;
					default:
						Con_Printf(">> kEventClassApplication (UNKNOWN eventKind: %u) <<\n", (unsigned)eventKind);
						break;
				}
				break;

			case kEventClassAppleEvent:
				switch (eventKind)
				{
					case kEventAppleEvent :
						break;
					default:
						Con_Printf(">> kEventClassAppleEvent (UNKNOWN eventKind: %u) <<\n", (unsigned)eventKind);
						break;
				}
				break;

			case kEventClassWindow:
				switch (eventKind)
				{
					case kEventWindowUpdate :
						break;
					default:
						Con_Printf(">> kEventClassWindow (UNKNOWN eventKind: %u) <<\n", (unsigned)eventKind);
						break;
				}
				break;

			case kEventClassControl:
				break;

			default:
				/*Con_Printf(">> UNKNOWN eventClass: %c%c%c%c, eventKind: %d <<\n",
							eventClass >> 24, (eventClass >> 16) & 0xFF,
							(eventClass >> 8) & 0xFF, eventClass & 0xFF,
							eventKind);*/
				break;
		}

		SendEventToEventTarget (theEvent, theTarget);
		ReleaseEvent(theEvent);
	}
}
Example #23
0
void check_input_events()      {
  OSStatus err;
  EventTargetRef target;
  EventRef event;
  UInt32 event_class, event_kind;
  byte mac_keycode;
  UInt32 keycode;
  UInt32 modifiers;
  Point mouse_point, mouse_delta_point;
  WindowRef window_ref;
  int button, button_state;
  EventMouseButton mouse_button;
  int handled;
  int mouse_events;
  int is_up;
  int in_win;
  int ignore;

  if(g_quit_seen) {
    exit(0);
  }

  SetPortWindowPort(g_main_window);

  mouse_events = 0;
  target = GetEventDispatcherTarget();
  while(1) {
    err = ReceiveNextEvent(0, NULL, kEventDurationNoWait,
                           true, &event);

    if(err == eventLoopTimedOutErr) {
      break;
    }
    if(err != noErr) {
      printf("ReceiveNextEvent err: %d\n", (int)err);
      break;
    }

    event_class = GetEventClass(event);
    event_kind = GetEventKind(event);
    handled = 0;
    switch(event_class) {
      case kEventClassKeyboard:
        handled = 1;
        keycode = 0;
        modifiers = 0;
        GetEventParameter(event, kEventParamKeyMacCharCodes,
                          typeChar, NULL, sizeof(byte), NULL,
                          &mac_keycode);
        GetEventParameter(event, kEventParamKeyCode,
                          typeUInt32, NULL, sizeof(UInt32), NULL,
                          &keycode);
        GetEventParameter(event, kEventParamKeyModifiers,
                          typeUInt32, NULL, sizeof(UInt32), NULL,
                          &modifiers);

        mac_update_modifiers((word32)modifiers);

        // Key up/down event
        is_up = -1;
        switch(event_kind) {
          case kEventRawKeyDown:
            is_up = 0;
            //printf("key down: %02x, %08x\n",
            //	(int)mac_keycode, (int)keycode);
            break;
          case kEventRawKeyUp:
            is_up = 1;
            //printf("key up: %02x, %08x\n",
            //	(int)mac_keycode, (int)keycode);
            break;
          case kEventRawKeyModifiersChanged:
            is_up = -1;
            //printf("key xxx: %08x\n", (int)modifiers);
            break;
        }
        if(is_up >= 0) {
          adb_physical_key_update((int)keycode, is_up);
        }
        break;
      case kEventClassMouse:
        handled = 2;
        mouse_events++;
        GetEventParameter(event, kEventParamMouseLocation,
                          typeQDPoint, NULL, sizeof(Point), NULL,
                          &mouse_point);
        GetWindowRegion(g_main_window, kWindowContentRgn,
                        g_event_rgnhandle);
        in_win =  PtInRgn(mouse_point, g_event_rgnhandle);
        // in_win = 1 if it was in the contect region of window
        err = GetEventParameter(event, kEventParamMouseDelta,
                                typeQDPoint, NULL, sizeof(Point), NULL,
                                &mouse_delta_point);
        button = 0;
        button_state = -1;
        switch(event_kind) {
          case kEventMouseDown:
            button_state = 7;
            handled = 3;
            break;
          case kEventMouseUp:
            button_state = 0;
            handled = 3;
            break;
        }
        if(button_state >= 0) {
          GetEventParameter(event, kEventParamMouseButton,
                            typeMouseButton, NULL,
                            sizeof(EventMouseButton), NULL,
                            &mouse_button);
          button = mouse_button;
          if(button > 1) {
            button = 4 - button;
            button = 1 << button;
          }
          ignore = (button_state != 0) &&
                   (!in_win || g_ignore_next_click);
          ignore = ignore || !g_mainwin_active;
          if(ignore) {
            // Outside of A2 window, ignore clicks
            button = 0;
          }
          if(button_state == 0) {
            g_ignore_next_click = 0;
          }
        }

        GlobalToLocal(&mouse_point);

        if(g_warp_pointer) {
          if(err == 0) {
            g_mac_mouse_x += mouse_delta_point.h;
            g_mac_mouse_y += mouse_delta_point.v;
          }
          mac_warp_mouse();
        } else {
          g_mac_mouse_x = mouse_point.h -
                          g_video_act_margin_left;
          g_mac_mouse_y = mouse_point.v -
                          g_video_act_margin_top;
        }

#if 0
        printf("Mouse %d at: %d,%d button:%d, button_st:%d\n",
               mouse_events, g_mac_mouse_x, g_mac_mouse_y,
               button, button_state);
        printf("Mouse deltas: err:%d, %d,%d\n", (int)err,
               mouse_delta_point.h, mouse_delta_point.v);
#endif

        update_mouse(g_mac_mouse_x, g_mac_mouse_y,
                     button_state, button & 7);
        if(g_warp_pointer) {
          g_mac_mouse_x = A2_WINDOW_WIDTH/2;
          g_mac_mouse_y = A2_WINDOW_HEIGHT/2;
          update_mouse(g_mac_mouse_x, g_mac_mouse_y,0,-1);
        }
        break;
      case kEventClassApplication:
        switch(event_kind) {
          case kEventAppActivated:
            handled = 1;
            g_mainwin_active = 1;
            window_ref = 0;
            GetEventParameter(event, kEventParamWindowRef,
                              typeWindowRef, NULL, sizeof(WindowRef),
                              NULL, &window_ref);
            if(window_ref == g_main_window) {
              g_ignore_next_click = 1;
            }
            break;
          case kEventAppDeactivated:
            handled = 1;
            g_mainwin_active = 0;
            g_ignore_next_click = 1;
            break;
        }
        break;
    }
    //	show_event(event_class, event_kind, handled);
    if(handled != 1) {
      (void)SendEventToEventTarget(event, target);
    }
    ReleaseEvent(event);
  }

  return;
}
Example #24
0
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

	LLPluginProcessChild *plugin = new LLPluginProcessChild();

	plugin->init(port);

	LLTimer timer;
	timer.start();

#if LL_WINDOWS
	checkExceptionHandler();
#endif

#if LL_DARWIN
	EventTargetRef event_target = GetEventDispatcherTarget();
#endif
	while(!plugin->isDone())
	{
		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);
			}
		}
#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
	}

	delete plugin;

	ll_cleanup_apr();

	return 0;
}
Example #25
0
void
osx_launch_special_handling(MCAP_CMD_S *mc_cmd, char *image_file)
{
    CFStringRef str_ref = NULL;
    CFURLRef url_ref = NULL;
    LSLaunchFSRefSpec launch_spec;
    FSRef app_ref, file_ref;
    static EXEC_EVENT_DATA_S event_data;

    install_app_launch_cb((void *)&event_data);
    if((str_ref = CFStringCreateWithCString(NULL, mc_cmd->command,
					kCFStringEncodingASCII)) == NULL)
      return;
    if((url_ref = CFURLCreateWithString(NULL, str_ref, NULL)) == NULL)
      return;
    if(CFURLGetFSRef(url_ref, &app_ref) == false)
      return;
    if(FSPathMakeRef((unsigned char *)image_file,
		     &file_ref, NULL) != noErr)
      return;
    launch_spec.appRef = &app_ref;
    launch_spec.numDocs = 1;
    launch_spec.itemRefs = &file_ref;
    launch_spec.passThruParams = NULL;
    launch_spec.launchFlags = kLSLaunchDontAddToRecents | kLSLaunchNoParams
      | kLSLaunchAsync | kLSLaunchNewInstance;
    /* would want to use this if we ever did true event handling */
    launch_spec.asyncRefCon = 0;

    if(LSOpenFromRefSpec( &launch_spec, NULL) == noErr){
	/*
	 * Here's the strategy:  we want to be able to just launch
	 * the app and then just delete the temp file, but that
	 * doesn't work because the called app needs the temp file
	 * at least until it's finished loading.  Being that there's
	 * no way to tell when the app has finished loading, we wait
	 * until the program has exited, which is the safest thing to
	 * do and is what we do for windows.  Since we haven't totally
	 * embraced event handling at this point, we must do the waiting
	 * synchronously.  We allow for a keystroke to stop waiting, and
	 * just delete the temp file.
	 *   Ideally, we would launch the app, and keep running, checking
	 * the events until the process terminates, and then delete the
	 * temp file.  In this method, we would delete the temp file
	 * at close time if the app was still running.
	 */
	int ch;
	OSStatus rne_rv;
	EventTargetRef target;
	EventRef out_event;
	EventTypeSpec event_types[2] = {
	    {kEventClassApplication, kEventAppTerminated},
	    {kEventClassApplication, kEventAppLaunchNotification}};

	q_status_message(SM_ORDER, 0, 4,
	  "Waiting for program to finish, or press a key to stop waiting...");
	flush_status_messages(1);
	target = GetEventDispatcherTarget();
	event_data.done = 0;
	event_data.set_pid = 0;
	while(!event_data.done){
	    if((rne_rv = ReceiveNextEvent(2, event_types, 1,
					  true, &out_event)) == noErr){
		SendEventToEventTarget(out_event, target);
		ReleaseEvent(out_event);
	    }
	    else if(rne_rv == eventLoopTimedOutErr){
		ch = read_char(1);
		if(ch)
		  event_data.done = 1;
	    }
	    else if(rne_rv == eventLoopQuitErr)
	      event_data.done = 1;
	}
	our_unlink(image_file);
    }
    q_status_message(SM_ORDER, 0, 4, "VIEWER command completed");
}
Example #26
0
int main(int argc, char *argv[])
{
    WindowRef window;
    HIViewRef content;
    HIViewRef combo;
    HIViewRef group;
    HIViewRef check;
    HIViewRef text;
    HIViewRef slider;
    HIViewRef quit;

    MenuRef menu;
    HIRect rect;

    // Window bounds

    Rect bounds = {0, 0, 436, 590};

    // Create window

    CreateNewWindow(kDocumentWindowClass,
                    kWindowStandardFloatingAttributes |
                    kWindowStandardHandlerAttribute |
		    kWindowInWindowMenuAttribute |
                    kWindowCompositingAttribute,
                    &bounds, &window);

    // Set the title

    SetWindowTitleWithCFString(window, CFSTR("Accordion"));

    // Create an application menu

    CreateNewMenu(0, 0, &menu);

    // Set menu title

    SetMenuTitleWithCFString(menu,
	CFStringCreateWithPascalString(kCFAllocatorDefault,
                                       "\p\024",
                                       kCFStringEncodingMacRoman));
    // Create an about item

    InsertMenuItemTextWithCFString(menu, CFSTR("About Accordion"),
                                   0, 0, kHICommandAbout);

    // Insert the menu

    InsertMenu(menu, 0);

    // Create a standard window menu

    CreateStandardWindowMenu(0, &menu);

    // Insert the menu

    InsertMenu(menu, 0);

    // Show and position the window

    ShowWindow(window);
    RepositionWindow(window, NULL, kWindowCascadeOnMainScreen);

    // Find the window content

    HIViewFindByID(HIViewGetRoot(window),
                   kHIViewWindowContentID,
                   &content);

    // Set bounds for group box

    bounds.bottom = 92;
    bounds.right  = 550;

    // Create group box

    CreateGroupBoxControl(window, &bounds, NULL, true, &group);

    // Place in the window

    HIViewAddSubview(content, group);
    HIViewPlaceInSuperviewAt(group, 20, 20);

    // Bounds of text

    bounds.bottom = 16;
    bounds.right = 74;

    // Create static text

    CreateStaticTextControl(window, &bounds, CFSTR("Instrument:"),
			    NULL, &text);

    // Place in the group box

    HIViewAddSubview(group, text);
    HIViewPlaceInSuperviewAt(text, 16, 18);

    // Bounds of combo box

    rect.size.height = 20;
    rect.size.width = 168;    

    // Create combo box

    HIComboBoxCreate(&rect, CFSTR(" Accordion"), NULL, NULL,
                     kHIComboBoxStandardAttributes,
                     &combo);

    // Set visible and set command ID

    HIViewSetVisible(combo, true);
    HIViewSetCommandID(combo, kCommandInst); 

    // Add the instruments

    for (int i = 0; i < Length(instruments); i++)
    {
        HIComboBoxAppendTextItem(combo,
            CFStringCreateWithCString(kCFAllocatorDefault,
                                      instruments[i],
                                      kCFStringEncodingMacRoman), NULL);

        // Set the current instrument

        if (strcmp(instruments[i], " Accordion") == 0)
            instrument = i;
    }

    // Place in the group box

    HIViewAddSubview(group, combo);
    HIViewPlaceInSuperviewAt(combo, 102, 16);

    // Bounds of check box

    bounds.bottom = 18;
    bounds.right = 121;

    // Create check box

    CreateCheckBoxControl(window, &bounds, CFSTR("Reverse"),
                          false, true, &check);

    // Set the control ID and the command ID

    HIViewSetID(check, kHIViewIDReverse);
    HIViewSetCommandID(check, kCommandReverse); 

    // Place in the group box

    HIViewAddSubview(group, check);
    HIViewPlaceInSuperviewAt(check, 286, 17);

    // Bounds of text

    bounds.bottom = 16;
    bounds.right  = 32;

    // Create static text

    CreateStaticTextControl(window, &bounds, CFSTR("Key:"), NULL, &text);

    // Place in the group box

    HIViewAddSubview(group, text);
    HIViewPlaceInSuperviewAt(text, 400, 18);

    // Bounds of combo box

    rect.size.width = 90;

    // Create combo box

    HIComboBoxCreate(&rect, CFSTR(" A/D/G"), NULL, NULL,
                     kHIComboBoxStandardAttributes,
                     &combo);

    // Set visible and set command ID

    HIViewSetVisible(combo, true);
    HIViewSetID(combo, kHIViewIDKey);
    HIViewSetCommandID(combo, kCommandKey); 

    // Add keys

    for (int i = 0; i < Length(keys); i++)
    {
        HIComboBoxAppendTextItem(combo,
            CFStringCreateWithCString(kCFAllocatorDefault,
                                      keys[i],
                                      kCFStringEncodingMacRoman), NULL);

        // Set current key

        if (strcmp(keys[i], " A/D/G") == 0)
            key = i;
    }

    // Place in the group box

    HIViewAddSubview(group, combo);
    HIViewPlaceInSuperviewAt(combo, 440, 16);

    // Bounds of text

    bounds.bottom = 16;
    bounds.right  = 54;

    // Create static text

    CreateStaticTextControl(window, &bounds, CFSTR("Volume:"), NULL, &text);

    // Place in the group box

    HIViewAddSubview(group, text);
    HIViewPlaceInSuperviewAt(text, 16, 56);
    
    // Bounds of slider

    bounds.bottom = 16;
    bounds.right  = 168;

    // Create slider

    CreateSliderControl(window, &bounds, MAXVOL, 0, MAXVOL,
                        kControlSliderDoesNotPoint, 0, false, NULL, &slider);

    // Set command ID

    HIViewSetCommandID(slider, kCommandVolume); 

    // Place in the group box

    HIViewAddSubview(group, slider);
    HIViewPlaceInSuperviewAt(slider, 100, 58);

    // Bounds of check box

    bounds.bottom = 18;
    bounds.right = 121;

    // Create check box

    CreateCheckBoxControl(window, &bounds, CFSTR("Notes"),
                          false, true, &check);

    // Set the control ID and the command ID

    HIViewSetID(check, kHIViewIDNote);
    HIViewSetCommandID(check, kCommandNote); 

    // Place in the group box

    HIViewAddSubview(group, check);
    HIViewPlaceInSuperviewAt(check, 286, 56);

    // Bounds of push button

    bounds.bottom = 20;
    bounds.right  = 90;

    // Create push button

    CreatePushButtonControl(window, &bounds, CFSTR("Quit"), &quit);

    // Set command ID

    HIViewSetCommandID(quit, kHICommandQuit); 

    // Place in the group box

    HIViewAddSubview(group, quit);
    HIViewPlaceInSuperviewAt(quit, 440, 54);

    // Group box bounds

    bounds.bottom = 48;
    bounds.right  = 550;

    // Create group box

    CreateGroupBoxControl(window, &bounds, NULL, true, &group);

    // Place in the window

    HIViewAddSubview(content, group);
    HIViewPlaceInSuperviewAt(group, 20, 132);

    // Font style

    ControlFontStyleRec style;
    style.flags = kControlUseFontMask|kControlUseJustMask;
    style.font = kControlFontBigSystemFont;
    style.just = teCenter;

    // Bounds of text
    
    bounds.bottom = 16;
    bounds.right  = 550;

    // Create static text

    CreateStaticTextControl(window, &bounds, CFSTR("Accordion"),
                            &style, &text);

    // Place in the group box

    HIViewAddSubview(group, text);
    HIViewPlaceInSuperviewAt(text, 0, 8);

    // Bounds of text

    bounds.bottom = 16;
    bounds.right  = 550;

    // Create static text

    CreateStaticTextControl(window, &bounds,
                            CFSTR("Play accordion on your keyboard"),
                            &style, &text);

    // Place in the group box

    HIViewAddSubview(group, text);
    HIViewPlaceInSuperviewAt(text, 0, 24);

    // Group box bounds

    bounds.bottom = 196;
    bounds.right  = 550;

    // Create group box

    CreateGroupBoxControl(window, &bounds, NULL, true, &group);

    // Place in the window

    HIViewAddSubview(content, group);
    HIViewPlaceInSuperviewAt(group, 20, 200);

    // Button bounds

    bounds.bottom = SIZE;
    bounds.right  = SIZE;

    // Create row of bass buttons

    for (int i = 0; i < Length(bassdisplay); i++)
    {
	int x = 15 + 44 * i;
	int y = 15;

	// Create button

	CreateBevelButtonControl(window, &bounds, NULL,
				 kControlBevelButtonNormalBevel,
				 kControlBehaviorPushbutton,
				 NULL, 0, 0, 0, &bassdisplay[i]);

	// Place in the group box

	HIViewAddSubview(group, bassdisplay[i]);
	HIViewPlaceInSuperviewAt(bassdisplay[i], x, y);
    }

    // Create three rows of buttons

    for (int i = 0; i < Length(display); i++)
    {
	for (int j = 0; j < ((i == 1)? Length(display[i]):
			 Length(display[i]) - 1); j++)
	{
	    int x = (i == 1)? 37 + 44 * j: 59 + 44 * j;
	    int y = 59 + 44 * i;

	    // Create button

	    CreateBevelButtonControl(window, &bounds, NULL,
				     kControlBevelButtonNormalBevel,
				     kControlBehaviorPushbutton,
				     NULL, 0, 0, 0, &display[i][j]);

	    // Place in the group box

	    HIViewAddSubview(group, display[i][j]);
	    HIViewPlaceInSuperviewAt(display[i][j], x, y);
        }
    }

    // Create spacebar button

    CreateBevelButtonControl(window, &bounds, NULL,
			     kControlBevelButtonNormalBevel,
			     kControlBehaviorPushbutton,
			     NULL, 0, 0, 0, &spacebar);

    // Place in the group box

    HIViewAddSubview(group, spacebar);
    HIViewPlaceInSuperviewAt(spacebar, 16, 147);

    // Group box bounds, wider than the window to hide rounded corners

    bounds.bottom = 20;
    bounds.right = 598;

    // Create group box for fake status bar

    CreateGroupBoxControl(window, &bounds, NULL, false, &group);

    // Place in window at negative offset to hide rounded corners

    HIViewAddSubview(content, group);
    HIViewPlaceInSuperviewAt(group, -4, 416);

    // Text bounds

    bounds.bottom = 16;
    bounds.right  = 590;

    // Font style

    style.flags = kControlUseFontMask|kControlUseJustMask;
    style.font = kControlFontSmallSystemFont;
    style.just = teCenter;

    // Create static text

    CreateStaticTextControl(window, &bounds,
        CFSTR("Press the keyboard keys as accordion buttons "
              "and the space bar as the bellows. 3rd button start."),
                            &style, &text);

    // Place in group box

    HIViewAddSubview(group, text);
    HIViewPlaceInSuperviewAt(text, 0, 2);

    // Application events type spec

    EventTypeSpec applicationEvents[] =
        {{kEventClassApplication, kEventAppFrontSwitched}};

    // Install event handler

    InstallApplicationEventHandler(NewEventHandlerUPP(ApplicationHandler),
                                   Length(applicationEvents), applicationEvents,
                                   NULL, NULL);

    // Mouse events type spec

    EventTypeSpec mouseEvents[] =
	{{kEventClassMouse, kEventMouseDown}};

    // Install event handler on the event dispatcher, so that we can
    // see mouse events before the default handler gets them

    InstallEventHandler(GetEventDispatcherTarget(),
                        NewEventHandlerUPP(MouseHandler),
                        Length(mouseEvents), mouseEvents,
                        NULL, NULL);

    // Window events type spec

    EventTypeSpec windowEvents[] =
        {{kEventClassWindow, kEventWindowClose}};

    // Install event handler

    InstallWindowEventHandler(window, NewEventHandlerUPP(WindowHandler),
                              Length(windowEvents), windowEvents,
                              NULL, NULL);

    // Combo box events type spec

    EventTypeSpec comboBoxEvents[] =
        {{kEventClassHIComboBox, kEventComboBoxListItemSelected}};

    // Install event handler

    InstallApplicationEventHandler(NewEventHandlerUPP(ComboBoxHandler),
                                   Length(comboBoxEvents), comboBoxEvents,
                                   NULL, NULL);

    // Command events type spec

    EventTypeSpec commandEvents[] =
        {{kEventClassCommand, kEventCommandProcess}};

    // Install event handler

    InstallApplicationEventHandler(NewEventHandlerUPP(CommandHandler),
                                   Length(commandEvents), commandEvents,
                                   NULL, NULL);

    // Keyboard events type spec

    EventTypeSpec keyboardEvents[] =
        {{kEventClassKeyboard, kEventRawKeyDown},
         {kEventClassKeyboard, kEventRawKeyUp},
         {kEventClassKeyboard, kEventRawKeyModifiersChanged}};

    // Install event handler on the event dispatcher

    InstallEventHandler(GetEventDispatcherTarget(),
			NewEventHandlerUPP(KeyboardHandler),
			Length(keyboardEvents), keyboardEvents,
			NULL, NULL);

    // Audio Unit graph

    AUGraph graph;

    // Audio Unit synthesizer and output node

    AUNode synthNode;
    AUNode outNode;

    // Component description

    ComponentDescription cd;
    cd.componentManufacturer = kAudioUnitManufacturer_Apple;
    cd.componentFlags = 0;
    cd.componentFlagsMask = 0;

    do
    {
	// New AU graph

	OSStatus status = NewAUGraph(&graph);

	if (status != noErr)
	{
	    DisplayAlert(CFSTR("NewAUGraph"), 
			 CFSTR("Can't create a new AUGraph"),
			 status);
	    break;
	}

	// Synthesizer

	cd.componentType = kAudioUnitType_MusicDevice;
	cd.componentSubType = kAudioUnitSubType_DLSSynth;

	// New synthesizer node

	status = AUGraphNewNode(graph, &cd, 0, NULL, &synthNode);

	if (status != noErr)
	{
	    DisplayAlert(CFSTR("AUGraphNewNode"), 
			 CFSTR("Can't create a new  AUGraph node"),
			 status);
	    break;
	}

	// Output

	cd.componentType = kAudioUnitType_Output;
	cd.componentSubType = kAudioUnitSubType_DefaultOutput;
 
	// New output node

	status = AUGraphNewNode(graph, &cd, 0, NULL, &outNode);

	if (status != noErr)
	{
	    DisplayAlert(CFSTR("AUGraphNewNode"), 
			 CFSTR("Can't create a new  AUGraph node"),
			 status);
	    break;
	}

	// Open graph

	status = AUGraphOpen(graph);

	if (status != noErr)
	{
	    DisplayAlert(CFSTR("AUGraphOpen"), 
			 CFSTR("Can't open AUGraph"),
			 status);
	    break;
	}

	// Connect synthesizer node to output node

	status = AUGraphConnectNodeInput(graph, synthNode, 0, outNode, 0);

	if (status != noErr)
	{
	    DisplayAlert(CFSTR("AUGraphConnectNodeInput"), 
			 CFSTR("Can't connect AUGraph input node"),
			 status);
	    break;
	}

	// Get a synthesizer unit

	status =
	    AUGraphGetNodeInfo(graph, synthNode, NULL, 0, NULL, &synthUnit);

	if (status != noErr)
	{
	    DisplayAlert(CFSTR("AUGraphGetNodeInfo"), 
			 CFSTR("Can't get AUGraph node info"),
			 status);
	    break;
	}

	// Initialise

	status = AUGraphInitialize(graph);

	if (status != noErr)
	{
	    DisplayAlert(CFSTR("AUGraphInitialize"), 
			 CFSTR("Can't initialize AUGraph"),
			 status);
	    break;
	}

	// Start

	status = AUGraphStart(graph);

	if (status != noErr)
	{
	    DisplayAlert(CFSTR("AUGraphStart"), 
			 CFSTR("Can't start AUGraph"),
			 status);
	    break;
	}

	// Show the graph

	//     CAShow(graph);

    } while (false);

    // Change instrument

    ChangeInstrument(instrument);

    // Run the application event loop

    RunApplicationEventLoop();

    // Stop the graph

    AUGraphStop(graph);

    // Dispose of the graph

    DisposeAUGraph(graph);

    // Exit

    return 0;
}
Example #27
0
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;
}