Carbon API list for Mac

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

Carbon API list for Mac

Post by WilliamL »

Attention: Starting with version 4.7, Pure Basic began using the Cocoa system as the default for drawing gadgets (etc.). If you want to use the Carbon system (like for old code) you can set the subsystem in "Compiler/Compiler Options.../Library Subsystem:" to "Carbon". Doing this will allow you to use the carbon gadget api below. Carbon will not work at all in x64 (64 bit)! To see how to use Cocoa and many examples of gadget modifications see [PB Cocoa] Methods, Tips & Tricks which is moderated by wilbert.

This is a list of the API usages for the Mac that I have found on the forum along with many other items of interest that are entirely in PureBasic. Although PureBasic has gone to Cocoa, with version 4.7, I am still adding any Carbon code that is contributed and I am also adding information of interest that is not in Cocoa (if there a Cocoa equivalent of an existing Carbon API I will try to post the link to it) . (see update date and red asterisk for newest addition)

- these items have cross-platform api code provided at this link.

List of API examples: (see examples below in numerical order or links) - updated 01/28/13! *
  • Declare API functions - #1 [freak]
    Passing & Receiving Structures in API - explanation [wilbert]]
    Safe Procedure calling (replace CallFunctionFast) [wilbert]
    plists can automatically be copied to new executable [jamirokwai]
    PB preferences - where to find #32 [jamirokwai]
    Debugger - is running? #34 [Demivec]
    RunProgram seems not to create executable [mitchel51]
    Get list of processes running [Shardik]
    Open pdf [Polo]
    Open folder on desktop [jamirokwai]
    Make files double-click able (associate with app)[Carbon] - #2 [freak] (Cocoa version)
    Library of commands (image/speech/printing/AppleScript/JavaScript) [wilbert]
    Printing with Carbon's Print Manager [Coder14/wilbert] printing Include file (also see library above)
    Window - create window with API (with embedded pb gadgets) [Shardik/Tarantino]
    Window - EventHandler to detect key+modifier presses & mouse click [Shardik]
    Window - put black dot into window close button (red) - #3 [airr] (Cocoa version)
    Window - capture using PB (2 ways)
    Window - live resize window [wilbert]
    Window - transparent grow box [Shardik]
    Window - change transparency [Shardik]
    Window - use of transition effects when minimizing/restoring windows [Shardik]
    Window - change various window controls & appearance [Shardik]
    Window - add a non-window dependent timer - #6 [Shardik]
    Window - hiding app icon (from dock) using plist [jamirokwai]
    Callback examples here and here
    Event handler installing example here or here. [shardik]
    System colors - Theme colors - background and text [Shardik]
    Toolbar - get and set height - link [Shardik]
    Gadgets displayed in large, small, or mini size. updated [Shardik]
    Gadget colors using Carbon (pre 4.7) - #5
    Gadgets sized automatically to font selected - #7 [freak]
    Gadget re-draw - force re-drawing of partially blanked-out gadget [Shardik]
    ButtonGadget - eliminate artifacts when resizing (Snow Leopard) [Shardik]
    ButtonGadget - detect right-click using an EventHandler [Shardik]
    ButtonGadget - make default any size! [wilbert] (Cocoa)
    ButtonGadget - right/left text justification [Shardik]
    ButtonGadget - create blue, pulsating blue, and metallic grey buttons [Shardik]
    CanvasGadget - to intercept right-click on laptops [Shardik]
    CanvasGadget - Calendar gadget #35 [williaml]
    CanvasGadget - Track Selection gadget #36 [netmaestro]
    CanvasGadget - event handler for #PB_EventType_MouseLeave [Shardik]
    CanvasGadget - button up outside of gadget [Shardik] or inside gadget [srod]
    CanvasGadget - drawing with CGContext functions. [wilbert]
    ComboBoxGadget (editable) - auto sort [Shardik]
    EditorGadget - scroll to bottom [freak]
    EditorGadget - set word wrap - unicode [Shardik] √
    EditorGadget - change font() - #19 [Shardik]
    EditorGadget - change background color [Shardik]
    EditorGadget - show ruler [wilbert] (Cocoa)
    EditorGadget - remove scrollbars get text with API - updated to change font by line! [Shardik]
    EditorGadget - SetGadgetState for EditorGadget (Cocoa version too) [Shardik] *
    EditorGadget - keep line visible (Cocoa version too) [Shardik] √
    ListIconGadget - set column justification [Shardik] √
    ListIconGadget - get column width [Shardik]
    ListIconGadget - set min/max column width [Shardik]
    ListIconGadget - set truncate text to center or right [Shardik]
    ListIconGadget - full row select [Shardik]
    ListIconGadget - put in grid lines [Shardik]
    ListIconGadget - set text indent width [Shardik]
    ListIconGadget - set gadget flags 'on the fly' (eg. Disable/Enable MultiSelection) [Shardik]
    ListIconGadget - Sort a column of by clicking on the header [Shardik]
    ListIconGadget - Display selected row in center of gadget [Shardik] √
    ListIconGadget - Toggle multi selection of items [Shardik] √
    ListView/IconGadget - auto alternating line color - #9 [Shardik] (Cocoa version)
    ListViewGadget - hide/activate scrollbars [freak] (Cocoa version)
    ListViewGadget - Find all selected lines (non-api or Carbon or Cocoa) [shardik/wilbert]
    ListViewGadget - hide/adjust header [freak]
    ListViewGadget - get scrollbar position - #11 [williaml]
    ListViewGadget - move/center scrollbar selection [Shardik]
    PanelGadget - make tab size normal/small/mini (new)! [Shardik]
    PanelGadget - force redraw of background. (to eliminate old background showing) [Shardik]
    PanelGadget - Enable and disable single tab in PanelGadget [Shardik]
    PanelGadget - Ger absolute position of gadget on panel [Shardik]
    ProgressBarGadget - intermediate state - #25 [Shardik]
    ScrollBar - Custom ScrollBar with live scrolling (Cross-platform)-updated [Shardik] √
    Scroll wheel - detect events and status change (German forum) [Shardik]
    Scroll wheel - horizontal mousewheel movement [Shardik]
    StringGadget - change font style of text (Bold/Italic/Underline) and type (Normal/Compressed/Wide) [Shardik]
    StringGadget - set/get select characters (cross-platform) [Shardik] √
    StringGadget - autoselect text on mouse over gadget [Shardik] √
    StringGadget - right justify [Shardik] (Cocoa version)
    StringGadget - using color - #23 [williaml]
    TextGadget - change fore/background color, justification, style - #8 [Shardik]
    TextGadget - make text underlined/italic/bold [Shardik]
    TrackBarGadget - show tick marks - updated - #27 [Shardik]
    TrackBarGadget - live scrolling [niffo]
    WebGadget - frame load delegate -print (Cocoa) [wilbert]
    Keypress (GetAsyncKeyState) - get key press (w/modifiers), mouse up/down updated [Shardik]
    Simulate keypress - set key press [Shardik]
    MessageRequester- new plus 3 new types [jamirokwai ]
    Mouse -changing cursor even animating (also non-API solutions) - 19 cursors! (first example shows them all) [Shardik]
    Mouse -get mouse up/down - #28 [niffo]
    Mouse - simulating mouse click [Shardik]
    Mouse - get left/right mouse click when not on gadget - #29 [Shardik]
    Mouse - discriminate between right click on Window or Gadget - #30 [Shardik]
    Mouse - discriminate between left & right click on Window or Gadget (German forum) [Shardik]
    Mouse - get mouse click/movement when on a gadget - #31 [niffo]
    Mouse - A cross-platform procedure to obtain the double click time [Shardik] √
    Web - Getting online-state. updated [jamirokwai]
    Web - Disconnect/Connect event for Client (cross-platform) [DarkPlayer]
    Getting UTC time offline [wilbert] √
    Nanosecond & microsecond timing [wilbert]
    Obtaining dates including days between dates! [wilbert]
    Replace 'Open File Requester' with Cocoa library [wilbert]
    Find the UUID and serial number of the Mac hardware. (Coca version too!) [Shardik]
    Speak with random voice - link [wilbert]
    Find file owner/group id - link [jamirokwai]
    Get a list of processes running (GetFrontProcess) [Shardik]
    Example of compressing/decompressing memory - link [TS-Soft]
    User level Application Preferences using CoreFoundation - link [airr]
    Read Preference values using CoreFoundation + Low Level API - link [Shardik]
    Using QuickTime with movies - link [niffo]
    Using USB ports - link [dhouston]
    Setting a non standard baudrate [wilbert]
    Simple PDF viewer - link [Shardik]
    Count pages of a PDF document - link [Shardik]
    Midi handling in OSX [wilbert]
    Audio recorder using PortAudio - link [chris319]
    Setting up OpenGl- link [luis] √
    Using OpenGl (Create Sprite)- link [nco2k]
    Using Cocoa guide - #33 [devulder]
    AppleScript - wrapper & link [wilbert]
    AppleScript - Growl notifications [jesperbrannmark] by program icon [jamirokwai]
    AppleScript - check if Growl is installed. [jesperbrannmark]
    AppleScript - Set Finder background. [jamirokwai]
    AppleScript - WebGadget printing [jesperbrannmark] and another example [wilbert]
    AppleScript - Dymo labelprinter [jesperbrannmark]
    AppleScript - speech synthesis [jesperbrannmark]
    Obtain computer name and user name. [Shardik] √
    Get Mac address from remote computer. [Shardik] √
    Add/Check/Remove login item using CFPreferences (Lion) [wy328]
    Using ProgramParameter to test OpenConsole. [Shardik]
    Making binary files of small images (example) . [srod/jesperbrannmark]
    Hints for submitting your program to the AppStore. #4
    ---------------------------------------------------------

