[PB Cocoa] Methods, Tips & Tricks

Mac OSX specific forum
jamirokwai
Enthusiast
Enthusiast
Posts: 772
Joined: Tue May 20, 2008 2:12 am
Location: Cologne, Germany
Contact:

Re: [PB Cocoa] Methods, Tips & Tricks

Post by jamirokwai »

Hi there,

quickly change the URL of the WebGadget:

Code: Select all

If OpenWindow(0, 270, 100, 600, 300, "WebGadget")
  WebGadget(0, 10, 10, 580, 280, "")
  CocoaMessage(0, GadgetID(0), "setMainFrameURL:$", @"http://www.purebasic.fr/")

  Repeat
  Until WaitWindowEvent() = #PB_Event_CloseWindow
EndIf
Regards,
JamiroKwai
jamirokwai
Enthusiast
Enthusiast
Posts: 772
Joined: Tue May 20, 2008 2:12 am
Location: Cologne, Germany
Contact:

Re: [PB Cocoa] Methods, Tips & Tricks

Post by jamirokwai »

Letting OS X fade the window... Start-value is current value.

Code: Select all

OpenWindow(0,100,100,400,400,"Fader")
fadeTo.CGFloat = 0.8
CocoaMessage(0, CocoaMessage(0, WindowID(0), "animator"), "setAlphaValue:@", @fadeTo)

Repeat
Until WaitWindowEvent() = #PB_Event_CloseWindow
Regards,
JamiroKwai
wilbert
PureBasic Expert
PureBasic Expert
Posts: 3870
Joined: Sun Aug 08, 2004 5:21 am
Location: Netherlands

Re: [PB Cocoa] Methods, Tips & Tricks

Post by wilbert »

To set the url of a WebGadget you can simply use SetGadgetText; there's no need to send a cocoa message.

The window fade is nice. :)
Is there any reference in the Apple docs about this ? I can't find it anywhere.
If it's not, it still is a nice code example but using private api can get an app rejected from the app store.
So that's why I'm just asking :wink:
Windows (x64)
Raspberry Pi OS (Arm64)
jamirokwai
Enthusiast
Enthusiast
Posts: 772
Joined: Tue May 20, 2008 2:12 am
Location: Cologne, Germany
Contact:

Re: [PB Cocoa] Methods, Tips & Tricks

Post by jamirokwai »

wilbert wrote:To set the url of a WebGadget you can simply use SetGadgetText; there's no need to send a cocoa message.
Yep. Just for fun... Just learning Cocoa in PB :wink:
wilbert wrote:The window fade is nice. :)
Is there any reference in the Apple docs about this ? I can't find it anywhere.
If it's not, it still is a nice code example but using private api can get an app rejected from the app store.
So that's why I'm just asking :wink:
See here: http://developer.apple.com/library/mac/ ... index.html
I assume, it's non-private :-)
Last edited by jamirokwai on Mon Apr 29, 2013 5:34 pm, edited 1 time in total.
Regards,
JamiroKwai
wilbert
PureBasic Expert
PureBasic Expert
Posts: 3870
Joined: Sun Aug 08, 2004 5:21 am
Location: Netherlands

Re: [PB Cocoa] Methods, Tips & Tricks

Post by wilbert »

jamirokwai wrote:See here: http://developer.apple.com/library/mac/ ... index.html
I assume, it's non-private :-)
Thanks. I was looking at the NSWindow reference. I added your fade example to the list on the first post.
Cocoa is fun :idea:
Windows (x64)
Raspberry Pi OS (Arm64)
jamirokwai
Enthusiast
Enthusiast
Posts: 772
Joined: Tue May 20, 2008 2:12 am
Location: Cologne, Germany
Contact:

Re: [PB Cocoa] Methods, Tips & Tricks

Post by jamirokwai »

Get parts of HTML from embedded WebGadget using JavaScript :-)

Code: Select all

