Example #1
0
bool wxSlider::Create(wxWindow *parent,
    wxWindowID id,
    int value, int minValue, int maxValue,
    const wxPoint& pos,
    const wxSize& size, long style,
    const wxValidator& validator,
    const wxString& name)
{
    m_macIsUserPane = false;

    m_macMinimumStatic = NULL;
    m_macMaximumStatic = NULL;
    m_macValueStatic = NULL;

    m_lineSize = 1;
    m_tickFreq = 0;

    m_rangeMax = maxValue;
    m_rangeMin = minValue;

    m_pageSize = (int)((maxValue - minValue) / 10);

    // our styles are redundant: wxSL_LEFT/RIGHT imply wxSL_VERTICAL and
    // wxSL_TOP/BOTTOM imply wxSL_HORIZONTAL, but for backwards compatibility
    // reasons we can't really change it, instead try to infer the orientation
    // from the flags given to us here
    switch ( style & (wxSL_LEFT | wxSL_RIGHT | wxSL_TOP | wxSL_BOTTOM) )
    {
        case wxSL_LEFT:
        case wxSL_RIGHT:
            style |= wxSL_VERTICAL;
            break;

        case wxSL_TOP:
        case wxSL_BOTTOM:
            style |= wxSL_HORIZONTAL;
            break;

        case 0:
        default:
            // no specific direction, do we have at least the orientation?
            if ( !(style & (wxSL_HORIZONTAL | wxSL_VERTICAL)) )
                // no: choose default
                style |= wxSL_BOTTOM | wxSL_HORIZONTAL;
            break;
    }

    wxASSERT_MSG( !(style & wxSL_VERTICAL) || !(style & wxSL_HORIZONTAL),
        wxT("incompatible slider direction and orientation") );

    if ( !wxControl::Create(parent, id, pos, size, style, validator, name) )
        return false;

    Rect bounds = wxMacGetBoundsForControl( this , pos , size );

    // NB: (RN) Ticks here are sometimes off in the GUI if there
    // are not as many tick marks as there are values
    //
    int tickMarks = 0;
    if ( style & wxSL_AUTOTICKS )
        tickMarks = (maxValue - minValue) + 1; // +1 for the 0 value

    // keep the number of tickmarks from becoming unwieldly, therefore below it is ok to cast
    // it to a UInt16
    while (tickMarks > 20)
        tickMarks /= 5;

    m_peer = new wxMacControl( this );
    OSStatus err = CreateSliderControl(
        MAC_WXHWND(parent->MacGetTopLevelWindowRef()), &bounds,
        value, minValue, maxValue,
        kControlSliderPointsDownOrRight,
        (UInt16) tickMarks, true /* liveTracking */,
        GetwxMacLiveScrollbarActionProc(),
        m_peer->GetControlRefAddr() );
    verify_noerr( err );

    if (style & wxSL_VERTICAL)
        // Forces SetSize to use the proper width
        SetSizeHints(10, -1, 10, -1);
    else
        // Forces SetSize to use the proper height
        SetSizeHints(-1, 10, -1, 10);

    // NB: SetSizeHints is overloaded by wxSlider and will substitute 10 with the
    // proper dimensions, it also means other people cannot bugger the slider with
    // other values

    if (style & wxSL_LABELS)
    {
        m_macMinimumStatic = new wxStaticText( parent, wxID_ANY, wxEmptyString );
        m_macMaximumStatic = new wxStaticText( parent, wxID_ANY, wxEmptyString );
        m_macValueStatic = new wxStaticText( parent, wxID_ANY, wxEmptyString );
    }

    SetRange(minValue, maxValue);
    SetValue(value);

    MacPostControlCreate(pos, size);

    return true;
}
Example #2
0
bool wxMacSearchFieldControl::IsCancelButtonVisible() const
{
    OptionBits attributes = 0;
    verify_noerr( HISearchFieldGetAttributes( m_controlRef, &attributes ) );
    return ( attributes & kHISearchFieldAttributesCancel ) != 0;
}
Example #3
0
OSStatus wxMacListBoxItem::GetSetData(wxMacDataItemBrowserControl *owner ,
    DataBrowserPropertyID property,
    DataBrowserItemDataRef itemData,
    bool changeValue )
{
    wxMacDataBrowserListControl *lb = wxDynamicCast(owner,wxMacDataBrowserListControl);
    OSStatus err = errDataBrowserPropertyNotSupported;
    if ( !changeValue )
    {
        if ( property >= kMinColumnId )
        {
            wxMacDataBrowserColumn* col = lb->GetColumnFromProperty( property );
            unsigned int n = owner->GetLineFromItem( this );
            wxListBox *list = wxDynamicCast( owner->GetWXPeer() , wxListBox );
            wxMacDataBrowserCellValue valueholder(itemData);
            list->GetValueCallback( n , col, valueholder );

            err = noErr;
        }
        else
        {
            if ( property == kDataBrowserItemIsEditableProperty )
            {
                DataBrowserPropertyID propertyToEdit ;
                GetDataBrowserItemDataProperty( itemData, &propertyToEdit );
                wxMacDataBrowserColumn* col = lb->GetColumnFromProperty( propertyToEdit );

                verify_noerr(SetDataBrowserItemDataBooleanValue( itemData, col->IsEditable() ));
                err = noErr;
            }

        }

    }
    else
    {
        if ( property >= kMinColumnId )
        {
            wxMacDataBrowserColumn* col = lb->GetColumnFromProperty( property );

            unsigned int n = owner->GetLineFromItem( this );
            wxListBox *list = wxDynamicCast( owner->GetWXPeer() , wxListBox );
            wxMacDataBrowserCellValue valueholder(itemData);
            list->SetValueCallback( n , col, valueholder );

            /*
            // we have to change this behind the back, since Check() would be triggering another update round
            bool newVal = !m_isChecked;
            verify_noerr(SetDataBrowserItemDataButtonValue( itemData, newVal ? kThemeButtonOn : kThemeButtonOff ));
            m_isChecked = newVal;
            err = noErr;

            wxCommandEvent event( wxEVT_CHECKLISTBOX, checklist->GetId() );
            event.SetInt( owner->GetLineFromItem( this ) );
            event.SetEventObject( checklist );
            checklist->HandleWindowEvent( event );

            */
            err = noErr;
        }
    }

    // call inherited if not ours
    if ( err == errDataBrowserPropertyNotSupported )
    {
        err = wxMacDataItem::GetSetData(owner, property, itemData, changeValue);
    }

    return err;
}
//_______________________________________________
//
//
//_______________________________________________
uint8_t coreAudioDevice::init(uint8_t channels, uint32_t fq) 
{
_channels = channels;
OSStatus 		err;
ComponentDescription 	desc;
AudioUnitInputCallback 	input;
AudioStreamBasicDescription streamFormat;
AudioDeviceID 		theDevice;
UInt32			sz=0;
UInt32			kFramesPerSlice=512; 

	desc.componentType = 'aunt';
	desc.componentSubType = kAudioUnitSubType_Output;
	desc.componentManufacturer = kAudioUnitID_DefaultOutput;
	desc.componentFlags = 0;
	desc.componentFlagsMask = 0;
		
	comp= FindNextComponent(NULL, &desc);
	if (comp == NULL)
	{
		printf("coreAudio: Cannot find component\n");
		return 0;
	}
		
	err = OpenAComponent(comp, &theOutputUnit);
	if(err)
	{
		printf("coreAudio: Cannot open component\n");
		return 0;
	}
	// Initialize it
	verify_noerr(AudioUnitInitialize(theOutputUnit));
	
	// Set up a callback function to generate output to the output unit
#if 1
	input.inputProc = MyRenderer;
	input.inputProcRefCon = NULL;
	
	verify_noerr(AudioUnitSetProperty(theOutputUnit, 
					kAudioUnitProperty_SetInputCallback, 
					kAudioUnitScope_Global,
					0,
					&input, 
					sizeof(input)));
#endif
	streamFormat.mSampleRate = fq;		
	streamFormat.mFormatID = kAudioFormatLinearPCM;	
	streamFormat.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger 
								| kLinearPCMFormatFlagIsBigEndian
								| kLinearPCMFormatFlagIsPacked;

	streamFormat.mBytesPerPacket = channels * sizeof (UInt16);	
	streamFormat.mFramesPerPacket = 1;	
	streamFormat.mBytesPerFrame = channels * sizeof (UInt16);		
	streamFormat.mChannelsPerFrame = channels;	
	streamFormat.mBitsPerChannel = sizeof (UInt16) * 8;	
	
	verify_noerr(AudioUnitSetProperty(
		theOutputUnit,
		kAudioUnitProperty_StreamFormat,
		kAudioUnitScope_Input,
		0,
		&streamFormat,
		sizeof(AudioStreamBasicDescription)));
	
	printf("Rendering source:\n\t");
	printf ("SampleRate=%f,", streamFormat.mSampleRate);
	printf ("BytesPerPacket=%ld,", streamFormat.mBytesPerPacket);
	printf ("FramesPerPacket=%ld,", streamFormat.mFramesPerPacket);
	printf ("BytesPerFrame=%ld,", streamFormat.mBytesPerFrame);
	printf ("BitsPerChannel=%ld,", streamFormat.mBitsPerChannel);
	printf ("ChannelsPerFrame=%ld\n", streamFormat.mChannelsPerFrame);

	sz=sizeof (theDevice);
	verify_noerr(AudioUnitGetProperty 
		(theOutputUnit, kAudioOutputUnitProperty_CurrentDevice, 0, 0, &theDevice, &sz));
	sz = sizeof (kFramesPerSlice);
	verify_noerr(AudioDeviceSetProperty(theDevice, 0, 0, false,
		kAudioDevicePropertyBufferFrameSize, sz, &kFramesPerSlice));

	sz = sizeof (kFramesPerSlice);
	verify_noerr(AudioDeviceGetProperty(theDevice, 0, false, 
		kAudioDevicePropertyBufferFrameSize, &sz, &kFramesPerSlice));

	verify_noerr (AudioDeviceAddPropertyListener(theDevice, 0, false,
		kAudioDeviceProcessorOverload, OverloadListenerProc, 0));

	printf ("size of the device's buffer = %ld frames\n", kFramesPerSlice);
	
	frameCount=0;
	
	audioBuffer=new int16_t[BUFFER_SIZE]; // between hald a sec and a sec should be enough :)
	
    return 1;
}
Example #5
0
//-----------------------------------------------------------------------------
// wxDockEventHandler
//
// This is the global Mac/Carbon event handler for the dock.
// We need this for two reasons:
// 1) To handle wxTaskBarIcon menu events (see below for why)
// 2) To handle events from the dock when it requests a menu
//-----------------------------------------------------------------------------
pascal OSStatus wxDockEventHandler( EventHandlerCallRef inHandlerCallRef,
                                    EventRef inEvent, void *pData )
{
    // Get the parameters we want from the event
    wxDockTaskBarIcon* pTB = (wxDockTaskBarIcon*) pData;
    const UInt32 eventClass = GetEventClass(inEvent);
    const UInt32 eventKind = GetEventKind(inEvent);

    // Handle wxTaskBar menu events (note that this is a global event handler
    // so it will actually get called by all commands/menus)
    if ((eventClass == kEventClassCommand) && (eventKind == kEventCommandProcess))
    {
        // if we have no taskbar menu quickly pass it back to wxApp
        if (pTB->m_pMenu == NULL)
            return eventNotHandledErr;

        // This is the real reason why we need this. Normally menus
        // get handled in wxMacAppEventHandler
        //
        // pascal OSStatus wxMacAppEventHandler(EventHandlerCallRef handler,
        //                                      EventRef event, void *data)
        //
        // However, in the case of a taskbar menu call
        // command.menu.menuRef IS NULL!
        // Which causes the wxApp handler just to skip it.
        MenuRef taskbarMenuRef = MAC_WXHMENU(pTB->m_pMenu->GetHMenu());
        OSStatus err;

        // get the HICommand from the event
        HICommand command;
        err = GetEventParameter(
            inEvent, kEventParamDirectObject,
            typeHICommand, NULL,
            sizeof(HICommand), NULL, &command );
        if (err == noErr)
        {
            // Obtain the REAL menuRef and the menuItemIndex in the real menuRef
            //
            // NOTE: menuRef is generally used here for submenus, as
            // GetMenuItemRefCon could give an incorrect wxMenuItem if we pass
            // just the top level wxTaskBar menu
            MenuItemIndex menuItemIndex;
            MenuRef menuRef;

            err = GetIndMenuItemWithCommandID(
                taskbarMenuRef,
                command.commandID,
                1, &menuRef, &menuItemIndex );
            if (err == noErr)
            {
                MenuCommand id = command.commandID;
                wxMenuItem *item = NULL;

                if (id != 0) // get the wxMenuItem reference from the MenuRef
                    GetMenuItemRefCon( menuRef, menuItemIndex, (URefCon*) &item );

                if (item)
                {
                    // Handle items that are checkable
                    // FIXME: Doesn't work (at least on 10.2)!
                    if (item->IsCheckable())
                        item->Check( !item->IsChecked() );

                    // send the wxEvent to the wxMenu
                    item->GetMenu()->SendEvent( id, item->IsCheckable() ? item->IsChecked() : -1 );

                    // successfully handled the event
                    err = noErr;
                }
            }
        } //end if noErr on getting HICommand from event

        // return whether we handled the event or not
        return err;
    }

    // We better have a kEventClassApplication/kEventAppGetDockTileMenu combo here,
    // otherwise something is truly funky
    wxASSERT(eventClass == kEventClassApplication &&
             eventKind == kEventAppGetDockTileMenu);

    // process the right click events
    // NB: This may result in double or even triple-creation of the menus
    // We need to do this for 2.4 compat, however
    wxTaskBarIconEvent downevt(wxEVT_TASKBAR_RIGHT_DOWN, NULL);
    pTB->m_parent->ProcessEvent(downevt);

    wxTaskBarIconEvent upevt(wxEVT_TASKBAR_RIGHT_UP, NULL);
    pTB->m_parent->ProcessEvent(upevt);

    // create popup menu
    wxMenu* menu = pTB->DoCreatePopupMenu();

    OSStatus err = eventNotHandledErr;

    if (menu != NULL)
    {
        // note to self - a MenuRef *is* a MenuHandle
        MenuRef hMenu = MAC_WXHMENU(menu->GetHMenu());

        // When SetEventParameter is called it will decrement
        // the reference count of the menu - we need to make
        // sure it stays around in the wxMenu class here
        CFRetain(hMenu);

        // set the actual dock menu
        err = SetEventParameter(
            inEvent, kEventParamMenuRef,
            typeMenuRef, sizeof(MenuRef), &hMenu );
        verify_noerr( err );
    }

    return err;
}
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;
}
Example #7
0
wxSize wxStaticText::DoGetBestSize() const
{
    Point bounds;
#if wxOSX_USE_CARBON
    Rect bestsize = { 0 , 0 , 0 , 0 } ;

    // try the built-in best size if available
    Boolean former = GetPeer()->GetData<Boolean>( kControlStaticTextIsMultilineTag);
    GetPeer()->SetData( kControlStaticTextIsMultilineTag, (Boolean)0 );
    GetPeer()->GetBestRect( &bestsize ) ;
    GetPeer()->SetData( kControlStaticTextIsMultilineTag, former );
    
    if ( !EmptyRect( &bestsize ) )
    {
        bounds.h = bestsize.right - bestsize.left ;
        bounds.v = bestsize.bottom - bestsize.top ;
    }
    else
#endif
    {
#if wxOSX_USE_CARBON
        ControlFontStyleRec controlFont;
        OSStatus err = GetPeer()->GetData<ControlFontStyleRec>( kControlEntireControl, kControlFontStyleTag, &controlFont );
        verify_noerr( err );

#if wxOSX_USE_ATSU_TEXT
        SInt16 baseline;
        if ( m_font.MacGetThemeFontID() != kThemeCurrentPortFont )
        {
            // GetThemeTextDimensions will cache strings and the documentation
            // says not to use the NoCopy string creation calls.
            // This also means that we can't use CFSTR without
            // -fno-constant-cfstrings if the library might be unloaded,
            // as GetThemeTextDimensions may cache a pointer to our
            // unloaded segment.
            wxCFStringRef str( !m_label.empty() ? m_label : wxString(" "),
                              GetFont().GetEncoding() );

            err = GetThemeTextDimensions(
                (CFStringRef)str,
                m_font.MacGetThemeFontID(), kThemeStateActive, false, &bounds, &baseline );
            verify_noerr( err );
        }
        else
#endif
#endif
        {
            wxClientDC dc(const_cast<wxStaticText*>(this));
            wxCoord width, height ;
            dc.GetTextExtent( m_label , &width, &height);
            bounds.h = width;
            bounds.v = height;
        }

        if ( m_label.empty() )
            bounds.h = 0;
    }
    bounds.h += MacGetLeftBorderSize() + MacGetRightBorderSize();
    bounds.v += MacGetTopBorderSize() + MacGetBottomBorderSize();

    return wxSize( bounds.h, bounds.v );
}
Example #8
0
void wxMacDataItemBrowserControl::RemoveItem(wxMacDataItem *container, wxMacDataItem* item)
{
    OSStatus err = wxMacDataBrowserControl::RemoveItems( (DataBrowserItemID)container, 1,
        (DataBrowserItemID*) &item, kDataBrowserItemNoProperty );
    verify_noerr( err );
}
Example #9
0
void wxMacDataItemBrowserControl::RemoveAllItems(wxMacDataItem *container)
{
    SetScrollPosition(0, 0);
    OSStatus err = wxMacDataBrowserControl::RemoveItems( (DataBrowserItemID)container, 0 , NULL , kDataBrowserItemNoProperty );
    verify_noerr( err );
}
Example #10
0
void wxMacDataItemBrowserControl::SetColumnWidth(int colId, int width)
{
    DataBrowserPropertyID id;
    GetColumnIDFromIndex(colId, &id);
    verify_noerr( wxMacDataBrowserControl::SetColumnWidth(id, width));
}
Example #11
0
void wxMacDataItemBrowserControl::AddItem(wxMacDataItem *container, wxMacDataItem *item)
{
    verify_noerr( wxMacDataBrowserControl::AddItems( (DataBrowserItemID)container, 1,
        (DataBrowserItemID*) &item, kDataBrowserItemNoProperty ) );
}
Example #12
0
void wxMacDataItemBrowserControl::UpdateItem(const wxMacDataItem *container,
        const wxMacDataItem *item , DataBrowserPropertyID property) const
{
    verify_noerr( wxMacDataBrowserControl::UpdateItems((DataBrowserItemID)container, 1,
        (DataBrowserItemID*) &item, kDataBrowserItemNoProperty /* notSorted */, property ) );
}
Example #13
0
void wxMenuBar::MacInstallMenuBar()
{
    if ( s_macInstalledMenuBar == this )
        return ;

    MenuBarHandle menubar = NULL ;

#if TARGET_API_MAC_OSX
    menubar = NewHandleClear( 6 /* sizeof( MenuBarHeader ) */ ) ;
#else
    menubar = NewHandleClear( 12 ) ;
    (*menubar)[3] = 0x0a ;
#endif

    ::SetMenuBar( menubar ) ;
    DisposeMenuBar( menubar ) ;
    MenuHandle appleMenu = NULL ;

    verify_noerr( CreateNewMenu( kwxMacAppleMenuId , 0 , &appleMenu ) ) ;
    verify_noerr( SetMenuTitleWithCFString( appleMenu , CFSTR( "\x14" ) ) );

    // Add About/Preferences separator only on OS X
    // KH/RN: Separator is always present on 10.3 but not on 10.2
    // However, the change from 10.2 to 10.3 suggests it is preferred
#if TARGET_API_MAC_OSX
    InsertMenuItemTextWithCFString( appleMenu,
                CFSTR(""), 0, kMenuItemAttrSeparator, 0); 
#endif
    InsertMenuItemTextWithCFString( appleMenu,
                CFSTR("About..."), 0, 0, 0); 
    MacInsertMenu( appleMenu , 0 ) ;

    // clean-up the help menu before adding new items
    static MenuHandle mh = NULL ;

    if ( mh != NULL )
    {
        MenuItemIndex firstUserHelpMenuItem ;
        if ( UMAGetHelpMenu( &mh , &firstUserHelpMenuItem) == noErr )
        {
            for ( int i = CountMenuItems( mh ) ; i >= firstUserHelpMenuItem ; --i )
                DeleteMenuItem( mh , i ) ;
        }
        else
        {
            mh = NULL ;
        }
    }

#if TARGET_CARBON
    if ( UMAGetSystemVersion() >= 0x1000 && wxApp::s_macPreferencesMenuItemId)
    {
        wxMenuItem *item = FindItem( wxApp::s_macPreferencesMenuItemId , NULL ) ;
        if ( item == NULL || !(item->IsEnabled()) )
            DisableMenuCommand( NULL , kHICommandPreferences ) ;
        else
            EnableMenuCommand( NULL , kHICommandPreferences ) ;
    }

    // Unlike preferences which may or may not exist, the Quit item should be always
    // enabled unless it is added by the application and then disabled, otherwise
    // a program would be required to add an item with wxID_EXIT in order to get the
    // Quit menu item to be enabled, which seems a bit burdensome.
    if ( UMAGetSystemVersion() >= 0x1000 && wxApp::s_macExitMenuItemId)
    {
        wxMenuItem *item = FindItem( wxApp::s_macExitMenuItemId , NULL ) ;
        if ( item != NULL && !(item->IsEnabled()) )
            DisableMenuCommand( NULL , kHICommandQuit ) ;
        else
            EnableMenuCommand( NULL , kHICommandQuit ) ;
    }
#endif

    wxMenuList::compatibility_iterator menuIter = m_menus.GetFirst();
    for (size_t i = 0; i < m_menus.GetCount(); i++, menuIter = menuIter->GetNext())
    {
        wxMenuItemList::compatibility_iterator node;
        wxMenuItem *item;
        wxMenu* menu = menuIter->GetData() , *subMenu = NULL ;

        if ( m_titles[i] == wxT("?") || m_titles[i] == wxT("&?")  || m_titles[i] == wxApp::s_macHelpMenuTitleName )
        {
            for (node = menu->GetMenuItems().GetFirst(); node; node = node->GetNext())
            {
                item = (wxMenuItem *)node->GetData();
                subMenu = item->GetSubMenu() ;
                if (subMenu)
                {
                    // we don't support hierarchical menus in the help menu yet
                }
                else
                {
                    if ( item->GetId() != wxApp::s_macAboutMenuItemId )
                    {
                        if ( mh == NULL )
                        {
                            MenuItemIndex firstUserHelpMenuItem ;
                            if ( UMAGetHelpMenu( &mh , &firstUserHelpMenuItem) != noErr )
                            {
                                mh = NULL ;
                                break ;
                            }
                        }
                    }

                    if ( item->IsSeparator() )
                    {
                        if ( mh )
                            AppendMenuItemTextWithCFString( mh,
                                CFSTR(""), kMenuItemAttrSeparator, 0,NULL); 
                    }
                    else
                    {
                        wxAcceleratorEntry*
                            entry = wxAcceleratorEntry::Create( item->GetText() ) ;

                        if ( item->GetId() == wxApp::s_macAboutMenuItemId )
                        {
                            // this will be taken care of below
                        }
                        else
                        {
                            if ( mh )
                            {
                                UMAAppendMenuItem(mh, wxStripMenuCodes(item->GetText()) , wxFont::GetDefaultEncoding(), entry);
                                SetMenuItemCommandID( mh , CountMenuItems(mh) , wxIdToMacCommand ( item->GetId() ) ) ;
                                SetMenuItemRefCon( mh , CountMenuItems(mh) , (URefCon) item ) ;
                            }
                        }

                        delete entry ;
                    }
                }
            }
        }
        else
        {
            UMASetMenuTitle( MAC_WXHMENU(menu->GetHMenu()) , m_titles[i], m_font.GetEncoding()  ) ;
            menu->MacBeforeDisplay(false) ;
            ::InsertMenu(MAC_WXHMENU(_wxMenuAt(m_menus, i)->GetHMenu()), 0);
        }
    }

    // take care of the about menu item wherever it is
    {
        wxMenu* aboutMenu ;
        wxMenuItem *aboutMenuItem = FindItem(wxApp::s_macAboutMenuItemId , &aboutMenu) ;
        if ( aboutMenuItem )
        {
            wxAcceleratorEntry*
                entry = wxAcceleratorEntry::Create( aboutMenuItem->GetText() ) ;
            UMASetMenuItemText( GetMenuHandle( kwxMacAppleMenuId ) , 1 , wxStripMenuCodes ( aboutMenuItem->GetText() ) , wxFont::GetDefaultEncoding() );
            UMAEnableMenuItem( GetMenuHandle( kwxMacAppleMenuId ) , 1 , true );
            SetMenuItemCommandID( GetMenuHandle( kwxMacAppleMenuId ) , 1 , kHICommandAbout ) ;
            SetMenuItemRefCon(GetMenuHandle( kwxMacAppleMenuId ) , 1 , (URefCon)aboutMenuItem ) ;
            UMASetMenuItemShortcut( GetMenuHandle( kwxMacAppleMenuId ) , 1 , entry ) ;
        }
    }

    if ( GetAutoWindowMenu() )
    {
        if ( MacGetWindowMenuHMenu() == NULL )
            CreateStandardWindowMenu( 0 , (MenuHandle*) &s_macWindowMenuHandle ) ;

        InsertMenu( (MenuHandle) MacGetWindowMenuHMenu() , 0 ) ;
    }

    ::DrawMenuBar() ;
    s_macInstalledMenuBar = this;
}
Example #14
0
wxSize wxStaticText::DoGetBestSize() const
{
    Rect bestsize = { 0 , 0 , 0 , 0 } ;
    Point bounds;
    
    // try the built-in best size if available
    Boolean former = m_peer->GetData<Boolean>( kControlStaticTextIsMultilineTag);
    m_peer->SetData( kControlStaticTextIsMultilineTag, (Boolean)0 );
    m_peer->GetBestRect( &bestsize ) ;
    m_peer->SetData( kControlStaticTextIsMultilineTag, former );
    if ( !EmptyRect( &bestsize ) )
    {
        bounds.h = bestsize.right - bestsize.left ;
        bounds.v = bestsize.bottom - bestsize.top ;
    }
    else
    {
        ControlFontStyleRec controlFont;
        OSStatus err = m_peer->GetData<ControlFontStyleRec>( kControlEntireControl, kControlFontStyleTag, &controlFont );
        verify_noerr( err );

        SInt16 baseline;
        wxMacCFStringHolder str( m_label,  m_font.GetEncoding() );

#ifndef __LP64__
        if ( m_font.MacGetThemeFontID() != kThemeCurrentPortFont )
        {
            err = GetThemeTextDimensions(
                (!m_label.empty() ? (CFStringRef)str : CFSTR(" ")),
                m_font.MacGetThemeFontID(), kThemeStateActive, false, &bounds, &baseline );
            verify_noerr( err );
        }
        else
#endif
        {
    #if wxMAC_USE_CORE_GRAPHICS
            wxClientDC dc(const_cast<wxStaticText*>(this));
            wxCoord width, height ;
            dc.GetTextExtent( m_label , &width, &height);
            bounds.h = width;
            bounds.v = height;
    #else
            wxMacWindowStateSaver sv( this );
            ::TextFont( m_font.MacGetFontNum() );
            ::TextSize( (short)(m_font.MacGetFontSize()) );
            ::TextFace( m_font.MacGetFontStyle() );

            err = GetThemeTextDimensions(
                (!m_label.empty() ? (CFStringRef)str : CFSTR(" ")),
                kThemeCurrentPortFont, kThemeStateActive, false, &bounds, &baseline );
            verify_noerr( err );
    #endif
        }

        if ( m_label.empty() )
            bounds.h = 0;
    }
    bounds.h += MacGetLeftBorderSize() + MacGetRightBorderSize();
    bounds.v += MacGetTopBorderSize() + MacGetBottomBorderSize();

    return wxSize( bounds.h, bounds.v );
}
Example #15
0
/*
	Event handler for the content view that gets attached to the menu frame.

	The content view will (eventually) contain the menu view.
*/
OSStatus ContentViewEventHandler(
	EventHandlerCallRef inCallRef,
	EventRef inEvent,
	void *refcon)
{
	OSStatus retVal = eventNotHandledErr;
	if(GetEventClass(inEvent) == kEventClassMenu) {
		return noErr;
	} else
	if(GetEventClass(inEvent) == kEventClassControl) {
		HIViewRef hiSelf = NULL;
		verify_noerr(GetEventParameter(inEvent, kEventParamDirectObject, typeControlRef, NULL, sizeof(hiSelf), NULL, &hiSelf));

		if(hiSelf) {
			HIRect frame;
			HIViewGetFrame(hiSelf, &frame);

			switch(GetEventKind(inEvent)) {
				case kEventControlAddedSubControl : {
					HIViewRef subControl;
					ControlID subControlID;

					GetEventParameter(inEvent, kEventParamControlSubControl, typeControlRef, NULL, sizeof(subControl), NULL, &subControl );
					GetControlID(subControl, &subControlID);

					// This should be comparing against kHIViewMenuContentID as shown inside the
					// #if 0. At the time of this writing, however, using that constant causes a
					// linker error (and a crash if you use ZeroLink).  I extracted the signature
					// and id by determining the value at run-time the value I compare against.
#if 0
					if( kHIViewMenuContentID.signature == subControlID.signature && kHIViewMenuContentID.id == subControlID.id ) {
#else
					if( 'menu' == subControlID.signature && 0 == subControlID.id ) {
#endif
						// If we have the menu content view then set up some view bindings for it.
						HIRect bounds;
						HIViewGetBounds(hiSelf, &bounds);
						HIViewSetFrame(subControl, &bounds);

						HILayoutInfo contentLayout = {
							kHILayoutInfoVersionZero,
							{
								{ NULL, kHILayoutBindTop },
								{ NULL, kHILayoutBindLeft },
								{ NULL, kHILayoutBindBottom },
								{ NULL, kHILayoutBindRight }
							},
							{
								{ NULL, kHILayoutScaleAbsolute, 0 },
								{ NULL, kHILayoutScaleAbsolute, 0 }
							},
							{
								{ NULL, kHILayoutPositionTop, 0 },
								{ NULL, kHILayoutPositionLeft, 0 }
							}
						};

						verify_noerr(HIViewSetLayoutInfo(subControl, &contentLayout));
					}

					retVal = noErr;
				} break;

				case kEventControlGetFrameMetrics :
					HIViewFrameMetrics metrics;

					// The offset from the frame view to the content view is 
					// given by the kFrameOffset constant
					metrics.top = kFrameOffset;
					metrics.left = kFrameOffset;
					metrics.right = kFrameOffset;
					metrics.bottom = kFrameOffset;

					verify_noerr(SetEventParameter(inEvent, kEventParamControlFrameMetrics, typeControlFrameMetrics, sizeof(metrics), &metrics));

					retVal = noErr;
				break;

				case kEventControlBoundsChanged :
				case kEventControlOwningWindowChanged : {
					// Maintain the QuickDraw port by changing its position to
					// match that of the content view.
					CGrafPtr windowPort = NULL;
					WindowRef window = GetControlOwner(hiSelf);

					if(window && (windowPort = GetWindowPort(window))) {
						CGrafPtr savePort;
						bool swapped = QDSwapPort(windowPort, &savePort);

						MovePortTo((short) frame.origin.x, (short) frame.origin.y);
						PortSize((short) frame.size.width, (short) frame.size.height);

						if(swapped) {
							QDSwapPort(savePort, NULL);
						}
					}

					retVal = noErr;
				} break;
			} // switch
		} // if (hiSelf)
	}

	return retVal;
}


/* ------------------------------------------ CreatePathForEntireStarMenu */
/*
	Create a path shape for the star frame.
	
	This looks an awful lot like CreatePathForEntireStarMenu in
	StarMenu.cpp but takes the radius to use as a parameter and
	then takes into account the kFrameOffest when creating the path.

	In true Core Foundation style, this is a CreateXXX routine and the
	caller is responsible for freeing the path that is returned.
*/
CGPathRef CreatePathForStarFrame(StarFrameData *menuData, float radius)
{
   CGMutablePathRef retVal = CGPathCreateMutable();
   MenuItemIndex numItems = CountMenuItems(menuData->menu);

   if(numItems > 0) {
	  const CGPoint fullRadiusPoint = { radius, 0 };
	  const CGPoint halfRadiusPoint = { ((radius - kFrameOffset) / 2.0) + kFrameOffset , 0 };

	  float   anglePerItem = 2 * pi / (float)numItems;   // in radians naturally
	  float   halfAngle = anglePerItem / 2.0;

	  CGPoint startPoint = halfRadiusPoint;
	  CGAffineTransform midRotate = CGAffineTransformMakeRotation(halfAngle);
	  CGPoint midPoint = CGPointApplyAffineTransform(fullRadiusPoint, midRotate);

	  CGAffineTransform rotateToNext = CGAffineTransformMakeRotation(anglePerItem);

	  CGPathMoveToPoint(retVal, NULL, startPoint.x, startPoint.y);
	  CGPathAddLineToPoint(retVal, NULL, midPoint.x, midPoint.y);

	  for(short ctr = 0; ctr < numItems; ctr++) {
		 startPoint = CGPointApplyAffineTransform(startPoint, rotateToNext);
		 midPoint = CGPointApplyAffineTransform(midPoint, rotateToNext);

		 CGPathAddLineToPoint(retVal, NULL, startPoint.x, startPoint.y);
		 CGPathAddLineToPoint(retVal, NULL, midPoint.x, midPoint.y);
	  }

	  CGPathCloseSubpath(retVal);
   }

   return retVal;
}
Example #16
0
void wxMacDataItemBrowserControl::SetSelectedItem(wxMacDataItem* item , DataBrowserSetOption option)
{
    verify_noerr(wxMacDataBrowserControl::SetSelectedItems( 1, (DataBrowserItemID*) &item, option ));
}
Example #17
0
bool wxIcon::LoadFile(
    const wxString& filename, wxBitmapType type,
    int desiredWidth, int desiredHeight )
{
    UnRef();

    if ( type == wxBITMAP_TYPE_ICON_RESOURCE )
    {
        OSType theId = 0 ;

        if ( filename == wxT("wxICON_INFORMATION") )
        {
            theId = kAlertNoteIcon ;
        }
        else if ( filename == wxT("wxICON_QUESTION") )
        {
            theId = kAlertCautionIcon ;
        }
        else if ( filename == wxT("wxICON_WARNING") )
        {
            theId = kAlertCautionIcon ;
        }
        else if ( filename == wxT("wxICON_ERROR") )
        {
            theId = kAlertStopIcon ;
        }
        else
        {
#if 0
            Str255 theName ;
            OSType theType ;
            wxMacStringToPascal( name , theName ) ;

            Handle resHandle = GetNamedResource( 'cicn' , theName ) ;
            if ( resHandle != 0L )
            {
                GetResInfo( resHandle , &theId , &theType , theName ) ;
                ReleaseResource( resHandle ) ;
            }
#endif
        }

        if ( theId != 0 )
        {
            IconRef iconRef = NULL ;
            verify_noerr( GetIconRef( kOnSystemDisk, kSystemIconsCreator, theId, &iconRef ) ) ;
            if ( iconRef )
            {
                m_refData = new wxIconRefData( (WXHICON) iconRef ) ;

                return true ;
            }
        }

        return false ;
    }
    else
    {
        wxBitmapHandler *handler = wxBitmap::FindHandler( type );

        if ( handler )
        {
            wxBitmap bmp ;
            if ( handler->LoadFile( &bmp , filename, type, desiredWidth, desiredHeight ))
            {
                CopyFromBitmap( bmp ) ;

                return true ;
            }

            return false ;
        }
        else
        {
#if wxUSE_IMAGE
            wxImage loadimage( filename, type );
            if (loadimage.Ok())
            {
                if ( desiredWidth == -1 )
                    desiredWidth = loadimage.GetWidth() ;
                if ( desiredHeight == -1 )
                    desiredHeight = loadimage.GetHeight() ;
                if ( desiredWidth != loadimage.GetWidth() || desiredHeight != loadimage.GetHeight() )
                    loadimage.Rescale( desiredWidth , desiredHeight ) ;

                wxBitmap bmp( loadimage );
                CopyFromBitmap( bmp ) ;

                return true;
            }
#endif
        }
    }
    return true ;
}
Example #18
0
void wxMacDataItemBrowserControl::SetSelectedAllItems(DataBrowserSetOption option)
{
    verify_noerr(wxMacDataBrowserControl::SetSelectedItems( 0 , NULL , option ));
}
Example #19
0
 void SetLabel(const wxString& title, wxFontEncoding encoding)
 {
     wxCFStringRef str( title, encoding );
     OSStatus err = SetData<CFStringRef>(kControlEntireControl, kControlStaticTextCFStringTag, str);
     verify_noerr( err );
 }
Example #20
0
void wxMacDataItemBrowserControl::RevealItem( wxMacDataItem* item, DataBrowserRevealOptions options)
{
    verify_noerr(wxMacDataBrowserControl::RevealItem( (DataBrowserItemID) item, kDataBrowserNoItem , options ) );
}
Example #21
0
//---------------------------------------------------------------------
// Gets a file to save from the user. Caller must release the CFURLRef.
//
CFURLRef GetSaveFileFromUser(WindowRef window)
{
	CFURLRef previousFile;
	CFStringRef saveFileName;
	UniChar *chars = NULL;
    CFIndex length;
	NavDialogCreationOptions dialogOptions;
	NavDialogRef dialog;
	NavReplyRecord replyRecord;
	CFURLRef fileAsCFURLRef = NULL;
	FSRef fileAsFSRef;
	FSRef parentDirectory;
	OSStatus status;

	if ( window == NULL ) return NULL;

	// Get the standard set of defaults
	status = NavGetDefaultDialogCreationOptions(&dialogOptions);
	require_noerr( status, CantGetNavOptions );

	// Change a few things (app-wide modal, show the extension)
	dialogOptions.modality = kWindowModalityAppModal;
	dialogOptions.parentWindow = window;
	dialogOptions.optionFlags = kNavDefaultNavDlogOptions | kNavPreserveSaveFileExtension;

	// Set up the default save name
	previousFile = GetWindowProxyFileCFURL(window);
	if (previousFile == NULL)
		dialogOptions.saveFileName = CFStringCreateWithCString(NULL, "Untitled.rtf", kCFStringEncodingASCII);
	else	
		dialogOptions.saveFileName = CFURLCopyLastPathComponent(previousFile);

	// Create the dialog
	status = NavCreatePutFileDialog(&dialogOptions, kUnknownType, kUnknownType, NULL, NULL, &dialog);
	require_noerr( status, CantCreateDialog );

	// Show it
	status = NavDialogRun(dialog);
	require_noerr( status, CantRunDialog );
	
	// Get the reply
	status = NavDialogGetReply(dialog, &replyRecord);
	require( ((status == noErr) || (status == userCanceledErr)), CantGetReply );

	// If the user clicked "Cancel", just bail
	if ( status == userCanceledErr ) goto UserCanceled;

	// Get the file's location and name
	status = AEGetNthPtr(&(replyRecord.selection), 1, typeFSRef, NULL, NULL, &parentDirectory, sizeof(FSRef), NULL);
	require_noerr( status, CantExtractFSRef );

	saveFileName = replyRecord.saveFileName;
    length = CFStringGetLength(saveFileName);
	chars = malloc(length * sizeof(UniChar));
	CFStringGetCharacters(saveFileName, CFRangeMake(0, length), chars);

    // If we are replacing a file, erase the previous one
    if ( replyRecord.replacing ) {

		status = FSMakeFSRefUnicode(&parentDirectory, length, chars, kTextEncodingUnknown, &fileAsFSRef);
		require_noerr( status, CantMakeFSRef );

        status = FSDeleteObject(&fileAsFSRef);
		require_noerr( status, CantDeletePreviousFile );
    }

    // Create the file
	status = FSCreateFileUnicode(&parentDirectory, length, chars, kFSCatInfoNone, NULL, &fileAsFSRef, NULL);
	require_noerr( status, CantCreateSaveFile );

	// Convert the reference to the file to a CFURL
	fileAsCFURLRef = CFURLCreateFromFSRef(NULL, &fileAsFSRef);

	// Cleanup
CantCreateSaveFile:
CantDeletePreviousFile:
CantMakeFSRef:
	if ( chars != NULL ) free(chars);
CantExtractFSRef:
UserCanceled:
	verify_noerr( NavDisposeReply(&replyRecord) );
CantGetReply:
CantRunDialog:
	NavDialogDispose(dialog);
CantCreateDialog:
	if (previousFile) CFRelease(previousFile);
	CFRelease(dialogOptions.saveFileName);
CantGetNavOptions:
    return fileAsCFURLRef;
}
Example #22
0
void wxMacDataItemBrowserControl::GetSelectionAnchor( wxMacDataItemPtr* first , wxMacDataItemPtr* last) const
{
    verify_noerr(wxMacDataBrowserControl::GetSelectionAnchor( (DataBrowserItemID*) first, (DataBrowserItemID*) last) );
}
Example #23
0
//-----------------------------------------------------------------------------
// wxDockEventHandler
//
// This is the global Mac/Carbon event handler for the dock.
// We need this for two reasons:
// 1) To handle wxTaskBarIcon menu events (see below for why)
// 2) To handle events from the dock when it requests a menu
//-----------------------------------------------------------------------------
pascal OSStatus
wxDockEventHandler(EventHandlerCallRef WXUNUSED(inHandlerCallRef),
                   EventRef inEvent,
                   void *pData)
{
    // Get the parameters we want from the event
    wxDockTaskBarIcon* pTB = (wxDockTaskBarIcon*) pData;
    const UInt32 eventClass = GetEventClass(inEvent);
    const UInt32 eventKind = GetEventKind(inEvent);

    OSStatus err = eventNotHandledErr;

    // Handle wxTaskBar menu events (note that this is a global event handler
    // so it will actually get called by all commands/menus)
    if ((eventClass == kEventClassCommand) && (eventKind == kEventCommandProcess || eventKind == kEventCommandUpdateStatus ))
    {
        // if we have no taskbar menu quickly pass it back to wxApp
        if (pTB->m_pMenu != NULL)
        {
            // This is the real reason why we need this. Normally menus
            // get handled in wxMacAppEventHandler
            // However, in the case of a taskbar menu call
            // command.menu.menuRef IS NULL!
            // Which causes the wxApp handler just to skip it.

            // get the HICommand from the event
            HICommand command;
            if (GetEventParameter(inEvent, kEventParamDirectObject,
                typeHICommand, NULL,sizeof(HICommand), NULL, &command ) == noErr)
            {
                // Obtain the REAL menuRef and the menuItemIndex in the real menuRef
                //
                // NOTE: menuRef is generally used here for submenus, as
                // GetMenuItemRefCon could give an incorrect wxMenuItem if we pass
                // just the top level wxTaskBar menu
                MenuItemIndex menuItemIndex;
                MenuRef menuRef;
                MenuRef taskbarMenuRef = MAC_WXHMENU(pTB->m_pMenu->GetHMenu());

                // the next command is only successful if it was a command from the taskbar menu
                // otherwise we pass it on
                if (GetIndMenuItemWithCommandID(taskbarMenuRef,command.commandID,
                    1, &menuRef, &menuItemIndex ) == noErr)
                {
                    wxMenu* itemMenu = wxFindMenuFromMacMenu( menuRef ) ;
                    int id = wxMacCommandToId( command.commandID ) ;
                    wxMenuItem *item = NULL;

                    if (id != 0) // get the wxMenuItem reference from the MenuRef
                        GetMenuItemRefCon( menuRef, menuItemIndex, (URefCon*) &item );

                    if (item && itemMenu )
                    {
                        if ( eventKind == kEventCommandProcess )
                        {
                            if ( itemMenu->HandleCommandProcess( item ) )
                                err = noErr;
                        }
                        else if ( eventKind == kEventCommandUpdateStatus )
                        {
                            if ( itemMenu->HandleCommandUpdateStatus( item ) )
                                err = noErr;
                        }
                    }
                }
            }
        } //end if noErr on getting HICommand from event
    }
    else if ((eventClass == kEventClassApplication) && (eventKind == kEventAppGetDockTileMenu ))
    {
        // process the right click events
        // NB: This may result in double or even triple-creation of the menus
        // We need to do this for 2.4 compat, however
        wxTaskBarIconEvent downevt(wxEVT_TASKBAR_RIGHT_DOWN, NULL);
        pTB->m_parent->ProcessEvent(downevt);

        wxTaskBarIconEvent upevt(wxEVT_TASKBAR_RIGHT_UP, NULL);
        pTB->m_parent->ProcessEvent(upevt);

        // create popup menu
        wxMenu* menu = pTB->DoCreatePopupMenu();

        if (menu != NULL)
        {
            // note to self - a MenuRef *is* a MenuHandle
            MenuRef hMenu = MAC_WXHMENU(menu->GetHMenu());

            // When SetEventParameter is called it will decrement
            // the reference count of the menu - we need to make
            // sure it stays around in the wxMenu class here
            CFRetain(hMenu);

            // set the actual dock menu
            err = SetEventParameter(
                inEvent, kEventParamMenuRef,
                typeMenuRef, sizeof(MenuRef), &hMenu );
            verify_noerr( err );
        }
    }

    return err;
}
Example #24
0
void	AUEditWindow::TimerProc(EventLoopTimerRef inTimer, void *inUserData)
{
	AUEditWindow *This = (AUEditWindow *)inUserData;
	verify_noerr(CloseComponent(This->mEditView));
	This->mEditView = NULL;
}
Example #25
0
AUEditWindow::~AUEditWindow()
{
	if (mEditView) verify_noerr(CloseComponent(mEditView));
}
Example #26
0
//-----------------------------------------------------------------------------
FILE* openFileDialog (const char* fileName, int dialogType, void* dataRef)
{																			//zz-osx debug
	FILE* filePtr = NULL;
	
	NavDialogCreationOptions dialogOptions;
	NavDialogRef dialog;
	NavReplyRecord replyRecord;
	CFURLRef fileAsCFURLRef = NULL;
	FSRef fileAsFSRef;
	OSStatus status;
	bool result = false;
	
	unsigned char filePath[1024];
	char msg[4096];
	
	// Get the standard set of defaults
	status = NavGetDefaultDialogCreationOptions (&dialogOptions);
	require_noerr( status, CantGetNavOptions );
	
	// Make the	window app-wide modal
	dialogOptions.modality = kWindowModalityAppModal;
	
	//	dialogOptions.location = fileName;
	
	// Create the dialog
	status = NavCreateGetFileDialog (&dialogOptions, NULL, NULL, NULL, NULL, NULL, &dialog);
	require_noerr( status, CantCreateDialog );
	
	// Show it
	status = NavDialogRun (dialog);
	require_noerr( status, CantRunDialog );
	
	// Get the reply
	status = NavDialogGetReply (dialog, &replyRecord);
	require( ((status == noErr) || (status == userCanceledErr)), CantGetReply );
	
	// If the user clicked "Cancel", just bail
	if ( status == userCanceledErr ) goto UserCanceled;
	
	// Get the file
	status = AEGetNthPtr ( &(replyRecord.selection), 1, typeFSRef, NULL, NULL, &fileAsFSRef, sizeof(FSRef), NULL);
	require_noerr( status, CantExtractFSRef );
	
	// Convert it to a CFURL
	fileAsCFURLRef = CFURLCreateFromFSRef(NULL, &fileAsFSRef);
	
	result = CFURLGetFileSystemRepresentation(fileAsCFURLRef, true, filePath, 1024);
	
	if (!result)
		npPostMsg("err 9824 - cannot convert file dialog path", kNPmsgErr, dataRef);
	else
	{
		// printf ("\nFile Path: %s\n", filePath);
		
		sprintf (msg, "%s", filePath);
		
		filePtr = fopen (msg, "r");
		
		if (filePtr != NULL)
		{
			sprintf (msg, "File Open: %s", filePath);
			npPostMsg (msg, kNPmsgCtrl, dataRef);
		}
		else
			npPostMsg ("err 2995 - File Pointer is NULL", kNPmsgErr, dataRef);
		
		return filePtr;
	}
	
	// Cleanup
CantExtractFSRef:
UserCanceled:
	verify_noerr( NavDisposeReply(&replyRecord) );
CantGetReply:
CantRunDialog:
	NavDialogDispose(dialog);
CantCreateDialog:
CantGetNavOptions:
	// return fileAsCFURLRef;	//part of original sample, does not apply here
	
	return NULL;
}
Example #27
0
void wxMacSearchFieldControl::SetDescriptiveText(const wxString& text)
{
    verify_noerr( HISearchFieldSetDescriptiveText(
                      m_controlRef,
                      wxCFStringRef( text, wxFont::GetDefaultEncoding() )));
}
Example #28
0
/*
	Handle events of kEventClassControl that get sent to the Frame
*/
OSStatus HandleStarFrameControlEvents(
	EventHandlerCallRef inCallRef,
	EventRef inEvent,
	StarFrameData* frameData)
{
	OSStatus retVal = eventNotHandledErr;

	switch(GetEventKind(inEvent)) {
		case kEventControlInitialize :
			retVal = HandleStarFrameInitialize(inCallRef, inEvent, frameData);
		break;

		case kEventControlOwningWindowChanged : {
			// We only want the star-shaped opaque area of our frame view to
			// draw.  Everything else should be transparent.  To accomplish that
			// we change the features of the owning window so that only the
			// content we draw shows up on screen
			WindowRef newWindow = GetControlOwner(frameData->hiSelf);
			HIWindowChangeFeatures(newWindow, 0, kWindowIsOpaque);
		} break;

		case kEventControlBoundsChanged : {
			retVal = HandleStarFrameBoundsChanged(inCallRef, inEvent, frameData);
		} break;

        case kEventControlDraw : {
			HIRect			bounds;
			CGContextRef	cgContext;

			HIViewGetBounds(frameData->hiSelf, &bounds);
			float radius = fmin(CGRectGetWidth(bounds) / 2.0, CGRectGetHeight(bounds) / 2.0);

			GetEventParameter(inEvent, kEventParamCGContextRef, typeCGContextRef, NULL, sizeof(cgContext), NULL, &cgContext );
			if(NULL != cgContext) {
				HIThemeMenuDrawInfo drawInfo;
				CGPathRef starPath = CreatePathForStarFrame(frameData, radius);

				drawInfo.version = 0;
				drawInfo.menuType = frameData->menuType;

				// HIThemeDrawMenuBackground is designed to draw the pin striped background
				// of standard menus.  Our menu is a star and so HIThemeDrawMenuBackground may not be
				// appropriate in this case.  Nevertheless, we'll draw the standard menu background for
				// this menu and clip it to a star.
				CGContextClearRect(cgContext, bounds);
				CGContextSaveGState(cgContext);
				CGContextTranslateCTM(cgContext, radius, radius);
				CGContextAddPath(cgContext, starPath);
				CGContextClip(cgContext);
				CGContextTranslateCTM(cgContext, -radius, -radius);
				HIThemeDrawMenuBackground(&bounds, &drawInfo, cgContext, kHIThemeOrientationNormal);
				CGContextRestoreGState(cgContext);

				// The pin striping looks a bit odd sort of floating out by itself.  We'll also add
				// a lovely gray line to help emphasize the boundary
				CGContextTranslateCTM(cgContext, radius, radius);
				CGContextAddPath(cgContext, starPath);
				CGContextSetRGBStrokeColor(cgContext, 0.8, 0.8, 0.8, 1.0);
				CGContextSetLineWidth(cgContext, 1.0);
				CGContextStrokePath(cgContext);
				
				CGPathRelease(starPath);
				starPath = NULL;
			}

			retVal = noErr;
		} break;

		// Mac OS X v10.4 introduced a Window Manager bug.
		// The workaround is to implement the kEventControlGetFrameMetrics handler.
		// Even after the bug is fixed, the workaround will not be harmful.
		case kEventControlGetFrameMetrics: {
			HIViewRef contentView = NULL;

			// If we can find our content view, ask it for our metrics
			verify_noerr(HIViewFindByID(frameData->hiSelf, kHIViewWindowContentID, &contentView));
			if(NULL != contentView) {
				retVal = SendEventToEventTargetWithOptions( inEvent, GetControlEventTarget( contentView ), kEventTargetDontPropagate );
			}
		} break;

		default:
		break;
	}

	return retVal;
}
Example #29
0
wxMacDataBrowserListControl::wxMacDataBrowserListControl( wxWindow *peer, const wxPoint& pos, const wxSize& size, long style)
    : wxMacDataItemBrowserControl( peer, pos, size, style )
{
    m_nextColumnId = 0 ;

    OSStatus err = noErr;
    m_clientDataItemsType = wxClientData_None;
    if ( style & wxLB_SORT )
        m_sortOrder = SortOrder_Text_Ascending;

    DataBrowserSelectionFlags  options = kDataBrowserDragSelect;
    if ( style & wxLB_MULTIPLE )
    {
        options |= kDataBrowserAlwaysExtendSelection | kDataBrowserCmdTogglesSelection;
    }
    else if ( style & wxLB_EXTENDED )
    {
        options |= kDataBrowserCmdTogglesSelection;
    }
    else
    {
        options |= kDataBrowserSelectOnlyOne;
    }
    err = SetSelectionFlags( options );
    verify_noerr( err );

    DataBrowserListViewColumnDesc columnDesc;
    columnDesc.headerBtnDesc.titleOffset = 0;
    columnDesc.headerBtnDesc.version = kDataBrowserListViewLatestHeaderDesc;

    columnDesc.headerBtnDesc.btnFontStyle.flags =
        kControlUseFontMask | kControlUseJustMask;

    columnDesc.headerBtnDesc.btnContentInfo.contentType = kControlNoContent;
    columnDesc.headerBtnDesc.btnFontStyle.just = teFlushDefault;
    columnDesc.headerBtnDesc.btnFontStyle.font = kControlFontViewSystemFont;
    columnDesc.headerBtnDesc.btnFontStyle.style = normal;
    columnDesc.headerBtnDesc.titleString = NULL;
/*
    columnDesc.headerBtnDesc.minimumWidth = 0;
    columnDesc.headerBtnDesc.maximumWidth = 10000;

    columnDesc.propertyDesc.propertyID = kTextColumnId;
    columnDesc.propertyDesc.propertyType = kDataBrowserTextType;
    columnDesc.propertyDesc.propertyFlags = kDataBrowserTableViewSelectionColumn;
    columnDesc.propertyDesc.propertyFlags |= kDataBrowserListViewTypeSelectColumn;

    verify_noerr( AddColumn( &columnDesc, kDataBrowserListViewAppendColumn ) );
*/
    columnDesc.headerBtnDesc.minimumWidth = 0;
    columnDesc.headerBtnDesc.maximumWidth = 0;
    columnDesc.propertyDesc.propertyID = kNumericOrderColumnId;
    columnDesc.propertyDesc.propertyType = kDataBrowserPropertyRelevanceRankPart;
    columnDesc.propertyDesc.propertyFlags = kDataBrowserTableViewSelectionColumn;
    columnDesc.propertyDesc.propertyFlags |= kDataBrowserListViewTypeSelectColumn;

    verify_noerr( AddColumn( &columnDesc, kDataBrowserListViewAppendColumn ) );

/*
    SetDataBrowserSortProperty( m_controlRef , kTextColumnId);
    if ( m_sortOrder == SortOrder_Text_Ascending )
    {
        SetDataBrowserSortProperty( m_controlRef , kTextColumnId);
        SetDataBrowserSortOrder( m_controlRef , kDataBrowserOrderIncreasing);
    }
    else
*/
    {
        SetDataBrowserSortProperty( m_controlRef , kNumericOrderColumnId);
        SetDataBrowserSortOrder( m_controlRef , kDataBrowserOrderIncreasing);
    }

    verify_noerr( AutoSizeColumns() );
    verify_noerr( SetHiliteStyle(kDataBrowserTableViewFillHilite ) );
    verify_noerr( SetHeaderButtonHeight( 0 ) );
    err = SetHasScrollBars( (style & wxHSCROLL) != 0 , true );
#if 0
    // shouldn't be necessary anymore under 10.2
    GetPeer()->SetData( kControlNoPart, kControlDataBrowserIncludesFrameAndFocusTag, (Boolean)false );
    GetPeer()->SetNeedsFocusRect( true );
#endif
}
OSStatus WindowEventHandler(EventHandlerCallRef inCaller, EventRef inEvent, void* inRefcon)
{
    OSStatus    err = eventNotHandledErr;
	WindowRef Ref;
    
    switch ( GetEventClass( inEvent ) )
    {
        case kEventClassCommand:
        {
            HICommandExtended cmd;
            verify_noerr( GetEventParameter( inEvent, kEventParamDirectObject, typeHICommand, NULL, sizeof( cmd ), NULL, &cmd ) );
            
            switch ( GetEventKind( inEvent ) )
            {
                case kEventCommandProcess:
                    switch ( cmd.commandID )
                    {
                        // Add your own command-handling cases here
                        
                        default:
                            break;
                    }
                    break;
            }
            break;
        }

		case kEventClassWindow:
			switch (GetEventKind(inEvent)) {
				case kEventWindowClose:{
//					kspi::IGUI* pGUI = (kspi::IGUI*)inRefcon;
//					pGUI->Destroy();
					// Hide window, but don't close it
					Ref = (WindowRef)inRefcon;

					::HideWindow(Ref);

					gpMainContext->WindowClosed((void*)Ref);

					return noErr;
				}
				case kEventWindowActivated:{
					Ref = (WindowRef)inRefcon;

					return noErr;
				}
				/*
				case kEventWindowDeactivated:{
					WindowRef Ref = (WindowRef)inRefcon;
					
					if(Ref == gWndZoom){
							::HideWindow(gWndZoom);
							//gbShowZoom = false;
						}
					break;
				
				}
				*/

				case kEventWindowBoundsChanged:
				{
					UInt32 Attributes;
					OSStatus err;

					err = GetEventParameter (inEvent, kEventParamAttributes, typeUInt32,
						NULL, sizeof(UInt32), NULL, &Attributes);

					if (!err) {
						if (Attributes & kWindowBoundsChangeSizeChanged) {
							// Window is being resized
							WindowRef Ref = (WindowRef)inRefcon;
							Rect rct;
							::GetWindowBounds(Ref, kWindowContentRgn, &rct);
							gpMainContext->SizeChanged(Ref, SSize(rct.right - rct.left+1, rct.bottom - rct.top+1));
							return noErr;
						}
						else if (Attributes & kWindowBoundsChangeOriginChanged) {
							// Window is being moved
						}
					}

					return noErr;
				}

				case kEventWindowCursorChange:
				{
					((CWindowOSX*)inRefcon)->SetCurrentMouseCursor();
				}
				return noErr;

		}
		break;

        default:
            break;
    }
    
    return err;
}