utils

Various utility functions.

Members

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

Methods

static CheckComponent(name, is_dllopt) → {boolean}

Checks the availability of foobar2000 component.
Parameters:
Name Type Attributes Default Description
name string
is_dll boolean <optional>
true If true, method checks filename as well as the internal name.
Returns:
boolean
Example
console.log(utils.CheckComponent("foo_playcount", true));

static CheckFont(name) → {boolean}

Check if the font is installed.
Note: it cannot detect fonts loaded by `foo_ui_hacks`. However, gdi.Font can use those fonts.
Parameters:
Name Type Description
name string Can be either in English or the localised name in your OS.
Returns:
boolean

static ColourPicker(window_id, default_colour) → {number}

Spawns a windows popup dialog to let you choose a colour.
Parameters:
Name Type Description
window_id number unused
default_colour number This colour is used if OK button was not clicked.
Returns:
number
Example
let colour = utils.ColourPicker(0, RGB(255, 0, 0));
// See docs\Helper.js for RGB function.

static DetectCharset(path) → {number}

Detect the codepage of the file.\n Note: detection algorithm is probability based (unless there is a UTF BOM), i.e. even though the returned codepage is the most likely one, there's no 100% guarantee it's the correct one.\n Performance note: detection algorithm is quite slow, so results should be cached as much as possible.
Parameters:
Name Type Description
path number Path to file
Returns:
number - Codepage number on success, 0 if codepage detection failed

static EditTextFile(path)

Edit a text file with the default text editor.
Default text editor can be changed via `Edit` button on the main tab of window.ShowConfigureV2.
Parameters:
Name Type Description
path number Path to file

static FileExists(path) → {boolean}

Parameters:
Name Type Description
path number Path to file
Returns:
boolean - true, if file exists.

static 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.
Parameters:
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.
"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:
*
Deprecated:
  • Yes
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"

static FormatDuration(seconds) → {string}

Parameters:
Name Type Description
seconds number
Returns:
string
Example
console.log(utils.FormatDuration(plman.GetPlaylistItems(plman.ActivePlaylist).CalcTotalDuration())); // 1wk 1d 17:25:30

static FormatFileSize(bytes) → {string}

Parameters:
Name Type Description
bytes number
Returns:
string
Example
console.log(utils.FormatFileSize(plman.GetPlaylistItems(plman.ActivePlaylist).CalcTotalSize())); // 7.9 GB

static GetAlbumArtAsync(window_id, handle, art_idopt, need_stubopt, only_embedopt, no_loadopt)

Load art image for the track asynchronously.

Performance note: consider using gdi.LoadImageAsync or gdi.LoadImageAsyncV2 if there are a lot of images to load or if the image is big.
Parameters:
Name Type Attributes Default Description
window_id number unused
handle FbMetadbHandle
art_id number <optional>
0 See Flags.js > AlbumArtId
need_stub boolean <optional>
true
only_embed boolean <optional>
false
no_load boolean <optional>
false If true, "image" parameter will be null in on_get_album_art_done callback.
Example
// See `samples/basic/GetAlbumArtAsync.js`

static GetAlbumArtAsyncV2(window_id, handle, art_idopt, need_stubopt, only_embedopt, no_loadopt) → {Promise.<ArtPromiseResult>}

Load art image for the track asynchronously.
Returns a `Promise` object, which will be resolved when art loading is done.
Parameters:
Name Type Attributes Default Description
window_id number unused
handle FbMetadbHandle
art_id number <optional>
0 See Flags.js > AlbumArtId
need_stub boolean <optional>
true If true, will return a stub image from `Preferences`>`Display`>`Stub image path` when there is no art image available.
only_embed boolean <optional>
false If true, will only try to load the embedded image.
no_load boolean <optional>
false If true, then no art loading will be performed and only path to art will be returned in ArtPromiseResult.
Returns:
Promise.<ArtPromiseResult>
Example
// See `samples/basic/GetAlbumArtAsyncV2.js`

static GetAlbumArtEmbedded(rawpath, art_idopt) → {GdiBitmap}

Load embedded art image for the track.

Performance note: consider using fb.GetAlbumArtAsync or fb.GetAlbumArtAsyncV2 if there are a lot of images to load.
Parameters:
Name Type Attributes Default Description
rawpath string Path to track file
art_id number <optional>
0 See Flags.js > AlbumArtId
Returns:
GdiBitmap
Example
let img = utils.GetAlbumArtEmbedded(fb.GetNowPlaying().RawPath, 0);

static GetAlbumArtV2(handle, art_idopt, need_stubopt) → {GdiBitmap}

Load art image for the track.

Performance note: consider using fb.GetAlbumArtAsync or fb.GetAlbumArtAsyncV2 if there are a lot of images to load.
Parameters:
Name Type Attributes Default Description
handle FbMetadbHandle
art_id number <optional>
0 See Flags.js > AlbumArtId
need_stub boolean <optional>
true
Returns:
GdiBitmap
Example
// See `samples/basic/GetAlbumArtV2.js`

static GetFileSize(path) → {number}

Parameters:
Name Type Description
path string
Returns:
number - File size, in bytes

static GetPackagePath(package_id) → {string}

Get path to a package directory with the specified id.
Throws exception if package is not found.
Parameters:
Name Type Description
package_id string
Returns:
string

static GetSysColour(index) → {number}

Returns:
number - 0 if failed
Example
let splitter_colour = utils.GetSysColour(15);

static GetSystemMetrics(index) → {number}

Returns:
number - 0 if failed

static Glob(pattern, exc_maskopt, inc_maskopt) → {Array.<string>}