If OpenWindow(0, 270, 100, 700, 330, "WebGadget")
  WebGadget(0, 10, 10, 700, 280, "")
  CocoaMessage(0, GadgetID(0), "setMainFrameURL:$", @"http://www.google.de")
  ButtonGadget(1, 10,300,160,20,"Get Source")
  ButtonGadget(2,180,300,160,20,"Get Head")
  ButtonGadget(3,350,300,160,20,"Get Body")
  ButtonGadget(4,520,300,160,20,"Get Title")

  Repeat
    event = WaitWindowEvent()
    If event = #PB_Event_Gadget 
      gadget = EventGadget()
      If gadget
        Select gadget
          Case 1 : URL$ = "document.documentElement.outerHTML;"                    ; Get whole Document (including <html>)
          Case 2 : URL$ = "document.getElementsByTagName('head')[0].innerHTML;"    ; Get Head-Part
          Case 3 : URL$ = "document.getElementsByTagName('body')[0].innerHTML;"    ; Get Body-Part
          Case 4 : URL$ = "document.getElementsByTagName('title')[0].innerHTML;"   ; Get Page-Title
        EndSelect

        NSString = CocoaMessage(0, GadgetID(0), "stringByEvaluatingJavaScriptFromString:$", @URL$)
        Debug PeekS(CocoaMessage(0, NSString, "UTF8String"), -1, #PB_UTF8)
      EndIf
    EndIf
    
  Until event = #PB_Event_CloseWindow
EndIf
Regards,
JamiroKwai
jamirokwai
Enthusiast
Enthusiast
Posts: 772
Joined: Tue May 20, 2008 2:12 am
Location: Cologne, Germany
Contact:

Re: [PB Cocoa] Methods, Tips & Tricks

Post by jamirokwai »

Move window animated to new coordinates...
Caveat: the Y-coordinate is calculated from bottom of screen, and to bottom pixel of window... Phew :-)

Code: Select all

