Documentation/utils
namespaceWORKER

utils

jsdoc/utils.js:46

Various utility functions.

propertyWORKER

HighResolutionTimersEnabled

jsdoc/utils.js:86
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.

propertyWORKERreadonly

Is64Bit

jsdoc/utils.js:96
Is64Bit: boolean

Indicates whether the current foobar2000 process architecture is 64-bit. This does not describe the operating system architecture; use IsOS64Bit for that.

propertyWORKERreadonly

IsOS64Bit

jsdoc/utils.js:106
IsOS64Bit: boolean

Indicates whether the operating system architecture is 64-bit. Unlike Is64Bit, this value describes Windows itself and remains true when 32-bit foobar2000 runs on 64-bit Windows.

propertyWORKERreadonly

SystemInfo

jsdoc/utils.js:116
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.

Example

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`);
}
propertyWORKER

Version

jsdoc/utils.js:54
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}.`);
}
methodWORKERMAIN THREAD

CheckComponent

jsdoc/utils.js:134
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));
methodWORKER

CheckFont

jsdoc/utils.js:148
CheckFont(name, mode)

Checks whether a font name exists in the selected graphics backend, including fonts loaded with LoadFont. Uses exact, case-insensitive matching; a substituted font or partial name does not count as a match.
In Direct2D mode, also recognizes localized names, Win32 and typographic family names, and full font names. These aliases need not appear in ListFonts.

Parameters

NameTypeDescription
namestring

Font family or supported font name.

mode = 0optionalnumber

0 - Auto (current panel backend), 1 - GDI, 2 - Direct2D.

Returns

boolean —

True if the requested name is found, false otherwise.

Throws

Error —

If font enumeration fails or Direct2D font resources are unavailable.

Example

utils.CheckFont('Arial');    // Current backend.
utils.CheckFont('Arial', 1); // GDI.
utils.CheckFont('Arial', 2); // Direct2D.
method

ColourPicker

jsdoc/utils.js:168
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

Throws

Error —

If no valid owner window is supplied and the panel host is not fully initialized.

methodWORKER

ConvertToAscii

jsdoc/utils.js:183
ConvertToAscii(str)

Converts string from UTF-8 to ASCII.

Parameters

NameTypeDescription
strstring

Returns

string
methodWORKER

CopyFile

jsdoc/utils.js:192
CopyFile(from, to, overwrite)

Copies a file.

Relative filesystem paths are resolved as described in ReadTextFile.

Parameters

NameTypeDescription
fromstring
tostring
overwrite = trueoptionalboolean

Returns

boolean
methodWORKER

CopyFolder

jsdoc/utils.js:205
CopyFolder(from, to, overwrite, recur)

Copies a folder.

Relative filesystem paths are resolved as described in ReadTextFile.

Parameters

NameTypeDescription
fromstring
tostring
overwrite = trueoptionalboolean
recur = trueoptionalboolean

Returns

boolean
methodWORKER

CRC32

jsdoc/utils.js:230
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

methodWORKER

CRC32FromFile

jsdoc/utils.js:239
CRC32FromFile(path)

Calculates CRC32 value for file content

Relative filesystem paths are resolved as described in ReadTextFile.

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

methodWORKER

CreateFolder

jsdoc/utils.js:219
CreateFolder(path)

Creates a folder.

Relative filesystem paths are resolved as described in ReadTextFile.

Parameters

NameTypeDescription
pathstring

Returns

boolean
methodWORKER

DetectCharset

jsdoc/utils.js:250
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.

Performance note: detection algorithm is quite slow, so results should be cached as much as possible.

Relative filesystem paths are resolved as described in ReadTextFile.

Parameters

NameTypeDescription
pathnumber

Path to file

Returns

number —

Codepage number on success, 0 if codepage detection failed

methodWORKER

DownloadFileAsync

jsdoc/utils.js:267
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 ReadTextFile.

Parameters

NameTypeDescription
urlstring

