SkOSWindow::SkOSWindow(void* hWnd) : fHWND(hWnd)
{	
	static const EventTypeSpec  gTypes[] = {
		{ kEventClassKeyboard,  kEventRawKeyDown			},
        { kEventClassKeyboard,  kEventRawKeyUp              },
		{ kEventClassMouse,		kEventMouseDown				},
		{ kEventClassMouse,		kEventMouseDragged			},
		{ kEventClassMouse,		kEventMouseUp				},
		{ kEventClassTextInput, kEventTextInputUnicodeForKeyEvent   },
		{ kEventClassWindow,	kEventWindowBoundsChanged	},
		{ kEventClassWindow,	kEventWindowDrawContent		},
		{ SK_MacEventClass,		SK_MacEventKind				}
	};

	EventHandlerUPP handlerUPP = NewEventHandlerUPP(SkOSWindow::EventHandler);
	int				count = SK_ARRAY_COUNT(gTypes);
	OSStatus		result;

	result = InstallEventHandler(GetWindowEventTarget((WindowRef)hWnd), handlerUPP,
						count, gTypes, this, nil);
	SkASSERT(result == noErr);

	gCurrOSWin = this;
	gCurrEventQ = GetCurrentEventQueue();
	gEventTarget = GetWindowEventTarget((WindowRef)hWnd);

	static bool gOnce = true;
	if (gOnce) {
		gOnce = false;
		gPrevNewHandler = set_new_handler(sk_new_handler);
	}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//	AURenderQualityPopup::RegisterEvents
//
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
void	AURenderQualityPopup::RegisterEvents ()
{
	EventTypeSpec events[] = {
		{ kEventClassCommand, kEventCommandProcess}
	};
	
	WantEventTypes(GetWindowEventTarget(mView->GetCarbonWindow()), GetEventTypeCount(events), events);
}
Ejemplo n.º 3
0
//
// Build a custom event to send to our window handler when movie audio extraction 
// completes for the current movie (without the user pressing the "Stop" button
// to stop it before it runs to the end). We'll then update our button title to 
// reflect this.
//
OSStatus SendExtractionStatusEventToWindow(Boolean extractionPaused)
{
    OSStatus	err		= noErr;
    EventRef    event	= NULL;
		
	err = CreateEvent( NULL,  kEventClassMovieExtractState, kEventKQueue, GetCurrentEventTime(), kEventAttributeNone, &event );
	if ( err != noErr ) goto Bail;
	
	err = SetEventParameter( event, kEventParamDirectObject, typeKEvent, sizeof(Boolean), &extractionPaused );	//  Send the event
	if ( err != noErr ) goto Bail;

	err = SendEventToEventTarget (event, GetWindowEventTarget(mWindow));	// Post the event for our window handler
Bail:
	if ( event != NULL )	(void) ReleaseEvent( event );
	return( err );
}
Ejemplo n.º 4
0
// Create a new demo window
OSStatus
NewWindow()
{
    IBNibRef nibRef;
    WindowRef window;
	EventTypeSpec commandEventType = {kEventClassWindow, kEventWindowFocusAcquired};
    OSStatus status = noErr;

    // Create a Nib reference passing the name of the nib file (without the .nib extension)
    // CreateNibReference only searches into the application bundle.
	status = CreateNibReference(CFSTR("main"), &nibRef);
    require_noerr( status, CantGetNibRef );
    
    // Then create a window. "MainWindow" is the name of the window object. This name is set in 
    // InterfaceBuilder when the nib is created.
    status = CreateWindowFromNib(nibRef, CFSTR("MainWindow"), &window);
    require_noerr( status, CantCreateWindow );

    // We don't need the nib reference anymore.
    DisposeNibReference(nibRef);
	
	// Let's customize the HITextView in that window
	status = SetUpTheTextView( window );	
	check_noerr( status );

    // The window was created hidden so show it.
    ShowWindow( window );

	// by default, focus the HITextView at start
	status = TextViewFocusInWindow( window );
    require_noerr( status, CantFocusTextView );

	// set up the control state from the state of the text view
	status = UpdateControlsFromTextViewWindow( window );
    require_noerr( status, CantSetControlState );

	// Install a handler to update the UI when this window comes to the front
	status = InstallEventHandler(GetWindowEventTarget(window), NewEventHandlerUPP(WindowFocusAcquired), 1, &commandEventType, NULL, NULL);
    require_noerr( status, CantInstallWindowEventHandler );
	
CantFocusTextView:
CantSetControlState:
CantInstallWindowEventHandler:
CantCreateWindow:
CantGetNibRef:
	return status;
}
Ejemplo n.º 5
0
MODULE_SCOPE void
TkMacOSXInstallWindowCarbonEventHandler(
	Tcl_Interp *interp, WindowRef window)
{
    const EventTypeSpec windowEventTypes[] = {
	{kEventClassMouse,	 kEventMouseDown},
	{kEventClassMouse,	 kEventMouseUp},
	{kEventClassMouse,	 kEventMouseMoved},
	{kEventClassMouse,	 kEventMouseDragged},
	{kEventClassMouse,	 kEventMouseWheelMoved},
	{kEventClassWindow,	 kEventWindowActivated},
	{kEventClassWindow,	 kEventWindowDeactivated},
	{kEventClassWindow,	 kEventWindowUpdate},
	{kEventClassWindow,	 kEventWindowExpanding},
	{kEventClassWindow,	 kEventWindowBoundsChanged},
	{kEventClassWindow,	 kEventWindowDragStarted},
	{kEventClassWindow,	 kEventWindowDragCompleted},
	{kEventClassWindow,	 kEventWindowConstrain},
	{kEventClassWindow,	 kEventWindowGetRegion},
	{kEventClassWindow,	 kEventWindowDrawContent},
    };

    ChkErr(InstallEventHandler, GetWindowEventTarget(window),
	    carbonEventHandlerUPP, GetEventTypeCount(windowEventTypes),
	    windowEventTypes, (void *) (interp ? interp : 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 = windowEventTypes;
		i < GetEventTypeCount(windowEventTypes); i++, e++) {
	    if (!(e->eventClass == kEventClassMouse && (
		    e->eventKind == kEventMouseMoved ||
		    e->eventKind == kEventMouseDragged))) {
		DebugTraceEvent(e->eventClass, e->eventKind, 1);
	    }
	}
    }
#endif /* TK_MAC_DEBUG_CARBON_EVENTS */
}
Ejemplo n.º 6
0
// ---------------------------------------------------------------------------
OSXWindowImpl::OSXWindowImpl(Window* window)
  : WindowImpl(window)
{
  OSStatus s;
  WindowClass wc = kDocumentWindowClass;
  WindowAttributes wa = 0
    // |kWindowCompositingAttribute
    |kWindowStandardDocumentAttributes
    |kWindowStandardHandlerAttribute
    |kWindowLiveResizeAttribute
  ;
  mRect.left = 100;
  mRect.right = mRect.left + 256;
  mRect.top = 100;
  mRect.bottom = mRect.top + 256;
  s = CreateNewWindow(wc,wa,&mRect,&mWindowRef);
  check_noerr(s); 
  EventTypeSpec typeList[] = {
    { kEventClassWindow,    kEventWindowClosed },
    { kEventClassWindow,    kEventWindowDrawContent },
    { kEventClassWindow,    kEventWindowBoundsChanged },
    { kEventClassKeyboard,  kEventRawKeyDown },
    { kEventClassKeyboard,  kEventRawKeyUp },
    { kEventClassMouse,     kEventMouseDown },
    { kEventClassMouse,     kEventMouseUp },
    { kEventClassMouse,     kEventMouseMoved },
    { kEventClassMouse,     kEventMouseDragged },
    { kEventClassMouse,     kEventMouseWheelMoved }
  };
  int numTypes = sizeof(typeList)/sizeof(EventTypeSpec);
  EventHandlerUPP handlerUPP = NewEventHandlerUPP(OSXWindowImpl::memberDelegate);
  EventTargetRef theTarget; 
  theTarget = GetWindowEventTarget(mWindowRef);
  InstallEventHandler(
    theTarget, handlerUPP,
    numTypes, typeList,
    this, 
    NULL
  );  	
  on_init();	
}
/*****************************************************
*
* Handle_TextInputEvent(inHandlerCallRef, inEvent, inUserData) 
*
* Purpose:  called to intercept keystrokes which are destined for a control
*
* Inputs:   inHandlerCallRef    - reference to the current handler call chain
*           inEvent             - the event
*           inUserData          - app-specified data you passed in the call to InstallEventHandler
*
* Returns:  OSStatus            - noErr indicates the event was handled
*                                 eventNotHandledErr indicates the event was not handled and the Toolbox should take over
*/
static pascal OSStatus Handle_TextInputEvent(EventHandlerCallRef inHandlerCallRef, EventRef inEvent, void *inUserData)
	{
	OSStatus status;
	
	UniChar ch = 0;
	status = GetEventParameter(inEvent, kEventParamTextInputSendText, typeUnicodeText, NULL, sizeof(ch), NULL, &ch);
	require_noerr(status, ExitTextInput);
	
	if ((ch == kReturnCharCode) || (ch == kEnterCharCode))
		{
		//
		// we got return or enter so we validate the edit text control by sending a command
		//
		EventRef theEvent;
		CreateEvent(NULL, kEventClassCommand, kEventCommandProcess, GetCurrentEventTime(), kEventAttributeUserEvent, &theEvent);
		HICommandExtended theCommand;
		theCommand.attributes = kHICommandFromControl;
		theCommand.commandID = 'SVet';
		theCommand.source.control = (ControlRef)inUserData;
		SetEventParameter(theEvent, kEventParamDirectObject, typeHICommand, sizeof(theCommand), &theCommand);
		SendEventToEventTarget(theEvent, GetWindowEventTarget(GetControlOwner((ControlRef)inUserData)));
		ReleaseEvent(theEvent);
		status = noErr;
		}
	if (	((ch >= '0') && (ch <= '9'))	||
			(ch == kBackspaceCharCode)		||
			(ch == kLeftArrowCharCode)		||
			(ch == kRightArrowCharCode)		||
			(ch == kUpArrowCharCode)		||
			(ch == kDownArrowCharCode)		)
		status = eventNotHandledErr;
	else
		status = noErr;

ExitTextInput:

	return status;
	}   // Handle_TextInputEvent
Ejemplo n.º 8
0
OSStatus sendDone(void)
{
	OSStatus result;
	EventRef evt;
	
	result = CreateEvent( 
			NULL,
			kEventClassCustom, 
			kEventCustomDone,
			0, 
			kEventAttributeNone, 
			&evt);
	
	// This event needs to be targeted at the window so it goes to the window's handler.
	if(result == noErr)
	{
		EventTargetRef target = GetWindowEventTarget(gWindow);
		result = SetEventParameter (
			evt,
			kEventParamPostTarget,
			typeEventTargetRef,
			sizeof(target),
			&target);
	}

	if(result == noErr)
	{
		// Send the event
		PostEventToQueue(
			GetMainEventQueue(),
			evt,
			kEventPriorityStandard);

	}
	
	return(result);
}
//----------------------------------------------------------------------------//
bool MacCEGuiRendererSelector::invokeDialog()
{
    loadDialogWindow();
    int rendererCount = populateRendererMenu();

    // 'cancel' if there are no renderers available
    if (rendererCount == 0)
        d_cancelled = true;
    // only bother with the dialog if there is a choice ;)
    else if (rendererCount > 1)
    {
        // set the event handling
        EventTypeSpec cmdEvt;	
        cmdEvt.eventClass = kEventClassCommand;
        cmdEvt.eventKind = kEventCommandProcess;
        
        InstallEventHandler(
            GetWindowEventTarget(d_dialog),
            NewEventHandlerUPP(MacCEGuiRendererSelector::eventDispatcher), 1,
            &cmdEvt, this, 0); 

        ShowWindow(d_dialog);
        RunApplicationEventLoop();
    }

    SInt32 idx = HIViewGetValue(d_rendererPopup);
    DisposeWindow(d_dialog);

    // bail out if user cancelled dialog or if selected index is 0
    if (d_cancelled || (idx == 0))
        return false;

    // set the last selected renderer - i.e. the one we want to use.
    d_lastSelected = d_rendererTypes[idx - 1];

    return true;
}
Ejemplo n.º 10
0
void MCStack::syncscroll(void)
{
	// If we have no window, no need to adjust the HIView.
	if (window == nil)
		return;
	
	// And tweak the HIView's location...
	ControlRef t_root_control;
	GetRootControl((WindowPtr)window -> handle . window, &t_root_control);
	ControlRef t_subcontrol;
	if (GetIndexedSubControl(t_root_control, 1, &t_subcontrol) == noErr)
	{
		Rect t_bounds;
		t_bounds . left = 0;
		t_bounds . top = -m_scroll;
		t_bounds . right = rect . width;
		t_bounds . bottom = rect . height;
		SetControlBounds(t_subcontrol, &t_bounds);
	}
	
	// MW-2011-11-30: [[ Bug 9887 ]] Make sure all the player objects on this
	//   stack are adjusted as appropriate.
	for(MCPlayer *t_player = MCplayers; t_player != nil; t_player = t_player -> getnextplayer())
		if (!t_player -> isbuffering() && t_player -> getstack() == this)
			t_player -> setrect(t_player -> getrect());
			
	// MW-2012-10-08: [[ Bug 10442 ]] Set the scroll window property so revBrowser
	//   works properly.
	SetWindowProperty((WindowPtr)window -> handle . window, 'revo', 'scrl', 4, &m_scroll);
	
	// Now send a sync event so revBrowser picks it up.
	EventRef t_event;
	CreateEvent(NULL, 'revo', 'sync', GetCurrentEventTime(), 0, &t_event);
	SendEventToEventTarget(t_event, GetWindowEventTarget((WindowPtr)window -> handle . window));
	ReleaseEvent(t_event);
}
void CL_DisplayWindow_OpenGL::set_windowed()
{
	if(!fullscreen)
		return;

	if (context == fs_context)
	{
	    aglSetDrawable(fs_context, 0);
	}
	
	CGReleaseAllDisplays();
	aglSetCurrentContext(win_context);
	aglUpdateContext(win_context);
	install_event_handler(GetWindowEventTarget(window_ref));

	fullscreen = false;
	context = win_context;
	focus = IsWindowHilited(window_ref);
	
	//After toggling to the fullscreen context, nothing is going draw unless
	//we reapply the GL states/properties -mrfun 6-2-2006
	CL_GLStateChecker::from_gc(get_gc())->reinitialize_asap();
	
}
Ejemplo n.º 12
0
OSStatus sendProgress(long cur, long max, CFStringRef text = NULL)
{
	OSStatus result;
	EventRef evt;
	
	result = CreateEvent( 
			NULL,
			kEventClassCustom, 
			kEventCustomProgress,
			0, 
			kEventAttributeNone, 
			&evt);
	
	// This event needs to be targeted at the window so it goes to the window's handler.
	if(result == noErr)
	{
		EventTargetRef target = GetWindowEventTarget(gWindow);
		result = SetEventParameter (
			evt,
			kEventParamPostTarget,
			typeEventTargetRef,
			sizeof(target),
			&target);
	}

	if(result == noErr)
	{
		result = SetEventParameter (
			evt,
			kEventParamCustomCurValue,
			typeLongInteger,
			sizeof(cur),
			&cur);
	}

	if(result == noErr)
	{
		result = SetEventParameter (
			evt,
			kEventParamCustomMaxValue,
			typeLongInteger,
			sizeof(max),
			&max);
	}
	
	if(result == noErr)
	{
		if(text != NULL)
		{
			result = SetEventParameter (
				evt,
				kEventParamCustomText,
				typeCFStringRef,
				sizeof(text),
				&text);
		}
	}
	
	if(result == noErr)
	{
		// Send the event
		PostEventToQueue(
			GetMainEventQueue(),
			evt,
			kEventPriorityStandard);

	}
	
	return(result);
}
OSStatus CL_DisplayWindow_OpenGL::on_window_event(EventHandlerCallRef call_ref, EventRef event_ref, void *user_data)
{
	CL_DisplayWindow_OpenGL *self = (CL_DisplayWindow_OpenGL *) user_data;

	OSStatus result = CallNextEventHandler(call_ref, event_ref);

	UInt32 event_class = GetEventClass(event_ref);
	UInt32 event_kind = GetEventKind(event_ref);
	
	if (event_class == kEventClassKeyboard)
	{
		Point mouse_pos;
		UInt32 key_modifiers = 0;
		UInt32 click_count = 0;
		UInt32 key_code = 0;
                
		// Todo:
		// KeyboardLayoutRef layout;
		// KLGetCurrentKeyboardLayout(&layout);
		// KLGetKeyboardLayoutProperty(layout, kKLuchrData, &data);
		// call UCKeyTranslate to get unicode string for keys being pressed.

		GetMouse(&mouse_pos);
		GetEventParameter(event_ref, kEventParamKeyModifiers, typeUInt32, 0, sizeof(UInt32), 0, &key_modifiers);
		GetEventParameter(event_ref, kEventParamKeyCode, typeUInt32, 0, sizeof(UInt32), 0, &key_code);
		GetEventParameter(event_ref, kEventParamClickCount, typeUInt32, 0, sizeof(UInt32), 0, &click_count);

		if (!self->fullscreen) {
			Rect wbounds;
			GetWindowBounds(self->window_ref, kWindowContentRgn, &wbounds);
			mouse_pos.h -= wbounds.left;
			mouse_pos.v -= wbounds.top;
		}

		static unsigned long state = 0;
		static Ptr keymap = nil;
		Ptr new_keymap;

		// Get the current keyboard map resource
		new_keymap = (Ptr)GetScriptManagerVariable(smKCHRCache);
		if (new_keymap != keymap)
		{
			keymap = new_keymap;
			state = 0;
		}

		CL_InputEvent event;
		event.str = KeyTranslate(keymap, key_code|key_modifiers, &state) & 0xffff;
		event.device = self->keyboard;
		event.mouse_pos = CL_Point(mouse_pos.h, mouse_pos.v);
		event.repeat_count = click_count;

		self->mouse_pos = event.mouse_pos; // if kEventParamMouseLocation is not valid here, reverse this.
		
		switch (event_kind)
		{
		case kEventRawKeyModifiersChanged:
			{
				std::set<int> current_keys = modifiercode_to_clkeys(key_modifiers);
				for (std::set<int>::iterator i=current_keys.begin(); i!=current_keys.end(); i++)
				{
					if (!self->prev_modifier_keys.count(*i))
					{
						event.id = *i;
						event.type = CL_InputEvent::pressed;
						self->keyboard.sig_key_down().call(event);
					}
				}
				for (std::set<int>::iterator i=self->prev_modifier_keys.begin(); i!=self->prev_modifier_keys.end(); i++)
				{
					if (!current_keys.count(*i))
					{
						event.id = *i;
						event.type = CL_InputEvent::released;
						self->keyboard.sig_key_up().call(event);
					}
				}
				self->prev_modifier_keys = current_keys;
				return noErr;
			}
		
		case kEventRawKeyDown:
			// first tests for cmd-q(12) or cmd-w(13) to close the window if needed
			if ((key_modifiers & cmdKey) && (key_code==12 || key_code==13))
			{
				EventRef close_event;
				CreateEvent(NULL, kEventClassWindow, kEventWindowClose, 0, kEventAttributeNone, &close_event);
				EventTargetRef target = GetWindowEventTarget(self->window_ref);
				SendEventToEventTarget(close_event, target);
				return noErr;
			}
			else
			{
				event.id = keycode_to_clkey(key_code);
				event.type = CL_InputEvent::pressed;
				self->keyboard.sig_key_down().call(event);
				return noErr;
			}
			
		case kEventRawKeyRepeat:
			event.id = keycode_to_clkey(key_code);
			event.type = CL_InputEvent::pressed;
			self->keyboard.sig_key_down().call(event);
			return noErr;
			
		case kEventRawKeyUp:
			event.id = keycode_to_clkey(key_code);
			event.type = CL_InputEvent::released;
			self->keyboard.sig_key_up().call(event);
			return noErr;
		}
	}
	else if (event_class == kEventClassMouse)
	{
		Point mouse_pos;
		EventMouseButton mouse_button;
		UInt32 key_modifiers = 0;

		GetEventParameter(event_ref, kEventParamMouseLocation, typeQDPoint, 0, sizeof(Point), 0, &mouse_pos);
		GetEventParameter(event_ref, kEventParamMouseButton, typeMouseButton, 0, sizeof(EventMouseButton), 0, &mouse_button);
		GetEventParameter(event_ref, kEventParamKeyModifiers, typeUInt32, 0, sizeof(UInt32), 0, &key_modifiers);
				
		if (!self->fullscreen) {
			Rect wbounds;
			GetWindowBounds(self->window_ref, kWindowContentRgn, &wbounds);
			mouse_pos.h -= wbounds.left;
			mouse_pos.v -= wbounds.top;
		}

		CL_InputEvent event;
		event.id = mouse_button-1;
		event.device = self->mouse;
		event.mouse_pos = CL_Point(mouse_pos.h, mouse_pos.v);

		// Simulate second mouse button.
		if ((key_modifiers & controlKey) && (event.id == CL_MOUSE_LEFT))
			event.id = CL_MOUSE_RIGHT;

		self->mouse_pos = event.mouse_pos;

		switch (event_kind)
		{
		case kEventMouseDown:
			self->mouse_states[event.id] = true;
			event.type = CL_InputEvent::pressed;
			self->mouse.sig_key_down().call(event);
			return noErr;
			
		case kEventMouseUp:
			self->mouse_states[event.id] = false;
			event.type = CL_InputEvent::released;
			self->mouse.sig_key_up().call(event);
			return noErr;
			
		case kEventMouseMoved:
		case kEventMouseDragged:
			self->mouse.sig_pointer_move().call(event);
			return noErr;

		case kEventMouseWheelMoved:
			//Note, this is not properly handling large quick wheel movements, but the implementation on other
			//platforms don't seem to either so I will do it their way for consistancy - mrfun
			
			EventMouseWheelAxis axis;
			GetEventParameter(event_ref, kEventParamMouseWheelAxis, typeMouseWheelAxis, NULL, sizeof(axis), NULL, &axis);

			if (axis == kEventMouseWheelAxisY)
			{
			
			long wheel_delta = 0;
			GetEventParameter(event_ref, kEventParamMouseWheelDelta, typeLongInteger, 0, sizeof(long), 0, &wheel_delta);
			
			//Ok, let me explain this bIgnoreThisOne thing.  We are being passed two identical wheel events for every wheel movement -
			//This behavior is also in the apple example app GLCarbonAGLWindow and I can't figure out a way to get it to send only one
			//event or a difference in the events. (like a press and release tag differentiating them)

			//So the hack solution is to simply ignore every other mouse wheel event.  This way, programs behave the same on every
			//platform instead of wheel zooming being twice as fast on macs.

			//If anybody has a better solution or finds a problem here please feel free to dig in. -mrfun
			
			static bool bIgnoreThisOne = true;
			bIgnoreThisOne = !bIgnoreThisOne;
			
			if (bIgnoreThisOne)
				if (wheel_delta)
				{
					if (wheel_delta > 0)
					{
						event.id = CL_MOUSE_WHEEL_UP;
					} else
					{
						event.id = CL_MOUSE_WHEEL_DOWN;
					}
			
					//sending both the down and up event, like the linux version
					event.type = CL_InputEvent::pressed;
					self->mouse.sig_key_down().call(event);
					event.type = CL_InputEvent::released;
					self->mouse.sig_key_up().call(event);
				} else
				{
				//handle the X axis someday?
				}
			}
			
			return noErr;
		}
	}
	else if (event_class == kEventClassWindow)
	{
		switch (event_kind)
		{
		case kEventWindowCollapsing:
			break;

		case kEventWindowDrawContent:
			{
				if (!self->fullscreen) 
				{
					Rect rectPort;
					GetWindowPortBounds(self->window_ref, &rectPort);
					self->sig_paint(
						CL_Rect(
							rectPort.left,
							rectPort.top,
							rectPort.right,
							rectPort.bottom));
				}
			}
			break;
			
		case kEventWindowShown: // called on initial show (not on un-minimize)
			break;
			
		case kEventWindowClose:
			self->sig_window_close();
			return noErr;

		case kEventWindowActivated:
		case kEventWindowFocusAcquired:
			self->focus = true;
			self->sig_got_focus();
			return noErr;
			
		case kEventWindowDeactivated:
		case kEventWindowFocusRelinquish:
			self->focus = false;
			self->sig_lost_focus();
			return noErr;
			
		case kEventWindowBoundsChanged:
			{
				if (!self->fullscreen) {
					Rect rectPort;
					GetWindowPortBounds (self->window_ref, &rectPort);
					self->set_size(rectPort.right-rectPort.left, rectPort.bottom-rectPort.top);
				}
			}
			return noErr;
			
		case kEventWindowZoomed:
			// when maximized, but kEventWindowBoundsChanged is also called
			break;
		}
	}

	return result;
}
Ejemplo n.º 14
0
static WindowRef DrawDialogTheMacOSXWay(void)
{
	// Create a window. "DLOG:257" is the name of the window object. This name is set in 
	// InterfaceBuilder when the resource file is imported.
	
	OSStatus status = noErr;
	IBNibRef nibRef;
	WindowRef window  = NULL;
	
	static HIObjectClassRef	theClass;
	if (theClass == NULL)
	{
		static EventTypeSpec kFactoryEvents[] =
	{
				{ kEventClassHIObject, kEventHIObjectConstruct },
				{ kEventClassHIObject, kEventHIObjectInitialize },
				{ kEventClassHIObject, kEventHIObjectDestruct },
				{ kEventClassControl, kEventControlHitTest },
				{ kEventClassControl, kEventControlTrack },
				{ kEventClassControl, kEventControlBoundsChanged },
				{ kEventClassControl, kEventControlDraw }
	};
		HIObjectRegisterSubclass(kCustomSpotViewClassID, kHIViewClassID, 0, CustomSpotViewHandler, GetEventTypeCount(kFactoryEvents), kFactoryEvents, 0, &theClass);
	}
	
	status = CreateNibReference(CFSTR("main"), &nibRef);
	require_noerr(status, CantGetNibRef);
	
	status = CreateWindowFromNib(nibRef, CFSTR("DLOG:257"), &window);
	require_noerr(status, CantCreateWindow);
	
	// Let's react to User's commands.
	EventTypeSpec eventTypeCP = {kEventClassCommand, kEventCommandProcess};
	InstallEventHandler(GetWindowEventTarget(window), MacOSXDialogCommandProcess, 1, &eventTypeCP, window, NULL);
	
	// we still assign the key filter on our edit text box so that only digits can be entered
	HIViewID hidnst = {0, 9};
	HIViewRef numEditText;
	HIViewFindByID(HIViewGetRoot(window), hidnst, &numEditText);
	ControlKeyFilterUPP keyFilter = MyEditKeyFilter;
	SetControlData(numEditText, kControlEntireControl, kControlEditTextKeyFilterTag, sizeof(keyFilter), &keyFilter);
	SetKeyboardFocus(window, numEditText, kControlFocusNextPart);
	
	// we still set the action proc for the scroll bar so that the PageUp/PageDown/Up/Down buttons work
	// and still associate the previous edit text box with the scroll bar so it gets updated
	HIViewID hidsb = {0, 14};
	HIViewRef scrollBar;
	HIViewFindByID(HIViewGetRoot(window), hidsb, &scrollBar);
	SetControlAction(scrollBar, ScrollBar32BitActionProc);
	SetControlReference(scrollBar, (SInt32)numEditText);
	
	// Move it!
	MoveWindow(window, 854, 271, false);
	
	// and use the replacement for ModalDialog
	// one good thing is that our behaviors are no longer half-done at the dialog level
	// and half-done at the control level, they are all handled by the view handlers
	ShowWindow(window);
	
CantCreateWindow:
CantGetNibRef:
		return (window);
}
Ejemplo n.º 15
0
void  wxTopLevelWindowMac::MacCreateRealWindow( const wxString& title,
           const wxPoint& pos,
           const wxSize& size,
           long style,
           const wxString& name )
{
    OSStatus err = noErr ;
    SetName(name);
    m_windowStyle = style;
    m_isShown = FALSE;

    // create frame.

    Rect theBoundsRect;

    m_x = (int)pos.x;
    m_y = (int)pos.y;
    if ( m_y < 50 )
        m_y = 50 ;
    if ( m_x < 20 )
        m_x = 20 ;

    m_width = WidthDefault(size.x);
    m_height = HeightDefault(size.y);

    ::SetRect(&theBoundsRect, m_x, m_y , m_x + m_width, m_y + m_height);

    // translate the window attributes in the appropriate window class and attributes

    WindowClass wclass = 0;
    WindowAttributes attr = kWindowNoAttributes ;

    if ( HasFlag( wxFRAME_TOOL_WINDOW) )
    {
        if (
            HasFlag( wxMINIMIZE_BOX ) || HasFlag( wxMAXIMIZE_BOX ) ||
            HasFlag( wxSYSTEM_MENU ) || HasFlag( wxCAPTION ) ||
            HasFlag(wxTINY_CAPTION_HORIZ) ||  HasFlag(wxTINY_CAPTION_VERT)
            )
        {
            wclass = kFloatingWindowClass ;
            if ( HasFlag(wxTINY_CAPTION_VERT) )
            {
                attr |= kWindowSideTitlebarAttribute ;
            }
        }
        else
        {
#if TARGET_CARBON
            wclass = kPlainWindowClass ;
#else
            wclass = kFloatingWindowClass ;
#endif
        }
    }
    else if ( HasFlag( wxCAPTION ) )
    {
        wclass = kDocumentWindowClass ;
    }
    else
    {
        if ( HasFlag( wxMINIMIZE_BOX ) || HasFlag( wxMAXIMIZE_BOX ) ||
            HasFlag( wxCLOSE_BOX ) || HasFlag( wxSYSTEM_MENU ) )
        {
            wclass = kDocumentWindowClass ;
        }
        else
        {
#if TARGET_CARBON
            wclass = kPlainWindowClass ;
#else
            wclass = kModalWindowClass ;
#endif
        }
    }

    if ( HasFlag( wxMINIMIZE_BOX ) )
    {
        attr |= kWindowCollapseBoxAttribute ;
    }
    if ( HasFlag( wxMAXIMIZE_BOX ) )
    {
        attr |= kWindowFullZoomAttribute ;
    }
    if ( HasFlag( wxRESIZE_BORDER ) )
    {
        attr |= kWindowResizableAttribute ;
    }
    if ( HasFlag( wxCLOSE_BOX) )
    {
        attr |= kWindowCloseBoxAttribute ;
    }

    if (UMAGetSystemVersion() >= 0x1000)
    {
        //turn on live resizing (OS X only)
        attr |= kWindowLiveResizeAttribute;
    }

#if TARGET_CARBON
#if 0 //  having problems right now with that
    if (HasFlag(wxSTAY_ON_TOP))
        wclass = kUtilityWindowClass;
#endif
#endif

    //this setup lets us have compositing and non-compositing 
    //windows in the same application. 
  
#if UNIVERSAL_INTERFACES_VERSION >= 0x0400  
    if ( wxTopLevelWindowMac::s_macWindowCompositing )
    {
        attr |= kWindowCompositingAttribute;
        m_macUsesCompositing = TRUE;
    }
    else
#endif
    {
        m_macUsesCompositing = FALSE;
    }
    
#if TARGET_CARBON
    if ( HasFlag(wxFRAME_SHAPED) )
    {
        WindowDefSpec customWindowDefSpec;
        customWindowDefSpec.defType = kWindowDefProcPtr;
        customWindowDefSpec.u.defProc = NewWindowDefUPP(wxShapedMacWindowDef);

        err = ::CreateCustomWindow( &customWindowDefSpec, wclass,
                              attr, &theBoundsRect,
                              (WindowRef*) &m_macWindow);
    }
    else
#endif
    {
        err = ::CreateNewWindow( wclass , attr , &theBoundsRect , (WindowRef*)&m_macWindow ) ;
    }

    wxCHECK_RET( err == noErr, wxT("Mac OS error when trying to create new window") );
    wxAssociateWinWithMacWindow( (WindowRef) m_macWindow , this ) ;
    UMASetWTitle( (WindowRef)m_macWindow , title , m_font.GetEncoding() ) ;
    if ( wxTopLevelWindowMac::s_macWindowCompositing )
    {
        ::GetRootControl( (WindowRef)m_macWindow, (ControlHandle*)&m_macRootControl ) ;
    }
    else
    {
        ::CreateRootControl( (WindowRef)m_macWindow , (ControlHandle*)&m_macRootControl ) ;
    }
#if TARGET_CARBON
    InstallStandardEventHandler( GetWindowEventTarget(MAC_WXHWND(m_macWindow)) ) ;
    InstallWindowEventHandler(MAC_WXHWND(m_macWindow), GetwxMacWindowEventHandlerUPP(),
        GetEventTypeCount(eventList), eventList, this, (EventHandlerRef *)&m_macEventHandler);
#endif
    m_macFocus = NULL ;


#if TARGET_CARBON
    if ( HasFlag(wxFRAME_SHAPED) )
    {
        // default shape matches the window size
        wxRegion rgn(0, 0, m_width, m_height);
        SetShape(rgn);
    }
#endif

    wxWindowCreateEvent event(this);
    GetEventHandler()->ProcessEvent(event);
}
Ejemplo n.º 16
0
void tool_wind_open(void)
{
	int							x,t,rspace,wid;
	Rect						wbox,box;
	ControlButtonContentInfo	icon_info;
	HMHelpContentRec			tag;
	EventTypeSpec				wind_events[]={{kEventClassControl,kEventControlHit}};

    GetAvailableWindowPositioningBounds(GetMainDevice(),&wbox);
	
	SetRect(&box,wbox.left,wbox.top,wbox.right,(wbox.top+28));
	CreateNewWindow(kFloatingWindowClass,kWindowStandardFloatingAttributes|kWindowStandardHandlerAttribute,&box,&toolwind);
	ChangeWindowAttributes(toolwind,kWindowNoConstrainAttribute,kWindowCloseBoxAttribute|kWindowFullZoomAttribute|kWindowCollapseBoxAttribute|kWindowResizableAttribute);
	
	/*
    SetRect(&box,2,2,26,26);
    
	for (t=0;t!=maxtool;t++) {
	
			// create button
			
		icon_info.contentType=kControlContentCIconRes;
		icon_info.u.resID=500+t;
		CreateBevelButtonControl(toolwind,&box,NULL,kControlBevelButtonSmallBevel,kControlBehaviorToggles,&icon_info,0,0,0,&tool_ctrl[t]);
	
			// create tooltip
			
		tag.version=kMacHelpVersion;
		tag.tagSide=kHMDefaultSide;
		SetRect(&tag.absHotRect,0,0,0,0);
		tag.content[kHMMinimumContentIndex].contentType=kHMCFStringContent;
		tag.content[kHMMinimumContentIndex].u.tagCFString=CFStringCreateWithCString(NULL,tool_tooltip_str[t],kCFStringEncodingMacRoman);
		tag.content[kHMMaximumContentIndex].contentType=kHMNoContent;
		
		HMSetControlHelpContent(tool_ctrl[t],&tag);

			// next button position
			
		OffsetRect(&box,24,0);
		if ((t==2) || (t==5) || (t==13) || (t==15) || (t==18)) OffsetRect(&box,5,0);
	}
	
		// remaining space
	
	rspace=wbox.right-(box.left+5);
	
		// group combo
		
	CreateNewMenu(group_combo_menu_id,kMenuAttrExcludesMarkColumn,&group_menu);
	InsertMenu(group_menu,kInsertHierarchicalMenu);
		
	wid=(rspace-5)/2;
	if (wid>200) wid=200;
	
	group_box=box;
	group_box.top++;
	group_box.bottom++;
	group_box.left+=5;
	group_box.right=group_box.left+wid;
	
	CreatePopupButtonControl(toolwind,&group_box,NULL,group_combo_menu_id,FALSE,0,0,0,&group_combo);
	
		// magnify slider

	wid=(rspace-5)/2;
	x=wbox.right-wid;
	
	SetRect(&box,x,5,(x+16),21);
	icon_info.contentType=kControlContentCIconRes;
	icon_info.u.resID=130;
	CreateIconControl(toolwind,&box,&icon_info,TRUE,&magnify_icon);
	
	tag.version=kMacHelpVersion;
	tag.tagSide=kHMDefaultSide;
	SetRect(&tag.absHotRect,0,0,0,0);
	tag.content[kHMMinimumContentIndex].contentType=kHMCFStringContent;
	tag.content[kHMMinimumContentIndex].u.tagCFString=CFStringCreateWithCString(NULL,"Magnify",kCFStringEncodingMacRoman);
	tag.content[kHMMaximumContentIndex].contentType=kHMNoContent;
		
	HMSetControlHelpContent(magnify_icon,&tag);
	
	SetRect(&box,(x+20),5,(x+(wid-6)),25);
	magnify_proc=NewControlActionUPP(tool_wind_magnify_action);
	CreateSliderControl(toolwind,&box,(magnify_factor-1),5,210,kControlSliderDoesNotPoint,0,TRUE,magnify_proc,&magnify_slider);
	*/
		// tool window events
		
	tool_wind_upp=NewEventHandlerUPP(tool_wind_event_callback);
	InstallEventHandler(GetWindowEventTarget(toolwind),tool_wind_upp,GetEventTypeCount(wind_events),wind_events,NULL,&tool_wind_event);

	ShowWindow(toolwind);
}
Ejemplo n.º 17
0
    void OSXCarbonWindow::createNewWindow(unsigned int width, unsigned int height, String title)
    {
        if(!mWindow)
        {
            // Create the window rect in global coords
            ::Rect windowRect;
            windowRect.left = 0;
            windowRect.top = 0;
            windowRect.right = width;
            windowRect.bottom = height;
            
            // Set the default attributes for the window
            WindowAttributes windowAttrs = kWindowStandardDocumentAttributes; // default: "resize"

            windowAttrs |= kWindowStandardDocumentAttributes | kWindowStandardHandlerAttribute | kWindowHideOnFullScreenAttribute | kWindowNoShadowAttribute;

            // Create the window
            CreateNewWindow(kDocumentWindowClass, windowAttrs, &windowRect, &mWindow);

            // Color the window background black
            SetThemeWindowBackground(mWindow, kThemeBrushBlack, true);
            
            // Set the title of our window
            CFStringRef titleRef = CFStringCreateWithCString( kCFAllocatorDefault, title.c_str(), kCFStringEncodingASCII );
            SetWindowTitleWithCFString( mWindow, titleRef );
            CFRelease(titleRef);
            mWindowTitle = title;
            
            // Center our window on the screen
            RepositionWindow( mWindow, NULL, kWindowCenterOnMainScreen );
            
            // Get our view
            HIViewFindByID( HIViewGetRoot( mWindow ), kHIViewWindowContentID, &mView );
            
            // Set up our UPP for Window Events
            EventTypeSpec eventSpecs[] = {
                {kEventClassWindow, kEventWindowActivated},
                {kEventClassWindow, kEventWindowDeactivated},
                {kEventClassWindow, kEventWindowShown},
                {kEventClassWindow, kEventWindowHidden},
                {kEventClassWindow, kEventWindowDragCompleted},
                {kEventClassWindow, kEventWindowBoundsChanged},
                {kEventClassWindow, kEventWindowExpanded},
                {kEventClassWindow, kEventWindowCollapsed},
                {kEventClassWindow, kEventWindowClosed},
                {kEventClassWindow, kEventWindowClose}
            };

            EventHandlerUPP handlerUPP = NewEventHandlerUPP(WindowEventUtilities::_CarbonWindowHandler);
            
            // Install the standard event handler for the window
            EventTargetRef target = GetWindowEventTarget(mWindow);
            InstallStandardEventHandler(target);
            
            // We also need to install the WindowEvent Handler, we pass along the window with our requests
            InstallEventHandler(target, handlerUPP, 10, eventSpecs, (void*)this, &mEventHandlerRef);
        }
        HIRect winBounds = CGRectZero;
        HIViewRef root = HIViewGetRoot(HIViewGetWindow(mView)); 
        HIViewGetBounds(root, &winBounds); 

        HIRect viewBounds = CGRectZero;
        HIViewGetBounds(mView, &viewBounds);

        // Display and select our window
        if(!mHidden && mVisible)
        {
            ShowWindow(mWindow);
            SelectWindow(mWindow);
        }

        // Add our window to the window event listener class
        WindowEventUtilities::_addRenderWindow(this);
    }
/*****************************************************
*
* Handle_TextShouldChangeInRange(inHandlerCallRef, inEvent, inUserData) 
*
* Purpose:  called to intercept text changes which are destined for a text control
*
* Inputs:   inHandlerCallRef    - reference to the current handler call chain
*           inEvent             - the event
*           inUserData          - app-specified data you passed in the call to InstallEventHandler
*
* Returns:  OSStatus            - noErr indicates the event was handled
*                                 eventNotHandledErr indicates the event was not handled and the Toolbox should take over
*/
static pascal OSStatus Handle_TextShouldChangeInRange(EventHandlerCallRef inHandlerCallRef, EventRef inEvent, void *inUserData)
	{
	OSStatus status;

	CFStringRef theCFString = NULL;
	status = GetEventParameter(inEvent, kEventParamCandidateText, typeCFStringRef, NULL, sizeof(theCFString), NULL, &theCFString);
	require_noerr(status, ExitShouldChange);
	require_action(theCFString != NULL, ExitShouldChange, status = userCanceledErr);
	
	UniChar *buffer = NULL;
	CFIndex i, j, len = CFStringGetLength(theCFString);
	if (len == 0) goto ExitShouldChange; // there's nothing to filter
	
	// Grabbing the characters as Unicode chars
	buffer = (UniChar *)malloc(len * sizeof(UniChar));
	require(buffer != NULL, ExitShouldChange);
	CFStringGetCharacters(theCFString, CFRangeMake(0, len), buffer);
	
	// Checking if we just have the return code
	if ((len == 1) && (buffer[0] == kReturnCharCode))
		{
		EventRef theEvent;
		CreateEvent(NULL, kEventClassCommand, kEventCommandProcess, GetCurrentEventTime(), kEventAttributeUserEvent, &theEvent);
		HICommandExtended theCommand;
		theCommand.attributes = kHICommandFromControl;
		theCommand.commandID = 'SVet';
		theCommand.source.control = (ControlRef)inUserData;
		SetEventParameter(theEvent, kEventParamDirectObject, typeHICommand, sizeof(theCommand), &theCommand);
		SendEventToEventTarget(theEvent, GetWindowEventTarget(GetControlOwner((ControlRef)inUserData)));
		ReleaseEvent(theEvent);
		// we don't want the return character to be added to the text so we abort the input
		status = userCanceledErr;
		}
	else
		{
		// Checking to see if we have only digits
		Boolean ok = true;
		for (i = 0; (i < len) && ok; i++)
			ok = (buffer[i] >= '0') && (buffer[i] <= '9');
		
		if (!ok)
			{
			// if not, we remove the offending characters
			for (i = 0, j = 0; i < len; i++)
				if ((buffer[i] >= '0') && (buffer[i] <= '9')) buffer[j++] = buffer[i];
			
			if (j == 0)
				// not a single digit in the candidate text, we abort the inout
				status = userCanceledErr;
			else
				{
				theCFString = CFStringCreateWithCharacters(NULL, buffer, j);
				require_action(theCFString != NULL, ExitShouldChange, status = userCanceledErr);

				status = SetEventParameter(inEvent, kEventParamReplacementText, typeCFStringRef, sizeof(theCFString), &theCFString);
				require_noerr(status, ExitShouldChange);
				// if we reach here, status is already set to noErr so we don't set it again
				}
			}
		else
			// only digits, we just let the HIToolbox do its job
			status = eventNotHandledErr;
		}

ExitShouldChange:

	if (buffer != NULL) free(buffer);

	return status;
	}   // Handle_TextShouldChangeInRange
Ejemplo n.º 19
0
int main(int argc, char **argv)
{
	// We assume that all the logs we're looking for reside on the current drive
	gDirUtilp->initAppDirs("SecondLife");

	LLError::initForApplication( gDirUtilp->getExpandedFilename(LL_PATH_APP_SETTINGS, ""));

	// Rename current log file to ".old"
	std::string old_log_file = gDirUtilp->getExpandedFilename(LL_PATH_LOGS, "updater.log.old");
	std::string log_file = gDirUtilp->getExpandedFilename(LL_PATH_LOGS, "updater.log");
	LLFile::rename(log_file.c_str(), old_log_file.c_str());

	// Set the log file to updater.log
	LLError::logToFile(log_file);

	/////////////////////////////////////////
	//
	// Process command line arguments
	//
	gUpdateURL  = NULL;
	gProductName = NULL;
	gBundleID = NULL;
	gDmgFile = NULL;
	gMarkerPath = NULL;
	parse_args(argc, argv);
	if ((gUpdateURL == NULL) && (gDmgFile == NULL))
	{
		llinfos << "Usage: mac_updater -url <url> | -dmg <dmg file> [-name <product_name>] [-program <program_name>]" << llendl;
		exit(1);
	}
	else
	{
		llinfos << "Update url is: " << gUpdateURL << llendl;
		if (gProductName)
		{
			llinfos << "Product name is: " << gProductName << llendl;
		}
		else
		{
			gProductName = "Second Life";
		}
		if (gBundleID)
		{
			llinfos << "Bundle ID is: " << gBundleID << llendl;
		}
		else
		{
			gBundleID = "com.secondlife.indra.viewer";
		}
	}
	
	llinfos << "Starting " << gProductName << " Updater" << llendl;

	// Real UI...
	OSStatus err;
	IBNibRef nib = NULL;
	
	err = CreateNibReference(CFSTR("AutoUpdater"), &nib);

	char windowTitle[MAX_PATH];		/* Flawfinder: ignore */
	snprintf(windowTitle, sizeof(windowTitle), "%s Updater", gProductName);		
	CFStringRef windowTitleRef = NULL;
	windowTitleRef = CFStringCreateWithCString(NULL, windowTitle, kCFStringEncodingUTF8);
	
	if(err == noErr)
	{
		err = CreateWindowFromNib(nib, CFSTR("Updater"), &gWindow);
	}

	if (err == noErr)
	{
		err = SetWindowTitleWithCFString(gWindow, windowTitleRef);	
	}
	CFRelease(windowTitleRef);

	if(err == noErr)
	{
		// Set up an event handler for the window.
		EventTypeSpec handlerEvents[] = 
		{
			{ kEventClassCommand, kEventCommandProcess },
			{ kEventClassCustom, kEventCustomProgress },
			{ kEventClassCustom, kEventCustomDone }
		};
		InstallStandardEventHandler(GetWindowEventTarget(gWindow));
		InstallWindowEventHandler(
				gWindow, 
				NewEventHandlerUPP(dialogHandler), 
				GetEventTypeCount (handlerEvents), 
				handlerEvents, 
				0, 
				&gEventHandler);
	}
	
	if(err == noErr)
	{
		ShowWindow(gWindow);
		SelectWindow(gWindow);
	}
		
	if(err == noErr)
	{
		pthread_create(&updatethread, 
                         NULL,
                         &updatethreadproc, 
                         NULL);
						 
	}
	
	if(err == noErr)
	{
		RunAppModalLoopForWindow(gWindow);
	}

	void *threadresult;

	pthread_join(updatethread, &threadresult);

	if(!gCancelled && (gFailure != noErr))
	{
		// Something went wrong.  Since we always just tell the user to download a new version, we don't really care what.
		AlertStdCFStringAlertParamRec params;
		SInt16 retval_mac = 1;
		DialogRef alert = NULL;
		OSStatus err;

		params.version = kStdCFStringAlertVersionOne;
		params.movable = false;
		params.helpButton = false;
		params.defaultText = (CFStringRef)kAlertDefaultOKText;
		params.cancelText = 0;
		params.otherText = 0;
		params.defaultButton = 1;
		params.cancelButton = 0;
		params.position = kWindowDefaultPosition;
		params.flags = 0;

		err = CreateStandardAlert(
				kAlertStopAlert,
				CFSTR("Error"),
				CFSTR("An error occurred while updating Second Life.  Please download the latest version from www.secondlife.com."),
				&params,
				&alert);
		
		if(err == noErr)
		{
			err = RunStandardAlert(
					alert,
					NULL,
					&retval_mac);
		}
		
		if(gMarkerPath != 0)
		{
			// Create a install fail marker that can be used by the viewer to
			// detect install problems.
			std::ofstream stream(gMarkerPath);
			if(stream) stream << -1;
		}
		exit(-1);
	} else {
		exit(0);
	}

	if(gWindow != NULL)
	{
		DisposeWindow(gWindow);
	}
	
	if(nib != NULL)
	{
		DisposeNibReference(nib);
	}
	
	return 0;
}
Ejemplo n.º 20
0
ComponentResult		AUCarbonViewBase::CreateCarbonView(AudioUnit inAudioUnit, WindowRef inWindow, ControlRef inParentControl, const Float32Point &inLocation, const Float32Point &inSize, ControlRef &outParentControl)
{
    mEditAudioUnit = inAudioUnit;
    mCarbonWindow = inWindow;

    Rect area;
    area.left = short(inLocation.x);
    area.top = short(inLocation.y);
    area.right = short(area.left + inSize.x);
    area.bottom = short(area.top + inSize.y);
    OSStatus err = ::CreateUserPaneControl(inWindow, &area,
                                           kControlSupportsEmbedding,
                                           &mCarbonPane);	// subclass can resize mCarbonPane to taste
    verify_noerr(err);
    if (err) return err;
    outParentControl = mCarbonPane;

    // register for mouse-down in our pane -- we want to clear focus
    EventTypeSpec paneEvents[] = {
        { kEventClassControl, kEventControlClick }
    };
    WantEventTypes(GetControlEventTarget(mCarbonPane), GetEventTypeCount(paneEvents), paneEvents);

    // register for window-closed hook
    EventTypeSpec windowEvents[] = {
        { kEventClassWindow, kEventWindowClosed }
    };
    WantEventTypes(GetWindowEventTarget(mCarbonWindow), GetEventTypeCount(windowEvents), windowEvents);

    WindowAttributes attributes;
    verify_noerr(GetWindowAttributes(mCarbonWindow, &attributes));
    if (attributes & kWindowCompositingAttribute) {
        verify_noerr(::HIViewAddSubview(inParentControl, mCarbonPane));
        mXOffset = 0;
        mYOffset = 0;
    }
    else {
        verify_noerr(::EmbedControl(mCarbonPane, inParentControl));
        mXOffset = inLocation.x;
        mYOffset = inLocation.y;
    }
    mBottomRight.h = mBottomRight.v = 0;

    /*	err = CreateUI (mXOffset, mYOffset);
    			// we should only resize the control if a subclass has embedded
    		// controls in this AND this is done with the EmbedControl call below
    		// if mBottomRight is STILL equal to zero, then that wasn't done
    		// so don't size the control
    	if (mBottomRight.h != 0 && mBottomRight.v != 0)
    		SizeControl(mCarbonPane, short(mBottomRight.h - mXOffset), short(mBottomRight.v - mYOffset));
    */

    SizeControl(mCarbonPane, 0, 0);
    err = CreateUI(mXOffset, mYOffset);
    // we should only resize the control if a subclass has embedded
    // controls in this AND this is done with the EmbedControl call below
    // if mBottomRight is STILL equal to zero, then that wasn't done
    // so don't size the control
    Rect paneBounds;
    GetControlBounds(mCarbonPane, &paneBounds);
    // only resize mCarbonPane if it has not already been resized during CreateUI
    if ((paneBounds.top == paneBounds.bottom) && (paneBounds.left == paneBounds.right)) {
        if (mBottomRight.h != 0 && mBottomRight.v != 0)
            SizeControl(mCarbonPane, (short) (mBottomRight.h - mXOffset), (short) (mBottomRight.v - mYOffset));
    }
    return err;
}
OSStatus YASTControlAttachToExistingControl(ControlRef theControl) {
	OSStatus err;
	YASTControlVars *varsp;
	UInt32 outCommandID;
	EventHandlerRef controlEvents, windowEvents;
	TXNObject theTXNObject;
	RgnHandle outlineRegion;
	
		/* set up our locals */
	controlEvents = windowEvents = NULL;
	theTXNObject = NULL;
	outlineRegion = NULL;
	varsp = NULL;
	err = noErr;
	
		/* allocate our private storage and set up initial settings*/
	varsp = (YASTControlVars *) malloc(sizeof(YASTControlVars));
	if (varsp == NULL) {
		err = memFullErr;
	} else {
		varsp->fInFocus = false;
		varsp->fIsActive = true;
		varsp->fTXNObjectActive = false;
		varsp->fControl = theControl;
		varsp->fTabMovesFocus = true;
		varsp->fDrawFocusBox = true;
		varsp->fFocusDrawState = false;
		varsp->fIsReadOnly = false;
		varsp->fRTextOutlineRegion = NULL;
		varsp->fWindow = GetControlOwner(theControl);
		varsp->fGrafPtr = GetWindowPort(varsp->fWindow);
	}
	
		/* set our control's command id.  we don't actually use it, but it must
		be non-zero for our control to be sent command events.  only set it
		if it has not already been set.  */
	err = GetControlCommandID(theControl, &outCommandID);
	if (err == noErr) {
		if (outCommandID == 0) {
			err = SetControlCommandID(theControl, 1);
		}
	}
		/* calculate the rectangles used by the control */
	if (err == noErr) {
		outlineRegion = NewRgn();
		if (outlineRegion == NULL) {
			err = memFullErr;
		} else {
			Rect bounds;
			varsp->fRTextOutlineRegion = outlineRegion;
			GetControlBounds(theControl, &bounds);
			YASTControlCalculateBounds(varsp, &bounds);
		}
	}

		/* create the new edit field */
	if (err == noErr) {
		err = TXNNewObject(NULL, varsp->fWindow, &varsp->fRTextArea,
			kTXNWantVScrollBarMask | kTXNAlwaysWrapAtViewEdgeMask,
			kTXNTextEditStyleFrameType, kTXNTextensionFile, kTXNSystemDefaultEncoding, 
			&theTXNObject, &varsp->fTXNFrameID, (TXNObjectRefcon) varsp);
		if (err == noErr) {
			varsp->fTXNObject = theTXNObject;
		}
	}
	
		/* set the field's background */
	if (err == noErr) {
		RGBColor rgbWhite = {0xFFFF, 0xFFFF, 0xFFFF};
		TXNBackground tback;
		tback.bgType = kTXNBackgroundTypeRGB;
		tback.bg.color = rgbWhite;
		TXNSetBackground( varsp->fTXNObject, &tback);
	}
	
		/* set the margins for easier selection and display */
	if (err == noErr) {
		TXNControlData txnCControlData;
		TXNControlTag txnControlTag = kTXNMarginsTag;
		TXNMargins txnMargins = { 2, 3, 2, 1 };	/* t,l,b,r */
		txnCControlData.marginsPtr	= &txnMargins; 
		(void) TXNSetTXNObjectControls( varsp->fTXNObject, false, 1, &txnControlTag, &txnCControlData );
	}
	
		/* install our carbon event handlers */
	if (err == noErr) {
		static EventHandlerUPP gTPEventHandlerUPP = NULL;
		if (gTPEventHandlerUPP == NULL)
			gTPEventHandlerUPP = NewEventHandlerUPP(YASTControlCarbonEventHandler);
	
			/* carbon event handlers for the control */
		err = InstallEventHandler( GetControlEventTarget( theControl ),
			gTPEventHandlerUPP,
			(sizeof(gYASTControlEvents)/sizeof(EventTypeSpec)),
			gYASTControlEvents,
			varsp, &controlEvents);
		if (err == noErr) { 
			varsp->fControlEvents = windowEvents;
			
				/* carbon event handlers for the control's window */
			err = InstallEventHandler( GetWindowEventTarget( varsp->fWindow ),
				gTPEventHandlerUPP, (sizeof(gYASTControlWindowEvents)/sizeof(EventTypeSpec)),
				gYASTControlWindowEvents, varsp, &windowEvents);
			if (err == noErr) {
				varsp->fWindowEvents = windowEvents;
			}
		}
	}
	
		/* perform final activations and setup for our text field.  Here,
		we assume that the window is going to be the 'active' window. */
	if (err == noErr) {
		SetTextActivation(varsp, (varsp->fIsActive && varsp->fInFocus));
	}
	
		/* clean up on error */
	if (err != noErr) {
		if (controlEvents != NULL) RemoveEventHandler(controlEvents);
		if (windowEvents != NULL) RemoveEventHandler(windowEvents);
		if (theTXNObject != NULL) TXNDeleteObject(theTXNObject);
		if (outlineRegion != NULL) DisposeRgn(outlineRegion);
		if (varsp != NULL) free((void*) varsp);
	}
	
		/* all done */
	return err;
}
Ejemplo n.º 22
0
int main(int argc, char **argv)
{
	// We assume that all the logs we're looking for reside on the current drive
	gDirUtilp->initAppDirs("SecondLife");

	/////////////////////////////////////////
	//
	// Process command line arguments
	//
	gUpdateURL  = NULL;
	gProductName = NULL;
	parse_args(argc, argv);
	if (!gUpdateURL)
	{
		llinfos << "Usage: mac_updater -url <url> [-name <product_name>] [-program <program_name>]" << llendl;
		exit(1);
	}
	else
	{
		llinfos << "Update url is: " << gUpdateURL << llendl;
		if (gProductName)
		{
			llinfos << "Product name is: " << gProductName << llendl;
		}
		else
		{
			gProductName = "Second Life";
		}
	}
	
	llinfos << "Starting " << gProductName << " Updater" << llendl;

	// Real UI...
	OSStatus err;
	IBNibRef nib = NULL;
	
	err = CreateNibReference(CFSTR("AutoUpdater"), &nib);

	char windowTitle[MAX_PATH];		/* Flawfinder: ignore */
	snprintf(windowTitle, sizeof(windowTitle), "%s Updater", gProductName);		
	CFStringRef windowTitleRef = NULL;
	windowTitleRef = CFStringCreateWithCString(NULL, windowTitle, kCFStringEncodingUTF8);
	
	if(err == noErr)
	{
		err = CreateWindowFromNib(nib, CFSTR("Updater"), &gWindow);
	}

	if (err == noErr)
	{
		err = SetWindowTitleWithCFString(gWindow, windowTitleRef);	
	}
	CFRelease(windowTitleRef);

	if(err == noErr)
	{
		// Set up an event handler for the window.
		EventTypeSpec handlerEvents[] = 
		{
			{ kEventClassCommand, kEventCommandProcess },
			{ kEventClassCustom, kEventCustomProgress },
			{ kEventClassCustom, kEventCustomDone }
		};
		InstallStandardEventHandler(GetWindowEventTarget(gWindow));
		InstallWindowEventHandler(
				gWindow, 
				NewEventHandlerUPP(dialogHandler), 
				GetEventTypeCount (handlerEvents), 
				handlerEvents, 
				0, 
				&gEventHandler);
	}
	
	if(err == noErr)
	{
		ShowWindow(gWindow);
	}
		
	if(err == noErr)
	{
		pthread_create(&updatethread, 
                         NULL,
                         &updatethreadproc, 
                         NULL);
						 
	}
	
	if(err == noErr)
	{
		RunAppModalLoopForWindow(gWindow);
	}

	void *threadresult;

	pthread_join(updatethread, &threadresult);

	if(!gCancelled && (gFailure != noErr))
	{
		// Something went wrong.  Since we always just tell the user to download a new version, we don't really care what.
		AlertStdCFStringAlertParamRec params;
		SInt16 retval_mac = 1;
		DialogRef alert = NULL;
		OSStatus err;

		params.version = kStdCFStringAlertVersionOne;
		params.movable = false;
		params.helpButton = false;
		params.defaultText = (CFStringRef)kAlertDefaultOKText;
		params.cancelText = 0;
		params.otherText = 0;
		params.defaultButton = 1;
		params.cancelButton = 0;
		params.position = kWindowDefaultPosition;
		params.flags = 0;

		err = CreateStandardAlert(
				kAlertStopAlert,
				CFSTR("Error"),
				CFSTR("An error occurred while updating Second Life.  Please download the latest version from www.secondlife.com."),
				&params,
				&alert);
		
		if(err == noErr)
		{
			err = RunStandardAlert(
					alert,
					NULL,
					&retval_mac);
		}

	}
	
	// Don't dispose of things, just exit.  This keeps the update thread from potentially getting hosed.
	exit(0);

	if(gWindow != NULL)
	{
		DisposeWindow(gWindow);
	}
	
	if(nib != NULL)
	{
		DisposeNibReference(nib);
	}
	
	return 0;
}
Ejemplo n.º 23
0
//-------------------------------------------------------------------------------------------------//
void OSXCarbonWindow::create( const String& name, unsigned int width, unsigned int height,
	            bool fullScreen, const NameValuePairList *miscParams )
{
	bool hasDepthBuffer;
	String title = name;
	size_t fsaa_samples = 0;
	int left = 0;
	int top = 0;
	int depth = 32;
	
	if( miscParams )
	{
		
		NameValuePairList::const_iterator opt = NULL;
		
		// Full screen anti aliasing
		opt = miscParams->find( "FSAA" );
		if( opt != miscParams->end() )
			fsaa_samples = StringConverter::parseUnsignedInt( opt->second );

		opt = miscParams->find( "left" );
		if( opt != miscParams->end() )
			left = StringConverter::parseUnsignedInt( opt->second );

		opt = miscParams->find( "top" );
		if( opt != miscParams->end() )
			top = StringConverter::parseUnsignedInt( opt->second );

		opt = miscParams->find( "title" );
		if( opt != miscParams->end() )
			title = opt->second;

		opt = miscParams->find( "depthBuffer" );
		if( opt != miscParams->end() )
			hasDepthBuffer = StringConverter::parseBool( opt->second );
		
		opt = miscParams->find( "colourDepth" );
		if( opt != miscParams->end() )
			depth = StringConverter::parseUnsignedInt( opt->second );
	}
	
	if(fullScreen)
	{
		GLRenderSystem *rs = static_cast<GLRenderSystem*>(Root::getSingleton().getRenderSystem());
		OSXContext *mainContext = (OSXContext*)rs->_getMainContext();
		
		CGLContextObj share = NULL;
		if(mainContext == 0)
		{
			share = NULL;
		}
		else if(mainContext->getContextType() == "AGL")
		{
			OSXCarbonContext* aglShare = static_cast<OSXCarbonContext*>(mainContext);
			aglGetCGLContext(aglShare->getContext(), &((void*)share));
		}
		else if(mainContext->getContextType() == "CGL")
		{
			OSXCGLContext* cglShare = static_cast<OSXCGLContext*>(mainContext);
			share = cglShare->getContext();
		}
		
		// create the context
		createCGLFullscreen(width, height, depth, fsaa_samples, share);		
	}
	else
	{
		int i = 0;
		AGLPixelFormat pixelFormat;
		GLint attribs[ 20 ];
		
		attribs[ i++ ] = AGL_NO_RECOVERY;
		attribs[ i++ ] = GL_TRUE;
		attribs[ i++ ] = AGL_ACCELERATED;
		attribs[ i++ ] = GL_TRUE;
		attribs[ i++ ] = AGL_RGBA;
		attribs[ i++ ] = AGL_DOUBLEBUFFER;
		attribs[ i++ ] = AGL_ALPHA_SIZE;
		attribs[ i++ ] = 8;
		attribs[ i++ ] = AGL_STENCIL_SIZE;
		attribs[ i++ ] = 8;
		attribs[ i++ ] = AGL_DEPTH_SIZE;
		attribs[ i++ ] = depth;
	
		if(fsaa_samples > 1)
		{
			attribs[ i++ ] = AGL_MULTISAMPLE;
			attribs[ i++ ] = 1;
			attribs[ i++ ] = AGL_SAMPLE_BUFFERS_ARB;
			attribs[ i++ ] = fsaa_samples;
		}
	
		attribs[ i++ ] = AGL_NONE;
	
		pixelFormat = aglChoosePixelFormat( NULL, 0, attribs );
	
		// Create the AGLContext from our pixel format
		// Share it with main
		GLRenderSystem *rs = static_cast<GLRenderSystem*>(Root::getSingleton().getRenderSystem());
		OSXContext* mainContext = static_cast<OSXContext*>( rs->_getMainContext() );
		if(mainContext == 0)
		{
			mAGLContext = aglCreateContext(pixelFormat, NULL);
		}
		else if(mainContext->getContextType() == "AGL")
		{
			OSXCarbonContext* context = static_cast<OSXCarbonContext*>( rs->_getMainContext() );
			AGLContext shared = context->getContext();
			mAGLContext = aglCreateContext(pixelFormat, context->getContext());
		}
		else
		{
			// If we do not have an AGL, we can not clone it using this window
			LogManager::getSingleton().logMessage( "Warning: You asked to create a second window, "
				"when the previous window was not of this type.  OgreOSXCarbonWindow can only share "
				"with an AGL context.");
		}
		
		NameValuePairList::const_iterator opt = 0;
		if(miscParams)
			opt = miscParams->find("externalWindowHandle");
		if(!miscParams || opt == miscParams->end())
		{
			// create the window rect in global coords
			::Rect windowRect;
			windowRect.left = 0;
			windowRect.top = 0;
			windowRect.right = width;
			windowRect.bottom = height;
			
			// set the default attributes for the window
			WindowAttributes windowAttrs = kWindowStandardDocumentAttributes; // default: "resize"
			
			if (miscParams)
			{
				opt = miscParams->find("border");
				if( opt != miscParams->end() )
				{
					String borderType = opt->second;
					if( borderType == "none" )
						windowAttrs = kWindowNoTitleBarAttribute;
					else if( borderType == "fixed" )
						windowAttrs = kWindowStandardFloatingAttributes;
				}
			}
			
			windowAttrs |= kWindowStandardHandlerAttribute | kWindowInWindowMenuAttribute | kWindowHideOnFullScreenAttribute;
			
			// Create the window
			CreateNewWindow(kDocumentWindowClass, windowAttrs, &windowRect, &mWindow);
			
			// Color the window background black
			SetThemeWindowBackground (mWindow, kThemeBrushBlack, true);
			
			// Set the title of our window
			CFStringRef titleRef = CFStringCreateWithCString( kCFAllocatorDefault, title.c_str(), kCFStringEncodingASCII );
			SetWindowTitleWithCFString( mWindow, titleRef );
			
			// Center our window on the screen
			RepositionWindow( mWindow, NULL, kWindowCenterOnMainScreen );
            
            // Get our view
            HIViewFindByID( HIViewGetRoot( mWindow ), kHIViewWindowContentID, &mView );
			
			// Set up our UPP for Window Events
            EventTypeSpec eventSpecs[] = {
                {kEventClassWindow, kEventWindowActivated},
                {kEventClassWindow, kEventWindowDeactivated},
                {kEventClassWindow, kEventWindowShown},
                {kEventClassWindow, kEventWindowHidden},
                {kEventClassWindow, kEventWindowDragCompleted},
                {kEventClassWindow, kEventWindowBoundsChanged},
                {kEventClassWindow, kEventWindowExpanded},
                {kEventClassWindow, kEventWindowCollapsed},
                {kEventClassWindow, kEventWindowClosed},
                {kEventClassWindow, kEventWindowClose}
            };
            
            EventHandlerUPP handlerUPP = NewEventHandlerUPP(WindowEventUtilities::_CarbonWindowHandler);
            
            // Install the standard event handler for the window
            EventTargetRef target = GetWindowEventTarget(mWindow);
			InstallStandardEventHandler(target);
            
            // We also need to install the WindowEvent Handler, we pass along the window with our requests
            InstallEventHandler(target, handlerUPP, 10, eventSpecs, (void*)this, &mEventHandlerRef);
			
			// Display and select our window
			ShowWindow(mWindow);
			SelectWindow(mWindow);
            
            // Add our window to the window event listener class
            WindowEventUtilities::_addRenderWindow(this);
		}
		else
		{
			// TODO: The Contol is going to report the incorrect location with a
			// Metalic / Textured window.  The default windows work just fine.
			
			// First get the HIViewRef / ControlRef
			mView = (HIViewRef)StringConverter::parseUnsignedLong(opt->second);
			mWindow = GetControlOwner(mView);
			
			// Lets try hiding the HIView
			//HIViewSetVisible(mView, false);
					
			// Get the rect bounds
			::Rect ctrlBounds;
			GetControlBounds(mView, &ctrlBounds);
			GLint bufferRect[4];

			bufferRect[0] = ctrlBounds.left;					// left edge
			bufferRect[1] = ctrlBounds.bottom;					// bottom edge
			bufferRect[2] =	ctrlBounds.right - ctrlBounds.left; // width of buffer rect
			bufferRect[3] = ctrlBounds.bottom - ctrlBounds.top; // height of buffer rect
			aglSetInteger(mAGLContext, AGL_BUFFER_RECT, bufferRect);
			aglEnable (mAGLContext, AGL_BUFFER_RECT);
            
            mIsExternal = true;
		}
		
		// Set the drawable, and current context
		// If you do this last, there is a moment before the rendering window pops-up
		// This could go once inside each case above, before the window is displayed,
		// if desired.
		aglSetDrawable(mAGLContext, GetWindowPort(mWindow));
		aglSetCurrentContext(mAGLContext);

		// Give a copy of our context to the render system
		mContext = new OSXCarbonContext(mAGLContext, pixelFormat);
	}
	
	mName = name;
	mWidth = width;
	mHeight = height;
	mActive = true;
    mClosed = false;
    mCreated = true;
	mIsFullScreen = fullScreen;
}
Ejemplo n.º 24
0
SkOSWindow::SkOSWindow(void* hWnd) : fHWND(hWnd), fAGLCtx(NULL)
{
	OSStatus    result;
    WindowRef   wr = (WindowRef)hWnd;

    HIViewRef imageView, parent;
    HIViewRef rootView = HIViewGetRoot(wr);
    HIViewFindByID(rootView, kHIViewWindowContentID, &parent);
    result = HIImageViewCreate(NULL, &imageView);
	SkASSERT(result == noErr);

    result = HIViewAddSubview(parent, imageView);
	SkASSERT(result == noErr);

    fHVIEW = imageView;

    HIViewSetVisible(imageView, true);
    HIViewPlaceInSuperviewAt(imageView, 0, 0);

    if (true) {
        HILayoutInfo layout;
        layout.version = kHILayoutInfoVersionZero;
        set_bindingside(&layout.binding.left, parent, kHILayoutBindLeft);
        set_bindingside(&layout.binding.top, parent, kHILayoutBindTop);
        set_bindingside(&layout.binding.right, parent, kHILayoutBindRight);
        set_bindingside(&layout.binding.bottom, parent, kHILayoutBindBottom);
        set_axisscale(&layout.scale.x, parent);
        set_axisscale(&layout.scale.y, parent);
        set_axisposition(&layout.position.x, parent, kHILayoutPositionLeft);
        set_axisposition(&layout.position.y, rootView, kHILayoutPositionTop);
        HIViewSetLayoutInfo(imageView, &layout);
    }

    HIImageViewSetOpaque(imageView, true);
    HIImageViewSetScaleToFit(imageView, false);

	static const EventTypeSpec  gTypes[] = {
		{ kEventClassKeyboard,  kEventRawKeyDown			},
        { kEventClassKeyboard,  kEventRawKeyUp              },
		{ kEventClassMouse,		kEventMouseDown				},
		{ kEventClassMouse,		kEventMouseDragged			},
		{ kEventClassMouse,		kEventMouseMoved			},
		{ kEventClassMouse,		kEventMouseUp				},
		{ kEventClassTextInput, kEventTextInputUnicodeForKeyEvent   },
		{ kEventClassWindow,	kEventWindowBoundsChanged	},
//		{ kEventClassWindow,	kEventWindowDrawContent		},
		{ SK_MacEventClass,		SK_MacEventKind				}
	};

	EventHandlerUPP handlerUPP = NewEventHandlerUPP(SkOSWindow::EventHandler);
	int				count = SK_ARRAY_COUNT(gTypes);

	result = InstallEventHandler(GetWindowEventTarget(wr), handlerUPP,
						count, gTypes, this, nil);
	SkASSERT(result == noErr);

	gCurrOSWin = this;
	gCurrEventQ = GetCurrentEventQueue();
	gEventTarget = GetWindowEventTarget(wr);

	static bool gOnce = true;
	if (gOnce) {
		gOnce = false;
		gPrevNewHandler = set_new_handler(sk_new_handler);
	}
}