Documentation/utils
namespace

utils

js/foo_uie_jsplitter.js:1685

Various utility functions.

property

Version

js/foo_uie_jsplitter.js:1692
Version: string

A string corresponding to the version.

Component uses semantic versioning (see https://semver.org).

Example

function is_compatible(requiredVersionStr) {
    let requiredVersion = requiredVersionStr.split('.');
    let currentVersion = utils.Version.split('.'); // e.g. 0.1.0-alpha.2
    if (currentVersion.length > 3) {
        currentVersion.length = 3; // We need only numbers
    }

    for(let i = 0; i< currentVersion.length; ++i) {
      if (currentVersion[i] != requiredVersion[i]) {
          return currentVersion[i] > requiredVersion[i];
      }
    }

    return true;
}

let requiredVersionStr = '1.0.0';
if (!is_compatible(requiredVersionStr)) {
    fb.ShowPopupMessage(`This script requires v${requiredVersionStr}. Current component version is v${utils.Version}.`);
}
method

CheckComponent

js/foo_uie_jsplitter.js:1723
CheckComponent(name, is_dll)

Checks the availability of foobar2000 component.

Parameters

NameTypeDescription
namestring
is_dll = trueoptionalboolean

If true, method checks filename as well as the internal name.

Returns

boolean

Example

console.log(utils.CheckComponent("foo_playcount", true));
method

CheckFont

js/foo_uie_jsplitter.js:1735
CheckFont(name)

Check if the font is installed.
Note: it cannot detect fonts loaded by foo_ui_hacks. However, gdi.Font can use those fonts.

Parameters

NameTypeDescription
namestring

Can be either in English or the localised name in your OS.

Returns

boolean
method

ColourPicker

js/foo_uie_jsplitter.js:1744
ColourPicker(window_id, default_colour)

Opens system colour picker dialog window (with some additional controls).

  • HEX: RRGGBB color value
  • Alpha: alpha component
  • Copy ARGB: button for copying the current color value in 0xAARRGGBB format

Parameters

NameTypeDescription
window_idnumber

Native window handle (HWND) to use as the dialog owner. Pass 0 to use the default foobar2000 window.

default_colournumber

Color in ARGB format

Returns

number

Chosen color in ARGB format or default_colour if cancelled

method

ConvertToAscii

js/foo_uie_jsplitter.js:1758
ConvertToAscii(str)

Converts string from UTF-8 to ASCII.

Parameters

NameTypeDescription
strstring

Returns

string
method

CopyFile

js/foo_uie_jsplitter.js:1766
CopyFile(from, to, overwrite)

Copies a file.

Parameters

NameTypeDescription
fromstring
tostring
overwrite = trueoptionalboolean

Returns

boolean
method

CopyFolder

js/foo_uie_jsplitter.js:1776
CopyFolder(from, to, overwrite, recur)

Copies a folder.

Parameters

NameTypeDescription
fromstring
tostring
overwrite = trueoptionalboolean
recur = trueoptionalboolean

Returns

boolean
method

CRC32

js/foo_uie_jsplitter.js:1795
CRC32(str)

Calculates CRC32 value for string

Parameters

NameTypeDescription
strstring

input string

Returns

number

CRC32 value for input string. If string is empty returns 0

method

CRC32FromFile

js/foo_uie_jsplitter.js:1803
CRC32FromFile(path)

Calculates CRC32 value for file content

Parameters

NameTypeDescription
pathstring

input file path

Returns

number

CRC32 value for input file content. If it was an error while reading file or file is empty returns 0

method

CreateFolder

js/foo_uie_jsplitter.js:1787
CreateFolder(path)

Creates a folder.

Parameters

NameTypeDescription
pathstring

Returns

boolean
method

DetectCharset

js/foo_uie_jsplitter.js:1811
DetectCharset(path)

Detect the codepage of the file.
Note: detection algorithm is probability based (unless there is a UTF BOM), i.e. even though the returned codepage is the most likely one, there's no 100% guarantee it's the correct one.\n Performance note: detection algorithm is quite slow, so results should be cached as much as possible.

Parameters

NameTypeDescription
pathnumber

Path to file

Returns

number

Codepage number on success, 0 if codepage detection failed

method

DownloadFileAsync

js/foo_uie_jsplitter.js:1824
DownloadFileAsync(url, path)

Downloads file from specified URL to save file path. Result of asyncronous operation can be found in callback on_download_file_done

Parameters

NameTypeDescription
urlstring

File URL

pathstring

Save file path

Example

utils.DownloadFileAsync("https://lastfm.freetls.fastly.net/i/u/770x0/0be145cbf80930684d41ad524fe53768.jpg", "z:\\blah.jpg");

function on_download_file_done(path, success, error_text) {
    console.log(path, success, error_text);
}
method

EditTextFile

js/foo_uie_jsplitter.js:1871
EditTextFile(path)

Edit a text file with the default text editor.
Default text editor can be changed via Edit button on the main tab of window.ShowConfigureV2.

Parameters

NameTypeDescription
pathnumber

Path to file

method

FileExists

js/foo_uie_jsplitter.js:1879
FileExists(path)

Parameters

NameTypeDescription
pathnumber

Path to file

Returns

boolean

true, if file exists.

method

FilePicker

js/foo_uie_jsplitter.js:1885
FilePicker(title, default_path, filter, mode)

Opens system file picker dialog window

Parameters

NameTypeDescription
title = undefinedoptionalstring

Title of dialog. If empty it will be the title by system default

default_path = undefinedoptionalstring

Default file path to choose. If only path without file name is specified it will open specified folder

filter = undefinedoptionalstring

Files filter in form (for ex.): "Image files (*.jpg;*.png;*.bmp)|*.jpg;*.png;*.bmp|All files (*.*)|*.*"

mode = 0optionalstring

File dialog mode. 0 - open, 1 - save

Returns

string

Chosen file path. If dialog is cancelled returns empty string

methoddeprecated

FileTest

js/foo_uie_jsplitter.js:1896
FileTest(path, mode)
Deprecated.

Various utility functions for working with file.

Deprecated: use utils.DetectCharset, utils.FileExists, utils.GetFileSize, utils.IsDirectory, utils.IsFile and utils.SplitFilePath instead.

Parameters

NameTypeDescription
pathstring
modestring

"chardet" - Detects the codepage of the given file. Returns a corresponding codepage number on success, 0 if codepage detection failed.
"e" - If file path exists, returns true.
"s" - Retrieves file size, in bytes.
"d" - If path is a directory, returns true.
"split" - Returns an array of [directory, filename, filename_extension].

Returns

*

Example

let arr = utils.FileTest("D:\\Somedir\\Somefile.txt", "split");
// arr[0] <= "D:\\Somedir\\" (always includes backslash at the end)
// arr[1] <= "Somefile"
// arr[2] <= ".txt"
method

FolderPicker

js/foo_uie_jsplitter.js:1921
FolderPicker(title, default_path)

Opens system folder picker dialog window

Parameters

NameTypeDescription
title = undefinedoptionalstring

Title of dialog. If empty it will be the title by system default

default_path = undefinedoptionalstring

Default folder path to choose

Returns

string

Chosen folder path. If dialog is cancelled returns empty string

method

FontPicker

js/foo_uie_jsplitter.js:1930
FontPicker(default_font, window_id)

Opens system font picker dialog window (with pixel size field extension).

Parameters

NameTypeDescription
default_font = undefinedoptionalGdiFont

(or D2DFont if window.DrawMode=1) If specified, it will be selected in the dialog, otherwise the default system message font will be selected

window_id = 0optionalnumber

Native window handle (HWND) to use as the dialog owner. Pass 0 to use the default foobar2000 window.

Returns

?GdiFont

(or D2DFont if window.DrawMode=1) Chosen font or default_font if cancelled (if default_font is undefined returns null)

Example source

method

FormatDuration

js/foo_uie_jsplitter.js:1941
FormatDuration(seconds)

Parameters

NameTypeDescription
secondsnumber

Returns

string

Example

console.log(utils.FormatDuration(plman.GetPlaylistItems(plman.ActivePlaylist).CalcTotalDuration())); // 1wk 1d 17:25:30
method

FormatFileSize

js/foo_uie_jsplitter.js:1950
FormatFileSize(bytes)

Parameters

NameTypeDescription
bytesnumber

Returns

string

Example

console.log(utils.FormatFileSize(plman.GetPlaylistItems(plman.ActivePlaylist).CalcTotalSize())); // 7.9 GB
method

GetAlbumArtAsync

js/foo_uie_jsplitter.js:1959
GetAlbumArtAsync(window_id, handle, art_id, need_stub, only_embed, no_load)

Load art image for the track asynchronously.

Parameters

NameTypeDescription
window_idnumber

unused

handleFbMetadbHandle
art_id = 0optionalnumber

See AlbumArtId enum

need_stub = trueoptionalboolean
only_embed = falseoptionalboolean
no_load = falseoptionalboolean

If true, "image" parameter will be null in on_get_album_art_done callback.

Example source

method

GetAlbumArtAsyncV2

js/foo_uie_jsplitter.js:1979
GetAlbumArtAsyncV2(window_id, handle, art_id, need_stub, only_embed, no_load)

Load art image for the track asynchronously.
Returns a Promise object, which will be resolved when art loading is done.

Parameters

NameTypeDescription
window_idnumber

unused

handleFbMetadbHandle
art_id = 0optionalnumber

See AlbumArtId enum

need_stub = trueoptionalboolean

If true, will return a stub image from Preferences>Display>Stub image path when there is no art image available.

only_embed = falseoptionalboolean

If true, will only try to load the embedded image.

no_load = falseoptionalboolean

If true, then no art loading will be performed and only path to art will be returned in ArtPromiseResult.

Returns

Promise.<ArtPromiseResult>

Example source

method

GetAlbumArtEmbedded

js/foo_uie_jsplitter.js:1995
GetAlbumArtEmbedded(rawpath, art_id)

Load embedded art image for the track.

Performance note: consider using utils.GetAlbumArtAsync or utils.GetAlbumArtAsyncV2 if there are a lot of images to load.

Parameters

NameTypeDescription
rawpathstring

Path to track file

art_id = 0optionalnumber

See AlbumArtId enum

Returns

GdiBitmap

(or D2DBitmap if window.DrawMode == 1)

Example

let img = utils.GetAlbumArtEmbedded(fb.GetNowPlaying().RawPath, 0);
method

GetAlbumArtV2

js/foo_uie_jsplitter.js:2009
GetAlbumArtV2(handle, art_id, need_stub)

Load art image for the track.

Performance note: consider using utils.GetAlbumArtAsync or utils.GetAlbumArtAsyncV2 if there are a lot of images to load.

Parameters

NameTypeDescription
handleFbMetadbHandle
art_id = 0optionalnumber

See AlbumArtId enum

need_stub = trueoptionalboolean

Returns

GdiBitmap

(or D2DBitmap if window.DrawMode == 1)

Example source

method

GetClipboardText

js/foo_uie_jsplitter.js:2023
GetClipboardText()

Returns

string

Returns an empty string if clipboard contents are not text.

method

GetCountryFlag

js/foo_uie_jsplitter.js:2028
GetCountryFlag(country_or_code)

Returns string code for display country flag with "Twemoji Mozilla" font
ATTENTION! Country flags are displayed correctly only in Direct2D draw mode (window.DrawMode == 1); GDI+ does not render "Twemoji Mozilla" color glyphs.

Parameters

NameTypeDescription
country_or_codestring

Case is not important. You can supply the code or full name. A few examples (full list see in the EXAMPLE file):
"by" "Belarus"
"gb" "United Kingdom"
"cn" "China"

Returns

string

Country string code

Example source

method

GetFileSize

js/foo_uie_jsplitter.js:2047
GetFileSize(path)

Parameters

NameTypeDescription
pathstring

Returns

number

File size, in bytes

method

GetLastModified

js/foo_uie_jsplitter.js:2040
GetLastModified(path)

Gets "last modified" attribute for file

Parameters

NameTypeDescription
pathstring

Returns

number

UNIX-time (seconds)

method

GetPackageInfo

js/foo_uie_jsplitter.js:2071
GetPackageInfo(package_id)

Get information about a package with the specified id.

Parameters

NameTypeDescription
package_idstring

Can be obtained by window.ScriptInfo

Returns

?JsPackageInfo

null if not found, package information otherwise

methoddeprecated

GetPackagePath

js/foo_uie_jsplitter.js:2079
GetPackagePath(package_id)
Deprecated.

Get path to a package directory with the specified id.
Throws exception if package is not found.

Deprecated: use utils.GetPackageInfo instead.

Parameters

NameTypeDescription
package_idstring

Can be obtained by window.ScriptInfo

Returns

string
method

GetSysColour

js/foo_uie_jsplitter.js:2092
GetSysColour(index)

Parameters

Returns

number

0 if failed

Example

let splitter_colour = utils.GetSysColour(15);
method

GetSystemMetrics

js/foo_uie_jsplitter.js:2101
GetSystemMetrics(index)

Parameters

Returns

number

0 if failed

method

Glob

js/foo_uie_jsplitter.js:2107
Glob(pattern, exc_mask, inc_mask)

Retrieves filepaths that match the supplied pattern.

Parameters

NameTypeDescription
patternstring

For the path, you can use the * and ? wildcards for any intermediate directory and for the file name.

exc_mask = 0x10optionalnumber

Mask to exclude files. Default is FILE_ATTRIBUTE_DIRECTORY. See flags like FILE_ATTRIBUTE_NORMAL etc.

inc_mask = 0xffffffffoptionalnumber

Mask to include files

Returns

Array<string>

Example

let arr = utils.Glob("C:\\*.*");
let arr2 = utils.Glob(fb.ProfilePath + 'image*\\album?\\*.jpg');
method

HTTPRequestAsync

js/foo_uie_jsplitter.js:1841
HTTPRequestAsync(type, url, user_agent_or_headers, post_data)

Does HTTP request of specified type to URL with optional user headers and post data

Parameters

NameTypeDescription
typenumber

Use 0 for GET, 1 for POST.

urlnumber
user_agent_or_headers = ""optionalstring

can be a string specifying the user agent, or a stringified JSON object specifying user HTTP request headers (see examples)

post_data = ""optionalstring

This is ignored for GET requests and can be omitted. It is required for POST requests. It could be form data or a stringified JSON object/array.

Returns

number

a unique task_id which is used as the first argument in the on_http_request_done callback.
When making a POST request, you should set a Content-Type header. Valid values could be application/json or application/x-www-form-urlencoded.

Example

let headers = JSON.stringify({
  'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:123.0) Gecko/20100101 Firefox/123.0',
  'Referer' : 'https://www.last.fm',
});
let url = 'https://www.last.fm/music/Madonna/+images';
let task_id = utils.HTTPRequestAsync(0, url, headers);

function on_http_request_done(task_id, success, response_text, status, content_type)
{
  console.log("status = ", status, "response_text = ", response_text);
}

Example sources

method

InputBox

js/foo_uie_jsplitter.js:2121
InputBox(window_id, prompt, caption, default_val, error_on_cancel, help_text)

Parameters

NameTypeDescription
window_idnumber

Native window handle (HWND) to use as the dialog owner. Pass 0 to use the default foobar2000 window.

promptstring
captionstring
default_val = ''optionalstring
error_on_cancel = falseoptionalboolean

If set to true, use try/catch like Example2.

help_text = ''optionalstring

If not empty, a Help button will show in the dialog. If help_text begins with "http://" or "https://", it will launch a web browser otherwise it will open a popup window containing the text

Returns

string

Examples

// With "error_on_cancel" not set (or set to false), cancelling the dialog will return "default_val".
let username = utils.InputBox(0, "Enter your username", "Spider Monkey Panel", "");
// Using Example1, you can't tell if OK or Cancel was pressed if the return value is the same
// as "default_val". If you need to know, set "error_on_cancel" to true which throws a script error
// when Cancel is pressed.
let username = "";
try {
   username = utils.InputBox(0, "Enter your username", "Spider Monkey Panel", "", true);
   // OK was pressed.
} catch(e) {
    // Dialog was closed by pressing Esc, Cancel or the Close button.
}
method

IsDirectory

js/foo_uie_jsplitter.js:2148
IsDirectory(path)

Parameters

NameTypeDescription
pathstring

Returns

boolean

true, if location exists and it's a directory

method

IsFile

js/foo_uie_jsplitter.js:2154
IsFile(path)

Parameters

NameTypeDescription
pathstring

Returns

boolean

true, if location exists and it's a file

method

IsKeyPressed

js/foo_uie_jsplitter.js:2160
IsKeyPressed(vkey)

Parameters

NameTypeDescription
vkeynumber

See https://docs.microsoft.com/en-us/windows/win32/inputdev/virtual-key-codes.
Some are defined in Flags, like VK_LEFT

Returns

boolean
method

ListFonts

js/foo_uie_jsplitter.js:2167
ListFonts(mode)

Gets system font collection array filled up by font families' names.

Parameters

NameTypeDescription
mode = 0optionalnumber

0 - Auto, 1 - GDI fonts, 2 - DirectWrite fonts

Returns

Array<string>

array of font family names

method

MapString

js/foo_uie_jsplitter.js:2174
MapString(text, lcid, flags)

Parameters

NameTypeDescription
textstring
lcidstring
flagsnumber

defined in Flags, like LCMAP_LOWERCASE

Returns

string
method

MD5

js/foo_uie_jsplitter.js:2183
MD5(str)

Calculates MD5 for string

Parameters

NameTypeDescription
strstring

input string

Returns

string

MD5 value for input in hex format string. If input string is empty returns "d41d8cd98f00b204e9800998ecf8427e"

method

MD5FromFile

js/foo_uie_jsplitter.js:2191
MD5FromFile(path)

Calculates MD5 value for file content

Parameters

NameTypeDescription
pathstring

input file path

Returns

string

MD5 value for input file content in hex format string. If it was an error while reading file returns empty string. If file is empty returns "d41d8cd98f00b204e9800998ecf8427e"

method

MessageBox

js/foo_uie_jsplitter.js:2199
MessageBox(msg, title, buttons, icon, default_button, help_text)

Shows system message box with specified parameters

Parameters

NameTypeDescription
msgstring
title = "JSplitter"optionalstring
buttons = MessageBoxButtons.OKoptionalMessageBoxButtons

See MessageBoxButtons

icon = MessageBoxIcon.InformationoptionalMessageBoxIcon

See MessageBoxIcon

default_button = MessageBoxDefaultButton.Button1optionalMessageBoxDefaultButton

See MessageBoxDefaultButton

help_text = ""optionalstring

If not empty, a Help button will show in the dialog. If help_text begins with "http://" or "https://", it will launch a web browser otherwise it will open a popup window containing the text

Returns

number

Result of message box. See DialogResult

method

ParseHtml

js/foo_uie_jsplitter.js:2212
ParseHtml(html)

Parses an HTML string and returns a lightweight DOM-like document.

This parser is backed by the native HTML parser. It does not use ActiveX, MSHTML, a browser engine, or external resource loading.

Notes:
- The input must be HTML text, not a file path.
- The returned API is DOM-like, but it is not a full browser DOM.
- CSS, layout, visibility, scripts, network loading, and browser events are not processed.
- innerText is currently an alias of textContent.
- The method returns null if the document could not be created.

Parameters

NameTypeDescription
htmlstring

HTML source text.

Returns

?HtmlDocument

Parsed document, or null on failure.

Example

const doc = utils.ParseHtml("<html><body><p>Hello <b>world</b></p></body></html>");
if (doc) console.log(doc.body.textContent); // "Hello world"

Example source

method

PathWildcardMatch

js/foo_uie_jsplitter.js:2235
PathWildcardMatch(pattern, str)

Check if the supplied string matches the pattern.
Using Microsoft MS-DOS wildcards match type. eg "*.txt", "abc?.tx?"

Parameters

NameTypeDescription
patternstring
strstring

Returns

boolean
method

ReadBinaryFile

js/foo_uie_jsplitter.js:2299
ReadBinaryFile(path)

Read a file as raw binary.

Parameters

NameTypeDescription
pathstring

Absolute file path

Returns

Uint8Array

File bytes, or null if was an error

Example source

method

ReadINI

js/foo_uie_jsplitter.js:2308
ReadINI(filename, section, key, default_val)

Note: this only returns up to 255 characters per value.

Parameters

NameTypeDescription
filenamestring
sectionstring
keystring
default_valoptionalstring

Returns

string

Example

let username = utils.ReadINI("e:\\my_file.ini", "Last.fm", "username");
method

ReadTextFile

js/foo_uie_jsplitter.js:2245
ReadTextFile(filename, codepage)

Performance note: supply codepage argument if it is known, since codepage detection might take some time.

Parameters

NameTypeDescription
filenamestring
codepage = 65001optionalnumber

See Codepages.js. If codepage is 0, then automatic detection is performed.

Returns

string

Example

let text = utils.ReadTextFile("E:\\some text file.txt");
method

ReadUTF8

js/foo_uie_jsplitter.js:2257
ReadUTF8(path)

Returns a string. Will be empty if path doesn't exist or there was an error opening it.
For UTF8 files with or without BOM. If you're unsure about the file encoding, continue to use utils.ReadTextFile

Parameters

NameTypeDescription
pathstring

Returns

string
method

RecyclePath

js/foo_uie_jsplitter.js:2265
RecyclePath(path)

Moves a file or directory to the Recycle Bin.

Parameters

NameTypeDescription
pathstring

path to a file or directory

Returns

boolean

true on success, false otherwise

method

RemovePath

js/foo_uie_jsplitter.js:2273
RemovePath(path)

Returns a number to indicate how many files/folders were removed.
May be 0 if the path did not exist or -1 if some other internal error occurred.

Parameters

NameTypeDescription
pathstring

Returns

number
method

RenamePath

js/foo_uie_jsplitter.js:2281
RenamePath(from, to)

Renames file or folder path.

Parameters

NameTypeDescription
fromstring
tostring

Returns

boolean
method

ReplaceIllegalChars

js/foo_uie_jsplitter.js:2290
ReplaceIllegalChars(str, strip_trailing_periods)

Uses the same modern unicode replacements as the foobar2000 converter/file operations.

Parameters

NameTypeDescription
strstring
strip_trailing_periods = falseoptionalboolean

Set to true if str is a folder name.

Returns

boolean
method

Run

js/foo_uie_jsplitter.js:2322
Run(target, args, working_dir, verb, show, wait)

Runs a file, executable, URL, or document through the Windows shell.
This method uses ShellExecuteEx, so it supports shell verbs, file associations, URLs, and elevation through "runas".
Unlike RunCmdAsync, this method does not capture stdout or stderr and does not provide timeout handling.
If wait is true, the call blocks until the launched process exits, when a process handle is available.

Parameters

NameTypeDescription
targetstring

File, executable, URL, or document to run/open.
If this value is empty, the method returns a RunResult with OK=false and Win32Error=ERROR_INVALID_PARAMETER.

argsoptionalstring|string[]

Command line arguments.
If a string is passed, it is appended as-is.
If an array is passed, each item is quoted automatically when needed.
For documents, URLs, or shell verbs that do not use parameters, this can be omitted.
For complex cmd.exe commands using shell syntax such as redirection, pipes, &, or &&, a string is usually more appropriate.

working_dir = ""optionalstring

Working directory for the process.
Pass an empty string to use the default working directory.

verb = ""optionalstring

Shell verb to use.
Pass an empty string to use the default verb.
Common values are "open", "edit", "print", and "runas".
Use "runas" to request elevation through UAC.

show = ShowWindow.Hideoptionalnumber

Requested window display mode.
Use one of the ShowWindow values, for example ShowWindow.Hide or ShowWindow.Show.
The target application or shell handler may ignore this value.

wait = falseoptionalboolean

Whether to wait for the launched process to exit.
If false, OK means that ShellExecuteEx accepted the request.
If true, the method waits for the launched process to exit when a process handle is available, and then fills ExitCode.
When wait=true and a process exit code is available, OK is true only if the process exits with code 0.
A non-zero process exit code is reported as OK=false, with Win32Error usually remaining 0.
If wait=true but no process handle is available, OK=false and Win32Error=ERROR_INVALID_HANDLE.
Be careful: wait=true blocks the current script until the process exits and has no timeout.
Use RunCmdAsync if you need asynchronous completion, stdout/stderr capture, or timeout handling.

Returns

RunResult

Result object.

Examples

// Open a URL with the default browser.
const result = utils.Run("https://www.foobar2000.org");

console.log(result.OK);
console.log(result.Win32Error);
console.log(result.ShellCode);
// Run a command and wait for its exit code.
const result = utils.Run(
    "cmd.exe",
    '/c "exit /b 7"',
    "",
    "",
    ShowWindow.Hide,
    true
);

console.log(result.OK);        // false: process exited with a non-zero code
console.log(result.ExitCode);  // 7: process exit code
console.log(result.Win32Error); // 0: process was started successfully
// Run elevated.
const result = utils.Run(
    "notepad.exe",
    undefined,
    "",
    "runas",
    ShowWindow.Show,
    false
);
method

RunCmdAsync

js/foo_uie_jsplitter.js:2403
RunCmdAsync(app, args, working_dir, show, timeout_ms)

Runs an external process asynchronously.
Standard output and standard error are captured separately.
The method returns a task id immediately, and the result is delivered later to on_run_cmd_async_done.
Completion callbacks may arrive in a different order than the RunCmdAsync calls were made.
Use the returned task id to match the result with the original RunCmdAsync call.
If the process does not finish before timeout_ms, the whole process tree is terminated.
Pass 0 as timeout_ms to wait indefinitely.

Parameters

NameTypeDescription
appstring

Full path or executable name to run.
If this value is empty, the callback receives success=false and stderr contains an error message.

argsoptionalstring|string[]

Command line arguments.
If a string is passed, it is appended to the command line as-is.
If an array is passed, each item is quoted automatically when needed.

working_dir = ""optionalstring

Working directory for the process.

show = ShowWindow.Hideoptionalnumber

Window display mode.

timeout_ms = 0optionalnumber

Maximum time to wait for the process, in milliseconds.
Pass 0 to wait indefinitely.
On timeout, the callback receives success=false, exit_code=0xFFFFFFFF, and stderr contains a timeout message.

Returns

number

Task id of the asynchronous operation.

Throws

Throws if called before foobar2000 is fully initialized, if args is invalid, or if the worker thread could not be started.

method

SetClipboardText

js/foo_uie_jsplitter.js:2440
SetClipboardText(text)

Parameters

NameTypeDescription
textstring
method

SHA1

js/foo_uie_jsplitter.js:2445
SHA1(str)

Calculates SHA1 for string

Parameters

NameTypeDescription
strstring

input string

Returns

string

SHA1 value for input in hex format string. If input string is empty returns "da39a3ee5e6b4b0d3255bfef95601890afd80709"

method

SHA1FromFile

js/foo_uie_jsplitter.js:2453
SHA1FromFile(path)

Calculates SHA1 value for file content

Parameters

NameTypeDescription
pathstring

input file path

Returns

string

SHA1 value for input file content in hex format string. If it was an error while reading file returns empty string. If file is empty returns "da39a3ee5e6b4b0d3255bfef95601890afd80709"

method

ShowHtmlDialog

js/foo_uie_jsplitter.js:2461
ShowHtmlDialog(window_id, code_or_path, options)

Displays an html dialog, rendered by IE engine.
Utilizes the latest non-Edge IE that you have on your system.
Dialog is modal (blocks input to the parent window while open).

Html code must be IE compatible, meaning:

  • JavaScript features are limited by IE (see https://www.w3schools.com/js/js_versions.asp)
  • Objects passed to data are limited to standard JavaScript objects:
    • No extensions from Spider Monkey Panel (e.g. no FbMetadbHandle or GdiBitmap/D2DBitmap etc.)
There are also additional limitations:
  • options.data may contain only the following types:
    • Basic types: number, string, boolean, null, undefined
    • Objects as string: the only way to pass objects is to convert them to string and back with JSON.stringify() and JSON.parse()
    • Arrays: must be cast via .toArray() inside html. Each element has same type limitations as options.data
    • Functions: may have a maximum of 7 arguments. Each argument has same type limitations as options.data
The following properties are available through window.external inside the html dialog:
  • dialogArguments - read-only value containing options.data
  • dialogWindow - read-only native window handle (HWND) of the html dialog, represented as a number.
    It can be passed as window_id to JSplitter modal dialog functions to make the html dialog their owner, e.g. utils.ColourPicker, utils.FontPicker, utils.InputBox or utils.ShowHtmlDialog.
    The handle is valid only while the html dialog exists.

Parameters

NameTypeDescription
window_idnumber

native window handle (HWND) to use as the dialog owner; pass 0 to use the default foobar2000 window

code_or_pathstring

Html code or file path. File path must begin with file:// prefix.

options = undefinedoptionalobject
options.width = 250optionalnumber

Window width

options.height = 100optionalnumber

Window height

options.x = 0optionalnumber

Window horizontal position relative to desktop

options.y = 0optionalnumber

Window vertical position relative to desktop

options.center = trueoptionalboolean

If true and if options.x and options.y are not set, will center window relative to fb2k position.

options.context_menu = falseoptionalboolean

If true, will enable right-click context menu.

options.resizable = falseoptionalboolean

If true, will allow to resize the window.

options.selection = falseoptionalboolean

If true, will allow to select everything (label texts, buttons and etc).

options.scroll = falseoptionalboolean

If true, will display scrollbars.

options.data = undefinedoptional*

Will be saved in window.external.dialogArguments and can be accessed from JavaScript executed inside HTML window. This data is read-only and should not be modified. Has type limitations (see above).

Example

<caption>Dialog from file</caption>
utils.ShowHtmlDialog(0, `file://${fb.ComponentPath}samples/basic/html/PopupWithCheckBox.html`);

Example source

method

SplitFilePath

js/foo_uie_jsplitter.js:2521
SplitFilePath(path)

Parameters

NameTypeDescription
pathstring

Returns

Array<string>

An array of [directory, filename, filename_extension]

Example

let arr = utils.SplitFilePath('D:\\Somedir\\Somefile.txt');
// arr[0] <= 'D:\\Somedir\\' (always includes backslash at the end)
// arr[1] <= 'Somefile'
// arr[2] <= '.txt'
method

WriteBinaryFile

js/foo_uie_jsplitter.js:2533
WriteBinaryFile(path, data)

Write raw binary data to a file.

Parameters

NameTypeDescription
pathstring

Absolute file path

dataUint8Array

Bytes to write

Returns

boolean

true on success

Example

const img = gdi.Image(`${fb.ComponentPath}\\samples\\d2d\\images\\Field.jpg`);

let imgPixelData = img.GetPixelData();

utils.WriteBinaryFile("D:\\Field.bin", imgPixelData);

let rData = utils.ReadBinaryFile("D:\\Field.bin");

let rImg = gdi.CreateImageFromPixelData(rData, 2208, 1242);

function on_paint(gr) {
    gr.DrawImage(rImg, 0, 0, img.Width, img.Height, 0, 0, img.Width, img.Height);
}
method

WriteINI

js/foo_uie_jsplitter.js:2555
WriteINI(filename, section, key, val)

Parameters

NameTypeDescription
filenamestring
sectionstring
keystring
valstring

Returns

boolean

Example

utils.WriteINI("e:\\my_file.ini", "Last.fm", "username", "Bob");
method

WriteTextFile

js/foo_uie_jsplitter.js:2567
WriteTextFile(filename, content, write_bom)

Note: the parent folder must already exist. Note2: the file is written with UTF8 encoding.

Parameters

NameTypeDescription
filenamestring
contentstring
write_bom = trueoptionalboolean

Returns

boolean

Examples

<caption>Default encoding</caption>
// write_bom missing but defaults to true, resulting file is UTF8-BOM
utils.WriteTextFile("z:\\1.txt", "test");
<caption>UTF8 with BOM</caption>
utils.WriteTextFile("z:\\2.txt", "test", true);
<caption>UTF8 without BOM</caption>
utils.WriteTextFile("z:\\3.txt", "test", false);