1) Declare API functions

Code: Select all

ImportC "" - used to import and declare external functions (in this case for functions are already used by pb)
ImportC "/System/Library/Frameworks/Carbon.framework/Carbon"  - long form of 'ImportC ""' showing the complete path to Carbon
williaml wrote: I am puzzled of where 'ImportC "" ' actually is and what other commands might be available at this location.
freak wrote:
The required libraries for these commands are already linked to the executable because the Gadget commands themselves use them too, so you can just leave that part blank. This should work with most Carbon commands as long as you use some PB gui commands as well. My approach here is to just leave the string blank and only worry where things are if i get a linker error.

Just put it in such an ImportC and call it with GadgetID() as the first parameter like the others above. The ListIconGadget, ListViewGadget, TreeGadget, ExplorerListGadget and ExplorerTreeGadget all use the databrowser control with different settings, so the above reference can be useful for them.

In general, if you are looking for API commands to import, look in the Carbon and Core Foundation documentation. These are mostly used by PB commands internally (among some others). I usually use the XCode help as documentation. It makes searching simpler than using the web. For using PB objects with API commands, these are the most important object types returned from the [...]ID() functions:

  • WindowID() returns a WindowRef
    GadgetID() returns a ControlRef
    MenuID() returns a MenuRef
    ImageID() returns a CGImageRef
    StatusBarID() returns a ControlRef (its an ordinary userpane control)
    ToolBarID() returns a HIToolbarRef
    FontID() actually returns a PB internal pointer because a FontRef only specifies a name, not a size (so you have to load a font yourself if you need it for API stuff)
