Skip to content

utils#

Properties

utils.VersionString string read

Methods

utils.CalcTextWidth(text, font_str)#

Arguments
text string
font_str string See fonts.

Returns a number.

Example

var text = "blah";
var font = window.GetUIFont(0);
var width = utils.CalcTextWidth(text, font);

utils.CheckFont(name)#

Arguments
name string

Returns a boolean value.

utils.ColourPicker(default_colour)#

Arguments
default_colour number

Returns a number which can used as the colour in many methods.

utils.ConvertToAscii(str)#

Arguments
str string

Returns a string.

utils.CopyFile(from, to[, overwrite])#

Arguments
from string
to string
overwrite boolean Default true.

Returns a boolean value.

utils.CopyFolder(from, to[, overwrite, recur])#

Arguments
from string
to string
overwrite boolean Default true.
recur boolean Default true. If false, only files at the root of the folder are copied.

Returns a boolean value.

utils.CreateFolder(path)#

Arguments
path string

Returns a boolean value.

It will be true on success or if folder already exists. Returns false if the operation fails.

Parent folders are created if they don't exist.

utils.CreateImage(width, height)#

Arguments
width number
height number

Returns a JsImage instance.

utils.CreateTextLayout(text, font_str[, text_alignment, paragraph_alignment, word_wrapping, trimming_granularity])#

Arguments
text string
font_str string See fonts.
text_alignment DWRITE_TEXT_ALIGNMENT Default 0.
paragraph_alignment DWRITE_PARAGRAPH_ALIGNMENT Default 0.
word_wrapping DWRITE_WORD_WRAPPING Default 0.
trimming_granularity DWRITE_TRIMMING_GRANULARITY Default 0.

Returns a JsTextLayout instance.

You typically use this when you want to calculate the height of a string that wraps over multiple lines or need scrolling. When passing to JsGraphics WriteTextLayout, you can supply a vertical offset.

Example

include(fb.ComponentPath + 'helpers.js');

var font = CreateFontString('Segoe UI', 20);
var text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.';
var layout = utils.CreateTextLayout(text, font);
var offset = 0;
var text_height = 0;

var box = {
    x : 50,
    y : 50,
    w : 0,
    h : 0,
}

function on_paint(gr) {
    gr.Clear(RGB(255, 255, 255));
    gr.DrawRectangle(box.x, box.y, box.w, box.h, 1, RGB(255, 0, 0));
    gr.WriteTextLayout(layout, RGB(0, 0, 0), box.x, box.y, box.w, box.h, offset);
}

function on_mouse_wheel(step) {
    if (text_height < box.h)
        return;

    offset += step * 60;

    if (offset > 0)
        offset = 0;
    else if (offset < box.h - text_height)
        offset = box.h - text_height;

    window.Repaint();
}

function on_size() {
    box.w = window.Width / 2;
    box.h = window.Height / 2;
    text_height = layout.CalcTextHeight(box.w);

    if (text_height < box.h)
        offset = 0;
    else if (offset < box.h - text_height)
        offset = box.h - text_height;
}

utils.DateStringToTimestamp(str)#

Arguments
str string Must be in full YYYY-MM-DD HH:MM:SS format.

The return value is seconds since 00:00:00 Thursday, 1 January 1970 UTC.

It is expected date strings are timezone adjusted but timestamps are UTC (not adjusted).

Example

var last_played_string = "2018-08-30 00:00:00";
var last_played_timestamp = utils.DateStringToTimestamp(last_played_string);

var now = utils.Now();

// number of seconds in a day
var day = 24 * 60 * 60;

// number of days since last played
console.log(Math.floor((now - last_played_timestamp) / day));

utils.DetectCharset(path)#

Arguments
path string Path to a text file.

Returns a number which can be supplied to utils.ReadTextFile.

This may not be accurate and returns 0 if an error occurred.

utils.DownloadFileAsync(url, path[, verify_image])#

Arguments
url string The remote file you want to download.
path string Full path including extension. The parent folder must already exist.
verify_image boolean Default false.

No return value.

Use in conjunction with on_download_file_done.

Note

You must ensure none of the folders in the path end with a period character.

utils.Env(str)#

Arguments
str string