If OpenWindow(0,100,100,400,400,"Move-Test")

  Global Frame.CGRect
  
  CocoaMessage(@frame, WindowID(WebWindow), "frame")
  
  Frame\origin\x = 100
  ; this will be from bottom of screen!
  ; correct calculation: ScreenHeight() - WindowHeight() - 100
  Frame\origin\y = 100
  Frame\size\width = 200
  Frame\size\height = 300
  
  CocoaMessage(0, CocoaMessage(0, WindowID(WebWindow), "animator"), "setFrame:@", @Frame, "display:", #YES) 
  
  Repeat
    event = WaitWindowEvent()
  Until event = #PB_Event_CloseWindow

  MessageRequester("Width: " + StrF(WindowWidth(0,#PB_Window_FrameCoordinate)),"Height: " + StrF(WindowHeight(0,#PB_Window_FrameCoordinate)))
EndIf
Regards,
JamiroKwai
jamirokwai
Enthusiast
Enthusiast
Posts: 772
Joined: Tue May 20, 2008 2:12 am
Location: Cologne, Germany
Contact:

Re: [PB Cocoa] Methods, Tips & Tricks

Post by jamirokwai »

Shardik and Wilbert wrote:Display an alert (MessageRequester with OK button) specifying a predefined icon:

Code: Select all

CocoaMessage(0, Alert, "setIcon:", CocoaMessage(0, Workspace, "iconForFileType:$", @Type))
You can replace this line with a custom image. It uses CoreImage, to load every image-format supported by OS X :-)

Code: Select all

CocoaMessage(0, Alert, "setIcon:@", LoadImageEx(#PB_Any,Type))
Needs this function by wilbert from http://www.purebasic.fr/english/viewtop ... 3&#p392073

Code: Select all

Procedure LoadImageEx(Image, Filename.s)
  Protected.i Result, Rep, Width, Height
  Protected Size.NSSize, Point.NSPoint
  CocoaMessage(@Rep, 0, "NSImageRep imageRepWithContentsOfFile:$", @Filename)
  If Rep
    CocoaMessage(@Width, Rep, "pixelsWide")
    CocoaMessage(@Height, Rep, "pixelsHigh")
    If Width And Height
      Size\width = Width
      Size\height = Height
      CocoaMessage(0, Rep, "setSize:@", @Size)
      Result = CreateImage(Image, Width, Height, 32 | #PB_Image_Transparent)
      If Result
        If Image = #PB_Any : Image = Result : EndIf
        CocoaMessage(0, ImageID(Image), "lockFocus")
        CocoaMessage(0, Rep, "drawAtPoint:@", @Point)
        CocoaMessage(0, ImageID(Image), "unlockFocus")
      EndIf
    EndIf  
  EndIf
  ProcedureReturn Result
EndProcedure
Edit: Remember to free the allocated image!
Regards,
JamiroKwai
User avatar
Shardik
Addict
Addict
Posts: 1989
Joined: Thu Apr 21, 2005 2:38 pm
Location: Germany

Re: [PB Cocoa] Methods, Tips & Tricks

Post by Shardik »

Display 16 different informations for each mounted volume (tested on MacOS X 10.8.4 with PB 5.11 x86 and x64 and in both ASCII and Unicode mode):
- Volume name
- Localized volume name
- Volume partition format
- Space total on volume
- Space free on volume
- Is renaming possible?
- Is possible icon visible?
- File size limit
- Is volume ejectable?
- Is volume removable?
- Is volume an internal one?
- Has volume been automatically mounted?
- Is volume a local one?
- Is volume read-only?
- Creation date of volume
- UUID key of volume

Code: Select all

EnableExplicit

Structure VolumeEntry
  KeyName.S
  Format.S
  ColumnTitle.S
  ColumnWidth.I
EndStructure

If OSVersion() <= #PB_OS_MacOSX_10_5
  MessageRequester("Info", "Sorry, but this program needs at least OS X 10.6 (Snow Leopard) !")
  End
ElseIf OSVersion() = #PB_OS_MacOSX_10_6
  MessageRequester("Info", "Sorry, but OS X 10.6 (Snow Leopard) is only able to obtain the data for the first 5 columns!")
EndIf

NewList Volume.VolumeEntry()

Procedure DisplayVolumeInfos()
  Shared Volume.VolumeEntry()

  Protected CellContent.S
  Protected Error.I
  Protected FileManager.I
  Protected Format.S
  Protected i.I
  Protected j.I
  Protected KeyArray.I
  Protected NumColumns.I = ListSize(Volume())
  Protected NumVolumes.I
  Protected RowContent.S
  Protected Size.Q
  Protected URL.I
  Protected URLArray.I
  Protected Value.I

  FirstElement(Volume())
  KeyArray = CocoaMessage(0, 0, "NSArray arrayWithObject:$", @Volume()\KeyName)
  NextElement(Volume())
  
  If KeyArray
    For i = 1 To ListSize(Volume()) - 1
      KeyArray = CocoaMessage(0, KeyArray, "arrayByAddingObject:$", @Volume()\KeyName)
      NextElement(Volume())
    Next
    
    FileManager = CocoaMessage(0, 0, "NSFileManager defaultManager")
    
    If FileManager
      URLArray = CocoaMessage(0, FileManager, "mountedVolumeURLsIncludingResourceValuesForKeys:", KeyArray, "options:", 0)
      
      If URLArray
        NumVolumes = CocoaMessage(0, URLArray, "count")
        
        If NumVolumes > 0
          For j = 0 To NumVolumes - 1
            URL = CocoaMessage(0, URLArray, "objectAtIndex:", j)
            
            If URL
              FirstElement(Volume())

              For i = 0 To NumColumns - 1
                CellContent = ""

                Select Volume()\Format
                  Case "B" ; Boolean NSNumber
                    If CocoaMessage(0, URL, "getResourceValue:", @Value, "forKey:$", @Volume()\KeyName, "error:", @Error) = #YES
                      If Value
                        If CocoaMessage(0, Value, "boolValue")
                          CellContent = "Yes"
                        Else
                          CellContent = "No"
                        EndIf
                      EndIf
                    EndIf
                  Case "D" ; NSDate
                    If CocoaMessage(0, URL, "getResourceValue:", @Value, "forKey:$", @Volume()\KeyName, "error:", @Error) = #YES
                      If Value <> 0
                        CellContent = Left(PeekS(CocoaMessage(0, CocoaMessage(0, Value, "description"), "UTF8String"), -1, #PB_UTF8), 10)
                      EndIf
                    EndIf
                  Case "Q" ; NSNumber (Quad)
                    If CocoaMessage(0, URL, "getResourceValue:", @Value, "forKey:$", @Volume()\KeyName, "error:", @Error) = #YES
                      If Value
                        CocoaMessage(@Size, Value, "unsignedLongLongValue")

                        If Volume()\KeyName = "NSURLVolumeMaximumFileSizeKey"
                          If Size >> 30 < 1024
                            CellContent = Str(Size >> 30 + 1) + " GB"
                          Else
                            CellContent = Str((Size >> 60) & $FFFFFFFFFFFFFFFF + 1) + " EB"
                          EndIf
                        Else
                          CellContent = StrF(Size / 1024 / 1024 / 1024, 2)
                        EndIf
                      EndIf
                    EndIf
                  Case "S" ; NSString
                    If CocoaMessage(0, URL, "getResourceValue:", @Value, "forKey:$", @Volume()\KeyName, "error:", @Error) = #YES
                      If Value <> 0
                        CellContent = UCase(PeekS(CocoaMessage(0, Value, "UTF8String"), -1, #PB_UTF8))
                      EndIf
                    EndIf
                  Case "U" ; NSURL
                    CellContent = PeekS(CocoaMessage(0, CocoaMessage(0, URL, "path"), "UTF8String"), -1, #PB_UTF8)
                    CellContent = StringField(CellContent, CountString(CellContent, "/") + 1, "/")

                    If CellContent = ""
                      CellContent = "/"
                    EndIf
                EndSelect

                If i = 0
                  RowContent = CellContent
                Else
                  RowContent + #LF$ + CellContent
                EndIf

                NextElement(Volume())
              Next i
            EndIf

            AddGadgetItem(0, -1, RowContent)
          Next j
        EndIf
      EndIf
    EndIf
  EndIf
EndProcedure

Define ColumnWidth.S
Define ColumnWidthTotal.I
Define i.I
Define KeyName.S

Read.S KeyName

While KeyName <> ""
  AddElement(Volume())
  Volume()\KeyName = KeyName
  Read.S Volume()\ColumnTitle
  Read.S Volume()\Format  
  Read.S ColumnWidth
  Volume()\ColumnWidth = Val(ColumnWidth)
  ColumnWidthTotal + Volume()\ColumnWidth + 3
  Read.S KeyName
Wend


OpenWindow(0, 0, 0, ColumnWidthTotal + 22, 247, "Volume infos", #PB_Window_SystemMenu | #PB_Window_ScreenCentered)
FirstElement(Volume())
ListIconGadget(0, 10, 10, WindowWidth(0) - 20, WindowHeight(0) - 20, Volume()\ColumnTitle, Volume()\ColumnWidth, #PB_ListIcon_GridLines)
NextElement(Volume())

For i = 1 To ListSize(Volume()) - 1
  AddGadgetColumn(0, i, Volume()\ColumnTitle, Volume()\ColumnWidth)
  NextElement(Volume())
Next

DisplayVolumeInfos()

Repeat
Until WaitWindowEvent() = #PB_Event_CloseWindow

End

DataSection
  Data.S "NSURLVolumeNameKey", "Volume name", "U", "150"
  Data.S "NSURLVolumeLocalizedNameKey", "Localized name", "U", "150"
  Data.S "NSURLVolumeLocalizedFormatDescriptionKey", "Partition format", "S", "215"
  Data.S "NSURLVolumeTotalCapacityKey", "Total [GB]", "Q", "55"
  Data.S "NSURLVolumeAvailableCapacityKey", "Free [GB]", "Q", "50"
  Data.S "NSURLVolumeSupportsRenamingKey", "Renamable", "B", "62"
  Data.S "NSURLVolumeIsBrowsableKey", "Icon visible", "B", "63"
  Data.S "NSURLVolumeMaximumFileSizeKey", "File size limit", "Q", "72"
  Data.S "NSURLVolumeIsEjectableKey", "Ejectable", "B", "50"
  Data.S "NSURLVolumeIsRemovableKey", "Removable", "B", "60"
  Data.S "NSURLVolumeIsInternalKey", "Internal", "B", "45"
  Data.S "NSURLVolumeIsAutomountedKey", "Automounted", "B", "74"
  Data.S "NSURLVolumeIsLocalKey", "Local", "B", "30"
  Data.S "NSURLVolumeIsReadOnlyKey", "Read only", "B", "55"
  Data.S "NSURLVolumeCreationDateKey", "Creation date", "D", "90"
  Data.S "NSURLVolumeUUIDStringKey", "UUID", "S", "300"
  Data.S ""
EndDataSection
Update 1: I had to change

Code: Select all

      CocoaMessage(0, KeyArray, "arrayByAddingObject:$", @Volume()\KeyName)
into

Code: Select all

      KeyArray = CocoaMessage(0, KeyArray, "arrayByAddingObject:$", @Volume()\KeyName)
because arrayByAddingObject: returns a new array that isn't guaranteed to be the same as the original. Therefore it's necassary to get the new array always into KeyArray. Thank you very much, Wilbert, for your kind PM pinpointing this error and explaining several alternatives, especially as it always worked the old way in all my tests.

Furthermore I changed the OS version check, so that on Snow Leopard this program will be run with the info that only the first 5 columns will be filled because the data for the other columns are only retrievable on at least Lion. On Leopard and older versions all data retrieving keywords are not supported and the program will be terminated with an info message!

Update 2: The column names for total and free volume space had to be swapped. Thank you for spotting that mistake, gwhuntoon!
Last edited by Shardik on Sat Jun 22, 2013 5:56 pm, edited 1 time in total.
gwhuntoon
New User
New User
Posts: 9
Joined: Sun Mar 03, 2013 2:50 pm
Location: Muskegon, MI USA

Re: [PB Cocoa] Methods, Tips & Tricks

Post by gwhuntoon »

:) Shardik, first off, awesome post. This will be very useful. Just one thing though, I think the volume free vs. total volume was mistyped and is swapped.

From this:

Code: Select all

  Data.S "NSURLVolumeAvailableCapacityKey", "Total [GB]", "Q", "55"
  Data.S "NSURLVolumeTotalCapacityKey", "Free [GB]", "Q", "50"
To this:

Code: Select all

  Data.S "NSURLVolumeAvailableCapacityKey", "Free [GB]", "Q", "55"
  Data.S "NSURLVolumeTotalCapacityKey", "Total [GB]", "Q", "50"
gwhuntoon
New User
New User
Posts: 9
Joined: Sun Mar 03, 2013 2:50 pm
Location: Muskegon, MI USA

Re: [PB Cocoa] Methods, Tips & Tricks

Post by gwhuntoon »

:oops: And actually I goofed and forgot to swap the column widths.

It should be this:

Code: Select all

  Data.S "NSURLVolumeAvailableCapacityKey", "Free [GB]", "Q", "50"
  Data.S "NSURLVolumeTotalCapacityKey", "Total [GB]", "Q", "55"
User avatar
Mindphazer
Enthusiast
Enthusiast
Posts: 341
Joined: Mon Sep 10, 2012 10:41 am
Location: Savoie

Re: [PB Cocoa] Methods, Tips & Tricks

Post by Mindphazer »

Never mind !
Terrific post Shardik, thank you !!
MacBook Pro 14" M1 Pro - 16 Gb - MacOS 14 - Iphone 15 Pro Max - iPad at home
...and unfortunately... Windows at work...
wilbert
PureBasic Expert
PureBasic Expert
Posts: 3870
Joined: Sun Aug 08, 2004 5:21 am
Location: Netherlands

Re: [PB Cocoa] Methods, Tips & Tricks

Post by wilbert »

A simple star rating example

Code: Select all

EnableExplicit

Enumeration
  #NSRelevancyLevelIndicatorStyle
  #NSContinuousCapacityLevelIndicatorStyle
  #NSDiscreteCapacityLevelIndicatorStyle
  #NSRatingLevelIndicatorStyle
EndEnumeration

Procedure CreateRatingIndicator(x, y, maxStars)
  Protected Indicator, Frame.NSRect, Value.d = maxStars
  Frame\origin\x = x
  Frame\origin\y = y
  Frame\size\width = maxStars * 13
  Frame\size\height = 13
  Indicator = CocoaMessage(0, CocoaMessage(0, 0, "NSLevelIndicator alloc"), "initWithFrame:@", @Frame)
  CocoaMessage(0, CocoaMessage(0, Indicator, "cell"), "setLevelIndicatorStyle:", #NSRatingLevelIndicatorStyle)
  CocoaMessage(0, Indicator, "setMaxValue:@", @Value)
  ProcedureReturn Indicator
EndProcedure

Global ContentView, RatingIndicator

If OpenWindow(0, 0, 0, 200, 100, "Rating example", #PB_Window_SystemMenu | #PB_Window_ScreenCentered)
  ContentView = CocoaMessage(0, WindowID(0), "contentView")
  
  SpinGadget(0, 10, 10, 50, 25, 0, 10, #PB_Spin_Numeric)
  RatingIndicator = CreateRatingIndicator(10, 50, 10)
  CocoaMessage(0, ContentView, "addSubview:", RatingIndicator)
  
  SetGadgetState(0, 6); 6 stars   
  
  Repeat
    CocoaMessage(0, RatingIndicator, "setIntValue:", GetGadgetState(0))   
  Until WaitWindowEvent() = #PB_Event_CloseWindow
  
EndIf
Windows (x64)
Raspberry Pi OS (Arm64)
User avatar
Danilo
Addict
Addict
Posts: 3037
Joined: Sat Apr 26, 2003 8:26 am
Location: Planet Earth

Re: [PB Cocoa] Methods, Tips & Tricks

Post by Danilo »

In addition to the tricks by wilbert and fsw, some more window fullscreen switches and a procedure to get window fullscreen state:

Code: Select all

;--[ Window fullscreen procedures ]----------------------------------------------------------------

Procedure EnableWindowFullscreenGadget(window)
    NewCollectionBehaviour = CocoaMessage(0, WindowID(window), "collectionBehavior") | $80
    CocoaMessage(0, WindowID(window), "setCollectionBehavior:", NewCollectionBehaviour)
EndProcedure

Procedure ToggleWindowFullscreen(window)
    CocoaMessage(0, WindowID(window), "toggleFullScreen:")
EndProcedure

Procedure EnterWindowFullscreen(window)
    CocoaMessage(0, WindowID(window), "enterFullScreenMode:")
EndProcedure

Procedure ExitWindowFullscreen(window)
    CocoaMessage(0, WindowID(window), "exitFullScreenMode:")
EndProcedure

Procedure IsWindowFullscreen(window)
    #NSFullScreenWindowMask = 1 << 14
    ProcedureReturn Bool( CocoaMessage(0, WindowID(window), "styleMask") & #NSFullScreenWindowMask )
EndProcedure

;--------------------------------------------------------------------------------------------------


Procedure.s BoolToYesNo(bool)
    If bool : ProcedureReturn "Yes" : Else : ProcedureReturn "No" : EndIf
EndProcedure

Macro UpdateText()
    SetGadgetText(4, "Fullscreen: " + BoolToYesNo(IsWindowFullscreen(0)) )
EndMacro

#WinFlags = #PB_Window_SystemMenu|#PB_Window_ScreenCentered|#PB_Window_SizeGadget|#PB_Window_MaximizeGadget|#PB_Window_MinimizeGadget|#PB_Window_Invisible

If OpenWindow(0, 0, 0, 220, 175, "Fullscreen Switch", #WinFlags)
    WindowBounds(0, 220, 175, #PB_Ignore, #PB_Ignore)
    
    EnableWindowFullscreenGadget(0)
    
    ;AddKeyboardShortcut(0,#PB_Shortcut_Control|#PB_Shortcut_Command|#PB_Shortcut_F,1) ; not required when using a menu
    
    CreateMenu(0,0)
    MenuTitle("View")
    MenuItem(1, "Toggle Fullscreen"  +Chr(9)+"Ctrl+Cmd+F") ; Standard OS X menu switch = Ctrl + Cmd + F
    
    ButtonGadget(0,10, 10,200,25,"Exit")
    ButtonGadget(1,10, 40,200,25,"Toggle fullscreen")
    ButtonGadget(2,10, 70,200,25,"Enter fullscreen")
    ButtonGadget(3,10,100,200,25,"Exit fullscreen")
    TextGadget  (4,10,140,200,25,"",#PB_Text_Center)
    
    HideWindow(0,#False)
    
    EnterWindowFullscreen(0)
    
    UpdateText()
    
    Repeat
        Select WaitWindowEvent()
            Case #PB_Event_CloseWindow
                End
            Case #PB_Event_Gadget
                Select EventGadget()
                    Case 0 : End
                    Case 1 : ToggleWindowFullscreen(0) : UpdateText()  ; Toggle fullscreen mode
                    Case 2 : EnterWindowFullscreen(0)  : UpdateText()  ; Enter  fullscreen mode
                    Case 3 : ExitWindowFullscreen(0)   : UpdateText()  ; Exit   fullscreen mode
                EndSelect
            Case #PB_Event_Menu
                Select EventMenu()
                    Case -1 : End
                    Case  1 : ToggleWindowFullscreen(0) : UpdateText() ; "Toggle fullscreen" menu update
                EndSelect
            Case #PB_Event_SizeWindow
                UpdateText()                                           ; Update fullscreen mode after resize
                                                                       ; ( catches fullscreen window button clicks )
        EndSelect
    ForEver  
EndIf
Ctrl+Cmd+F is used as default in most Mac OS X applications to toggle fullscreen mode.
User avatar
Danilo
Addict
Addict
Posts: 3037
Joined: Sat Apr 26, 2003 8:26 am
Location: Planet Earth

Re: [PB Cocoa] Methods, Tips & Tricks

Post by Danilo »

Some functions for getting name and size for PB's gadget fonts, etc.:

Code: Select all

EnableExplicit


Procedure.s PeekNSString(string)
    ;
    ; converts NSString to PB string
    ;
    #NSASCIIStringEncoding   = 1
    #NSUTF8StringEncoding    = 4
    #NSUnicodeStringEncoding = 10
    
    Protected result.s, length, *buffer
    If string
        length = CocoaMessage(0,string,"length")
        If length
            length + 1
            length * SizeOf(Character)
            *buffer = AllocateMemory(length)
            If *buffer
                CompilerIf #PB_Compiler_Unicode
                    CocoaMessage(0,string,"getCString:@",@*buffer,"maxLength:@",@length,"encoding:",#NSUnicodeStringEncoding)
                    result = PeekS(*buffer,-1,#PB_Unicode)
                CompilerElse
                    CocoaMessage(0,string,"getCString:@",@*buffer,"maxLength:@",@length,"encoding:",#NSASCIIStringEncoding)
                    result = PeekS(*buffer,-1,#PB_Ascii)
                CompilerEndIf
                FreeMemory(*buffer)
            EndIf
        EndIf
    EndIf
    ProcedureReturn result
EndProcedure


Procedure.s GetFontName(FontID)
    ;
    ; returns the font name of FontID
    ;
    Protected name.s, string
    If FontID
        string = CocoaMessage(0,FontID,"displayName") ; "familyName" and "fontName" for internal use
                                                      ; use "displayName" for the real name
        If string
            ProcedureReturn PeekNSString(string)
        EndIf
    EndIf
EndProcedure



Procedure.s GetDefaultFontName()
    ;
    ; returns the font name used for ButtonGadget()
    ;
    ; call at program start to get the default font name for PB gadgets
    ;
    Protected name.s
    Protected win = OpenWindow(#PB_Any,0,0,0,0,"",#PB_Window_Invisible)
    If win
        Protected btn = ButtonGadget(#PB_Any,0,0,0,0,"text") ; alternative: TextGadget()
        If btn
            name = GetFontName( GetGadgetFont(btn) )
            FreeGadget(btn)
        EndIf
        CloseWindow(win)
    EndIf
    ProcedureReturn name
EndProcedure


Procedure.CGFloat GetFontSize(FontID)
    ;
    ; returns the font size of FontID
    ;
    Protected pointSize.CGFloat = 0.0
    If FontID
        CocoaMessage(@pointSize,FontID,"pointSize")
    EndIf
    ProcedureReturn pointSize
EndProcedure


Procedure.CGFloat GetDefaultFontSize()
    ;
    ; returns the font size used for ButtonGadget()
    ;
    ; call at program start to get the default font size for PB gadgets
    ;
    Protected size.CGFloat = 0.0
    Protected win = OpenWindow(#PB_Any,0,0,0,0,"",#PB_Window_Invisible)
    If win
        Protected btn = ButtonGadget(#PB_Any,0,0,0,0,"text") ; alternative: TextGadget()
        If btn
            size = GetFontSize( GetGadgetFont(btn) )
            FreeGadget(btn)
        EndIf
        CloseWindow(win)
    EndIf
    ProcedureReturn size
EndProcedure


Procedure IsFontFixedPitch(FontID)
    ;
    ; returns true if FontID is a monospaced font
    ;
    If FontID
        ProcedureReturn CocoaMessage(0,FontID,"isFixedPitch")
    EndIf
EndProcedure


Procedure.CGFloat GetSystemFontSize()
    ;
    ; returns Mac OS X default system font size
    ;
    Protected size.CGFLoat = 0.0
    CocoaMessage(@size,0,"NSFont systemFontSize")
    ProcedureReturn size
EndProcedure


Procedure.CGFloat GetSmallSystemFontSize()
    ;
    ; returns Mac OS X default small system font size
    ;
    Protected size.CGFLoat = 0.0
    CocoaMessage(@size,0,"NSFont smallSystemFontSize")
    ProcedureReturn size
EndProcedure


Procedure.CGFloat GetLabelFontSize()
    ;
    ; returns Mac OS X default font size used for labels (TextGadget in PB)
    ;
    Protected size.CGFLoat = 0.0
    CocoaMessage(@size,0,"NSFont labelFontSize")
    ProcedureReturn size
EndProcedure



Debug "Default PB font:"
Debug GetDefaultFontName()
Debug GetDefaultFontSize()


Debug "System font sizes:"
Debug GetSystemFontSize()
Debug GetSmallSystemFontSize()
Debug GetLabelFontSize()
Output:

Code: Select all

Default PB font:
Lucida Grande
12.0
System font sizes:
13.0
11.0
10.0
PB 5.20 beta 7 x86 & x64, Unicode & ASCII mode, tetsted on Mac OS X 10.8.4
Post Reply