[PB Cocoa] Methods, Tips & Tricks

Mac OSX specific forum
WilliamL
Addict
Addict
Posts: 1224
Joined: Mon Aug 04, 2008 10:56 pm
Location: Seattle, USA

Re: [PB Cocoa] Methods, Tips & Tricks

Post by WilliamL »

Here is Fred's code (modified) to load files associated with an app. Remember that you have to set the plist to recognize your extension so the app loads first! See the original code here.

Code: Select all

ImportC ""
  PB_Gadget_SetOpenFinderFiles(Callback)
EndImport

IsGadget(0) ; Ensures the gadget lib is linked as this command is in it

ProcedureC OpenFinderFilesCallback(*Utf8Files)
    Protected filecnt,filesin$,filename$
    filesin$ = PeekS(*Utf8Files, -1, #PB_UTF8) ; Each file is separated by a 'tab'
    If Len(filesin$) ; Here you have the filename to open
        MessageRequester("Raw Load...",filesin$+" filecount="+Str(CountString(filesin$,Chr(9)))) ; Use StringField() to iterate easily
        For filecnt=1 To CountString(filesin$,Chr(9))+1
            filename$=StringField(filesin$,filecnt,Chr(9))
            filepath$=GetPathPart(filename$)
            filename$=GetFilePart(filename$)
            MessageRequester("Loading file...",filePath$+Chr(13)+filename$)
        Next
    EndIf
EndProcedure

PB_Gadget_SetOpenFinderFiles(@OpenFinderFilesCallback()) ; should be put very early in the code, before any event loop
MacBook Pro-M1 (2021), Sonoma 14.4.1, PB 6.10LTS M1
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 »

Get the OS version string

Code: Select all

Procedure.s OSVersionString()
  Protected.i ProcessInfo = CocoaMessage(0, 0, "NSProcessInfo processInfo")
  Protected.i OperatingSystemVersionString = CocoaMessage(0, ProcessInfo, "operatingSystemVersionString")
  Protected.i UTF8String = CocoaMessage(0, OperatingSystemVersionString, "UTF8String")
  ProcedureReturn PeekS(UTF8String, -1, #PB_UTF8)
EndProcedure

Debug OSVersionString()
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 »

In case you want to know what's behind a PureBasic gadget ...

Code: Select all

Procedure.s ObjectInheritance(Object)
  
  Protected.i Result
  Protected.i MutableArray = CocoaMessage(0, 0, "NSMutableArray arrayWithCapacity:", 10)
  
  Repeat
    CocoaMessage(0, MutableArray, "addObject:", CocoaMessage(0, Object, "className"))
    CocoaMessage(@Object, Object, "superclass")
  Until Object = 0
  
  CocoaMessage(@Result, MutableArray, "componentsJoinedByString:$", @"  -->  ")
  CocoaMessage(@Result, Result, "UTF8String")
  
  ProcedureReturn PeekS(Result, -1, #PB_UTF8)
  
EndProcedure


If OpenWindow(0, 0, 0, 220, 200, "Object Inheritance", #PB_Window_SystemMenu | #PB_Window_ScreenCentered)
  
  ButtonGadget(0, 10, 10, 200, 20, "Button")
  
  Debug ObjectInheritance(GadgetID(0))
  
  Repeat : Until WaitWindowEvent() = #PB_Event_CloseWindow
  
EndIf
I had a similar procedure in one of my libs but this one only uses the CocoaMessage command.
It can be very helpful if you want to find ways to interact with PureBasic gadgets.
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 »

Anti-aliased drawing onto an image using the NSColor, NSGradient and NSBezierPath classes.
(this also works on CanvasGadget when CanvasOutput(#Gadget) is used)

Code: Select all

; *** Create image and draw onto it ***

CreateImage(0, 300, 200, 32, #PB_Image_Transparent)

StartDrawing(ImageOutput(0))

Crayons = CocoaMessage(0, CocoaMessage(0, 0, "NSColorList colorListNamed:$", @"Crayons"), "retain")

ColorGreen = CocoaMessage(0, 0, "NSColor greenColor")
ColorBrown = CocoaMessage(0, 0, "NSColor brownColor")
ColorMocha = CocoaMessage(0, Crayons, "colorWithKey:$", @"Mocha")
CocoaMessage(0, ColorMocha, "setStroke"); set stroke color to Mocha

Gradient = CocoaMessage(0, 0, "NSGradient alloc"); create gradient from green to brown
CocoaMessage(@Gradient, Gradient, "initWithStartingColor:", ColorGreen, "endingColor:", ColorBrown)
CocoaMessage(0, Gradient, "autorelease") 
GradientAngle.CGFloat = 315

Rect.NSRect
Rect\origin\x = 5
Rect\origin\y = 5
Rect\size\width = 290
Rect\size\height = 190

RadiusX.CGFloat = 20
RadiusY.CGFloat = 20

Path = CocoaMessage(0, 0, "NSBezierPath bezierPathWithRoundedRect:@", @Rect, "xRadius:@", @RadiusX, "yRadius:@", @RadiusY)
CocoaMessage(0, Gradient, "drawInBezierPath:", Path, "angle:@", @GradientAngle)
CocoaMessage(0, Path, "stroke")

StopDrawing()


; *** Show the result ***

If OpenWindow(0, 0, 0, 320, 220, "Drawing", #PB_Window_SystemMenu | #PB_Window_ScreenCentered)
  
  ImageGadget(0, 10, 10, 300, 200, ImageID(0))
  
  Repeat
    Event = WaitWindowEvent()
  Until Event = #PB_Event_CloseWindow
  
EndIf
Last edited by wilbert on Thu Feb 06, 2014 9:13 am, edited 5 times in total.
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 »

Image load and catch (all OS X supported image types, for example bmp, gif, icns, ico, jpeg, jpeg2000, png, tga, tiff).

Code: Select all

CompilerIf Not Defined(vImage_Buffer, #PB_Structure)
  Structure vImage_Buffer
    *data
    height.i
    width.i
    rowBytes.i
  EndStructure
CompilerEndIf

ImportC "/System/Library/Frameworks/Accelerate.framework/Accelerate"
  vImageUnpremultiplyData_RGBA8888 (*src, *dest, flags) 
EndImport

Procedure LoadImageEx(Image, Filename.s)
  Protected.i Result, Rep, vImg.vImage_Buffer
  Protected Size.NSSize, Point.NSPoint
  CocoaMessage(@Rep, 0, "NSImageRep imageRepWithContentsOfFile:$", @Filename)
  If Rep
    Size\width = CocoaMessage(0, Rep, "pixelsWide")
    Size\height = CocoaMessage(0, Rep, "pixelsHigh")
    If Size\width And Size\height
      CocoaMessage(0, Rep, "setSize:@", @Size)
    Else
      CocoaMessage(@Size, Rep, "size")
    EndIf
    If Size\width And Size\height
      Result = CreateImage(Image, Size\width, Size\height, 32, #PB_Image_Transparent)
      If Result
        If Image = #PB_Any : Image = Result : EndIf
        StartDrawing(ImageOutput(Image))
        CocoaMessage(0, Rep, "drawAtPoint:@", @Point)
        If CocoaMessage(0, Rep, "hasAlpha")
          vImg\data = DrawingBuffer()
          vImg\width = OutputWidth()
          vImg\height = OutputHeight()
          vImg\rowBytes = DrawingBufferPitch()
          vImageUnPremultiplyData_RGBA8888(@vImg, @vImg, 0)
        EndIf
        StopDrawing()
      EndIf
    EndIf
  EndIf  
  ProcedureReturn Result
EndProcedure

Procedure CatchImageEx(Image, *MemoryAddress, MemorySize)
  Protected.i Result, DataObj, Class, Rep, vImg.vImage_Buffer
  Protected Size.NSSize, Point.NSPoint
  CocoaMessage(@DataObj, 0, "NSData dataWithBytesNoCopy:", *MemoryAddress, "length:", MemorySize, "freeWhenDone:", #NO)
  CocoaMessage(@Class, 0, "NSImageRep imageRepClassForData:", DataObj)
  If Class
    CocoaMessage(@Rep, Class, "imageRepWithData:", DataObj)
    If Rep
      Size\width = CocoaMessage(0, Rep, "pixelsWide")
      Size\height = CocoaMessage(0, Rep, "pixelsHigh")
      If Size\width And Size\height
        CocoaMessage(0, Rep, "setSize:@", @Size)
      Else
        CocoaMessage(@Size, Rep, "size")
      EndIf    
      If Size\width And Size\height
        Result = CreateImage(Image, Size\width, Size\height, 32, #PB_Image_Transparent)
        If Result
          If Image = #PB_Any : Image = Result : EndIf
          StartDrawing(ImageOutput(Image))
          CocoaMessage(0, Rep, "drawAtPoint:@", @Point)
          If CocoaMessage(0, Rep, "hasAlpha")
            vImg\data = DrawingBuffer()
            vImg\width = OutputWidth()
            vImg\height = OutputHeight()
            vImg\rowBytes = DrawingBufferPitch()
            vImageUnPremultiplyData_RGBA8888(@vImg, @vImg, 0)
          EndIf
          StopDrawing()
        EndIf
      EndIf
    EndIf
  EndIf
  ProcedureReturn Result
EndProcedure
Save image (Compression is only used for #NSJPEGFileType)

Code: Select all

Procedure SaveImageEx(Image, FileName.s, Type = #NSPNGFileType, Compression.f = 0.8)
  Protected c.i = CocoaMessage(0, 0, "NSNumber numberWithFloat:@", @Compression)
  Protected p.i = CocoaMessage(0, 0, "NSDictionary dictionaryWithObject:", c, "forKey:$", @"NSImageCompressionFactor")
  Protected imageReps.i = CocoaMessage(0, ImageID(Image), "representations")
  Protected imageData.i = CocoaMessage(0, 0, "NSBitmapImageRep representationOfImageRepsInArray:", imageReps, "usingType:", Type, "properties:", p)
  CocoaMessage(0, imageData, "writeToFile:$", @FileName, "atomically:", #NO)
EndProcedure
Example

Code: Select all

Image = LoadImageEx(#PB_Any, "MyIcon.icns")
To show a full list of supported types

Code: Select all

Debug PeekS(CocoaMessage(0, CocoaMessage(0, CocoaMessage(0, 0, "NSImage imageTypes"), "description"), "UTF8String"), -1, #PB_UTF8)
Last edited by wilbert on Fri Feb 19, 2016 7:39 pm, edited 15 times in total.
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 »

Recolor a button gadget using a Core Image Filter

Code: Select all

If OpenWindow(0, 0, 0, 220, 200, "CIFilter example", #PB_Window_SystemMenu | #PB_Window_ScreenCentered)
  
  ButtonGadget(0, 10, 10, 200, 30, "Button")
  
  Filter  = CocoaMessage(0, 0, "CIFilter filterWithName:$", @"CIColorMonochrome") ; create a CIColorMonochrome filter
  CocoaMessage(0, Filter, "setDefaults")                                          ; set the default values for the filter
  Color = CocoaMessage(0, 0, "CIColor colorWithString:$", @"1.0 0.7 0.3 1.0")     ; create a CIColor object from a RGBA string
  CocoaMessage(0, Filter, "setValue:", Color, "forKey:$", @"inputColor")          ; assign the color to the filter
  FilterArray = CocoaMessage(0, 0, "NSArray arrayWithObject:", Filter)            ; create an array with only the filter
  
  Button = GadgetID(0)
  CocoaMessage(0, Button, "setWantsLayer:", #YES)                                 ; the gadget needs a layer for the filter to work
  CocoaMessage(0, Button, "setContentFilters:", FilterArray)                      ; set the filter Array
  
  Repeat : Until WaitWindowEvent() = #PB_Event_CloseWindow
  
EndIf
Last edited by wilbert on Fri Oct 05, 2012 3:19 pm, edited 1 time in total.
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 »

Changing the application icon while running

Code: Select all

CreateImage(0, 64, 64, 32 | #PB_Image_Transparent)
StartDrawing(ImageOutput(0))
DrawingMode(#PB_2DDrawing_AlphaBlend)
Circle(32, 32, 30, $ffd0f080)
StopDrawing()

Application = CocoaMessage(0, 0, "NSApplication sharedApplication")
CocoaMessage(0, Application, "setApplicationIconImage:", ImageID(0))

MessageRequester("", "Icon set")
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 »

Working with Cocoa sound objects

Code: Select all

Procedure Sound_Load(FileName.s)
  ProcedureReturn CocoaMessage(0,CocoaMessage(0,0,"NSSound alloc"), "initWithContentsOfFile:$", @FileName, "byReference:", #YES)
EndProcedure

Procedure Sound_Catch(*MemoryAddress, Size)
  Protected Result.i = CocoaMessage(0, 0, "NSData dataWithBytes:", *MemoryAddress, "length:", Size)
  If Result : Result = CocoaMessage(0, CocoaMessage(0, 0, "NSSound alloc"), "initWithData:", Result) : EndIf
  ProcedureReturn Result
EndProcedure

Procedure Sound_SetVolume(SoundObject, Volume.f)
  CocoaMessage(0, SoundObject, "setVolume:@", @Volume)
EndProcedure

Procedure Sound_Play(SoundObject, Loop = 0)
  Protected currentTime.d
  CocoaMessage(0, SoundObject, "setLoops:", Loop)
  CocoaMessage(0, SoundObject, "setCurrentTime:@", @currentTime)
  ProcedureReturn CocoaMessage(0, SoundObject, "play")
EndProcedure

Procedure Sound_Stop(SoundObject)
  ProcedureReturn CocoaMessage(0, SoundObject, "stop")
EndProcedure

Procedure Sound_IsPlaying(SoundObject)
  ProcedureReturn CocoaMessage(0, SoundObject, "isPlaying")
EndProcedure

Procedure Sound_Release(SoundObject)
  CocoaMessage(0, SoundObject, "stop")
  CocoaMessage(0, SoundObject, "release")
EndProcedure
Example :

Code: Select all

MySound = Sound_Load("MySoundFile.mp3")
Sound_SetVolume(MySound, 0.8)
Sound_Play(MySound)
Last edited by wilbert on Sun Sep 13, 2015 3:07 pm, edited 1 time in total.
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 »

Toggle window attributes on and off:

Code: Select all

EnableExplicit

#NSTitledWindowMask             = 1 << 0
#NSClosableWindowMask           = 1 << 1
#NSMiniaturizableWindowMask     = 1 << 2
#NSResizableWindowMask          = 1 << 3
#NSTexturedBackgroundWindowMask = 1 << 8

Define ButtonID.I
Define ButtonState.I
Define ButtonText.S
Define i.I
Define NumButtons.I
Define WindowAttributeName.S
Define WindowAttributes.I

Dim WindowAttributeID.I(0)
Dim WindowAttributeName.S(0)

OpenWindow(0, 270, 100, 300, 260, "Toggle Window attributes", #PB_Window_SystemMenu | #PB_Window_Invisible)

; ----- Read the constant descriptions and its values into 2 arrays and create buttons

Repeat
  Read.S WindowAttributeName

  If WindowAttributeName = ""
    NumButtons = i
    Break
  Else
    ReDim WindowAttributeID(i)
    ReDim WindowAttributeName(i)
    WindowAttributeName(i) = WindowAttributeName
    Read.I WindowAttributeID(i)

    WindowAttributes = CocoaMessage(0, WindowID(0), "styleMask")

    If WindowAttributes & WindowAttributeID(i)
      ButtonText = "Disable "
    Else
      ButtonText = "Enable "
    EndIf

    ButtonGadget(i, 10, i * 30 + 10, WindowWidth(0) - 20, 25, ButtonText + WindowAttributeName(i))
    i + 1
  EndIf
ForEver

; ----- Adapt vertical size of window to display all buttons

ResizeWindow(0, #PB_Ignore, #PB_Ignore, #PB_Ignore, NumButtons * 30 + 10)
HideWindow(0, #False)

Repeat
  Select WaitWindowEvent()
    Case #PB_Event_CloseWindow
      Break
    Case #PB_Event_Gadget
      ButtonID = EventGadget()

      ; ----- Read current attributes of window
      WindowAttributes = CocoaMessage(0, WindowID(0), "styleMask")

      ; ----- Toggle the window attribute connected to the pressed button
      WindowAttributes ! WindowAttributeID(ButtonID)
      CocoaMessage(0, WindowID(0), "setStyleMask:", WindowAttributes)

      ; ----- Change the text of the button
      If WindowAttributes & WindowAttributeID(ButtonID)
        ButtonText = "Disable "
        ButtonState = #False
      Else
        ButtonText = "Enable "
        ButtonState = #True
      EndIf

      SetGadgetText(ButtonID, ButtonText + WindowAttributeName(ButtonID))

      Select WindowAttributeName(ButtonID)
        Case "titlebar"
          For i = 1 To NumButtons - 1
            DisableGadget(i, ButtonState)
          Next i
        Case "resizing of window"
          DisableGadget(0, ButtonState ! 1)
      EndSelect

      SetWindowTitle(0, "Toggle Window attributes")
  EndSelect
ForEver

End

DataSection
  Data.S "titlebar"
  Data.I #NSTitledWindowMask
  Data.S "closing of window"
  Data.I #NSClosableWindowMask
  Data.S "minimizing to dock"
  Data.I #NSMiniaturizableWindowMask
  Data.S "resizing of window"
  Data.I #NSResizableWindowMask
  Data.S "metal look"
  Data.I #NSTexturedBackgroundWindowMask
  Data.S ""
EndDataSection
Toggle window shadow on and off:

Code: Select all

OpenWindow(0, 270, 100, 200, 200, "Test")
ButtonGadget(0, 10, 90, 180, 25, "Toggle window's shadow")

Repeat
  Select WaitWindowEvent()
    Case #PB_Event_CloseWindow
      Break
    Case #PB_Event_Gadget
      If EventGadget() = 0 And EventType() = #PB_EventType_LeftClick
        ShadowState = CocoaMessage(0, WindowID(0), "hasShadow") ! 1
        CocoaMessage(0, WindowID(0), "setHasShadow:", ShadowState)
      EndIf
  EndSelect
ForEver
Toggle toolbar button on and off:

Code: Select all

If OSVersion() > #PB_OS_MacOSX_10_6
  MessageRequester("Error", "Sorry, but with MacOS X Lion the toolbar button was eliminated by Apple!")
  End
EndIf

OpenWindow(0, 270, 100, 200, 200, "Test")
ButtonGadget(0, 10, 90, 180, 25, "Toggle toolbar button")
CreateToolBar(0, WindowID(0))

Repeat
  Select WaitWindowEvent()
    Case #PB_Event_CloseWindow
      Break
    Case #PB_Event_Gadget
      If EventGadget() = 0 And EventType() = #PB_EventType_LeftClick
        ToolbarButtonState = CocoaMessage(0, WindowID(0), "showsToolbarButton") ! 1
        CocoaMessage(0, WindowID(0), "setShowsToolbarButton:", ToolbarButtonState)
      EndIf
  EndSelect
ForEver
Update 1: Read.L changed to Read.I in the 1st example (toggle window attributes) in order to work on 32 and 64 bit and unnecessary ", 0" deleted in CocoaMessage(). Thank you for your hints, wilbert!

Update 2: I updated the toolbar button example to display an error message when trying it with an OS newer than Snow Leopard because Apple eliminated the toolbar button in Lion...
Last edited by Shardik on Thu Oct 11, 2012 2:05 pm, edited 2 times in total.
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 »

Thanks Shardik :)
Great to see someone else posting Cocoa tips.

A little remark, when retrieving something like "styleMask", you can omit the 0 you added after it.
String and value are always grouped together except for the first part of the method since that doesn't always have a value.
In its current form, the 0 will simply be ignored.

The last example (toolbar button) has no visible effect when I click the button ?

For the first example I only see one button when using x64 and all buttons when using x86.
It has to do with defining the WindowAttributeID as an integer and reading it as a long.
When you change the read part also to an integer it also works on x64.
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 »

Thank you wilbert for your hints and explanations but first and foremost a big thank you for your CocoaMessage userlib which makes it incredibly easy to implement cocoa API calls. I hesitated far too long before starting to study cocoa stuff because I got very comfortable in using the carbon framework. I am currently on vacation and while studying an Objective-C book, I also installed your CocoaMessage userlib for testing purposes.

Sorry for the Read.L in my Window attribute example. I missed that after converting the example from a similar Carbon example. I didn't test the examples on 64 bit because I currently don't have a good internet connection at my holiday resort. On my iMac's location I have no internet connection at all and I therefore have to always borrow the Windows laptop from my daughter if downloading something or visiting this forum... :wink:

But now I was able to successfully download the 64 bit Beta 4 and tested my 3 examples on Snow Leopard, Lion and Mountain Lion with PB 5.00 Beta 4 32 and 64 bit:
- Snow Leopard (10.6.8 ): all 3 examples work (on 64 bit after changing Read.L to Read.I).
- Lion (10.7.5): the toolbar button example doesn't work: when starting there is no toolbar button displayed and switching doesn't work.
- Mountain Lion (10.8.2): the toolbar button example doesn't work and in the windows attributes example the metal background is not displayed in the whole window but only behind the "Enable metal style" button.
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 »

Glad to hear you appreciate the way the CocoaMessage command works Shardik.
While I did the coding, Fred also provided valuable feedback on what the most logical implementation would be.
Fred also was so kind to add CGFloat (as a macro) and structures like NSPoint, NSSize and NSRect to the OS X version since those are used quite often.
What's great about cocoa is that it was possible to implement the command in a way so that passing and receiving structures is supported.
For x86 it was possible to write out structures in an import instruction because everything was passed on the stack but on x64 this doesn't work anymore because some things like structures are passed using the stack and others using cpu registers.

Thanks for fixing the examples. I added a link to them in the first post of this thread.
I'm using Mountain Lion so that explains why I don't see the toolbar button.
As for the metal background, you can insert CocoaMessage(0, WindowID(0), "display") after you set the stylemask so the window is updated. That sort of fixes it but it still acts a bit strange sometimes when toggling the titlebar after you enable the metal background.
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 »

Alert message with suppression checkbox

Code: Select all

Procedure AlertWithSuppression(Title.s, Text.s, SuppressionText.s)
  Protected Alert = CocoaMessage(0, CocoaMessage(0, 0, "NSAlert new"), "autorelease")
  CocoaMessage(0, Alert, "setMessageText:$", @Title)
  CocoaMessage(0, Alert, "setInformativeText:$", @Text)
  CocoaMessage(0, Alert, "setShowsSuppressionButton:", #YES)
  Protected SuppressionButton = CocoaMessage(0, Alert, "suppressionButton")
  CocoaMessage(0, SuppressionButton, "setTitle:$", @SuppressionText)
  CocoaMessage(0, Alert, "runModal")
  ProcedureReturn CocoaMessage(0, SuppressionButton, "state")
EndProcedure


Suppress = #NO

OpenWindow(0, 0, 0, 200, 100, "Alert with suppression", #PB_Window_SystemMenu | #PB_Window_ScreenCentered)
ButtonGadget(0, 10, 10, 180, 30, "Button")

Repeat
  Select WaitWindowEvent()
    Case #PB_Event_CloseWindow
      Break
    Case #PB_Event_Gadget
      If Suppress = #NO
        Suppress = AlertWithSuppression("Message", "You pressed the button", "Do not show this message again please")        
      EndIf
  EndSelect
ForEver
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 »

Justify text in columns of ListIconGadget:

Code: Select all

EnableExplicit

Procedure SetListIconColumnJustification(ListIconID.I, ColumnIndex.I, Alignment.I)
  Protected ColumnHeaderCell.I
  Protected ColumnObject.I
  Protected ColumnObjectArray.I

  ; ----- Justify text of column cells
  CocoaMessage(@ColumnObjectArray, GadgetID(ListIconID), "tableColumns")
  CocoaMessage(@ColumnObject, ColumnObjectArray, "objectAtIndex:", ColumnIndex)
  CocoaMessage(0, CocoaMessage(0, ColumnObject, "dataCell"), "setAlignment:", Alignment)

  ; ----- Justify text of column header
  CocoaMessage(@ColumnHeaderCell, ColumnObject, "headerCell")
  CocoaMessage(0, ColumnHeaderCell, "setAlignment:", Alignment)

  ; ----- Redraw ListIcon contents to see change
  CocoaMessage(0, GadgetID(ListIconID), "reloadData")
EndProcedure

Define OptionGadgetID.I

OpenWindow(0, 200, 100, 445, 140, "Change column justification")
ListIconGadget(0, 5, 5, 435, 58, "Name", 110)
AddGadgetColumn(0, 1, "Address", 300)
AddGadgetItem(0, -1, "Harry Rannit" + #LF$ + "12 Parliament Way, Battle Street, By the Bay")
AddGadgetItem(0, -1, "Ginger Brokeit" + #LF$ + "130 PureBasic Road, BigTown, CodeCity")
Frame3DGadget(1, 10, 75, WindowWidth(0) - 20, 50, "Justification of 2nd column:")
OptionGadget(2, 20, 95, 70, 20, "Left")
OptionGadget(3, 330, 95, 70, 20, "Right")
OptionGadget(4, 180, 95, 70, 20, "Center")
SetGadgetState(2, #True)

Repeat
  Select WaitWindowEvent()
    Case #PB_Event_CloseWindow
      Break
    Case #PB_Event_Gadget
      OptionGadgetID = EventGadget()

      Select OptionGadgetID
        Case 2 To 4
          SetListIconColumnJustification(0, 1, OptionGadgetID - 2)
      EndSelect
  EndSelect
ForEver
Update 1: I have added code to also change the justification of the column header's text
Update 2: In the procedure SetListIconColumnJustification() I changed GadgetID(0) into GadgetID(ListIconID) (thank you for your hint, wilbert!)
Last edited by Shardik on Mon Oct 15, 2012 11:34 am, edited 3 times in total.
Polo
Addict
Addict
Posts: 2422
Joined: Tue May 06, 2003 5:07 pm
Location: UK

Re: [PB Cocoa] Methods, Tips & Tricks

Post by Polo »

Love the fact you guys so quickly made that much Cocoa code! :)
Post Reply