Returns a string.

Example

console.log(utils.Env("%windir%")); // C:\Windows

utils.FormatDuration(seconds)#

Arguments
seconds number

Returns a string.

Example

var playlist_items = plman.GetPlaylistItems(plman.ActivePlaylist);
var playlist_length_seconds = playlist_items.CalcTotalDuration();
console.log(utils.FormatDuration(playlist_length_seconds)); // 5:24:44

utils.FormatFileSize(bytes)#

Arguments
bytes number

Returns a string.

Example

var playlist_items = plman.GetPlaylistItems(plman.ActivePlaylist);
var playlist_bytes = playlist_items.CalcTotalSize()
console.log(utils.FormatFileSize(playlist_bytes)); // 601 MB

utils.GetClipboardText()#

Returns a string. It will be empty if the clipboard contents are not text.

utils.GetCountryFlag(country_or_code)#

Arguments
country_or_code string

Returns a string. Could be empty on failure.

See Country Flags.

utils.GetFileSize(path)#

Arguments
path string

Returns the size in bytes.

utils.GetLastModified(path)#

Arguments
path string

The return value is seconds since 00:00:00 Thursday, 1 January 1970 UTC.

utils.GetSysColour(index)#

Arguments
index number https://docs.microsoft.com/en-gb/windows/win32/api/winuser/nf-winuser-getsyscolor

Returns a number which can used as the colour in many methods. Could be 0 if the index is invalid.

Example

var splitter_colour = utils.GetSysColour(15);

utils.GetSystemMetrics(index)#

Arguments
index number https://docs.microsoft.com/en-gb/windows/win32/api/winuser/nf-winuser-getsystemmetrics

Returns a number.

utils.Glob(pattern[, exc_mask, inc_mask])#

Arguments
pattern string
exc_mask FILE_ATTRIBUTE Default FILE_ATTRIBUTE_DIRECTORY.
inc_mask FILE_ATTRIBUTE Default 0xffffffff.

Returns an array.

Example

var arr = utils.Glob("C:\\Pictures\\*.jpg");

utils.HashString(str)#

Arguments
str string

Returns a string.

utils.HTTPRequestAsync(type, url[, user_agent_or_headers, body])#

Arguments
type number Use 0 for GET, 1 for POST.
url string
user_agent_or_headers string Optional. See Web Requests for examples.
body 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.

Note

This is for fetching plain text only. See utils.DownloadFileAsync for downloading binary files.

Returns a unique task_id which is used as the first argument in the on_http_request_done callback.

Note

When making a POST request, you should set a Content-Type header. Valid values could be application/json or application/x-www-form-urlencoded.

See Web Requests for examples.

utils.InputBox(prompt, title[, default_value, error_on_cancel])#

Arguments
prompt string
title string
default_value string Defaults to an empty string if omitted.
error_on_cancel boolean Default false. If set to true, you must use try/catch to prevent script errors.

Returns a string.

With error_on_cancel not set (or set to false), cancelling the dialog will return default_value.

Example

var username = utils.InputBox("Enter your username", "JavaScript Panel", "");

Using the above example, you can't tell if OK or Cancel was pressed if the return value is the same as default_value.

If you need to know, set error_on_cancel to true which throws a script error when Cancel is pressed.

Example

try {
    var username = utils.InputBox("Enter your name", "JavaScript Panel", "", true);
    // OK was pressed.
} catch(e) {
    // Dialog was closed by pressing Esc, Cancel or the Close button.
}

utils.IsFile(path)#

Arguments
path string

Returns a boolean value.

utils.IsFolder(folder)#

Arguments
folder string

Returns a boolean value.

utils.IsKeyPressed(vkey)#

Arguments
vkey number https://docs.microsoft.com/en-us/windows/win32/inputdev/virtual-key-codes

Returns a boolean value.

utils.ListFiles(folder[, recursive])#

Arguments
folder string
recursive boolean Default false.

Returns an array.

utils.ListFolders(folder[, recursive])#

Arguments
folder string
recursive boolean Default false.

Returns an array.

utils.ListFonts()#

Returns an array.

utils.LoadBitmap(path[, max_size])#