[/list]
Attention! freak has compiled a list of the underlying objects behind the PB gadgets. This should be a starting point for finding API commands in Carbon. http://www.purebasic.fr/blog/?p=336

2) Make files double-click able (associate with app)
freak provides the code that will make a file associate with an app and if a file is double-clicked the app will open. I've also noted that a file that is double-clicked while the app is running will also be received by the app. You will have to define the extensions in the plist and examples are given with this example too.

3) Window - put black dot into window close button (red)
Thanks airr for the info. http://www.purebasic.fr/english/viewtop ... 19&t=36651

Code: Select all

ImportC "/System/Library/Frameworks/Carbon.framework/Carbon" ; thanks for the code freak!
  SetWindowModified(WindowRef.l, State.l) 
  IsWindowModified(WindowRef.l) ; returns Boolean
EndImport
#SearchWnd=1
If OpenWindow(#SearchWnd, 0, 0, 230, 120, "Eventtypes example...", #PB_Window_SystemMenu | #PB_Window_ScreenCentered)
    setwindowmodified(WindowID(#SearchWnd),#True) ; close (red) window button with black dot
    ;setwindowmodified(WindowID(#SearchWnd),#False) ; no black dot
    Repeat:Until WindowEvent() = #PB_Event_CloseWindow
EndIf 
4) Hints for submitting your app to the Mac App Store:
  • -Detailed step-by-step instructions by J. Baker of how to submit your program.
    -More hints to streamline the process by adding a shell script by jamirokwai.
    -A suggestion on sandboxing and naming by J. Baker.

5) Gadget colors using Carbon (pre 4.7)
There has been some discussion of which gadgets show color. Shardik has made a chart showing all the gadgets and whether colors or fonts can be set for each, he has also made a picture showing all the gadgets with their colors. Colors can be added to some gadgets with the API above. Note that Mac API uses words instead of bytes for the color values. See conversion here.

6) Window - add a non-window dependent timer
This code will let you install a timer either with or without a window with API. Thanks to Shardik for the example. http://www.purebasic.fr/english/viewtop ... 98#p347707

7) Size gadget automatically to font selected
freak has posted an example http://www.purebasic.fr/english/viewtop ... 12&t=38349 of how to have a gadget (see which are affected in code comments) size itself to the font/size you've selected. The gadgets that can be changed are the Button, Checkbox, Option, Text, String, ComboBox, Image gadget.

8) TextGadget() - change fore/background color, justification, style
This is an example of complete control of the TextGadget including color, justification, and style with all the necessary constants. Now your textgadet background can match your window color background! Thanks to Shardik for this code at http://www.purebasic.fr/english/viewtop ... 72#p344872 . Shardik has posted another short example of changing the background with a procedure to convert the color values to the API requirement. http://www.purebasic.fr/english/viewtop ... 85#p348353

