TITLE:: Making Standalone Applications
SUMMARY:: A guide to making SuperCollider-based applications by 'exporting' existing SuperCollider app configurations and projects.
CATEGORIES:: Platform>macOS, Tutorials
KEYWORD:: standalones, stand-alones

NOTE:: The concept of standalone applications is mainly relevant on macOS. On linux, Miguel Negrão and Fredrik Olofsson have created similar ways of packing versions of SC3 into independent setups. ::

section:: Introduction

SuperCollider 3.6 and earlier versions supported macOS Cocoa interfaces, and a special XCode project that allowed very flexible interface design, including removing and adding Menus. Since 3.7, SuperCollider uses Qt only, and the (now obsolete) standalone XCode project has been removed for 3.9. While the current Qt implementation is less flexible ATM, useful standalone applications can still be created with it using the scripts provided here (or similar ones).

One can package performance setups, installation pieces, software synthesis instruments, complex sound generators and other projects, into fully independent copies of the  SuperCollider.app including the IDE, and the Help system if desired. Custom interfaces can make such apps easily accessible to audiences that need not know how to install SuperCollider, run SuperCollider code, or even know that SuperCollider is involved.
This is useful for distributing applications to the general public, or for creating special-purpose applications for your own use. There is one important restriction: the entire application must be open-source and comply with the GNU General Public License.

On macOS, applications are special directories with an ".app" extension, known as emphasis::bundles::. SuperCollider emphasis::standalone applications:: are bundles that contain your SuperCollider code, as well as a renamed copy of SuperCollider itself that  runs your code.

section:: Practical Guide

(written by Alberto de Campo, 2017)

This Guide is for exporting copies of an existing SC3 setup,
for at least two scenarios:

LIST::
## Freezing an SC-based setup for non-expert users,
say an installation for a piece that runs in a museum,
which is as easily movable and selfcontained as possible.

## Copying a setup for a piece or performance setup,as backup
or safety copy, keeping much flexibility for skilled users.
::

Creating more complex user-oriented applications with SC was possible in versions pre 3.6, and a number of people work on additions to SC that will allow similar flexibility again.

Note::
Known working versions for making standalones:
strong::SC3.8.0, SC3.9dev from branch [2a105f1]::
code::
"https://supercollider.github.io/download".openOS;
::
Self-built SC versions may assume their code:: Platform.userAppSupportDir :: is called code::.../SuperCollider/ :: and not the name of the newly made app.
::

subsection:: How this guide works

This guide is a set of scripts for creating a SuperCollider-based Standalone app in a few basic steps:

numberedlist::
## copy the open SuperCollider.app or SC3-derived standalone.

## fix the copy's info files so it uses its own userAppSupportDir

## test that Platform.userAppSupportDir is independent in the new app!

... Then the adaptation to the specific project begins: ...

## transfer active quarks and extensions to the new app

## copy the project folder used to the new app

## make an internal startupFile for it

## test and adapt until it does what you want
::

subsection:: What to prepare

list::
## have your system ready with all desired quarks installed,
and a working startup file. (can be a very simple test setup)

## read each section, then try evaluating it at once;
 in case of problems, evaluate line by line,
 and tell me where which problems happen

## when you get to the wakeup kiss, share and enjoy!
::

subsection:: Naming, copying, and fixing up the new app

code::
// TO PREPARE, CHECK YOUR CURRENT config in Preferences->Interpreter:
// you should be using the internal SCClassLibrary and HelpSource,
// not an external git repository!
// To test exporting extensions, it is best to have some quarks
// or other extensions installed, as seen in the includePaths.

// 0 - define name and location of new app + helper functions
(
// define the name for the new app and its location:
~newAppName = "StehAllein";
~newAppLocation = "~/Desktop".standardizePath;

// --- nothing to be changed below this line --- \\
// some helper functions
~readText = { |path| File.readAllString(path); };
~writeText = { |path, string| File(path, "w").write(string).close; };
~copyFolder = { |orig, dest|
	var str = "cp -ir" + quote(orig) + quote(dest);
	str.postcs;
	unixCmd(str);
};

// make some needed paths and folders
~pathToThisApp = Platform.resourceDir.dirname.dirname;
~thisAppName = ~pathToThisApp.basename.splitext.first;
~pathToNewApp = ~newAppLocation +/+ ~newAppName ++ ".app";
~newAppResDir = ~pathToNewApp +/+ "Contents/Resources";
~newAppSupportDir = Platform.userConfigDir.dirname +/+ ~newAppName;
);