File URL

pathstring

Save file path

Throws

Error —

If called from a panel before foobar2000 is fully initialized.

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

jsdoc/utils.js:320
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 ReadTextFile.

Parameters

NameTypeDescription
pathnumber

Path to file

Throws

Error —

If called before foobar2000 is fully initialized.

methodWORKER

FileExists

jsdoc/utils.js:331
FileExists(path)

Relative filesystem paths are resolved as described in ReadTextFile.

Parameters

NameTypeDescription
pathnumber

Path to file

Returns

boolean —

true, if file exists.

method

FilePicker

jsdoc/utils.js:340
FilePicker(title, default_path, filter, mode, window_id)

Opens system file picker dialog window

Relative filesystem paths are resolved as described in ReadTextFile.

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

window_id = 0optionalnumber

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

Returns

string —

Chosen file path. If dialog is cancelled returns empty string

Throws

Error —

If no valid owner window is supplied and the panel host is not fully initialized.

methodWORKERdeprecated

FileTest

jsdoc/utils.js:355
FileTest(path, mode)
Deprecated.

Various utility functions for working with file.

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

Relative filesystem paths are resolved as described in ReadTextFile. This applies only to modes that access the filesystem; split only splits the supplied path string.

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

*

Throws

Error —

If mode is not one of the supported values.

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

jsdoc/utils.js:385
FolderPicker(title, default_path, window_id)

Opens system folder picker dialog window

Relative filesystem paths are resolved as described in ReadTextFile.

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

window_id = 0optionalnumber

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

Returns

string —

Chosen folder path. If dialog is cancelled returns empty string

Throws

Error —

If no valid owner window is supplied and the panel host is not fully initialized.

method

FontPicker

jsdoc/utils.js:398
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)

Throws

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.

Example source

methodWORKER

FormatDuration

jsdoc/utils.js:410
FormatDuration(seconds)

Parameters

NameTypeDescription
secondsnumber

Returns

string

Example

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

FormatFileSize

jsdoc/utils.js:420
FormatFileSize(bytes)

Parameters

NameTypeDescription
bytesnumber

Returns

string

Example

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

GetAlbumArtAsync

jsdoc/utils.js:430
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.

Throws

Error —

If handle is null or the panel host is not fully initialized.

Example source

methodWORKER

GetAlbumArtAsyncV2

jsdoc/utils.js:452
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>

Throws

Error —

If handle is null, the panel host is not fully initialized, or Worker promise setup fails.

Example source

methodWORKER

GetAlbumArtEmbedded

jsdoc/utils.js:470
GetAlbumArtEmbedded(rawpath, art_id)

Load embedded art image for the track.

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

Relative filesystem paths are resolved as described in ReadTextFile. URLs and foobar2000 URI paths are passed through unchanged.

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);
methodWORKER

GetAlbumArtV2

jsdoc/utils.js:487
GetAlbumArtV2(handle, art_id, need_stub)

Load art image for the track.

Performance note: consider using GetAlbumArtAsync or 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)

Throws

Error —

If handle is null.

Example source

methodWORKERMAIN THREAD

GetClipboardText

jsdoc/utils.js:503
GetClipboardText()

Returns

string —

Returns an empty string if clipboard contents are not text.

methodWORKER

GetCountryFlag

jsdoc/utils.js:510
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 an ISO alpha-2 code, an ISO alpha-3 code, a full name or a supported alias. A few examples (full list see in the EXAMPLE file):
"by" "BLR" "Belarus"
"gb" "GBR" "United Kingdom"
"kp" "PRK" "North Korea"

Returns

string —

Country string code

Example source

methodWORKER

GetDriveInfo

jsdoc/utils.js:523
GetDriveInfo(path)

Returns information about a logical drive or volume containing the supplied path.
The method also works with drive roots returned by 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 ReadTextFile.

Parameters

NameTypeDescription
pathstring

Drive root or path on the drive

Returns