9) ListView/IconGadget - auto alternating line color
Shardik writes: Although the ListViewGadget and ListIconGadget (because of the underlying DataBrowser API) don't support colors, they nevertheless support the alternating coloring of rows. But it isn't possible to change the predefined colors. So if you can live with the predefined alternating row background colors white and light blue, the detection of the clicked item becomes quite easy.
http://www.purebasic.fr/english/viewtop ... 06#p345712

11) ListViewGadget - get scrollbar position

Code: Select all

ImportC ""
    GetDataBrowserScrollPosition(Control.i, *top.UNICODE, *left.UNICODE)
EndImport

Define top.u,left.u
Define lh=19 ; line height in listviewgadget (a guess)
w=350
h=200
If OpenWindow(0, 100, 100, w,h, "Scrollbar position", #PB_Window_SystemMenu | #PB_Window_ScreenCentered)
  ListViewGadget(0, 5, 5, w-5,h-5)
  AddGadgetColumn(0, 1, "", 200)
  AddGadgetItem(0, -1,"Click on number to see scrollbar position")
  For X = 1 To 50
    AddGadgetItem(0, -1, Str(x))
  Next

    Repeat
        Event = WaitWindowEvent()
        Select event
        Case #PB_Event_Gadget
            Select EventGadget()
            Case 0
                GetDataBrowserScrollPosition(GadgetID(0), @top.u, @left.u)
                Debug Str(top)+"/"+Str(lh)+"="+Str(top/lh)+" line at top of scrollbar (start at 0)"
            EndSelect
        EndSelect
    Until Event = #PB_Event_CloseWindow
EndIf
19) EditorGadget - change font()
There has been some discussion about not being able to change the font in the EditorGadget() this may be a bug and fixed in future versions of PB. Shardik has provided a way to change the font using the API in this thread . He has also gives this explanation about scroll bar behaviors The EditorGadget on MacOS uses a user pane rendering a TXN Object (PB blog). The underlying MLTE API (Multi Language Text Engine, deprecated since MacOS X 10.6) doesn't provide the option to hide the scroll bars. The only option provided is to change their activity states when obtaining or losing focus...

23) StringGadget - using color
I find I have to put the gadget and color commands in this order to keep the font the right size but I have noticed that the width of the text in the gadget is not being calculated correctly and sometimes the text is shifted off to the right when not necessary.

Code: Select all

    StringGadget(0, 10, lne*lh, 180, lf, "String gadget")
        SetGadgetColor(0, #PB_Gadget_BackColor, $00FFFF)
        SetGadgetColor(0, #PB_Gadget_FrontColor, $0000FF)
        SetGadgetFont(0,FontID(#geneva12)))
25) ProgressBarGadget - intermediate state
Shardik shows how to set the ProgressBar to the undefined state that is used when the fill time cannot be determined. Apple describes it as The so called "indeterminate" state of the ProgressBar does in principle not represent a ProgressBar at all. It "misuses" the ProgressBar to indicate that the program is performing some action and that the program doesn't know how long that action may take. One other example: when trying to connect to a busy server, the program cannot display a progress bar because it can't estimate at which time the connection will finally be established.

27) TrackBarGadget - show tick marks
Shardik shows how create custom TrackBarGagets in this thread. These gadgets show the missing division (hash) marks but custom TrackBars lose the ability to get the gadget state with the pb command so he shows how to get the gadget state with API. A new version that doesn't require you to create a custom gadget is shown here. With this code you can add tick marks, change pointer to up or down, or make it a non-pointer.

28) Mouse -get mouse up/down
This API requires a callback and the code shows how to set it up. Thanks to Niffo for the code.

29) Mouse - get left/right mouse click when not on gadget
Shardik has provided an example of getting a right/middle/left click of the mouse when the cursor is not over a gadget (otherwise the gadget will return the mouse click type).

30) Mouse - discriminate between right click on Window or Gadget
Shardik has posted the code to discriminate between right click on Window or Gadget on the German forum. If you don't read German this is his explanation in English. This example installs an EventHandler for a contextual menu click (right click) for a Window and for a ButtonGadget and calls the EventHandler with the handle of the window or gadget with the UserData parameter, so that the EventHandler can discriminate whether the right click was carried out on an empty window space or on the ButtonGadget. If the right click occured in the window, a variable in the EventHandler is set to #True and if this is detected in the event loop, the popup menu is displayed.