(
// 1. make a copy of thisApp with the newAppName:
// can take a while on slow harddisks.
// wait for RESULT = 0 to show!

if (File.exists(~pathToNewApp).not) {
	~copyFolder.(~pathToThisApp, ~pathToNewApp);
	File.mkdir(~newAppSupportDir);
} { warn("supportDir % already exists.".format(~pathToNewApp)) };
);

(
// 2. fixups in the new app:
// a. fix the Info.plist file by replacing the name:
~infoPlistPath = ~pathToNewApp +/+ "Contents/Info.plist";
// get its string, replace the SC names, write again
~infoString = ~readText.(~infoPlistPath);
~executableIndex = ~infoString.find("<key>CFBundleExecutable</key>");
~nameToReplace = ~infoString.copyRange(
	~infoString.find("<string>", offset: ~executableIndex) + 8,
	~infoString.find("</string>", offset: ~executableIndex) - 1
);

"replacing bundleName % in plist file at these locations: "
.postf(~nameToReplace.cs);
~foundNameLocs = ~infoString.findAll(~nameToReplace).postln;

~newInfoString = ~infoString.replace(~nameToReplace, ~newAppName );
~writeText.(~infoPlistPath, ~newInfoString);
// ~readText.(~infoPlistPath);

// b. rename the binary file:
"renaming macos binary to: ".post;
// fixups in the new app - 2. rename the binary inside the app folder
unixCmd("mv -i"
	+ quote(~pathToNewApp +/+ "Contents/MacOS/" +/+ ~nameToReplace)
	+ quote(~pathToNewApp +/+ "Contents/MacOS/" ++ ~newAppName).postln
);
);


// 3. *** time for the first wakeup kiss *** //
unixCmd("open" + ~pathToNewApp);

// ... and independence test:
// IN THE NEW APP, run this code:
Platform.userAppSupportDir.postcs;
::

NOTE:: THIS SHOULD END WITH ~newAppName! If it has the original ~thisAppName (the one you started from, e.g. ~/././SuperCollider), the new app will not be interfere with SuperCollider!
So, delete the app again, and start over using a recommended version of SC3 (see tested list on top)!

::

subsection:: Adaptation to the project

Quit the new standalone and go back to the starting app to do:
list::

##4. overwrite .startupFiles to look inside the app folder

##5. make a demo project folder and loadfile for the new app

##6.create a startup file that loads the project loadfile

##7. transfer active quarks and extensions to the new app

##8. replace/fill the project folder with your files, scripts etc
::

code::
(
// 4. write a class extension file to look for the startupFile
// in the app, in Platform.resourceDir for self-containment.
~overDir = ~newAppResDir +/+ "SCClassLibrary/SystemOverwrites";
File.mkdir(~overDir);
~writeText.value(~overDir +/+ "extModStartupFile.sc",
	"+ OSXPlatform {
	startupFiles {
		^[Platform.resourceDir +/+ \"startup.scd\"];
	}
}
"
);
~overDir.openOS;
)

(
// 5. write a basic startupFile:
~startupCode =
"// basic example startup file for osx standalone.
// avoid clash with default SC server
s.addr.port = 57105;

// boots server and plays a little sound
s.waitForBoot {
	{
		Line.kr(1, 0, 10, doneAction: 2) * SinOsc.ar(1000)
		* EnvGen.ar(Env.perc(0.01, 0.25), Impulse.kr(2, [0, 0.5]), 0.1)

	}.play;
};
";
~writeText.(~newAppResDir +/+ "startup.scd", ~startupCode);
(~newAppResDir +/+ "startup.scd").openOS;
)

