How to create plugins in swift - plugins

I found article describing how to create plugin using Swift and Cocoa. It uses NSBundle to load plugin, but that, as far as I know, is not available in pure swift (no Cocoa). Is there way how to achieve same result without using Cocoa?
More info:
In case it's relevant, here is what I want to achieve. I create app in swift that runs on linux server. User can connect to it using their browser. I want to be able to have other people write "plugins" that will implement functionality itself (what user can see and do once they connect), from printing out hello world, through chat programs to games without having to worry about low level stuff provided by my app. Some sort of dll, that my server application loads and runs.

Solution to this is not trivial, but it's not impossible to do either. I prefer to use swift package manager to manage dependencies and Xcode as IDE. This combination is not perfect as it needs a lot of tinkering but there is not any other useable free swift IDE as of now.
You will need to set up two projects, let's call them Plugin (3rd party library) and PluginConsumer (app that uses other people plugins). You will also need to decide on API, for now we will use simple
TestPluginFunc()
Create Plugin.swift file with TestPluginFunc implementation in your Plugin project:
public func TestPluginFunc() {
print("Hooray!")
}
Set the project to build framework, not executable and build[1]. You will get Plugin.framework file which contains your plugin.
Now switch to your PluginConsumer project
Copy Plugin.framework from your Plugin project somewhere where you can easily find it. To actually load the framework and use it:
// we need to define how our plugin function looks like
typealias TestPluginFunc = #convention(c) ()->()
// and what is its name
let pluginFuncName = "TestPluginFunc"
func loadPlugin() {
let pluginName = "Plugin"
let openRes = dlopen("./\(pluginName).framework/\(pluginName)", RTLD_NOW|RTLD_LOCAL)
if openRes != nil {
// this is fragile
let symbolName = "_TF\(pluginName.utf8.count)\(pluginName)\(initFuncName.utf8.count)\(initFuncName)FT_T_"
let sym = dlsym(openRes, symbolName)
if sym != nil {
// here we load func from framework based on the name we constructed in "symbolName" variable
let f: TestPluginFunc = unsafeBitCast(sym, to: TestPluginFunc.self)
// and now all we need to do is execute our plugin function
f()
} else {
print("Error loading \(realPath). Symbol \(symbolName) not found.")
dlclose(openRes)
}
} else {
print("error opening lib")
}
}
If done correctly, you should see "Hooray!" being printed to your log.
There is a lot of room for improvement, first thing you should do is replace Plugin.framework string with parameter, preferably using some file library (I am using PerfectLib). Another thing to look at is defining plugin API in your PluginConsumer project as a protocol or base class, creating framework out of that, importing that framework in your plugin project and basing your implementation on that protocol/base class. I am trying to figure out exactly how to do that. I will update this post if I mange to do it properly.
[1]: I usually do this by creating Package.swift file and creating xcode project out of it using swift package generate-xcodeproj. If your project doesn't contain main.swift, xcode will create framework instead of executable