31) Mouse - get mouse click/movement when on a gadget
Niffo has made an example of getting mouse events when the cursor is over a gadget (see his second example in the eighth entry). The code will provide moving on to the gadget, off of it, mouse up, and mouse down. You can use this code on many gadgets. I have used this code to get EditorGadget() clicks. http://www.purebasic.fr/english/viewtop ... 19&t=36625

32) PB preferences - where to find
jamirokwai writes: Should be a hidden folder inside your home-directory. Try "Go To Folder" in Finder and enter ~/.PureBasic - The folder should show up. http://www.purebasic.fr/english/viewtop ... es#p298281

Using 33) Cocoa guide
devulder has worked on creating a userlib here and wilbert has a userlib here with instruction of where to put the library here. Wilbert has also listed some of the Cocoa procedures here.

#34) Is the Debugger running?
Not API but a good tip. If the debugger is used in compiling the code then DisableDebugger and EnableDebugger can be used (for time sensitive code).

Code: Select all

If #PB_Compiler_Debugger ; 0=off 1=on
    MessageRequester("Debugger on...","")
EndIf
#35 CalendarGadget
This is not API but an attempt to use the (new) CanvasGadget to create a colorful CanvasCalendarGadget for the Mac (which is just B&W text). jesperbrannmark has also contributed a calendar replacement in this thread.

#36 Track Selection Gadget
netmaestro has made a selection gadget that presents a bar that you can select the beginning and ending point anywhere along the bar, similar to audio editing. I have changed his code so that it will run on a Mac (should be cross-platform).
Last edited by WilliamL on Mon Jan 28, 2013 7:17 pm, edited 230 times in total.
MacBook Pro-M1 (2021), Sonoma 14.3.1 (CLT 15.3), PB 6.10b7 M1
User avatar
DoubleDutch
Addict
Addict
Posts: 3219
Joined: Thu Aug 07, 2003 7:01 pm
Location: United Kingdom
Contact:

Re: API list for Mac

Post by DoubleDutch »

Great post. Thanks. :)
https://deluxepixel.com <- My Business website
https://reportcomplete.com <- School end of term reports system
spacebuddy
Enthusiast
Enthusiast
Posts: 346
Joined: Thu Jul 02, 2009 5:42 am

Re: API list for Mac

Post by spacebuddy »

I am trying to use OSErr GetFrontProcess ( ProcessSerialNumber *PSN); to get a list of processes running, is this possible in PB?
User avatar
Shardik
Addict
Addict
Posts: 1984
Joined: Thu Apr 21, 2005 2:38 pm
Location: Germany

Re: API list for Mac

Post by Shardik »

spacebuddy wrote:I am trying to use OSErr GetFrontProcess ( ProcessSerialNumber *PSN); to get a list of processes running, is this possible in PB?

Code: Select all

EnableExplicit

#kCFStringEncodingMacRoman = 0
#kCFStringEncodingUnicode = $100
#kNoProcess = 0

ImportC ""
  CFRelease(CFTypeRef.L)
  CFStringGetCString(CFStringRef.L, *StringBuffer, BufferSize.L, CFStringEncoding.L)
  CopyProcessName(*ProcessSerialNumber, *Name)
  GetNextProcess(*ProcessSerialNumber)
  GetProcessPID(*ProcessSerialNumber, *PID)
EndImport

Structure ProcessSerialNumber
  HighLongOfPSN.L
  LowLongOfPSN.L
EndStructure

Procedure.S ConvertCFStringIntoString(CFStringRef.L)
  Protected Encoding.L
  Protected String.S = Space(256)

  If #PB_Compiler_Unicode
    Encoding = #kCFStringEncodingUnicode
  Else
    Encoding = #kCFStringEncodingMacRoman
  EndIf

  CFStringGetCString(CFStringRef, @String, Len(String), Encoding)
  CFRelease(CFStringRef)

  ProcedureReturn Trim(String)
EndProcedure

Define PID.L
Define ProcessNameRef.L
Define PSN.ProcessSerialNumber

PSN\HighLongOfPSN = 0
PSN\LowLongOfPSN = #kNoProcess

Repeat
  If GetNextProcess(@PSN.ProcessSerialNumber) = 0
    If PSN\LowLongOfPSN <> #kNoProcess
      If GetProcessPID(@PSN, @PID) = 0
        If CopyProcessName(@PSN, @ProcessNameRef) = 0
          Debug "PID = " + Str(PID) + ": " + ConvertCFStringIntoString(ProcessNameRef)
        EndIf
      EndIf
    EndIf
  EndIf
Until PSN\LowLongOfPSN = #kNoProcess
spacebuddy
Enthusiast
Enthusiast
Posts: 346
Joined: Thu Jul 02, 2009 5:42 am

Re: API list for Mac

Post by spacebuddy »

