PureBasic Forum
https://www.purebasic.fr/english/

[PB Cocoa] Methods, Tips & Tricks
https://www.purebasic.fr/english/viewtopic.php?f=19&t=50795
Page 14 of 14

Author:  deseven [ Fri Sep 16, 2016 11:43 am ]
Post subject:  Re: [PB Cocoa] Methods, Tips & Tricks

More on that (do something when user changes interface mode):

Code:
Define app = CocoaMessage(0,0,"NSApplication sharedApplication")
Define appDelegate = CocoaMessage(0,app,"delegate")
Define delegateClass = object_getClass_(appDelegate)
Define selector = sel_registerName_("darkModeChanged:")
Define distributedNotificationCenter = CocoaMessage(0,0,"NSDistributedNotificationCenter defaultCenter")

Procedure darkModeChanged(notification)
  Debug "mode changed"
EndProcedure

class_addMethod_(delegateClass,selector,@darkModeChanged(),"v@:@")
CocoaMessage(0,distributedNotificationCenter,
             "addObserver:",appDelegate,
             "selector:",selector,
             "name:$",@"AppleInterfaceThemeChangedNotification",
             "object:",#nil)

OpenWindow(0,#PB_Ignore,#PB_Ignore,100,100,"",#PB_Window_SystemMenu|#PB_Window_ScreenCentered)

Repeat : Until WaitWindowEvent(100) = #PB_Event_CloseWindow


Again thanks wilbert for showing me how to add observers :)

Author:  wilbert [ Mon Dec 12, 2016 8:22 pm ]
Post subject:  Re: [PB Cocoa] Methods, Tips & Tricks

Small code to show how to format text of an EditorGadget with html code.
Code:
If OpenWindow(0, 0, 0, 320, 150, "EditorGadget", #PB_Window_SystemMenu | #PB_Window_ScreenCentered)
 
  EditorGadget(0, 10, 10, 300, 130)
 
 
  HTMLCode.s = "<font face='Helvetica' size='14'><b>Test</b> <font color='red'>code</font></font>"

  AttributedString = CocoaMessage(0, CocoaMessage(0, 0, "NSAttributedString alloc"), "initWithHTML:",
                                  CocoaMessage(0, CocoaMessage(0, 0, "NSString stringWithString:$", @HTMLCode),
                                               "dataUsingEncoding:", 10), "documentAttributes:", #Null)
  If AttributedString
    TextStorage = CocoaMessage(0, GadgetID(0), "textStorage")
    CocoaMessage(0, TextStorage, "setAttributedString:", AttributedString)
    CocoaMessage(0, AttributedString, "release")
  EndIf
 
  Repeat : Until WaitWindowEvent() = #PB_Event_CloseWindow
 
EndIf

Author:  deseven [ Thu May 04, 2017 11:23 pm ]
Post subject:  Re: [PB Cocoa] Methods, Tips & Tricks

Restarting your app (code ported from this gist)

Code:
Procedure restartApp(delay.i)
  Protected task = CocoaMessage(0,CocoaMessage(0,CocoaMessage(0,0,"NSTask alloc"),"init"),"autorelease")
  Protected args = CocoaMessage(0,0,"NSMutableArray arrayWithCapacity:",0)
  Protected appPath.s = PeekS(CocoaMessage(0,CocoaMessage(0,CocoaMessage(0,0,"NSBundle mainBundle"),"bundlePath"),"UTF8String"),-1,#PB_UTF8)
  Protected command.s = "sleep " + Str(delay) + ~"; open -a \"" + appPath + ~"\""
  CocoaMessage(0,args,"addObject:$",@"-c")
  CocoaMessage(0,args,"addObject:$",@command)
  CocoaMessage(0,task,"setLaunchPath:$",@"/bin/sh")
  CocoaMessage(0,task,"setArguments:",args)
  CocoaMessage(0,task,"launch")
  End
EndProcedure

OpenWindow(0,#PB_Ignore,#PB_Ignore,400,300,"restart app test",#PB_Window_SystemMenu|#PB_Window_ScreenCentered)
ButtonGadget(0,150,135,100,30,"restart")

Repeat
  ev = WaitWindowEvent()
  If ev = #PB_Event_Gadget And EventGadget() = 0
    restartApp(1)
  EndIf
Until ev = #PB_Event_CloseWindow

Author:  wilbert [ Fri Nov 03, 2017 4:39 pm ]
Post subject:  Re: [PB Cocoa] Methods, Tips & Tricks

Create UUID.

Method 1
Code:
ImportC ""
  CFUUIDCreate(alloc = #Null)
  CFUUIDCreateString(alloc, uuid)
EndImport

Procedure.s CreateUUID()
  Protected.i uuidRef, uuidStringRef, UUID.s
  uuidRef = CFUUIDCreate()
  uuidStringRef = CFUUIDCreateString(#Null, uuidRef)
  CFRelease_(uuidRef)
  UUID = PeekS(CocoaMessage(0, uuidStringRef, "UTF8String"), -1, #PB_UTF8)
  CFRelease_(uuidStringRef)
  ProcedureReturn UUID 
EndProcedure

Debug CreateUUID()


Method 2 (MacOS 10.8+)
Code:
UUID.s = PeekS(CocoaMessage(0, CocoaMessage(0, CocoaMessage(0, 0, "NSUUID UUID"), "UUIDString"), "UTF8String"), -1, #PB_UTF8)
Debug UUID

Author:  collectordave [ Sat Jun 13, 2020 10:24 am ]
Post subject:  Re: [PB Cocoa] Methods, Tips & Tricks

I have created a script to renew an applications icon and saved it as a script.

Can wilberts AppleScript procedure be used to run the script or is there another way?

Regards

CD

Author:  wilbert [ Sat Jun 13, 2020 5:12 pm ]
Post subject:  Re: [PB Cocoa] Methods, Tips & Tricks

collectordave wrote:
Can wilberts AppleScript procedure be used to run the script or is there another way?

If you load the script you can use that procedure.
Another option might be the terminal command osascript

Author:  deseven [ Sun Sep 27, 2020 11:37 am ]
Post subject:  Re: [PB Cocoa] Methods, Tips & Tricks

Run a program and write to its stdin using NSTask (because PB's RunProgram is buggy):

Code:
Procedure RunProgramNative(path.s,args.s,workdir.s = "",stdin.s = "")
  Protected i
  Protected argsArray
  If args
    Protected arg.s = StringField(args,1," ")
    If arg
      argsArray = CocoaMessage(0,0,"NSArray arrayWithObject:$",@arg)
      If CountString(args," ") > 0
        For i = 2 To CountString(args," ") + 1
          arg = StringField(args,i," ")
          If arg
            argsArray = CocoaMessage(0,argsArray,"arrayByAddingObject:$",@arg)
          EndIf
        Next
      EndIf
    EndIf
  EndIf
  Protected task = CocoaMessage(0,CocoaMessage(0,0,"NSTask alloc"),"init")
 
  CocoaMessage(0,task,"setLaunchPath:$",@path)
 
  If argsArray
    CocoaMessage(0,task,"setArguments:",argsArray)
  EndIf
 
  If workdir
    CocoaMessage(0,task,"setCurrentDirectoryPath:$",@workdir)
  EndIf
 
  If stdin
    Protected writePipe = CocoaMessage(0,0,"NSPipe pipe")
    Protected writeHandle = CocoaMessage(0,writePipe,"fileHandleForWriting")
    CocoaMessage(0,task,"setStandardInput:",writePipe)
    Protected string = CocoaMessage(0,0,"NSString stringWithString:$",@stdin)
    Protected stringData = CocoaMessage(0,string,"dataUsingEncoding:",#NSUTF8StringEncoding)
  EndIf
 
  CocoaMessage(0,task,"launch")
 
  If stdin
    CocoaMessage(0,writeHandle,"writeData:",stringData)
    CocoaMessage(0,writeHandle,"closeFile")
  EndIf
 
  CocoaMessage(0,task,"release")
EndProcedure

Based on this article. Reading from stdout is also an option, see the bottom example.

Author:  mk-soft [ Sun Feb 14, 2021 3:44 pm ]
Post subject:  Re: [PB Cocoa] Methods, Tips & Tricks

Thanks to Wilbert :wink:
Code:
;-TOP

; Comment : RunLoopTimer; None blocking GUI
; Author  : mk-soft
; Source  : Thanks to Wilbert, 25.10.2015
; Version : 1.01.0
; Create  : 14.02.2021

CompilerIf #PB_Compiler_OS = #PB_OS_MacOS
 
  ; Syntax Callback:
  ; - ProcedureC MyTimerCallback(timer, *info)
 
  ImportC ""
    CFRelease(object)
    CFAbsoluteTimeGetCurrent.d()
    CFRunLoopAddCommonMode(rl, mode)
    CFRunLoopAddTimer(rl, timer, mode)
    CFRunLoopGetCurrent()
    CFRunLoopGetMain()
    CFRunLoopTimerGetNextFireDate.d(timer)
    CFRunLoopRemoveTimer(rl, timer, mode)
    CFRunLoopTimerCreate(allocator, fireDate.d, interval.d, flags, order, callout, *context)
    dlsym(handle, symbol.p-utf8)
  EndImport
 
  Global *NSEventTrackingRunLoopMode.Integer = dlsym(-2, "NSEventTrackingRunLoopMode")
  Global *NSModalPanelRunLoopMode.Integer = dlsym(-2, "NSModalPanelRunLoopMode")
  Global *kCFRunLoopCommonModes.Integer = dlsym(-2, "kCFRunLoopCommonModes")
 
  Global NewMap RunLoopTimers()
 
  Procedure RunLoopRemoveTimer(Timer)
    Protected runLoop
    If FindMapElement(RunLoopTimers(), Str(Timer))
      myTimer = RunLoopTimers()
      runLoop = CFRunLoopGetCurrent()
      CFRunLoopRemoveTimer(runLoop, myTimer, *kCFRunLoopCommonModes\i)
      CFRelease(myTimer)
      DeleteMapElement(RunLoopTimers())
    EndIf
  EndProcedure
 
  Procedure RunLoopAddTimer(Timer, Timeout, TimerCallbackC)
    Static runLoop
    Protected time.d, myTimer
    If Not runLoop
      runLoop = CFRunLoopGetCurrent()
      CFRunLoopAddCommonMode(runLoop, *NSEventTrackingRunLoopMode\i)
    EndIf
    RunLoopRemoveTimer(Timer)
    time = Timeout / 1000.0
    myTimer = CFRunLoopTimerCreate(#Null, CFAbsoluteTimeGetCurrent(), time, 0, 0, TimerCallbackC, 0)
    If myTimer
      CFRunLoopAddTimer(runLoop, myTimer, *kCFRunLoopCommonModes\i)
      AddMapElement(RunLoopTimers(), Str(Timer))
      RunLoopTimers() = myTimer
    EndIf
    ProcedureReturn myTimer
  EndProcedure
 
CompilerEndIf

CompilerIf #PB_Compiler_IsMainFile
 
  ; Timer callback
 
  ProcedureC MyTimerCallback(timer, *info)
    AddGadgetItem(0, 0, StrD(CFRunLoopTimerGetNextFireDate(timer), 1))
  EndProcedure
 
  ; Window resize callback
 
  Procedure UpdateWindow()
    ResizeGadget(0, 10, 10, WindowWidth(0) - 20, WindowHeight(0) - 20)
  EndProcedure
 
  ; Main
 
  If OpenWindow(0, 0, 0, 400, 300, "Runloop Timer Example", #PB_Window_SystemMenu | #PB_Window_ScreenCentered | #PB_Window_SizeGadget)
    CreateMenu(0, WindowID(0))
    MenuTitle("Timer")
    MenuItem(0, "Start")
    MenuItem(1, "Stop")
   
    ListIconGadget(0, 10, 10, 380, 280, "Timer", 140)
    BindEvent(#PB_Event_SizeWindow, @UpdateWindow())
   
    RunLoopAddTimer(1, 500, @MyTimerCallback())
   
    Repeat
      Select WaitWindowEvent()
        Case #PB_Event_CloseWindow
          Break
        Case #PB_Event_Menu
          Select EventMenu()
            Case 0
              RunLoopAddTimer(1, 500, @MyTimerCallback())
            Case 1
              RunLoopRemoveTimer(1)
          EndSelect
      EndSelect
    ForEver
    RunLoopRemoveTimer(1)
  EndIf
 
CompilerEndIf

Page 14 of 14 All times are UTC + 1 hour
Powered by phpBB © 2000, 2002, 2005, 2007 phpBB Group
http://www.phpbb.com/