Arguments
path string Any valid image supported by the Windows Imaging Component.
max_size number Default is 0 which leaves the original untouched.

Returns a JsBitmap instance or null on failure.

utils.LoadImage(path[, max_size])#

Arguments
path string Any valid image supported by the Windows Imaging Component.
max_size number Default is 0 which leaves the original untouched.

Returns a JsImage instance or null on failure.

utils.MessageBox(prompt, title, flags)#

Arguments
prompt string
title string
flags MessageBox Buttons, MessageBox Icons Can be combined.

Returns a MessageBox Return Value.

Example

include(fb.ComponentPath + 'helpers.js');

var prompt = "Do you really want to open the Preferences?";
var title = "A very important question";
if (utils.MessageBox(prompt, title, MB_YESNO | MB_ICONQUESTION) == IDYES) {
    fb.ShowPreferences();
}

utils.Now()#

Returns a Unix timestamp.

This is just shorthand instead of writing

var now = Math.round(new Date().getTime() / 1000);

utils.ReadINI(path, section, key[, default_value])#

Arguments
path string
section string
key string
default_value string This will be the return value if the key isn't found. Defaults to an empty string if omitted.

Returns a string. The maximum length is limited to 255 characters.

An INI file should look something like this:

[section]
key=val

Example

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

utils.ReadTextFile(path[, codepage])#

Arguments
path string
codepage number Default 0. See utils.DetectCharset.

Returns a string. Will be empty if path doesn't exist or there was an error opening it.

Note

If the file is determined to be UTF16-LE or UTF8, any supplied codepage will be ignored.

Example

var path = "E:\\some text file.txt";
var text = utils.ReadTextFile(path);
var path = "E:\\some text file.txt";
var codepage = utils.DetectCharset(path);
var text = utils.ReadTextFile(path, codepage);

utils.ReadUTF8(path)#

Arguments
path string

Returns a string. Will be empty if path doesn't exist or there was an error opening it.

Note

It's preferable to use this when you know the file is UTF8. If you're unsure, continue to use utils.ReadTextFile

utils.RemovePath(path)#

Arguments
path string Can be a file or folder. If it's a folder, all contents will be removed as well.

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.

utils.RenamePath(from, to)#

Arguments
from string Can be a file or folder.
to string

Returns a boolean value.

utils.ReplaceIllegalChars(str[, strip_trailing_periods])#

Arguments
str string
strip_trailing_periods boolean Default false. Set to true if str is a folder name.

Returns a string.

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

Example

var chars = '"\\\/*|:<>?';
console.log(utils.ReplaceIllegalChars(chars));
Output
''⧵⁄∗∣∶˂˃?

utils.Run(app[, params])#

Arguments
app string Can be the path to a file and Windows will open the associated application.
params string Defaults to an empty string if omitted.

No return value.

Example

utils.Run('notepad');
utils.Run('https://www.foobar2000.org');

var file = ...
if (utils.IsFile(file)) {
    utils.Run('explorer', '/select,"' + file + '"');
}

utils.SetClipboardText(text)#

Arguments
text string

No return value.

utils.ShowPopupMessage(message[, title])#

Arguments
message string
title string Default JavaScript Panel.

No return value.

utils.TextBox(prompt, title[, default_value, help_text])#

Arguments
prompt string
title string
default_value string Defaults to an empty string if omitted.
help_text string Defaults to an empty string it omitted. If not empty, a Help button will show in the dialog. If help_text begins with http, it will launch a web browser otherwise it will open a popup window containing the text.

Returns a string.

This offers a multi-line text edit area.

Note

This always throws an error if cancelled so you must use try/catch.

utils.TimestampToDateString(ts)#

Arguments
ts number Should be the number of seconds since 00:00:00 Thursday, 1 January 1970 UTC.

Returns a string. It will be adjusted to your local time zone.

Example

var now = utils.Now();
console.log(utils.TimestampToDateString(now));

utils.WriteINI(path, section, key, value)#

Arguments
path string The parent folder must already exist.
section string
key string
value string

Returns a boolean value.

Example

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

utils.WriteTextFile(path, content)#

Arguments
path string The parent folder must already exist.
content string

Returns a boolean value.

Note

Files are written as UTF8 without BOM.