Thank you, that worked perfectly and I learned a lot from your code :D
jesperbrannmark
Enthusiast
Enthusiast
Posts: 536
Joined: Mon Feb 16, 2009 10:42 am
Location: sweden
Contact:

Re: Carbon API list for Mac

Post by jesperbrannmark »

The link for "Scroll wheel - detect events and status change (German forum) [Shardik]" is wrong...
WilliamL
Addict
Addict
Posts: 1214
Joined: Mon Aug 04, 2008 10:56 pm
Location: Seattle, USA

Re: Carbon API list for Mac

Post by WilliamL »

Thanks jesperbrannmark.

I fixed the link to be http://www.purebasic.fr/german/viewtopi ... 59&start=1
MacBook Pro-M1 (2021), Sonoma 14.3.1 (CLT 15.3), PB 6.10b7 M1
Lebostein
Addict
Addict
Posts: 806
Joined: Fri Jun 11, 2004 7:07 am

Re: Carbon API list for Mac

Post by Lebostein »

Thanks! Very cool and interesting.

But I would forbid to use API in PureBasic. The exchangeability of the code between platforms is lost... And that is the key feature of PB.
User avatar
luis
Addict
Addict
Posts: 3876
Joined: Wed Aug 31, 2005 11:09 pm
Location: Italy

Re: Carbon API list for Mac

Post by luis »

Lebostein wrote:But I would forbid to use API in PureBasic.
LOL !
"Have you tried turning it off and on again ?"
A little PureBasic review
User avatar
Shardik
Addict
Addict
Posts: 1984
Joined: Thu Apr 21, 2005 2:38 pm
Location: Germany

Re: Carbon API list for Mac

Post by Shardik »

Lebostein wrote:But I would forbid to use API in PureBasic. The exchangeability of the code between platforms is lost... And that is the key feature of PB.
No exchangeability is lost if cross-platform code examples contain the API functions for Windows, Linux and MacOS. I have already posted several examples with API functions for all 3 platforms. In some of these examples I needed special functions missing in PB to proceed in programming a cross-platform project.
User avatar
DoubleDutch
Addict
Addict
Posts: 3219
Joined: Thu Aug 07, 2003 7:01 pm
Location: United Kingdom
Contact:

Re: Carbon API list for Mac

Post by DoubleDutch »

It would be good if some of the examples where all three platforms had their own code would be added. Maybe there should be a special bit of the forum where you can post API code that works on all three platforms that Fred & co can consider for inclusion in the main code core?
https://deluxepixel.com <- My Business website
https://reportcomplete.com <- School end of term reports system
User avatar
Shardik
Addict
Addict
Posts: 1984
Joined: Thu Apr 21, 2005 2:38 pm
Location: Germany

Cross-platform examples with API functions extending PureBasic

Post by Shardik »

DoubleDutch wrote:It would be good if some of the examples where all three platforms had their own code would be added.
Cross-platform examples with API functions for all 3 platforms (keep in mind that some examples on MacOS are still only working for Carbon and don't work with Cocoa):
- Check if Gadget is disabled
- Check if Gadget is visable
- Display website in default browser
- Drag image from WebGadget onto ImageGadget and display image path
- Get double click time
- Get IP addresses from host name
- Get MAC address from remote computer
- Get computer name
- Get user idle time
- Get UTC Time from different countries
- OpenGL Demo

ButtonGadget:
- Toggle text justification between center and left

Custom Gadgets:
- TimePicker using SpinButtons and TextGadget
- Windows-like TimePicker

ComboBoxGadget:
- Enable and disable ComboBox and keep background white

Cursor:
- Change cursor into PNG image
- Hide and show cursor

EditorGadget:
- Add line and keep it visible
- Center text
- Convert text containing tags to RTF (supporting bold, italic and underlined characters)
- Detect right click and display context menu
- Enable word wrap
- Get number of lines
- Get single text line from wrapped text block
- Select line after line and keep line visible
- Search in EditorGadget for text line double clicked in a ListIconGadget and select that line
- Select and deselect all the text
- Set cursor

ExplorerListGadget:
- Select a row
- Select and unselect a row (without API)

ExplorerTreeGadget:
- Similar look and behaviour in Linux and MacOS as in Windows

HyperLinkGadget:
- Detect right click and display popup menu

ListIconGadget:
- Count number of columns
- Detect left click on cell
- Detect left click on header cell
- Detect movement of mouse wheel
- Display double-clicked row at top of list
- Display selected row in center of Gadget
- Get all selected items
- Get and set row height
- Get currently visible top row
- GetGadgetItemImage()
- Hide title header
- Set column justification
- Toggle multi selection of items

ListViewGadget:
- Get selected rows without iterating over all rows
- Get row at top of list

PanelGadget:
- Get absolute position of gadget on panel

ScrollBarGadget:
- Live scrolling

StringGadget:
- Align text right
- Autoselect text on mouse over gadget
- Center text
- Detect read only mode
- Detect right click and suppress context menu
- Get and set cursor position
- Get and set placeholder text
- Get and set selected text
- Set cursor to end of text
- Toggle read only state
- Toggle vertical centering

TextGadget:
- Toggle vertical centering

ToolBar:
- Detect if toolbar button is enabled or disabled

TreeGadget:
- Get row height
- GetGadgetItemImage()

WebGadget:
- Drag image from WebGadget to ImageGadget and display image path

Window:
- Change transparency
- Detect end of resizing
- Get background color of window and set same background color in CanvasGadget
- Set background image

Some examples have already been implemented in PB like "Get double click time", "Enable word wrap" or "Get computer name"... 8)