// *** time for a second wakeup kiss *** //
// should run the startup file and play a sound:
unixCmd("open" + ~pathToNewApp);


// 6. For larger projects:
//    make an example project folder with a loadfile in it,
//    and a startup file that points to the loadfile.
(
~projDirName = ~newAppName ++ "_files";
~projDir = ~newAppResDir +/+ ~projDirName;
File.mkdir(~projDir);
~projDir.openOS;

~loadFileCode =
"\"*** startup file for % loading.\".postln;
\"*** My Platform.userAppSupportDir is: \".postln;
Platform.userAppSupportDir.postcs;
thisProcess.nowExecutingPath.openOS;

// configure server options here if needed:
s.options.memSize = 8192 * 16;
// move server port away from default (57110)
// to avoid interference/clashes with SuperCollider itself:
s.addr.port = 57105;

s.waitForBoot {
	\"*** server booted, plays ping.\".postln;
	Env.perc.test;

	\"*** loading files next ? \".postln;
	// put your loading sequence here:
	// \"loadX.scd\".loadRelative;
	// s.sync; // e.g. when loading buffers
 	// 1.wait;
 	// \"loadY.scd\".loadRelative;
};"
.format(~newAppName);

~loadfilepath = ~projDir +/+ "00_loadMe.scd";
~writeText.value(~loadfilepath, ~loadFileCode);
~loadfilepath.openOS;


// write a startupFile that points to the load file:
~startupCode =
"// example startup file for osx standalone.
// running loadfile in this project folder:
%.loadRelative;
".format((~projDirName +/+ ~loadfilepath.basename).cs);

~writeText.(~newAppResDir +/+ "startup.scd", ~startupCode);
(~newAppResDir +/+ "startup.scd").openOS;
)

// *** time for the third wakeup kiss *** //
unixCmd("open" + ~pathToNewApp);

// this should open the new app, and its loadfile!


// 7. create an internal extensions folder inside the new app,
// and copy all the currently active includePaths there:
(
~newAppQuarksDir = ~newAppResDir +/+ "InternalExtensions";

// copy all folders in my current quarks includePaths
// to Resources/SCClassLibrary to freeze them:
File.mkdir(~newAppQuarksDir);

~pathsToCopy = LanguageConfig.includePaths.reject { |path|
	["SCClassLibrary", "HelpSource"].includesEqual(path.basename)
};

~pathsToCopy.collect(_.basename).sort.printcsAll;

if (~newAppQuarksDir.pathMatch.notEmpty) {
	"/*** copying Quarks : ***/".postln;
	~pathsToCopy.do { |path|
		unixCmd(
			"cd" + quote(~newAppQuarksDir) ++ ";" ++
			" cp -ir" + quote(path).postln + ".");
	};
};
"";
)
// and now the new app folder contains all quarks:
~newAppQuarksDir.openOS;

// open the new app:
unixCmd("open" + ~pathToNewApp);

// AND IN THE NEW APP, run this to create a self-contained startup config file:
(
// use the internal extensions - repeat this when you move the app!
LanguageConfig.addIncludePath(Platform.resourceDir +/+ "InternalExtensions");
// exclude the default
LanguageConfig.addExcludePath(Platform.userExtensionDir);
LanguageConfig.addExcludePath(Platform.systemExtensionDir);
LanguageConfig.store;

// see if the internal path was stored OK:
LanguageConfig.includePaths.last;
// this should not be empty:
LanguageConfig.includePaths.last.pathMatch.postln;
)

// STILL IN THE NEW APP, REBOOT THE INTERPRETER NOW!
// - the added quarks should now be present.
::

Note:: You can use the Standalone quark to make sure your app remains closed, keeps using its to its InternalExtensions dir, and continues to ignore anything in its userExtensionDir or systemExtensionDir.
::
code::
// IN THE NEW APP, DO:
Quarks.install("https://github.com/adcxyz/Standalone");
// reboot interpreter, then do
Standalone.activate;
// reboot interpreter again, and done.


// 8. Now, put your project files in the project folder,
// adapt the loading sequence,
// and test until everything works to perfection...

// Share and Enjoy your special standalone app!
::