?DriveInfo —

Drive information, or null if the path cannot be resolved to a drive

Example source

methodWORKER

GetDrives

jsdoc/utils.js:538
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 GetDriveInfo to query its state.

Returns

Array<string> —

Drive root paths, for example ["C:\\", "D:\\"]

Example source

methodWORKER

GetFileSize

jsdoc/utils.js:549
GetFileSize(path)

Relative filesystem paths are resolved as described in ReadTextFile.

Parameters

NameTypeDescription
pathstring

Returns

number —

File size, in bytes

methodWORKER

GetFolderSize

jsdoc/utils.js:558
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 ReadTextFile.

Parameters

NameTypeDescription
pathstring

Directory path

Returns

number —

Total size in bytes, or 0 if the path is not a directory

Example source

methodWORKER

GetFolderSizeAsync

jsdoc/utils.js:573
GetFolderSizeAsync(path)

Calculates the total size of files contained in a directory and its subdirectories asynchronously.
For synchronous calculation, use 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 ReadTextFile.

Parameters

NameTypeDescription
pathstring

Directory path

Returns

number —

Task id of the asynchronous operation

Throws

Error —

If called from a panel before foobar2000 is fully initialized or the worker thread cannot be started.

Example source

methodWORKER

GetLastModified

jsdoc/utils.js:591
GetLastModified(path)

Gets "last modified" attribute for file Relative filesystem paths are resolved as described in ReadTextFile.

Parameters

NameTypeDescription
pathstring

Returns

number —

UNIX-time (seconds)

methodWORKERMAIN THREAD

GetPackageInfo

jsdoc/utils.js:633
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

methodWORKERMAIN THREADdeprecated

GetPackagePath

jsdoc/utils.js:643
GetPackagePath(package_id)
Deprecated.

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

Deprecated: use GetPackageInfo instead.

Parameters

NameTypeDescription
package_idstring

Can be obtained by window.ScriptInfo

Returns

string

Throws

Error —

If no package with package_id exists.

methodWORKER

GetShortPath

jsdoc/utils.js:601
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 ReadTextFile.

Parameters

NameTypeDescription
pathstring

File or directory path

Returns

string —

Short path or an empty string on failure

Example source

methodWORKER

GetSysColour

jsdoc/utils.js:659
GetSysColour(index)

Parameters

Returns

number —

0 if failed

Throws

Error —

If index is not a valid system colour index.

Example

let splitter_colour = utils.GetSysColour(15);
methodWORKER

GetSystemMetrics

jsdoc/utils.js:670
GetSystemMetrics(index)

Parameters

Returns

number —

0 if failed

methodWORKER

GetWaveformAsync

jsdoc/utils.js:677
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 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.

Parameters

NameTypeDescription
handleFbMetadbHandle

Track to decode.

points = 2048optionalnumber

Number of output points. Valid range: 1..65536.

start = 0optionalnumber

Start position in seconds. Must be finite and non-negative.

duration = 0optionalnumber

Duration in seconds. Must be finite and non-negative. 0 means from start to the end of the track.

on_progressoptionalfunction(Float32Array, number)

Optional progress callback. Receives (values, start_index). Return false to cancel decoding.

Returns

Promise.<Float32Array> —

Promise resolved with exactly points linear amplitude values.

Throws

Error —

If handle is null; points, start, or duration is invalid; or on_progress is not a function, null, or undefined.

Examples