DoubleDutch wrote:Maybe there should be a special bit of the forum where you can post API code that works on all three platforms that Fred & co can consider for inclusion in the main code core?

It would be nice to have a subforum for cross-platform API code... :P
Last edited by Shardik on Thu Feb 01, 2024 12:13 pm, edited 42 times in total.
User avatar
Keya
Addict
Addict
Posts: 1891
Joined: Thu Jun 04, 2015 7:10 am

Re: Carbon API list for Mac

Post by Keya »

Shardik wrote:
DoubleDutch wrote:Maybe there should be a special bit of the forum where you can post API code that works on all three platforms that Fred & co can consider for inclusion in the main code core?
It would be nice to have a subforum for cross-platform API code... :P
^ This! (again! still! why not!?) :)

and thankyou Shardik, your Center Text demo works well :)

Shardik ps. in your demo if the OS is <= XP you "overwrite" the Gadget by recreating another one with the same ID (neat trick for re-styling! :)) ... so, the equivalent of
StringWindow(0, ...
StringWindow(0, ...

Im just wondering IS IT SAFE to use this overwrite trick that way, or should there be a FREEGADGET() call between those two?
It seems to work fine without FreeGadget but im wondering if its a resource leak, though when i checked in Windows Task Manager it showed the same number of Handles both with and without the FreeGadget call so perhaps internally FreeGadget is already being called, i dont know! but i dont know how to test for handle leak in linux or mac

For example...

Code: Select all

CompilerIf #PB_Compiler_OS = #PB_OS_Linux
  ImportC ""
    gtk_entry_set_alignment(Entry.I, XAlign.F)
  EndImport
CompilerEndIf

Procedure CenterEditGadgetText(GadgetConst)
CompilerSelect #PB_Compiler_OS               
  CompilerCase #PB_OS_Linux
    gtk_entry_set_alignment(GadgetID(GadgetConst), 0.5)
  CompilerCase #PB_OS_MacOS
    CocoaMessage(0, GadgetID(GadgetConst), "setAlignment:", 2)
  CompilerCase #PB_OS_Windows
    If OSVersion() > #PB_OS_Windows_XP
      SetWindowLongPtr_(GadgetID(GadgetConst), #GWL_STYLE, GetWindowLongPtr_(GadgetID(0), #GWL_STYLE) & $FFFFFFFC | #ES_CENTER)
    Else
      OldTxt.s = GetGadgetText(GadgetConst)
      OldX = GadgetX(GadgetConst): OldY = GadgetY(GadgetConst): OldW = GadgetWidth(GadgetConst): OldH = GadgetHeight(GadgetConst)
      FreeGadget(GadgetConst)
      StringGadget(GadgetConst, OldX, OldY, OldW, OldH, OldTxt, #ES_CENTER)
    EndIf
CompilerEndSelect
EndProcedure


#Edit1 = 1

OpenWindow(0, 100, 100, 280, 70, "StringGadget with centered text", #PB_Window_SystemMenu)

StringGadget(#Edit1, 20, 20, 240, 21, "Centered text")
CenterEditGadgetText(#Edit1)

Repeat
Until WaitWindowEvent() = #PB_Event_CloseWindow
User avatar
Keya
Addict
Addict
Posts: 1891
Joined: Thu Jun 04, 2015 7:10 am

Re: Carbon API list for Mac

Post by Keya »

I try Shardik's excellent example for listing processes - http://www.purebasic.fr/english/viewtop ... 53#p375953
it gets the Process ID list fine (not anywhere near as many as 'ps -x' though?) but is crashing (PB v5.31-64/Mac 10.10-64) getting the process name with invalid memory access in this function:

Code: Select all

Procedure.S ConvertCFStringIntoString(CFStringRef.L)
  Protected Encoding.L
  Protected String.S = Space(256)
  If #PB_Compiler_Unicode
    Encoding = #kCFStringEncodingUnicode
  Else
    Encoding = #kCFStringEncodingMacRoman
  EndIf
  CFStringGetCString(CFStringRef, @String, Len(String), Encoding)      ;<-- Crash
  CFRelease(CFStringRef)
  ProcedureReturn Trim(String)
EndProcedure
wilbert
PureBasic Expert
PureBasic Expert
Posts: 3870
Joined: Sun Aug 08, 2004 5:21 am
Location: Netherlands

Re: Carbon API list for Mac

Post by wilbert »

Keya wrote:I try Shardik's excellent example for listing processes - http://www.purebasic.fr/english/viewtop ... 53#p375953
it gets the Process ID list fine (not anywhere near as many as 'ps -x' though?) but is crashing (PB v5.31-64/Mac 10.10-64) getting the process name with invalid memory access in this function:
The code isn't ready for 64 bit. Also some things can be done easier now we got Cocoa support.
Here's some workarounds.

1. Code from Shardik adapted to support 64 bit and use Cocoa to retrieve the string

Code: Select all

EnableExplicit

#kNoProcess = 0

ImportC ""
  CopyProcessName(*ProcessSerialNumber, *Name)
  GetNextProcess(*ProcessSerialNumber)
  GetProcessPID(*ProcessSerialNumber, *PID)
EndImport

Structure ProcessSerialNumber
  HighLongOfPSN.l
  LowLongOfPSN.l
EndStructure

Define PID.i
Define ProcessNameRef.i
Define PSN.ProcessSerialNumber

PSN\HighLongOfPSN = 0
PSN\LowLongOfPSN = #kNoProcess

Repeat
  If GetNextProcess(@PSN.ProcessSerialNumber) = 0
    If PSN\LowLongOfPSN <> #kNoProcess
      If GetProcessPID(@PSN, @PID) = 0
        If CopyProcessName(@PSN, @ProcessNameRef) = 0
          Debug "PID = " + Str(PID) + ": " + PeekS(CocoaMessage(0, ProcessNameRef, "UTF8String"), -1, #PB_UTF8)
        EndIf
      EndIf
    EndIf
  EndIf
Until PSN\LowLongOfPSN = #kNoProcess
2. All Cocoa (take a look at the NSRunningApplication Class Reference for more information)

Code: Select all

RunningApps = CocoaMessage(0, CocoaMessage(0, 0, "NSWorkspace sharedWorkspace"), "runningApplications")
RunningAppsCount = CocoaMessage(0, RunningApps, "count")

i = 0
While i < RunningAppsCount
  
  RunningApp = CocoaMessage(0, RunningApps, "objectAtIndex:", i)
  PID.i = CocoaMessage(0, RunningApp, "processIdentifier")
  AppName.s = PeekS(CocoaMessage(0, CocoaMessage(0, RunningApp, "localizedName"), "UTF8String"), -1, #PB_UTF8)
  If CocoaMessage(0, RunningApp, "isActive")
    AppName + "  ** Active **"
  EndIf
  Debug "PID = " + Str(PID) + ": " + AppName
  
  i + 1
Wend
3. Cocoa but presented a bit nicer

Code: Select all

RunningApps = CocoaMessage(0, CocoaMessage(0, 0, "NSWorkspace sharedWorkspace"), "runningApplications")
RunningAppsCount = CocoaMessage(0, RunningApps, "count")

OpenWindow(0, 100, 100, 600, 400, "Running applications", #PB_Window_SystemMenu | #PB_Window_ScreenCentered)
ListIconGadget(0, 10, 10, 580, 380, "PID", 60, #PB_ListIcon_FullRowSelect | #PB_ListIcon_AlwaysShowSelection | #PB_ListIcon_CheckBoxes)
AddGadgetColumn(0, 1, "Name", 400)

Define i = 0
While i < RunningAppsCount
  
  RunningApp = CocoaMessage(0, RunningApps, "objectAtIndex:", i)
  PID.i = CocoaMessage(0, RunningApp, "processIdentifier")
  AppName.s = PeekS(CocoaMessage(0, CocoaMessage(0, RunningApp, "localizedName"), "UTF8String"), -1, #PB_UTF8)
  AddGadgetItem(0, i, Str(PID) + #LF$ + AppName)
  SetGadgetItemImage(0, i, CocoaMessage(0, RunningApp, "icon"))
  If CocoaMessage(0, RunningApp, "isActive")
    SetGadgetItemState(0, i, #PB_ListIcon_Checked)
  EndIf
  
  i + 1
Wend

Repeat
  Event = WaitWindowEvent()
Until Event = #PB_Event_CloseWindow
Windows (x64)
Raspberry Pi OS (Arm64)
Post Reply