utils
Various utility functions.
Various utility functions.
HighResolutionTimersEnabled: boolean
Allowing scripts to detect whether the high-resolution timer backend is actually active and adapt scheduling/yield strategies accordingly.
The value is derived from the Advanced Preferences → Performance → Use high-resolution timers setting, but reports the effective runtime state, not merely the checkbox: it returns true only when the option is enabled and the current Windows version actually supports high-resolution waitable timers; otherwise it returns false.
Is64Bit: boolean
Indicates whether the current foobar2000 process architecture is 64-bit. This does not describe the operating system architecture; use utils.IsOS64Bit for that.
IsOS64Bit: boolean
Indicates whether the operating system architecture is 64-bit. Unlike utils.Is64Bit, this value describes Windows itself and remains true when 32-bit foobar2000 runs on 64-bit Windows.
SystemInfo: SystemInfo
Returns a fresh snapshot of operating-system, physical-memory and dedicated/local video-memory information. All memory values are reported in bytes. See SystemInfo for the returned object properties.
const info = utils.SystemInfo;
console.log(`${info.OS} (build ${info.Build})`);
console.log(`RAM: ${utils.FormatFileSize(info.RAM.Process)} used by foobar2000`);
if (info.VRAM) {
console.log(`${info.VRAM.Adapter}: ${utils.FormatFileSize(info.VRAM.Process)} VRAM used`);
}
Version: string
A string corresponding to the version.
Component uses semantic versioning (see https://semver.org).
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}.`);
}
CheckComponent(name, is_dll)
Checks the availability of foobar2000 component.
| Name | Type | Description |
|---|---|---|
name | string | |
is_dll = trueoptional | boolean | If true, method checks filename as well as the internal name. |
booleanconsole.log(utils.CheckComponent("foo_playcount", true));
CheckFont(name)
Checks whether a font family is available to the current foobar2000 process. This includes system-installed fonts and fonts loaded with utils.LoadFont.
| Name | Type | Description |
|---|---|---|
name | string | Font family name. Can be either in English or the localised name in your OS. |
booleanError — If Windows font enumeration returns inconsistent data.
ColourPicker(window_id, default_colour)
Opens system colour picker dialog window (with some additional controls).
| Name | Type | Description |
|---|---|---|
window_id | number | Native window handle (HWND) to use as the dialog owner. Pass 0 to use the default foobar2000 window. |
default_colour | number | Color in ARGB format |
number — Chosen color in ARGB format or default_colour if cancelled
Error — If no valid owner window is supplied and the panel host is not fully initialized.
ConvertToAscii(str)
Converts string from UTF-8 to ASCII.
| Name | Type | Description |
|---|---|---|
str | string |
stringCopyFile(from, to, overwrite)
Copies a file.
Relative filesystem paths are resolved as described in utils.ReadTextFile.
| Name | Type | Description |
|---|---|---|
from | string | |
to | string | |
overwrite = trueoptional | boolean |
booleanCopyFolder(from, to, overwrite, recur)
Copies a folder.
Relative filesystem paths are resolved as described in utils.ReadTextFile.
| Name | Type | Description |
|---|---|---|
from | string | |
to | string | |
overwrite = trueoptional | boolean | |
recur = trueoptional | boolean |
booleanCRC32(str)
Calculates CRC32 value for string
| Name | Type | Description |
|---|---|---|
str | string | input string |
number — CRC32 value for input string. If string is empty returns 0
CRC32FromFile(path)
Calculates CRC32 value for file content
Relative filesystem paths are resolved as described in utils.ReadTextFile.
| Name | Type | Description |
|---|---|---|
path | string | input file path |
number — CRC32 value for input file content. If it was an error while reading file or file is empty returns 0
CreateFolder(path)
Creates a folder.
Relative filesystem paths are resolved as described in utils.ReadTextFile.
| Name | Type | Description |
|---|---|---|
path | string |
booleanDetectCharset(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.
Performance note: detection algorithm is quite slow, so results should be cached as much as possible.
Relative filesystem paths are resolved as described in utils.ReadTextFile.
| Name | Type | Description |
|---|---|---|
path | number | Path to file |
number — Codepage number on success, 0 if codepage detection failed
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
Relative filesystem paths are resolved as described in utils.ReadTextFile.
| Name | Type | Description |
|---|---|---|
url | string | File URL |
path | string | Save file path |
Error — If called from a panel before foobar2000 is fully initialized.
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);
}
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.
Relative filesystem paths are resolved as described in utils.ReadTextFile.
| Name | Type | Description |
|---|---|---|
path | number | Path to file |
Error — If called before foobar2000 is fully initialized.
FileExists(path)
Relative filesystem paths are resolved as described in utils.ReadTextFile.
| Name | Type | Description |
|---|---|---|
path | number | Path to file |
boolean — true, if file exists.
FilePicker(title, default_path, filter, mode, window_id)
Opens system file picker dialog window
Relative filesystem paths are resolved as described in utils.ReadTextFile.
| Name | Type | Description |
|---|---|---|
title = undefinedoptional | string | Title of dialog. If empty it will be the title by system default |
default_path = undefinedoptional | string | Default file path to choose. If only path without file name is specified it will open specified folder |
filter = undefinedoptional | string | Files filter in form (for ex.): "Image files (*.jpg;*.png;*.bmp)|*.jpg;*.png;*.bmp|All files (*.*)|*.*" |
mode = 0optional | string | File dialog mode. 0 - open, 1 - save |
window_id = 0optional | number | Native window handle (HWND) to use as the dialog owner. Pass 0 to use the default foobar2000 window. |
string — Chosen file path. If dialog is cancelled returns empty string
Error — If no valid owner window is supplied and the panel host is not fully initialized.
FileTest(path, mode)
Various utility functions for working with file.
Deprecated: use utils.DetectCharset, utils.FileExists, utils.GetFileSize, utils.IsDirectory, utils.IsFile and utils.SplitFilePath instead.
Relative filesystem paths are resolved as described in utils.ReadTextFile. This applies only to modes that access the filesystem; split only splits the supplied path string.
| Name | Type | Description |
|---|---|---|
path | string | |
mode | string | "chardet" - Detects the codepage of the given file. Returns a corresponding codepage number on success, 0 if codepage detection failed. |
*Error — If mode is not one of the supported values.
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"
FolderPicker(title, default_path, window_id)
Opens system folder picker dialog window
Relative filesystem paths are resolved as described in utils.ReadTextFile.
| Name | Type | Description |
|---|---|---|
title = undefinedoptional | string | Title of dialog. If empty it will be the title by system default |
default_path = undefinedoptional | string | Default folder path to choose |
window_id = 0optional | number | Native window handle (HWND) to use as the dialog owner. Pass 0 to use the default foobar2000 window. |
string — Chosen folder path. If dialog is cancelled returns empty string
Error — If no valid owner window is supplied and the panel host is not fully initialized.
FontPicker(default_font, window_id)
Opens system font picker dialog window (with pixel size field extension).
| Name | Type | Description |
|---|---|---|
default_font = undefinedoptional | GdiFont | (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 = 0optional | number | Native window handle (HWND) to use as the dialog owner. Pass 0 to use the default foobar2000 window. |
?GdiFont — (or D2DFont if window.DrawMode=1) Chosen font or default_font if cancelled (if default_font is undefined returns null)
Error — If no valid owner window is supplied and the panel host is not fully initialized, or default_font is not compatible with the current draw mode.
FormatDuration(seconds)
| Name | Type | Description |
|---|---|---|
seconds | number |
stringconsole.log(utils.FormatDuration(plman.GetPlaylistItems(plman.ActivePlaylist).CalcTotalDuration())); // 1wk 1d 17:25:30
FormatFileSize(bytes)
| Name | Type | Description |
|---|---|---|
bytes | number |
stringconsole.log(utils.FormatFileSize(plman.GetPlaylistItems(plman.ActivePlaylist).CalcTotalSize())); // 7.9 GB
GetAlbumArtAsync(window_id, handle, art_id, need_stub, only_embed, no_load)
Load art image for the track asynchronously.
| Name | Type | Description |
|---|---|---|
window_id | number | unused |
handle | FbMetadbHandle | |
art_id = 0optional | number | See AlbumArtId enum |
need_stub = trueoptional | boolean | |
only_embed = falseoptional | boolean | |
no_load = falseoptional | boolean | If true, "image" parameter will be null in on_get_album_art_done callback. |
Error — If handle is null or the panel host is not fully initialized.
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.
| Name | Type | Description |
|---|---|---|
window_id | number | unused |
handle | FbMetadbHandle | |
art_id = 0optional | number | See AlbumArtId enum |
need_stub = trueoptional | boolean | If true, will return a stub image from Preferences>Display>Stub image path when there is no art image available. |
only_embed = falseoptional | boolean | If true, will only try to load the embedded image. |
no_load = falseoptional | boolean | If true, then no art loading will be performed and only path to art will be returned in ArtPromiseResult. |
Promise.<ArtPromiseResult>Error — If handle is null, the panel host is not fully initialized, or Worker promise setup fails.
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.
Relative filesystem paths are resolved as described in utils.ReadTextFile. URLs and foobar2000 URI paths are passed through unchanged.
| Name | Type | Description |
|---|---|---|
rawpath | string | Path to track file |
art_id = 0optional | number | See AlbumArtId enum |
GdiBitmap — (or D2DBitmap if window.DrawMode == 1)
let img = utils.GetAlbumArtEmbedded(fb.GetNowPlaying().RawPath, 0);
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.
| Name | Type | Description |
|---|---|---|
handle | FbMetadbHandle | |
art_id = 0optional | number | See AlbumArtId enum |
need_stub = trueoptional | boolean |
GdiBitmap — (or D2DBitmap if window.DrawMode == 1)
Error — If handle is null.
GetClipboardText()
string — Returns an empty string if clipboard contents are not text.
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.
| Name | Type | Description |
|---|---|---|
country_or_code | string | Case is not important. You can supply the code or full name. A few examples (full list see in the EXAMPLE file): |
string — Country string code
GetDriveInfo(path)
Returns information about a logical drive or volume containing the supplied path.
The method also works with drive roots returned by utils.GetDrives.
Unready removable/CD drives still return an object with IsReady == false when the drive itself exists.
Relative filesystem paths are resolved as described in utils.ReadTextFile.
| Name | Type | Description |
|---|---|---|
path | string | Drive root or path on the drive |
?DriveInfo — Drive information, or null if the path cannot be resolved to a drive
GetDrives()
Returns logical drive roots known to Windows, including mapped network drives and removable drives.
A returned removable/CD drive may not currently be ready; use utils.GetDriveInfo to query its state.
Array<string> — Drive root paths, for example ["C:\\", "D:\\"]
GetFileSize(path)
Relative filesystem paths are resolved as described in utils.ReadTextFile.
| Name | Type | Description |
|---|---|---|
path | string |
number — File size, in bytes
GetFolderSize(path)
Calculates the total size of files contained in a directory and its subdirectories.
Directory reparse points are not followed. Entries that cannot be accessed are skipped.
This is a synchronous operation and may take time for large directory trees.
Relative filesystem paths are resolved as described in utils.ReadTextFile.
| Name | Type | Description |
|---|---|---|
path | string | Directory path |
number — Total size in bytes, or 0 if the path is not a directory
GetFolderSizeAsync(path)
Calculates the total size of files contained in a directory and its subdirectories asynchronously.
For synchronous calculation, use utils.GetFolderSize.
Directory reparse points are not followed. Entries that cannot be accessed are skipped.
The method returns a task id immediately, and the result is delivered later to on_get_folder_size_done.
Use the returned task id to match the result with the original call.
Relative filesystem paths are resolved as described in utils.ReadTextFile.
| Name | Type | Description |
|---|---|---|
path | string | Directory path |
number — Task id of the asynchronous operation
Error — If called from a panel before foobar2000 is fully initialized or the worker thread cannot be started.
GetLastModified(path)
Gets "last modified" attribute for file Relative filesystem paths are resolved as described in utils.ReadTextFile.
| Name | Type | Description |
|---|---|---|
path | string |
number — UNIX-time (seconds)
GetPackageInfo(package_id)
Get information about a package with the specified id.
| Name | Type | Description |
|---|---|---|
package_id | string | Can be obtained by window.ScriptInfo |
?JsPackageInfo — null if not found, package information otherwise
GetPackagePath(package_id)
Get path to a package directory with the specified id.
Throws exception if package is not found.
Deprecated: use utils.GetPackageInfo instead.
| Name | Type | Description |
|---|---|---|
package_id | string | Can be obtained by window.ScriptInfo |
stringError — If no package with package_id exists.
GetShortPath(path)
Converts an existing path to its Windows short (8.3) form.
Returns an empty string if the path does not exist, the conversion fails, or short-name generation is unavailable for the path.
Relative filesystem paths are resolved as described in utils.ReadTextFile.
| Name | Type | Description |
|---|---|---|
path | string | File or directory path |
string — Short path or an empty string on failure
GetSysColour(index)
| Name | Type | Description |
|---|---|---|
index | number | https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getsyscolor |
number — 0 if failed
Error — If index is not a valid system colour index.
let splitter_colour = utils.GetSysColour(15);
GetSystemMetrics(index)
| Name | Type | Description |
|---|---|---|
index | number | https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getsyscolor |
number — 0 if failed
GetWaveformAsync(handle, points, start, duration, on_progress)
Decodes an audio track asynchronously and returns a fixed-size waveform amplitude envelope.
Each element of the returned Float32Array is a linear amplitude value in the range 0.0..1.0 for the corresponding part of the requested time range.
Each output point represents one time interval. The interval is divided into up to 8 local windows; for each non-empty window, the peak absolute sample value across all channels is measured, and those local peaks are averaged to produce the output value. This preserves short transients while avoiding the dense appearance produced by taking a single maximum peak over the entire output interval.
Values are not normalized to the loudest point of the track, so their amplitudes remain relative to the decoded audio signal.
Decoding uses one sequential decoder pass. Decoded PCM data is not exposed to JavaScript.
If on_progress is supplied, finalized contiguous ranges of the output envelope are delivered while decoding is still in progress. The callback receives a Float32Array containing the new values and the zero-based output index where that range begins. Progress chunk size and delivery frequency are implementation details and must not be relied on.
For waveform UIs that should appear while decoding, this progressive form is the recommended approach. Use one utils.GetWaveformAsync call for the whole requested range instead of splitting the track into repeated range calls. One decoder remains open for the sequential pass, avoiding repeated open/seek/decode overhead. For visually smooth rendering, store progress chunks immediately but animate a separate visible front toward the loaded front rather than exposing the native chunk boundaries directly.
Return false from on_progress to cancel the native decode. This is recommended when a progressive request becomes obsolete, for example after the focused or playing track changes. Cancellation rejects the returned Promise. Any other return value continues decoding.
The Promise still resolves with the complete Float32Array when decoding finishes normally, whether or not a progress callback is used.
If duration is 0, the requested range extends from start to the end of the track. If the track length cannot be determined, a non-zero duration must be specified.
A range that extends past a known track end is clipped. If start is at or beyond the known track end, a zero-filled array is returned.
Decoder or input-opening failures reject the returned Promise.
| Name | Type | Description |
|---|---|---|
handle | FbMetadbHandle | Track to decode. |
points = 2048optional | number | Number of output points. Valid range: 1..65536. |
start = 0optional | number | Start position in seconds. Must be finite and non-negative. |
duration = 0optional | number | Duration in seconds. Must be finite and non-negative. 0 means from start to the end of the track. |
on_progressoptional | function(Float32Array, number) | Optional progress callback. Receives (values, start_index). Return false to cancel decoding. |
Promise.<Float32Array> — Promise resolved with exactly points linear amplitude values.
Error — If handle is null; points, start, or duration is invalid; or on_progress is not a function, null, or undefined.
const handle = fb.GetNowPlaying();
if (handle) {
utils.GetWaveformAsync(handle, 2048)
.then(waveform => {
console.log(`Decoded ${waveform.length} waveform points`);
})
.catch(e => console.log(`GetWaveformAsync failed: ${e}`));
}let requestId = 0;
let waveform = null;
let loaded = 0;
let visible = 0;
let producerRate = 0;
let lastFrame = 0;
const revealTimer = setInterval(() => {
if (!waveform || producerRate <= 0) return;
const now = performance.now();
const dt = lastFrame ? now - lastFrame : 0;
lastFrame = now;
// Smoothly follow what the decoder has really produced. Do not predict
// completion time from track duration and do not draw chunk boundaries directly.
visible = Math.min(loaded, visible + producerRate * dt);
window.Repaint();
}, 16);
async function loadFocusedWaveform() {
const id = ++requestId;
const handle = fb.GetFocusItem();
if (!handle) return;
const points = 2048;
const started = performance.now();
waveform = new Float32Array(points);
loaded = 0;
visible = 0;
producerRate = 0;
lastFrame = 0;
try {
const complete = await utils.GetWaveformAsync(handle, points, 0, 0, (values, start) => {
if (id !== requestId) return false; // cancel the obsolete native decode
waveform.set(values, start);
loaded = Math.max(loaded, start + values.length);
const elapsed = performance.now() - started;
if (elapsed > 0) producerRate = loaded / elapsed;
return true;
});
if (id !== requestId) return;
waveform = complete;
loaded = complete.length;
} catch (e) {
if (id === requestId) console.log(`GetWaveformAsync failed: ${e}`);
}
}
// See "Focus Track Waveform.js" for a complete rendering example.
Glob(pattern, exc_mask, inc_mask)
Retrieves filepaths that match the supplied pattern.
Relative filesystem paths are resolved as described in utils.ReadTextFile.
| Name | Type | Description |
|---|---|---|
pattern | string | For the path, you can use the * and ? wildcards for any intermediate directory and for the file name. |
exc_mask = 0x10optional | number | Mask to exclude files. Default is FILE_ATTRIBUTE_DIRECTORY. See flags like FILE_ATTRIBUTE_NORMAL etc. |
inc_mask = 0xffffffffoptional | number | Mask to include files |
Array<string>let arr = utils.Glob("C:\\*.*");
let arr2 = utils.Glob(fb.ProfilePath + 'image*\\album?\\*.jpg');
HTTPRequestAsync(type, url, user_agent_or_headers, post_data)
Does HTTP request of specified type to URL with optional user headers and post data
| Name | Type | Description |
|---|---|---|
type | number | Use 0 for GET, 1 for POST. |
url | number | |
user_agent_or_headers = ""optional | string | can be a string specifying the user agent, or a stringified JSON object specifying user HTTP request headers (see examples) |
post_data = ""optional | string | 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. |
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.
Error — If called from a panel before foobar2000 is fully initialized.
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);
}
InputBox(window_id, prompt, caption, default_val, error_on_cancel, help_text)
| Name | Type | Description |
|---|---|---|
window_id | number | Native window handle (HWND) to use as the dialog owner. Pass 0 to use the default foobar2000 window. |
prompt | string | |
caption | string | |
default_val = ''optional | string | |
error_on_cancel = falseoptional | boolean | If set to true, use try/catch like Example2. |
help_text = ''optional | string | 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 |
stringError — If no valid owner window is supplied and the panel host is not fully initialized, or the dialog is cancelled while error_on_cancel is true.
// 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.
}
IsDirectory(path)
Relative filesystem paths are resolved as described in utils.ReadTextFile.
| Name | Type | Description |
|---|---|---|
path | string |
boolean — true, if location exists and it's a directory
IsFile(path)
Relative filesystem paths are resolved as described in utils.ReadTextFile.
| Name | Type | Description |
|---|---|---|
path | string |
boolean — true, if location exists and it's a file
IsKeyPressed(vkey)
| Name | Type | Description |
|---|---|---|
vkey | number | See https://docs.microsoft.com/en-us/windows/win32/inputdev/virtual-key-codes. |
booleanListFonts(mode)
Gets an array of available font family names. Fonts loaded with utils.LoadFont are included. GDI and DirectWrite can expose different family names for the same font file.
| Name | Type | Description |
|---|---|---|
mode = 0optional | number | 0 - Auto, 1 - GDI fonts, 2 - DirectWrite fonts |
Array<string> — array of font family names
Error — If Direct2D font enumeration is requested before Direct2D resources are initialized.
LoadFont(path)
Loads a font file for private use by the current foobar2000 process. The font is not installed in Windows and is not made available to other processes.
After a successful call the font becomes available to the foobar2000 process. It can be used by gdi.Font and d2d.Font and is visible to other JSplitter panels and Workers. The font is registered privately for the foobar2000 process rather than for JSplitter alone. As a result, it may also become available to native foobar2000 UI and other components that use the Windows font APIs, depending on when they enumerate or create their fonts.
Relative filesystem paths are resolved as described in utils.ReadTextFile.
The file is registered (cached) once by its normalised absolute path. Calling LoadFont again with the same file returns true without registering it again. Loaded fonts remain available for the lifetime of the foobar2000 process; there is no corresponding unload operation.
A font may expose different legacy/GDI and typographic/DirectWrite family names. utils.CheckFont can be used to verify a family name after loading, while utils.ListFonts shows the names reported by the GDI and DirectWrite backends.
| Name | Type | Description |
|---|---|---|
path | string | Path to a font file, typically a .ttf or .otf file. |
boolean — true if the font is already loaded or was loaded successfully; false if the file does not exist, cannot be read as a font, contains no usable family, or cannot be registered.
if (utils.LoadFont('fonts/Rain Tungsten Medium.ttf')) {
const gdiFont = gdi.Font('Rain Tungsten Medium', 16);
...
}
MapString(text, lcid, flags)
| Name | Type | Description |
|---|---|---|
text | string | |
lcid | string | |
flags | number | defined in Flags, like LCMAP_LOWERCASE |
stringMD5(str)
Calculates MD5 for string
| Name | Type | Description |
|---|---|---|
str | string | input string |
string — MD5 value for input in hex format string. If input string is empty returns "d41d8cd98f00b204e9800998ecf8427e"
MD5FromFile(path)
Calculates MD5 value for file content
Relative filesystem paths are resolved as described in utils.ReadTextFile.
| Name | Type | Description |
|---|---|---|
path | string | input file path |
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"
MessageBox(msg, title, buttons, icon, default_button, help_text, window_id)
Shows system message box with specified parameters
| Name | Type | Description |
|---|---|---|
msg | string | |
title = "JSplitter"optional | string | |
buttons = MessageBoxButtons.OKoptional | MessageBoxButtons | |
icon = MessageBoxIcon.Informationoptional | MessageBoxIcon | See MessageBoxIcon |
default_button = MessageBoxDefaultButton.Button1optional | MessageBoxDefaultButton | |
help_text = ""optional | string | 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 |
window_id = 0optional | number | Native window handle (HWND) to use as the dialog owner. Pass 0 to use the default foobar2000 window. |
number — Result of message box. See DialogResult
OpenBinaryReader(filename)
Opens a binary file for incremental reading into a caller-provided Uint8Array.
The buffer is reused by the caller, so repeated reads do not allocate a new typed array for every chunk. This is intended for large files or other cases where whole-file utils.ReadBinaryFile would be inefficient.
Reading is synchronous. For one-shot large-file processing, use the reader inside Worker.RunAsync; for persistent pipelines, use it from a Worker. Both approaches keep blocking file I/O off the panel UI thread.
Ordinary read failures are reported through Read and EOF>; they are not thrown as exceptions.
Relative filesystem paths are resolved as described in utils.ReadTextFile.
| Name | Type | Description |
|---|---|---|
filename | string | File to open. |
?BinaryReader — Open streaming reader, or null if the reader could not be created. Ordinary file open/setup failures are reported as null, not exceptions.
const reader = utils.OpenBinaryReader('E:\\large-file.bin');
if (!reader) return;
const buffer = new Uint8Array(1024 * 1024);
for (;;) {
const bytesRead = reader.Read(buffer);
if (!bytesRead) {
if (!reader.EOF) console.log('Read failed');
break;
}
// Process buffer[0 .. bytesRead).
}
reader.Close();
OpenBinaryWriter(filename)
Opens a binary file for incremental writing from a caller-provided Uint8Array. The file is created or truncated when opened. The parent folder must already exist. Reusing the same typed array avoids allocating temporary buffers for every chunk. Write, flush, and close failures are reported through boolean return values.
Writing is synchronous. For long-running processing, use the writer from a Worker to avoid blocking the panel UI.
Relative filesystem paths are resolved as described in utils.ReadTextFile.
| Name | Type | Description |
|---|---|---|
filename | string | File to create or overwrite. |
?BinaryWriter — Open streaming writer, or null if the writer could not be created. Ordinary file creation/open failures are reported as null, not exceptions.
const writer = utils.OpenBinaryWriter('E:\\large-file.bin');
if (!writer) return;
const buffer = new Uint8Array(1024 * 1024);
// Fill buffer...
if (!writer.Write(buffer)) console.log('Write failed');
if (!writer.Close()) console.log('Close failed');
OpenDatabase(filename)
Opens or creates a SQLite database for synchronous read/write access by given filename.
The special filename :memory: creates an in-memory SQLite database and is not path-resolved. The parent folder of a file-backed database must already exist.
Database work is synchronous, so large imports or expensive queries should be run from a Worker to avoid blocking the panel UI thread.
SQL values should be passed through the optional parameter array instead of being concatenated into the SQL text. Supported parameter types are null, boolean, number, string, ArrayBuffer, and typed-array views.
Relative filesystem paths are resolved as described in utils.ReadTextFile.
| Name | Type | Description |
|---|---|---|
filename | string | Absolute or script-relative database filename, or :memory:. |
?SQLiteDatabase — Open database handle, or null if the database could not be opened or created. Ordinary open/create failures are reported as null, matching the other Open* resource factories. SQL and database-operation errors after a successful open are reported as exceptions.
const db = utils.OpenDatabase('example.db');
if (!db) {
console.log('Unable to open database');
return;
}
try {
db.Exec('CREATE TABLE IF NOT EXISTS settings (name TEXT PRIMARY KEY, value TEXT)');
db.Exec('INSERT OR REPLACE INTO settings(name, value) VALUES (?, ?)', ['theme', 'dark']);
const rows = db.Query('SELECT value FROM settings WHERE name = ?', ['theme']);
console.log(rows.length ? rows[0].value : 'not found');
} finally {
db.Close();
}
OpenTextReader(filename, codepage)
Opens a text file for incremental, line-by-line reading.
Unlike utils.ReadTextFile, the whole file is not materialized as one JavaScript string. This makes it suitable for processing large text files incrementally, one line at a time, without requiring the entire file contents to fit in the JavaScript heap.
ReadLine removes the line terminator. A return value of null means that no next line could be returned; in that case, EOF is true for a clean end of file and false for a read or decoding failure. UTF-16LE/BE and UTF-32LE/BE are supported with codepages 1200/1201 and 12000/12001 respectively.
Pass codepage 0 to use automatic charset detection, matching utils.ReadTextFile.
Reading is synchronous. For long-running processing, use the reader from a Worker to avoid blocking the panel UI.
Ordinary read and decoding failures are reported through ReadLine and EOF; they are not thrown as exceptions.
Relative filesystem paths are resolved as described in utils.ReadTextFile.
| Name | Type | Description |
|---|---|---|
filename | string | File to open. |
codepage = 65001optional | number | Windows codepage used to decode each line. UTF-16LE/BE use 1200/1201, UTF-32LE/BE use 12000/12001, and 0 enables automatic detection. See Codepages.js. |
?TextReader — Open streaming reader, or null if the reader could not be created. This includes invalid or unsupported codepages, an empty filename, and ordinary file open failures.
const reader = utils.OpenTextReader('E:\\large-file.txt');
if (!reader) {
console.log('Unable to open file');
return;
}
for (;;) {
const line = reader.ReadLine();
if (line === null) {
if (!reader.EOF) console.log('Read or decoding failed');
break;
}
console.log(line);
}
reader.Close();
OpenTextWriter(filename, write_bom, codepage)
Opens a text file for incremental writing.
The file is created or truncated when opened. The parent folder must already exist.
UTF-8 is used by default. UTF-16LE (1200), UTF-16BE (1201), UTF-32LE (12000), UTF-32BE (12001), and other valid Windows codepages are also supported.
If write_bom is true, the matching BOM is written for UTF-8, UTF-16, and UTF-32. Other Windows codepages do not have a BOM and ignore this option.
Use Write to append text without a line terminator or WriteLine to append text followed by CRLF. Encoding and I/O failures are reported through boolean return values. This avoids building one large JavaScript string before writing a large file.
Writing is synchronous. For one-shot large-file generation, use the writer inside Worker.RunAsync; for persistent pipelines, use it from a Worker. Both approaches keep blocking file I/O off the panel UI thread.
Relative filesystem paths are resolved as described in utils.ReadTextFile.
| Name | Type | Description |
|---|---|---|
filename | string | File to create or overwrite. |
write_bom = trueoptional | boolean | If true, writes a BOM for UTF-8/UTF-16/UTF-32. |
codepage = 65001optional | number | Output Windows codepage. Codepage 0 is not valid for writing. See Codepages.js. |
?TextWriter — Open streaming writer, or null if the writer could not be created. This includes an empty filename, an invalid codepage, and ordinary file creation/open failures.
const writer = utils.OpenTextWriter('E:\\large-file.txt', false);
if (!writer) {
console.log('Unable to create file');
return;
}
for (let i = 0; i < 100000; ++i) {
if (!writer.WriteLine(JSON.stringify({ id: i, value: `item ${i}` }))) {
console.log('Write failed');
break;
}
}
if (!writer.Close()) console.log('Close failed');
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.
| Name | Type | Description |
|---|---|---|
html | string | HTML source text. |
?HtmlDocument — Parsed document, or null on failure.
const doc = utils.ParseHtml("<html><body><p>Hello <b>world</b></p></body></html>");
if (doc) console.log(doc.body.textContent); // "Hello world"
PathWildcardMatch(pattern, str)
Check if the supplied string matches the pattern.
Using Microsoft MS-DOS wildcards match type. eg "*.txt", "abc?.tx?"
| Name | Type | Description |
|---|---|---|
pattern | string | |
str | string |
booleanReadBinaryFile(path)
Read a file as raw binary.
For large files, consider utils.OpenBinaryReader; it reads incrementally into a reusable caller-provided buffer instead of allocating one typed array for the whole file. Relative filesystem paths are resolved as described in utils.ReadTextFile.
| Name | Type | Description |
|---|---|---|
path | string | Absolute or script-relative file path. |
Uint8Array — File bytes, or null if was an error
ReadINI(filename, section, key, default_val)
Note: this only returns up to 255 characters per value.
Relative filesystem paths are resolved as described in utils.ReadTextFile.
| Name | Type | Description |
|---|---|---|
filename | string | |
section | string | |
key | string | |
default_valoptional | string |
stringlet username = utils.ReadINI("e:\\my_file.ini", "Last.fm", "username");
ReadTextFile(filename, codepage)
Performance note: supply codepage argument if it is known, since codepage detection might take some time.
UTF-8, UTF-16LE/BE, UTF-32LE/BE, and supported Windows codepages use the same decoding rules as utils.OpenTextReader. A matching BOM is removed for UTF encodings.
For large line-oriented files, consider utils.OpenTextReader; it avoids creating one JavaScript string containing the entire file.
| Name | Type | Description |
|---|---|---|
filename | string | |
codepage = 65001optional | number | See Codepages.js. UTF-16LE/BE use 1200/1201, UTF-32LE/BE use 12000/12001. If codepage is 0, automatic detection is performed. |
string — Decoded file contents, or an empty string if the file could not be read or decoded.
let text = utils.ReadTextFile("E:\\some text file.txt");
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
Relative filesystem paths are resolved as described in utils.ReadTextFile.
| Name | Type | Description |
|---|---|---|
path | string |
stringRecyclePath(path)
Moves a file or directory to the Recycle Bin.
Relative filesystem paths are resolved as described in utils.ReadTextFile.
| Name | Type | Description |
|---|---|---|
path | string | path to a file or directory |
boolean — true on success, false otherwise
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. Relative filesystem paths are resolved as described in utils.ReadTextFile.
| Name | Type | Description |
|---|---|---|
path | string |
numberRenamePath(from, to)
Renames file or folder path.
Relative filesystem paths are resolved as described in utils.ReadTextFile.
| Name | Type | Description |
|---|---|---|
from | string | |
to | string |
booleanReplaceIllegalChars(str, strip_trailing_periods)
Uses the same modern unicode replacements as the foobar2000 converter/file operations.
| Name | Type | Description |
|---|---|---|
str | string | |
strip_trailing_periods = falseoptional | boolean | Set to true if str is a folder name. |
booleanRun(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.
Relative filesystem paths are resolved as described in utils.ReadTextFile. This applies only to working_dir; target is not path-resolved.
| Name | Type | Description |
|---|---|---|
target | string | File, executable, URL, or document to run/open. |
argsoptional | string|string[] | Command line arguments. |
working_dir = ""optional | string | Working directory for the process. |
verb = ""optional | string | Shell verb to use. |
show = ShowWindow.Hideoptional | number | Requested window display mode. |
wait = falseoptional | boolean | Whether to wait for the launched process to exit. |
RunResult — Result object.
// 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
);
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.
Relative filesystem paths are resolved as described in utils.ReadTextFile. This applies only to working_dir; app is not path-resolved.
| Name | Type | Description |
|---|---|---|
app | string | Full path or executable name to run. |
argsoptional | string|string[] | Command line arguments. |
working_dir = ""optional | string | Working directory for the process. |
show = ShowWindow.Hideoptional | number | Window display mode. |
timeout_ms = 0optional | number | Maximum time to wait for the process, in milliseconds. |
number — Task id of the asynchronous operation.
Error — If args is invalid, the panel host is not fully initialized, or the worker thread cannot be started.
SetClipboardText(text)
| Name | Type | Description |
|---|---|---|
text | string |
SHA1(str)
Calculates SHA1 for string
| Name | Type | Description |
|---|---|---|
str | string | input string |
string — SHA1 value for input in hex format string. If input string is empty returns "da39a3ee5e6b4b0d3255bfef95601890afd80709"
SHA1FromFile(path)
Calculates SHA1 value for file content
Relative filesystem paths are resolved as described in utils.ReadTextFile.
| Name | Type | Description |
|---|---|---|
path | string | input file path |
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"
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 and JavaScript executed inside the dialog must be IE compatible (see https://www.w3schools.com/js/js_versions.asp).
options.data is exposed inside the html dialog through window.external.dialogArguments. The bridge supports the following values:
JSplitter objects such as FbMetadbHandle, GdiBitmap and D2DBitmap cannot be passed through this bridge.
The following properties are available through window.external inside the html dialog:
| Name | Type | Description |
|---|---|---|
window_id | number | native window handle (HWND) to use as the dialog owner; pass 0 to use the default foobar2000 window |
code_or_path | string | Html code or file path. File path must begin with file:// prefix. |
options = undefinedoptional | object | |
options.width = 250optional | number | Window width |
options.height = 100optional | number | Window height |
options.x = 0optional | number | Window horizontal position relative to desktop |
options.y = 0optional | number | Window vertical position relative to desktop |
options.center = trueoptional | boolean | If true and if options.x and options.y are not set, will center window relative to fb2k position. |
options.context_menu = falseoptional | boolean | If true, will enable right-click context menu. |
options.resizable = falseoptional | boolean | If true, will allow to resize the window. |
options.selection = falseoptional | boolean | If true, will allow to select everything (label texts, buttons and etc). |
options.scroll = falseoptional | boolean | If true, will display scrollbars. |
options.data = undefinedoptional | * | Read-only data exposed through window.external.dialogArguments. For multiple values, pass an array and call .toArray() inside html. Has type limitations described above. |
Error — If no valid owner window is supplied and the panel host is not fully initialized, or the dialog cannot be created.
utils.ShowHtmlDialog(0, `file://${fb.ComponentPath}samples/basic/html/PopupWithCheckBox.html`);
SplitFilePath(path)
| Name | Type | Description |
|---|---|---|
path | string |
Array<string> — An array of [directory, filename, filename_extension]
let arr = utils.SplitFilePath('D:\\Somedir\\Somefile.txt');
// arr[0] <= 'D:\\Somedir\\' (always includes backslash at the end)
// arr[1] <= 'Somefile'
// arr[2] <= '.txt'
WriteBinaryFile(path, data)
Write raw binary data to a file.
For large output, consider utils.OpenBinaryWriter; it writes incrementally from a reusable caller-provided buffer. Relative filesystem paths are resolved as described in utils.ReadTextFile.
| Name | Type | Description |
|---|---|---|
path | string | Absolute or script-relative file path. |
data | Uint8Array | Bytes to write |
boolean — true on success
Error — If data is not a Uint8Array.
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);
}
WriteINI(filename, section, key, val)
Relative filesystem paths are resolved as described in utils.ReadTextFile.
| Name | Type | Description |
|---|---|---|
filename | string | |
section | string | |
key | string | |
val | string |
booleanutils.WriteINI("e:\\my_file.ini", "Last.fm", "username", "Bob");
WriteTextFile(filename, content, write_bom, codepage)
Note: the parent folder must already exist.
UTF-8 is used by default, matching utils.OpenTextWriter. UTF-16LE (1200), UTF-16BE (1201), UTF-32LE (12000), UTF-32BE (12001), and other valid Windows codepages are also supported.
If write_bom is true, the matching BOM is written for UTF-8, UTF-16, and UTF-32. Other Windows codepages do not have a BOM and ignore this option.
For large output, consider utils.OpenTextWriter; it writes incrementally and does not require one large JavaScript string containing the entire file.
Relative filesystem paths are resolved as described in utils.ReadTextFile.
| Name | Type | Description |
|---|---|---|
filename | string | |
content | string | |
write_bom = trueoptional | boolean | |
codepage = 65001optional | number | Output Windows codepage. Codepage 0 is not valid for writing. See Codepages.js. |
boolean — true on success, false otherwise.
utils.WriteTextFile("z:\\1.txt", "test");utils.WriteTextFile("z:\\2.txt", "test", false);utils.WriteTextFile("z:\\3.txt", "test", true, 1200);