Retrieves filepaths that match the supplied pattern.
Parameters:
Name Type Attributes Default Description
pattern string
exc_mask number <optional>
0x10 Default is FILE_ATTRIBUTE_DIRECTORY. See Flags.js > Used in utils.Glob()
inc_mask number <optional>
0xffffffff
Returns:
Array.<string>
Example
let arr = utils.Glob("C:\\*.*");

static InputBox(window_id, prompt, caption, default_valopt, error_on_cancelopt) → {string}

Parameters:
Name Type Attributes Default Description
window_id number
prompt string
caption string
default_val string <optional>
''
error_on_cancel boolean <optional>
false If set to true, use try/catch like Example2.
Returns:
string
Examples
// With "error_on_cancel" not set (or set to false), cancelling the dialog will return "default_val".
let username = utils.InputBox(0, "Enter your username", "Spider Monkey Panel", "");
// Using Example1, you can't tell if OK or Cancel was pressed if the return value is the same
// as "default_val". If you need to know, set "error_on_cancel" to true which throws a script error
// when Cancel is pressed.
let username = "";
try {
   username = utils.InputBox(0, "Enter your username", "Spider Monkey Panel", "", true);
   // OK was pressed.
} catch(e) {
    // Dialog was closed by pressing Esc, Cancel or the Close button.
}

static IsDirectory(path) → {boolean}

Parameters:
Name Type Description
path string
Returns:
boolean - true, if location exists and it's a directory

static IsFile(path) → {boolean}

Parameters:
Name Type Description
path string
Returns:
boolean - true, if location exists and it's a file

static IsKeyPressed(vkey) → {boolean}

Parameters:
Name Type Description
vkey number https://docs.microsoft.com/en-us/windows/win32/inputdev/virtual-key-codes. Some are defined in Flags.js > Used with utils.IsKeyPressed().
Returns:
boolean

static MapString(text, lcid, flags) → {string}

Parameters:
Name Type Description
text string
lcid string
flags number
Returns:
string

static PathWildcardMatch(pattern, str) → {boolean}

Check if the supplied string matches the pattern.
Using Microsoft MS-DOS wildcards match type. eg "*.txt", "abc?.tx?"
Parameters:
Name Type Description
pattern string
str string
Returns:
boolean

static ReadINI(filename, section, key, default_valopt) → {string}

Note: this only returns up to 255 characters per value.
Parameters:
Name Type Attributes Description
filename string
section string
key string
default_val string <optional>
Returns:
string
Example
let username = utils.ReadINI("e:\\my_file.ini", "Last.fm", "username");

static ReadTextFile(filename, codepageopt) → {string}

Performance note: supply codepage argument if it is known, since codepage detection might take some time.
Parameters:
Name Type Attributes Default Description
filename string
codepage number <optional>
0 See Codepages.js. If codepage is 0, then automatic detection is performed.
Returns:
string
Example
let text = utils.ReadTextFile("E:\\some text file.txt");

static ShowHtmlDialog(window_id, code_or_path, optionsopt)

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

Html code must be IE compatible, meaning:
- JavaScript features are limited by IE (see https://www.w3schools.com/js/js_versions.asp).
- Objects passed to `data` are limited to standard JavaScript objects:
- No extensions from Spider Monkey Panel (e.g. no FbMetadbHandle or GdiBitmap).

There are also additional limitations:
- options.data may contain only the following types:
- Basic types: number, string, boolean, null, undefined.
- Objects as string: the only way to pass objects is to convert them to string and back with `JSON.stringify()` and `JSON.parse()`.
- Arrays: must be cast via `.toArray()` inside html. Each element has same type limitations as options.data.
- Functions: has maximum of 7 arguments. Each argument has same type limitations as options.data.
Parameters:
Name Type Attributes Description
window_id number unused
code_or_path string Html code or file path. File path must begin with `file://` prefix.
options object <optional>
Properties
Name Type Attributes Default Description
width number <optional>
250 Window width
height number <optional>
100 Window height
x number <optional>
0 Window horizontal position relative to desktop
y number <optional>
0 Window vertical position relative to desktop
center boolean <optional>
true If true and if options.x and options.y are not set, will center window relative to fb2k position.
context_menu boolean <optional>
false If true, will enable right-click context menu.
resizable boolean <optional>
false If true, will allow to resize the window.
selection boolean <optional>
false If true, will allow to select everything (label texts, buttons and etc).
scroll boolean <optional>
false If true, will display scrollbars.
data * <optional>
Will be saved in `window.external.dialogArguments` and can be accessed from JavaScript executed inside HTML window. This data is read-only and should not be modified. Has type limitations (see above).
Examples

Dialog from code

// See `samples/basic/HtmlDialogWithCheckbox.js`

Dialog from file

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

static SplitFilePath(path) → {Array.<string>}

Parameters:
Name Type Description
path string
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'

static WriteINI(filename, section, key, val) → {boolean}

Parameters:
Name Type Description
filename string
section string
key string
val string
Returns:
boolean
Example
utils.WriteINI("e:\\my_file.ini", "Last.fm", "username", "Bob");

static WriteTextFile(filename, content, write_bomopt) → {boolean}

Note: the parent folder must already exist. Note2: the file is written with UTF8 encoding.
Parameters:
Name Type Attributes Default Description
filename string
content string
write_bom boolean <optional>
true
Returns:
boolean
Examples

Default encoding

// write_bom missing but defaults to true, resulting file is UTF8-BOM
utils.WriteTextFile("z:\\1.txt", "test");

UTF8 with BOM

utils.WriteTextFile("z:\\2.txt", "test", true);

UTF8 without BOM

utils.WriteTextFile("z:\\3.txt", "test", false);