What you will want to do is create a folder your program will look in. Let's say it's called 'plugins'. It should make a list of names from the files in there, and then iterate through using them, passing parameters to the files and getting the output and making use of that in some way.
Activating a program and getting output:
func runCommand(cmd : String, args : String...) -> (output: [String], error: [String], exitCode: Int32) {
var output : [String] = []
var error : [String] = []
let task = Process()
task.launchPath = cmd
task.arguments = args
let outpipe = Pipe()
task.standardOutput = outpipe
let errpipe = Pipe()
task.standardError = errpipe
task.launch()
let outdata = outpipe.fileHandleForReading.readDataToEndOfFile()
if var string = String(data: outdata, encoding: .utf8) {
string = string.trimmingCharacters(in: .newlines)
output = string.components(separatedBy: "\n")
}
let errdata = errpipe.fileHandleForReading.readDataToEndOfFile()
if var string = String(data: errdata, encoding: .utf8) {
string = string.trimmingCharacters(in: .newlines)
error = string.components(separatedBy: "\n")
}
task.waitUntilExit()
let status = task.terminationStatus
return (output, error, status)
}
`
Here is how a swift plugin would accept arguments:
for i in 1..C_ARGC {
let index = Int(i);
let arg = String.fromCString(C_ARGV[index])
switch arg {
case 1:
println("1");
case 2:
println("2")
default:
println("3)
}
}
So once you have the program and plugin communicating you just have to add handling in your program based on the output so the plugins output can do something meaningful. Without cocoa libraries this seems the way to go, though if you use C there are a couple of other options available there as well. Hope this helps.

Related

Is there a faster way to loop through the installed applications on macOS?

I'm writing a menu bar extra that shows you a list of your installed apps and allows you to click on each button in the list to open that app. Obviously, to do this I need a list of every app the user has. The specific way I chose to do this was making a function that would loop through the files in the system's Applications folder, strip out anything in an app's contents or that didn't end in .app, and return an array containing a list of files as names, which is then iterated through to create a list of "app buttons" that the user can click on to launch the app.
The code for my function is
func enumerateAppsFolder() -> Array<String> {
var fileNames:Array<String> = []
let fileManager = FileManager.default
let enumerator:FileManager.DirectoryEnumerator = fileManager.enumerator(atPath:"/Applications/")!
while let element = enumerator.nextObject() as? String {
if element.hasSuffix("app") && !element.contains("Contents") { // checks the extension
fileNames.append(element)
}
}
return fileNames
}
And I create my list with
ForEach(enumerateAppsFolder(), id:\.self){
AppBarMenuItem(itemAppName: $0)
}
But when I do it like that, the result is what I expected, but the performance is horrible. This can be seen in the screenshot, and will just be made worse by larger applications folders on some people's systems
(When the app is starting up, which takes about 5 minutes, the CPU and disk usage are also extremely high)
Is there a better and faster method that will retrieve every app on the system, similarly to the macOS launchpad or "Open With.." list?
The enumerator method of FileManager that you are using performs a deep enumeration of the file tree. You don't want a deep enumeration, just a top-level enumeration. Use the version of the enumerator method that has the options parameter and pass in .skipsSubdirectoryDescendants.
Here's an updated version of your function getting a URL directly from FileManager for the Applications folder and then doing a shallow enumeration to get the list of apps.
func enumerateAppsFolder() -> [String] {
var appNames = [String]()
let fileManager = FileManager.default
if let appsURL = fileManager.urls(for: .applicationDirectory, in: .localDomainMask).first {
if let enumerator = fileManager.enumerator(at: appsURL, includingPropertiesForKeys: nil, options: .skipsSubdirectoryDescendants) {
while let element = enumerator.nextObject() as? URL {
if element.pathExtension == "app" { // checks the extension
appNames.append(element.deletingPathExtension().lastPathComponent)
}
}
}
}
return appNames
}
print(enumerateAppsFolder())
Sample output when run from a Swift Playground:
"Numbers", "Dropbox", "Xcode", "Apple Configurator 2", "iMovie"

How to remove sandbox without xcode

Earlier I asked a question regarding generateCGImagesAsynchronously. Thankfully it got answered and works great.
The issue is that it only works as a Cocoa app on xcode. I am now trying to move this logic to an executable Swift package but AVFoundation code, such as generateCGImagesAsynchronously, won't work. That is, no error is raised but those functions seem to be mocked. I presume this might have to do with my package being sandboxed? I was able to remove the sandbox from the Cocoa app I previously wrote the code for, but I can't figure out how to do that for this executable.
I am new to Swift and trying to understand it and it's kind of frustrating to think that what I want my code to do is dependent on the IDE I am using.
If anyone can point me in the direction of where to read in the docs, or some other sources, on how to make programs without using xcode, that would be great. Thanks!
Here is my code:
import Darwin
import Foundation
import AppKit
import AVFoundation
import Cocoa
#discardableResult func writeCGImage(
_ image: CGImage,
to destinationURL: URL
) -> Bool {
guard let destination = CGImageDestinationCreateWithURL(
destinationURL as CFURL,
kUTTypePNG,
1,
nil
) else { return false }
CGImageDestinationAddImage(destination, image, nil)
return CGImageDestinationFinalize(destination)
}
func imageGenCompletionHandler(
requestedTime: CMTime,
image: CGImage?,
actualTime: CMTime,
result: AVAssetImageGenerator.Result,
error: Error?
) {
guard let image = image else { return }
let path = saveToPath.appendingPathComponent(
"img\(actualTime).png"
)
writeCGImage(image, to: path)
}
let arguments: [String] = Array(CommandLine.arguments.dropFirst())
// For now, we assume the second arg, which is the
// path that the user wants us to save to, always exists.
let saveToPath = URL(fileURLWithPath: arguments[1], isDirectory: true)
let vidURL = URL(fileURLWithPath: arguments[0])
let vidAsset = AVAsset(url: vidURL)
let vidDuration = vidAsset.duration
let imageGen = AVAssetImageGenerator(asset: vidAsset)
var frameForTimes = [NSValue]()
let sampleCounts = 20
let totalTimeLength = Int(truncatingIfNeeded: vidDuration.value as Int64)
let steps = totalTimeLength / sampleCounts
for sampleCount in 0 ..< sampleCounts {
let cmTime = CMTimeMake(
value: Int64(sampleCount * steps),
timescale: Int32(vidDuration.timescale)
)
frameForTimes.append(NSValue(time: cmTime))
}
imageGen.generateCGImagesAsynchronously(
forTimes: frameForTimes,
completionHandler: imageGenCompletionHandler
)
As I said in a comment on your previous question, this has nothing to do with Xcode per se. Xcode just generates a lot of code and build commands for you.
macOS is a complex operating system and programs that want to use its more advanced features must follow certain patterns. One of this patterns is called the run loop. If you create a Cocoa app, you get most of these things for free.
Since you are trying to perform some asynchronous actions, you need a run loop. Appending this should work:
RunLoop.current.run()
Otherwise, your program will simply terminate when the main thread (your code) finishes. The run loop, however, causes the program to run a loop and wait for asynchronous events (this also includes UI interactions, for example) to occur.
Note that inserting this same line also fixes your issues from the other question.

Swift CSVImporter framework with remote URLs

Initial use and testing of the framework. The examples provided and most of the searches from across the internet are using "local" or downloaded CSV files to the device, with (path:).
I would like to pass various remote URLs but there are not many examples, using (url: URL).
So far, I am simply in viewDidLoad() following the same code as provided with the sample playground file, and trying to output to the console.
I have tried to run this in a simulator for the iPhone 8 device. Running Xcode 10.1.
From the documentation, there is an ".onFail" handler, which gets invoked on the sourceURL's I have provided, but I do not know what error objects exist to do any further troubleshooting.
let sourceURL = URL(string: "https://files.datapress.com/leeds/dataset/leeds-city-council-dataset-register/Dataset%20register.csv")
guard let sourceURL2 = URL(string: "https://minio.l3.ckan.io/ckan/ni/resources/2477b63a-b1c4-45cc-a5ee-8e33e5b20b5b/supplies-and-services-contracts---2014.2015-yr.csv?AWSAccessKeyId=aspjTDZu90BQVi&Expires=1546982840&Signature=dLDVWMu%2Fp4RiePIRhntCX6WFMpw%3D") else {
fatalError("URL string error")
}
let importer = CSVImporter<[String]>(url: sourceURL)
importer?.startImportingRecords { $0 }.onFail {
print("fail")
}.onFinish({ importedRecords in
print(importedRecords.count)
})

How to do a "say" in Swift 3 inside command-line program?

What should I do in this case with the following code?
func convertToM4A(filename: String, voice: String) -> Bool {
let full_string = speaking_queue?.joined(separator: " ")
let command_string: [String] = [/"-v \"\(voice)\"",*/ "--progress", "--output-file=\"\(filename)\"","-i", " \"\(full_string!)\""]
print(command_string)
/
let DocumentsDirectory = FileManager().homeDirectory(forUser: "shyamalchandra")
print((DocumentsDirectory?.absoluteString)!)
*/
let task = Process()
task.launchPath = "/usr/bin/say"
task.arguments = command_string
let pipe = Pipe()
task.standardOutput = pipe
task.launch()
let data = pipe.fileHandleForReading.readDataToEndOfFile()
let output: String? = String(data: data, encoding: String.Encoding.utf8)
task.waitUntilExit()
if let output = output {
if !output.isEmpty {
print(output.trimmingCharacters(in: .whitespacesAndNewlines))
}
}
return true
}
At run-time, it complains about the TERM environment being not set and furthermore, doesn't write the file to disk. What to do?
The main error is how you build the argument array. The given arguments
are passed directly to the process. Process does not use the shell to
interpret the arguments, therefore you must not enclose them in quotation
marks.
Another problem is that the "-i" (interactive) option cannot be used
when writing to a file.
So your code should look like this:
func convertToM4A(filename: String, voice: String) -> Bool {
let fullString = "Hello world"
let task = Process()
task.launchPath = "/usr/bin/say"
task.arguments = [ "-v", voice, "-o", filename, fullString]
task.launch()
task.waitUntilExit()
return true
}
The "--progress" option causes a progress meter to be displayed on
standard error. If you want to display that then you would have to
read asynchronously from standard error.
If you're writing a native Mac app and want to record synthesized speech to an audio file, don't go trying to wrap a shell command — there's native API
for that. NSSpeechSynthesizer is the macOS API for text-to-speech in general, and it has a method startSpeaking(_:to:) that records output to an audio file.
This API outputs to an AIFF file, but there are numerous APIs you can use to convert/encode that to M4A: AVAssetReader/AVAssetWriter, AVAudioFile, lower-level CoreAudio C APIs, etc.
(Generally, if you're writing a native Mac program and there's something you want to do, check to see if there's an API for it before you go trying to wrap a shell command. Usually those shell commands are using the same API, so you're just punishing yourself with all the indirection, I/O parsing, etc.)
Yes, NSSpeechSynthesizer is an AppKit API, but you can use it in a command line tool.
Take a look at this lib, I've used it before and it is very capable of running shell script. With that then you can use the "say" command and send in some arguments. https://github.com/kareman/SwiftShell
You could try it this way for instance
import SwiftShell
try runAndPrint("say", "Hello world", 4, "arguments")
let array = ["Hello world", "we", "are"]
try runAndPrint("say", array, array.count + 2, "arguments")

Getting input from stdin in a Cocoa command-line app's sub process

I have a command-line app A, and in A I execute an executable script B, in B I'm expecting an input from stdin.
I wrote a demo, implementing A in Swift, using Foundation's Process api, finding that B, no matter implemented in whatever language, cannot get user input from stdin.
Code:
// `A`'s main.swift
import Foundation
let process = Process()
process.launchPath = PATH_TO_SCRIPT_B
process.launch()
process.waitUntilExit()
// `B`
#!/usr/bin/swift
print("intpu something")
let input = readLine()
print("input: \(input)")
I did not set the process's input since according to the doc:
If this method isn’t used, the standard input is inherited from the process that created the receiver.
UPDATE:
A is an executable package created using Swift Package Manager. I used swift package generate-xcodeproj to generate an Xcode project file. I confirmed that if I run the executable built using swift build or xcodebuild in a shell, the problem with getting input from stdin from B arose. However if I run it directly inside Xcode, by pressing command + R inside Xcode, then it worked. So if I understand the difference between running an executable in a shell and Xcode, I can probably make everything work.
func task() {
print("input here")
let x = input()
print ("inputed:" + x)
}
func input() -> String {
let keyboard = FileHandle.standardInput
let inputData = keyboard.availableData
let strData = String(data: inputData, encoding: .utf8)!
let string = strData.trimmingCharacters(in: .newlines)
return string
}
task()
Hope it helps