Decode a complete waveform
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}`));
}
Recommended progressive UI pattern
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.

Example source

methodWORKER

Glob

jsdoc/utils.js:772
Glob(pattern, exc_mask, inc_mask)

Retrieves filepaths that match the supplied pattern.

Relative filesystem paths are resolved as described in ReadTextFile.

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');
methodWORKER

HTTPRequestAsync

jsdoc/utils.js:288
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.

Throws

Error —

If called from a panel before foobar2000 is fully initialized.

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

jsdoc/utils.js:789
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

Throws

Error —

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.

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.
}
methodWORKER

IsDirectory

jsdoc/utils.js:834
IsDirectory(path)

Relative filesystem paths are resolved as described in ReadTextFile.

Parameters

NameTypeDescription
pathstring

Returns

boolean —

true, if location exists and it's a directory

methodWORKER

IsFile

jsdoc/utils.js:843
IsFile(path)

Relative filesystem paths are resolved as described in ReadTextFile.

Parameters

NameTypeDescription
pathstring

Returns

boolean —

true, if location exists and it's a file

methodWORKER

IsKeyPressed

jsdoc/utils.js:852
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
methodWORKER

ListFonts

jsdoc/utils.js:902
ListFonts(mode)

Lists font family names available to the selected graphics backend, including fonts loaded with LoadFont. GDI and Direct2D organize families differently, so their lists and returned names may differ. Direct2D includes localized family names; duplicate names are removed, preserving their first occurrence.
Every returned name can be checked with CheckFont in the same mode.

Parameters

NameTypeDescription
mode = 0optionalnumber

0 - Auto (current panel backend), 1 - GDI, 2 - Direct2D.

Returns

Array<string> —

Available font family names.

Throws

Error —

If Direct2D font resources are unavailable.

methodWORKER

LoadFont

jsdoc/utils.js:860
LoadFont(path)

Loads a font file for private use by the current foobar2000 process and returns its font family names. 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. Registration is process-wide, so native foobar2000 UI and other components using Windows font APIs may also see the font, depending on when they enumerate or create fonts.

Relative filesystem paths are resolved as described in ReadTextFile. Each file is registered once by its normalised absolute path. Loading the same file again returns its saved family names without registering it again. Fonts remain available until foobar2000 exits; there is no corresponding unload operation.

Returns a non-empty array containing at least one font family name from the file, or — in the case of a TTC/OTC collection — all font family names present in that collection. Styles and localized names are not listed separately. The returned names depend on the panel's drawing mode: GDI may shorten long family names (cause of 31 character Windows font name limit), while Direct2D can return their full names. Use CheckFont with the corresponding mode to check a returned name.

In GDI mode, fonts with family names longer than 31 characters can be rendered with DrawString, but not with GdiDrawText. Direct2D does not have this limitation.

Parameters

NameTypeDescription
pathstring

Path to a font file, such as .ttf, .otf, .ttc or .otc.

Returns

Array<string>|null —

A non-empty array of font family names on success, or null if the file is missing, invalid, contains no usable families or cannot be registered.

Example

const families = utils.LoadFont('fonts/Rain Tungsten Medium.ttf');
if (families) {
    const name = families[0];
    const font = gdi.Font(name, 16);
    console.log(name);
}
methodWORKER

MapString

jsdoc/utils.js:915
MapString(text, lcid, flags)

Parameters

NameTypeDescription
textstring
lcidstring
flagsnumber

defined in Flags, like LCMAP_LOWERCASE

Returns

string
methodWORKER

MD5

jsdoc/utils.js:925
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"

methodWORKER

MD5FromFile

jsdoc/utils.js:934
MD5FromFile(path)

Calculates MD5 value for file content

Relative filesystem paths are resolved as described in ReadTextFile.

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

jsdoc/utils.js:945
MessageBox(msg, title, buttons, icon, default_button, help_text, window_id)

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

window_id = 0optionalnumber

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

Returns

number —

Result of message box. See DialogResult

methodWORKER

OpenBinaryReader

jsdoc/utils.js:994
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 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 ReadTextFile.

Parameters

NameTypeDescription
filenamestring

File to open.

Returns

?BinaryReader —

Open streaming reader, or null if the reader could not be created. Ordinary file open/setup failures are reported as null, not exceptions.

Example

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();

Example source

methodWORKER

OpenBinaryWriter

jsdoc/utils.js:1027
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 ReadTextFile.

Parameters

NameTypeDescription
filenamestring

File to create or overwrite.

Returns

?BinaryWriter —

Open streaming writer, or null if the writer could not be created. Ordinary file creation/open failures are reported as null, not exceptions.

Example

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');

Example source

methodWORKER

OpenDatabase

jsdoc/utils.js:1054
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 ReadTextFile.

Parameters

NameTypeDescription
filenamestring

Absolute or script-relative database filename, or :memory:.

Returns

?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.

Example

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();
}

Example source

methodWORKER

OpenTextReader

jsdoc/utils.js:1087
OpenTextReader(filename, codepage)

Opens a text file for incremental, line-by-line reading.
Unlike 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 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 ReadTextFile.

Parameters

NameTypeDescription
filenamestring

File to open.

codepage = 65001optionalnumber

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.

Returns

?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.

Example

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();

Example source

methodWORKER

OpenTextWriter

jsdoc/utils.js:1505
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 ReadTextFile.

Parameters

NameTypeDescription
filenamestring

File to create or overwrite.

write_bom = trueoptionalboolean

If true, writes a BOM for UTF-8/UTF-16/UTF-32.

codepage = 65001optionalnumber

Output Windows codepage. Codepage 0 is not valid for writing. See Codepages.js.

Returns

?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.

Example

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');

Example source

methodWORKER

ParseHtml

jsdoc/utils.js:959
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

methodWORKER

PathWildcardMatch

jsdoc/utils.js:983
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
methodWORKER

ReadBinaryFile

jsdoc/utils.js:1202
ReadBinaryFile(path)

Read a file as raw binary.
For large files, consider 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 ReadTextFile.

Parameters

NameTypeDescription
pathstring

Absolute or script-relative file path.

Returns

Uint8Array —

File bytes, or null if was an error

Example source

methodWORKER

ReadINI

jsdoc/utils.js:1215
ReadINI(filename, section, key, default_val)

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

Relative filesystem paths are resolved as described in ReadTextFile.

Parameters

NameTypeDescription
filenamestring
sectionstring
keystring
default_valoptionalstring

Returns

string

Example

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

ReadTextFile

jsdoc/utils.js:1125
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 OpenTextReader. A matching BOM is removed for UTF encodings.
For large line-oriented files, consider OpenTextReader; it avoids creating one JavaScript string containing the entire file.

Filesystem path resolution: absolute paths are used as-is. Relative paths are resolved against the file containing the current call. For the main script this is the main script directory; for an included script or a file-backed Worker it is that script's own directory. If there is no file-backed caller, the existing host fallback is used (the Worker's relative-path root, or the component directory for an in-memory panel script).

Parameters

NameTypeDescription
filenamestring
codepage = 65001optionalnumber

See Codepages.js. UTF-16LE/BE use 1200/1201, UTF-32LE/BE use 12000/12001. If codepage is 0, automatic detection is performed.

Returns

string —

Decoded file contents, or an empty string if the file could not be read or decoded.

Example

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

ReadUTF8

jsdoc/utils.js:1144
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 ReadTextFile

Relative filesystem paths are resolved as described in ReadTextFile.

Parameters

NameTypeDescription
pathstring

Returns

string
methodWORKERMAIN THREAD

RecyclePath

jsdoc/utils.js:1157
RecyclePath(path)

Moves a file or directory to the Recycle Bin.

Relative filesystem paths are resolved as described in ReadTextFile.

Parameters

NameTypeDescription
pathstring

path to a file or directory

Returns

boolean —

true on success, false otherwise

methodWORKER

RemovePath

jsdoc/utils.js:1169
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 ReadTextFile.

Parameters

NameTypeDescription
pathstring

Returns

number
methodWORKER

RenamePath

jsdoc/utils.js:1180
RenamePath(from, to)

Renames file or folder path.

Relative filesystem paths are resolved as described in ReadTextFile.

Parameters

NameTypeDescription
fromstring
tostring

Returns

boolean
methodWORKER

ReplaceIllegalChars

jsdoc/utils.js:1192
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
methodWORKERMAIN THREAD

Run

jsdoc/utils.js:1232
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.
Relative filesystem paths are resolved as described in ReadTextFile. This applies only to working_dir; target is not path-resolved.

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
);
methodWORKER

RunCmdAsync

jsdoc/utils.js:1316
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 ReadTextFile. This applies only to working_dir; app is not path-resolved.

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

Error —

If args is invalid, the panel host is not fully initialized, or the worker thread cannot be started.

methodWORKERMAIN THREAD

SetClipboardText

jsdoc/utils.js:1354
SetClipboardText(text)

Parameters

NameTypeDescription
textstring
methodWORKER

SHA1

jsdoc/utils.js:1361
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"

methodWORKER

SHA1FromFile

jsdoc/utils.js:1370
SHA1FromFile(path)

Calculates SHA1 value for file content

Relative filesystem paths are resolved as described in ReadTextFile.

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

jsdoc/utils.js:1381
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:

  • Basic types: number, string, boolean, null, undefined
  • Arrays: call window.external.dialogArguments.toArray() inside html to obtain a JavaScript array. Each element has the same type limitations as options.data.
  • Functions: callable from html as callbacks into panel JavaScript. A callback may have a maximum of 7 arguments, and each argument has the same type limitations as options.data.
  • Objects are not transferred directly. Serialize them with JSON.stringify() before passing them and restore them with JSON.parse() inside html.

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:

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*

Read-only data exposed through window.external.dialogArguments. For multiple values, pass an array and call .toArray() inside html. Has type limitations described above.

Throws

Error —

If no valid owner window is supplied and the panel host is not fully initialized, or the dialog cannot be created.

Example

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

Example source

methodWORKER

SplitFilePath

jsdoc/utils.js:1450
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

TextBox

jsdoc/utils.js:817
TextBox(window_id, prompt, caption, default_val, error_on_cancel, help_text)

Displays a resizable dialog with a multi-line text edit area.

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, cancelling the dialog throws an error.

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

Throws

Error —

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.

Example

let text = utils.TextBox(0, "Enter text", "JSplitter", "First line\nSecond line");
methodWORKER

WriteBinaryFile

jsdoc/utils.js:1463
WriteBinaryFile(path, data)

Write raw binary data to a file.
For large output, consider OpenBinaryWriter; it writes incrementally from a reusable caller-provided buffer. Relative filesystem paths are resolved as described in ReadTextFile.

Parameters

NameTypeDescription
pathstring

Absolute or script-relative file path.

dataUint8Array

Bytes to write

Returns

boolean —

true on success

Throws

Error —

If data is not a Uint8Array.

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);
}
methodWORKER

WriteINI

jsdoc/utils.js:1490
WriteINI(filename, section, key, val)

Relative filesystem paths are resolved as described in ReadTextFile.

Parameters

NameTypeDescription
filenamestring
sectionstring
keystring
valstring

Returns

boolean

Example

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

WriteTextFile

jsdoc/utils.js:1541
WriteTextFile(filename, content, write_bom, codepage)

Note: the parent folder must already exist.
UTF-8 is used by default, matching 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 OpenTextWriter; it writes incrementally and does not require one large JavaScript string containing the entire file.

Relative filesystem paths are resolved as described in ReadTextFile.

Parameters

NameTypeDescription
filenamestring
contentstring
write_bom = trueoptionalboolean
codepage = 65001optionalnumber

Output Windows codepage. Codepage 0 is not valid for writing. See Codepages.js.

Returns

boolean —

true on success, false otherwise.

Examples

Default UTF-8 with BOM
utils.WriteTextFile("z:\\1.txt", "test");
UTF-8 without BOM
utils.WriteTextFile("z:\\2.txt", "test", false);
UTF-16LE with BOM
utils.WriteTextFile("z:\\3.txt", "test", true, 1200);