MediaInfo - macOS Finder Sync Extension

October 4, 2024 · View on GitHub

counter counter

buy me a coffee

logo

MediaInfo - macOS Finder Sync Extension

Extension to display information about multimedia (images, videos and audio), PDF, Office, compressed archives and folders in the Finder contextual menu. Require maxOS 10.15 or higher.

contextual menu

MediaInfo is distributed in the hope that it will be useful but WITHOUT ANY WARRANTY.

If you like this application and find it useful, buy me a coffee!

Behavior

This application allows you to customize the context menu for supported files. When you right-click on a file within a monitored folder the extension extracts all available information for the file and generates the context menu.

Image menu example Image menuVideo menu example Video menu
Audio menu example Video menuPDF menu example PDF menu
Office menu example Office menuArchive menu example Archive menu
Folder menu example Folder menu

With the main application you can customize the menu. You can compose the file properties generating the menu items. It is also possible to use a script code to format the menu items.

Remember that all rendering operations must be completed before the menu can be displayed. MacOS does not allow you to populate on-demand the menu but only before viewing, so any information extraction and formatting operation must be as fast as possible in order not to slow down the opening of the menu.

Installation

Go to the releases page to download the latest version.

Move the downloaded app on your Applications folder and launch it to set the monitored folders and the other settings.

Then you need to enable the associated Finder Sync Extension on the System Preferences / Extensions.

System preferences/Extensions

Now right click (or control click) on a supported file within a monitored folder to see the contextual menu with the information.

The precompiled application is not notarized or signed. The application is compiled as universal binary (Intel and Apple Silicon processor).

When you manually download the precompiled app directly you must strip quarantine flag. The first time you can launch the app with right click (or ctrl click) on the app icon and choose the open action.

Alternatively, you can open System Preferences > Security & Privacy > General (tab) then clicking the Open Anyway button.

If the system warns that the application is damaged, use the following terminal command:

$ xattr -cr "FULL PATH OF THE MediaInfo .app (you can drag the file to get the pull path)"

This will resolve the error of an unsigned/damaged application when launching the app.

When the monitored folders are changed or when the Finder Sync extension is restarted, the System may display a confirmation warning to allow read access to the files of the monitored folders. Access must be granted for the Finder extension to work.

Grant access

Note for macOS Sequoia

Since macOS 15 Sequoia de Finder Extension is not available in the System Settings and cannot be easily enabled or disabled.

There's currently no official update or solution from Apple.

You can use the FinderSyncer utility to visual handle all Finder Extensions, or manually with these Terminal.app commands:

pluginkit -m CFBundleIdentifier=org.sbarex.MediaInfo.Finder-Extension -vv 

Copy the value of UUID that has a format similar to XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX and then execute the following code using the UUID copied:

pluginkit -e "use" -u "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"

Replace "use" with "ignore" if you want to disable the extension.

Settings

Monitored folders

With the Application you can customize the monitored folders and the properties to be shown inside the contextual menu.

Folder settings

You can also auto monitor external disk.

Information is shown only for files within the monitored folders (and their subfolders).

General

The General tab allow to set some common options.

General settings

OptionDescription
Show menu iconsShow icons inside the contextual menu. You can customize the icon for each menu item. Some icons (image, video, pdf, page, ratio, media box, bleed box, art box, text document) respect the orientation (portrait or landscape) of the source. The color icon respects the color space (RGB, CMYK, gray scale, B/W, Lab). The flag icon will be changed to the country language flag when used within a media file.
Skip items with no data for the placeholdersDo not insert menu item with all empty placeholders.
Show info on a submenuIf enabled, on the contextual menu is added a submenu with the info items, otherwise all items are put on the main contextual menu.
Show main info on the submenu titleIf enabled, a submenu with file information is added to the context menu, otherwise all items are placed in the main context menu.
Use first menu item as Main infoUse the first item as the main title for the submenu.
Menu actionAction performed when a menu item is selected. Some menu items always perform a custom action by ignoring this setting. You can use a custom trigger to handle the menu action.
Metadata value on a submenuIn the metadata menu, show the value as a submenu or with the attribute name.
Allow rounded aspect ratioFor images and videos, allow to round the size for a better ratio.
Format for bytesAllows you to choose how to display the values in bytes: using the system settings, in decimal format (1KB = 1000 bytes) or binary format (1KB = 1024 bytes)
Format for bitsAllows you to choose how to display the values in bits: in decimal format (1Kb = 1000 bits) or binary format (1Kb = 1024 bits)
Media engine priorityAllows you to choose the order in which the media engines are used to recognize images, videos and sounds. Not all engines can recognize all file properties. If one engine fails to process a file, the next engine is tried.

Media engines:

  • Core Media: it uses the Apple CoreMedia APIs to parse media files. It is able to recognize many formats and most of their properties.
  • FFMpeg: it uses the FFMpeg library to analyze multimedia files. It generally supports more files and provides more detailed information. However, it requires more resources.
  • Metadata: Use Apple Core Service APIs to extract information from metadata. It requires fewer resources but handle less information.

Customize the menu items

For each managed format it is possible to customize the list of menu items. For each item you can combine plain text with the placeholder which will be filled with its file property.

Customize a menu item

When composing the menu title, all worthless placeholders are left blank. Multiple spaces or punctuation marks (comma and semicolon) or empty parentheses are automatically deleted. For this reason, it is suggested to separate placeholders whose value may not always be available with spaces, commas or semicolons.

You can also specify an explanatory icon for each item. Some icons (image, video, pdf, page, ratio, media box, bleed box, art box) respect the orientation (portrait or landscape) of the source. The color icon respects the color space (RGB, CMYK, gray scale, B/W, LAB).

Use a single dash (-) to create a menu separator. Note that for a macOS limitation the separator element will not be shown with the usual dividing line.

If you need more control over the information displayed by the menu items you can also use custom scripts (see the Scripting support chapter).

Common information

For each type of file some common information is available:

infoplaceholderdescriptionexample
file size[[file-size]]File size.5 Mb
allocated file size (with resource fork and metadata)[[file-size-full]]Total file size including all resource fork and metadata.6 Mb
file name[[file-name]]Name of the file.image.jpg
file extension[[file-ext]]Extension of the file.jpg
file creation date[[file-cdate]]Creation date of the file.Yesterday 12:45
file modification date[[file-mdate]]Modification date of the file.Today 11:45
file access time[[file-adate]]Last access of the file.Today 12:35
file modes[[file-modes]]File modes.- rw- r-- r--
file acl[[acl]]Submenu with the access control list. The submenu title is the formatted file modes.
Extended attributes[[ext-attributes]]Submenu of the extended attributes.
file modes & ACL[[file-modes:acl]]File modes with the ACL submenu.
file modes & Extendend attributes[[file-modes:ext-attrs]]File modes with the Extended attributes submenu.
file modes & Extendend attributes[[file-modes:acl:ext-attrs]]File modes with the ACL and Extended attributes submenus.
inline script[[script-inline:code]] where code is the javascript source base64 encoded; [[script-inline:js:function_name]] where function_name is the name of a global function (defined somewere) to invoke.A script that returns a text value to show in the menu title.
global script[[script-global:code]] where code is the javascript source base64 encoded; [[script-global:js:function_name]] where function_name is the name of a global function (defined somewere) to invoke.A script that can generate multiple menu items.
UTI[[uti]]Uniform Type Identifier.public.jpeg
UTI description[[uti-desc]]Uniform Type Identifier description.JPEG Image
UTI conformances[[uti-conforms]]Submenu with the Uniform Type Identifier conforms.
Spotlight metadata[[spotlight]]Submenu with the Spotlight metadata

Images

Image settings

Available information:

infoplaceholderdescriptionexample
size[[size]]Size of the image.1920 × 1080 px
width[[width]]Width of the image.1920 px
height[[height]]Height of the image.1080 px
aspect ratio[[ratio]]Aspect ratio.16 : 9
resolution name[[resolution]]Name of the resolution.VGA, FullHD, …
number of pixel[[pixel-count]]Number of pixel.786432
number of pixel[[mega-pixel]]Number of pixel in mega pixel.0.79 Mpx
color space[[color]]Color space.RGB, CMYK, GRAYSCALE, …
color table[[color-table]]Color table.indexed, float, float colors
depth[[depth]]Number of bits per pixel.24 bit
color space & depth[[color-depth]]Color space and depth.RGB 8 bit
animation[[animated]]State of the animation.animated or static
is animated[[is-animated]]Show if the image is animated.animated or empty
with/without alpha channel[[alpha]]Show if the image has an alpha channeltransparent or opaque
with alpha channel[[is-alpha]]Show if the image has an alpha channelwith alpha channel or empty
profile name[[profile-name]]Name of the color profileDisplay LCD
dpi[[dpi]]Printer resolution.150 dpi
printed size[[print:dpi:um]]; [[print:um]] where um can be mm, cm, in.Printer size. You can choose a custom dpi resolution and different unit (cm, mm, inch).21 × 29.7 cm (300 dpi)
paper format[[paper]]Paper format for the printed size.A4, Letter, …
metadata[[metadata]]Show the metadata in a submenu.

Supported image formats:

  • images handled by the macOS via CoreGraphics
  • .webp with libwebp
  • .svg files
  • images handled by FFMpeg
  • .pbm formats
  • .bpg format (parsing the file header).

Extracting metadata is a wasteful operation that can slow down the contextual menu display. For this they are only processed if a metadata token is used. If you need to access metadata within a script, your code must have this comment at the beginning: /* require-metadata */.

Video files

Video settings

Available information:

infoplaceholderdescriptionexample
size[[size]]Size of the video.1920 × 1080 px
width[[width]]Width of the video.1920 px
height[[height]]Height of the video.1080 px
aspect ratio[[ratio]]Aspect ratio.16 : 9
resolution name[[resolution]]Name of the resolution.VGA, FullHD, …
duration[[duration]]Duration.01:15:23, …
seconds[[seconds]]Duration in seconds.60 s
bit rate[[bitrate]]Bit rate.1 Mb/s
start time[[start-time]]Start time.start at 00:00:00, …
start time (seconds)[[start-time-s]]Start time in seconds.start at second 0
language code[[language]]Language country code.EN
language flag[[language-flag]]Language country flag.:it:
languages[[language-count]]Number of languages.2 languages Show the number of available languages on video and audio tracks.
codec[[codec]]Codec name (full name if available, otherwise short name).HEVC H.265
codec short name[[codec-short]]Codec short name.hevc
codec long name[[codec-long]]Codec long name.HEVC H.265
video tracks count[[video-count]]Number of video tracks.2 video tracks
video tracks[[video]]Menu with the video tracks. You can customize the items shows.
audio tracks count[[audio-count]]Number of audio tracks.1 audio tracks
audio tracks[[audio]]Menu with the audio tracks. You can customize the items shows.
subtitles count[[subtitles-count]]Number of subtitles.3 subtitles
subtitles[[subtitles]]Menu with the subtitles list.
chapters count[[chapters-count]]Number of chapters.2 chapters**
chapters[[chapters]]Menu with the list of the chapters.**
frames[[frames]]Number of frames.1.500 frames
frame rates[[fps]]Frame rates.24 fps
profile[[profile]]Profile.Main*
title[[title]]Title.
encoder[[encoder]]Encoder.libffmpeg
compression[[compression]]Compression method.lossy, lossless
field order[[field-order]]Field order.top first*
pixel format[[pixel-format]]Pixel format.yuv420p*
color space[[color-space]]Color space.gbr*
engine[[engine]]CoreMedia

Not all properties are always available, depending on the type of file and the engine used to decode it.

* Available only for files decoded with the FFMpeg engine. ** Not Available for files decoded with the Metadata engine.

It also shows the data of all the video, audio and subtitle tracks present. This information can be viewed within submenus or in the main menu.

Supported video format:

  • video handled by the macOS via CoreMedia
  • video supported by FFMpeg library.

Audio files

Audio settings

Available information:

infoplaceholderdescriptionexample
duration[[duration]]Duration.01:15:23, …
seconds[[seconds]]Duration in seconds.60 s
bit rate[[bitrate]]Bit rate.1 Mb/s
sample rate[[sample-rate]]Sample rate.44.1 kHz
start time[[start-time]]Start time.start at 00:00:00, …
start time (seconds)[[start-time-s]]Start time in seconds.start at second 0
language code[[language]]Language country code.EN
language flag[[language-flag]]Language country flag.:it:
languages[[language-count]]Number of languages.2 languages Show the number of available languages on video and audio tracks.
codec[[codec]]Codec name (full name if available, otherwise short name).MPEG audio layer 2/3
codec short name[[codec-short]]Codec short name.mp3
codec long name[[codec-long]]Codec long name.MPEG audio layer 2/3
channels[[channels]]Number of channels.2 channels
channels[[channels-name]]Audio mono, stereo or number of channels.Mono, Stereo, 3 channels, …
chapters[[chapters]]Number of chapters.2 chapters If this placeholder is the only in the menu item will be added a submenu with the list of the chapters.
title[[title]]Title.
encoder[[encoder]]Encoder.libffmpeg

Not all properties are always available, depending on the type of file and the engine used to decode it.

Supported audio format:

  • audio handled by the macOS via CoreMedia
  • audio supported by FFMpeg library.

PDF documents

PDF settings

Available information:

infoplaceholderdescriptionexample
media box[[mediabox:um]] where um can be pt, mm, cm, inch, paper, paper:pt, paper:mm, paper:cm, paper:in.Media box. You can choose different unit (pt, inch, mm, cm).595 × 842 pt, A4, …
bleed box[[bleedbox:um]] where um can be pt, mm, cm, inch, paper, paper:pt, paper:mm, paper:cm, paper:in.Bleed box. You can choose different unit (pt, inch, mm, cm, paper size).595 × 842 pt, A4, …
crop box[[cropbox:um]] where um can be pt, mm, cm, inch, paper, paper:pt, paper:mm, paper:cm, paper:in.Crop box. You can choose different unit (pt, inch, mm, cm, paper size).595 × 842 pt, A4, …
art box[[artbox:um]] where um can be pt, mm, cm, inch, paper, paper:pt, paper:mm, paper:cm, paper:in.Art box. You can choose different unit (pt, inch, mm, cm, paper size).595 × 842 pt, A4, …
paper format[[mediabox:paper]]Paper format for the printed size.A4, Letter, …
pages[[pages]]Number of pages.15 pages
author[[author]]Author.sbarex
producer[[producer]]Producer.
creator[[creator]]Creator.
creation date[[creation-date]]Creation date.
modification date[[modification-date]]Modification date.
keywords[[keywords]]Keywords.
subject[[subject]]Subject.
title[[title]]Title.
locked[[locked]]Locked status.:lock: or empty
encrypted[[encrypted]]Encrypted status.:key: or empty
allows copy[[allows-copy]]Allows copy status.yes or no
allows print[[allows-print]]Allows print status.yes or no
security[[security]]Security state. Compose the locked, encrypted, copy and print tokens.:lock: no copy
version[[version]]PDF version.version 1.6

Adobe Illustrator .ai files are also supported.

Office files

The following file formats are supported: .docx, .rtfx, .pptx, .odt, .ods, .odp (standard office files based on the XML format).

Office settings

Extracting some metadata requires a deep scan of the main file. This can cause a delay in the display of the context menu of office files. For this reason, the deep scan is enabled only when requested by the chosen tokens are present. If you need to access metadata within a script, your code must have this comment at the beginning: /* require-deep-scan */

Available information:

infoplaceholderdescriptionexamplerequire deep scan
page size[[size:paper]], [[size:um]], [[size:paper:um]] where um can be mm, cm, in.Page size. Only for text document files. You can choose different unit (inch, cm, mm). Can also show the paper format, like A4.21 × 29.7 cm, A4, …Yes
creator[[creator]]File creator.sbarex
creation date[[creation-date]]Creation date.3 May 2021 11:23
creation user and date[[creation]]Creation user and date.created by sbarex on 3 May 2021 11:23
last author[[last-author]]User who made the last save.sbarex
modification date[[modification-date]]Last save date.3 May 2021 11:23
last author and date[[last-modification]]User who made the last save and the date.last saved by sbarex on Sunday 20 March 2022
title[[title]]
subject[[subject]]
description[[description]]File description / comments.
keywords[[keywords]]Keywords of the file, shown as a submenu.
number of pages[[pages]]Number of pages (document files), sheets (spreadsheets) or slides (presentations). For spreadsheets, if this placeholder is used alone, it also shows a submenu with the list of sheet names.4 pages, 3 spreadsheets, 24 slidesYes
characters[[characters]]Number of characters, without spaces. Only for text document files.1821 characters
characters (spaces included)[[characters-space]]Number of characters, with spaces included. Only for text document files.2300 characters
words[[words]]Number of words. Only for text document files.150 words
sheets[[sheets]]List of the sheet names, show as a submenu. Only for spreadsheet files.Yes
presentation format[[presentation-format]]
application[[application]]Application that generated the file.MicrosoftOffice/15.0 MicrosoftWord

Compressed archive files

The compressed archive files are handled by the libarchive library. The following file formats are supported: .zip, .rar, .7z, .tar, .pax, .ar, .xar, .cab.

Compressed archive settings

With the Max files option, you can set the maximum number of files to process from the compressed archive. Set to zero to disable the limit. Please note that processing a lot of entries can slow down the menu generation. Furthermore, displaying many menu items is a heavy operation.

The archive file parsing operation is automatically stopped if it takes too long.

Available information:

infoplaceholderdescriptionexample
number of files[[n-files]]Number of files and directories inside the archive. It is not affected by the setting of the maximum number of files.15 files
number of extracted files[[n-files-processed]]Number of files and directories processed to be shows in the files menu.15 processed files
files summary[[n-files-all]]Total number of files and number of processed files
files menu[[files]], [[files-with-icon]]Submenu with the structure of files inside the archive. It is possible to show also the icon of each files. The items are limited according to the max files and depth options.
plain files menu[[files-plain]], [[files-plain-with-icon]]Submenu with the list of files inside the archive. It is possible to show also the icon of each files. The items are limited according to the max files and depth options.
uncompressed size[[uncompressed-size]]Uncompressed size of the archived data. It is not affected by the setting of the maximum number of files .8 Mb uncompressed
compression ratio[[compression-ratio]]50%
compression summary[[compression-summary]]1Mb = 2Mb uncompressed (ratio 50%)
compression format[[compression-format]]gzip

Folders

You can handle plain folders and even macOS bundles.

Folders settings

You can limit the processed data with these options:

optiondescription
Ignore hidden files
Use generic iconUse the standard icon associated to the file type instead of a customized icon.
Max filesOverall maximum number of files to process.
Max depthMaximum depth of subfolders. Set to zero for no limit.
Max files per depthMaximum number of files processed within a depth level. Set to zero for no limit.

Processing the contents of a folder is a resource-intensive operation that can take time. It is recommended to limit the number of files to be processed.

Processing takes place in two steps:

  • calculation of the total number of files and their occupation on disk. All files (including hidden files and those contained in bundles) are counted ignoring the settings on hidden files and bundles.
  • extraction of the list of files according to the limits set in the preferences.

Each of these operations is aborted, returning a partial result, if it takes too long.

The total number of files and the folder size are acquired only if the specific token is used. If you need to access to the allocated size within a script, your code must begin with the comment /* require-deep-scan */. If is required to access only to the full size use the comment /* require-fast-scan */ as the first line.

Available information:

infoplaceholderdescriptionexample
number of files[[n-files]]Number of files and directories (including hidden files and those contained within bundles). It is not affected by the setting of the maximum number of files, hidden files and bundle. Extracting this information can slow down menu generation and stop if it takes too long, returning a partial value.150 files, More than 1500 files (if the operation was interrupted)
number of processed files[[n-files-processed]]Number of files and directories processed to be shows in the files menu.15 processed files
files summary[[n-files-all]]Total number of files and number of processed files
folder size[[file-size]]Size of all files inside the folder. It is not affected by the setting of the maximum number of files. The extraction of this info can slow down the menu generation and stop if it takes too long, returning a partial value.150 Mb, More than 430 Mb (if the operation was interrupted)
allocated folder size[[file-size-full]]Size on disk of all files inside the folder (considering also the metadata and resource fork). It is not affected by the setting of the maximum number of files. The extraction of this info can slow down the menu generation and stop if it takes too long, returning a partial value.155 Mb, More than 450 Mb (if the operation was interrupted)
files menu[[files]], [[files-with-icon]], [[files-plain]], [[files-plain-with-icon]]Submenu of contained files. The menu can be hierarchical or plain (with indented items). It is possible to show the icon of each files. The items are limited according to the max files and depth options.

Other files

You can also create generic file menus to show basic information. You can use scripts to extract information from the file and place it on the menu.

Other settings

It is possible to create menus for specific file formats (identified through the UTI) and also for all files not directly managed.

Other file settings editor

If a file conforms to several UTIs defined in the settings, the settings to be used will be chosen according to the order in which they were defined.

Menu actions

From the general settings you can set the action to be executed when you choose a menu item:

  • do nothing
  • open the file with the default application.

You can customize the action in several ways:

  • Use a special menu item with custom action.
  • Generate a menu item with a global script and define a custom function to be executed.
  • Define a custom action trigger.

To handle custom action, see the action functions.

Common actions

For each file type there are some special menu items with a predefined action:

infoplaceholderdescriptionexample
open…[[open]]Menu item for opening the file with the default application.Open with Preview…
open with…[[open-with:app]] where app contains the application full path base64 encoded.Menu item for opening the file with a custom application.Open with Adobe Photoshop…
settings…[[open-settings]]Menu item for open the MediaInfo application to customize settings.MediaInfo Settings…
about…[[about]]Menu item for opening the GitHub page of this project.MediaInfo 1.6.1 (19) developed by SBAREX…
copy to the clipboard…[[clipboard]]Menu item for copying the path to the clipboard.
export info to the clipboard…[[export]]Menu item for copying the file info (as json) to the clipboard.

Inline actions

Menu items created by a global script can have a custom action. You need to set the action attribute to "custom" and set userInfo["code"] to the name (a string) of an exists function to call to handle the action. The function receives as a parameter an object with the info of the selected menu item:

  • index (Int): index inside the template
  • tag: tag of the associated menu item
  • menuItem
    • image (String)
    • template (String)
  • action (String)
  • userInfo ([String: Any])

Trigger action

It is possible to define a trigger action executed when a user chooses a menu item. See below for more info.

Scripting support

You can use a javascript code to:

Customize the menu items

It is possible to customize the menu items with a javascript code.

The javascript environment is shared with all scripts defined for the menu items, thus allowing you to set values in the code to pass from one script to another. The scripts are executed in order of belonging in the menu.

Since the environment is shared among all the scripts, remember to be careful not to declare the same global variables in multiple scripts using let and const statement (If you need to redeclare a global variable you can use the var statement).

The javascript environment will be reset every time a new contextual menu generation in required. So, you cannot share data between menu generate for different files.

Exceptions thrown during code execution are indicated by an exclamation icon inside the application.

It is recommended that you enclose the code within an anonymous function:

(function() {
    let result = '';
    
    // your code here
    
    return result; // <- This will be the menu title.  
})()

Script editor

There are two script tokes: inline and global.

The before render trigger can be used to customize the templates defined in the settings before the menu generation.

Exposed data

There are some common global variables.

The fileData variable is an object that contains the data representation of the currently processed file. The variable settings have the current settings.

These two variables are locked and their properties cannot be changed (in strict mode, if you try to change one of their properties an exception is raised). Any changes made to the fileData or settings will not affect the standard token process.

vartypedescription
fileDataObjectProperties of the processed file.
currentFileTypeIntType of the processed file: 1 image, 2 video, 3 audio, 4 office, 5 PDF, 6 archive, 7 3D model, 8 folder, 9 video track, 10 audio track, 11 others.
settingsObjectCurrent settings.
templateItemIndexIntIndex (zero-based) of the processing menu item template. Defined only during rendering phase, for the asynchronous function this value is not guaranteed to remain valid.
currentItemObjectReference to the processing menu item {index: 0, menuItem: {image: "", template: "[[file-size]]", fileType: 1, action: "default", userInfo: {key1: 1, key2: "value"} }. Defined only during rendering phase, for the asynchronous function this value is not guaranteed to remain valid.
debugModeBoolTrue if the code is executed inside the main application.
macOS_versionStringCurrent macOS version (like "12.2.1").

For a descriptions of fileData and settings properties see the Common properties.

From the Window menu you can enable the JS Console to shows the output of the console commands.

Log console

Inline scripts

The inline script token allows you to place the result of the script evaluation inside a menu item with any other tokens.

The result of the script corresponds to the last statement executed in the code. The last statement must return a string value (or null).

(function() {
    const s1 = "Hello World";

    return s1 + " from " + fileData.fileName; // <- This will be the menu title.
})()

Global scripts

The global token script allows you to create multiple menu items at once.

(function() {
    let items = new Array();
    items.push({title: "label 1", image: null});
    items.push({title: "label 2", image: "pencil"});
    items.push("-"); // This is a separator
    items.push({
        title: "submenu",
        items: [
            {title: "first"},
            "second",
        ]
    });

    return items;
})()

The last statement executed must return an array representing the menu items to add.

Each element in the returned array can be:

  • A string that will be used as the title. You can use "-" to add a menu separator.
  • An object with these properties:
    • title (string, required) The title of the menu item.
    • image (string, optional) The image name for the menu item. See below for a list of the available images.
    • checked (bool, optional) Set to true to add the check mark to the menu item.
    • indent (int, optional) Indentation level (from 0 to 15).
    • tag (int, optional)
    • userInfo ([string: Any]) Dictionary of custom user information.
    • action (String) Action to be performed by selecting the menu item. It can be one of these values:
      • "none": do nothing.
      • "standard": execute the action set globally in the settings.
      • "open": open the file with the default application.
      • "openWith": open the file with an application. You need to set the full path of the application in userInfo["application"].
      • "openSettings": open the MediaInfo settings application.
      • "clipboard": copy the path to the clipboard.
      • "export": copy the file info to the clipboard.
      • "reveal": reveal a file on the Finder. You can set userInfo["file"] with the path of the file to reveal, otherwise the current file is used.
      • "about": open the GitHub page of this project.
      • "custom": perform a custom action. You need to set the function name to be called in userInfo["code"].
    • items (Array, optional) An array of the sub-elements.

For each items inside the menu (standard and created by a global script), is required that the combination of tag and the formatted title must be unique. For the standard elements, the assigned tag is the zero index of the template used.

The image property can be:

valueimage
null or "no-image"No image, but reserve a space if is set the visibility of icon in the menu items.
no-spaceNo image, and do not reserve a space.
target-iconCurrent file icon.
"image"imageauto oriented
"image_v"portrait image
"image_h"landscape image
"aspectratio"aspect ratioauto oriented
"aspectratio_h"landscape aspect ratio
"aspectratio_v"portrait aspect ratio vertical
"color"colordynamic
"color_rgb"color RGB
"color_cmyk"color CMYK
"color_gray"color Gray
"color_lab"color Lab
"color_bw"color BW
"print", "printer"printer
"video"videoauto oriented
"video_v"portrait video
"video_h"landscape video
"audio"audio
"speaker", "speaker_mono"speaker mono
"speaker_stereo"speaker stereo
"txt"text
"abc"abc
"page"pageauto oriented
"page_v"portrait page
"page_h"landscape page
"pages"pages
"office"documentauto icon (for word, excel or powerpoint)
"office" or "doc" or "docx", "word"documentauto oriented
"doc_h", "word_h", "docx_h"landscape document
"doc_v", "word_v", "docx_v"portrait document
"xls", "xlsx", "excel"spreadsheet
"ppt", "pptx", "powerpoint"presentation
"3D"3D
"3d_color"3D color
"3d_occlusion"3D occlusion
"3d_lines"3D lines
"3d_normal"3D normal
"3d_points"3D point
"3d_quads"3D quads
"3d_tangent"3D tangent
"3d_triangle_stripe"3D triangle stripe
"3d_triangle"3D triangle
"3d_uv"3D UV
"3d_variable"3D variable
"pdf"pdfauto oriented
"pdf_h"lanscape pdf
"pdf_v"portrait pdf
"artbox"artboxauto oriented
"artbox_h"artbox
"artbox_v"vertical artbox
"bleed"bleedauto oriented
"bleed_h"bleed
"bleed_v"vertical artbox
"crop"crop
"zip"zip
"script"script
"gear", "gearshape"gear
"calendar"calendar
"clipboard"clipboard
"flag"flag
"folder"folder
"info"folder
"size"size
"person"person
"person_n"person_n
"person_y"person_y
"people"person
"group_n"group_n
"group_y"group_y
"shield"shield
"tag"tag
"pencil"pencil
"exclamationmark"exclamationmark

With macOS 11+ you can also use a standard symbol name for the image.

Triggers

You can set up triggers to run for certain events:

  • trigger executed for validate the file before the info extraction.
  • trigger executed before the menu generation, allows to customize the menu item templates
  • trigger executed when a menu item was selected.

Validate trigger

You can define a trigger to be executed before processing the file. The script must return a Boolean value. false prevents the file to be analyzed and no menu will be generated.

// currentFile: path of the processing file
return currentFile.indexOf("test") < 0; // Skip files with "test" in the path.

Please note that the javascript context of the validate trigger is not shared with the other code inside the menu items or with the action trigger.

Before render trigger

This trigger can be used to change the menu items template defined in the settings. The script must return null to not change the settings. Otherwise, must returns an array of menu item templates:

return [
    {image: 'image', template: '[[size]]'},
    {image: 'clipboard', template: '[[clipboard]]'},
    {image: '', template: '-'}, // menu separator
    {image: '', template: ''}
];

For the image property see the Global scripts.

The trigger is evaluated inside an anonymous function, so any functions or variables are not propagated to other script.

If you need to export some data set as a property of the globalThis:

globalThis.myfunc = function() { 
    \\...
};

globalThis.myvar = 4;

return null;

There are two ways to generate a menu item template with a script token:

  • define the code as a base64 encoded string (with toBase64()) and insert it into the token:
let code = "return 'hello world';";
let token = "[[script-inline:"+toBase64(code)+"]]";
  • define a custom function for the globalThis and use its name for the token js attribute:
globalThis.myfunc = function {
    return "hello world";
};

let token = "[[script-inline:js:myfunc]]";

Action trigger

The user can define a custom trigger performed when a menu item is chosen.

The javascript context is the same as all the scripts called to generate the menu items.

Within the action trigger the var selectedMenuItem is set with the properties of the chosen menu item.

To manage the action, see the action functions.

Utility functions

These functions are available during the execution of a javascript code.

funcreturn typedescription
console.log(arg1[, arg2, ...])VoidOutput a log in the Javascript Console Window (available from the Window menu).
console.error(arg1[, arg2, ...])Void
console.warn(arg1[, arg2, ...])Void
console.info(arg1[, arg2, ...])Void
console.debug(arg1[, arg2, ...])Void
console.assert(condition, arg1[, arg2, ...])VoidOutput a log only if the condition is true.
toBase64(string)StringEncode the argument to a base64 value *.
fromBase64(string)StringDecode the argument from a base64 value *.
formatTemplate(template: String){output: String, filled: Bool}Format a template. Return an object, on output filed the formatted result, the filled field indicate if the return has some token filled.
systemExecSync(command, [arguments]){status: Int, output: String}Execute an external command passing the arguments. The command must finish as soon as possible in order not to slow down the display. The task is automatically stopped if it takes too long.

* Some standard tokens (such as scripts and open-width) encode the argument with the base64 standard.

Action functions

To manage the action when the user clicks on a menu item, these functions are available:

/**
 * Open the file at the specified path with the default application.
 *
 * @param {String} path Full path of the file.
 *
 * @returns {Promise} Returns a Promise.
 *
 * @example 
 * systemOpen(fileData.filePath)
 *    .then(
 *        function() {
 *            console.log("success");
 *        },
 *        function() {
 *            console.error("fail");
 *        },
 *    );
 **/
function systemOpen(path)

/**
 * Open the file path with the specified application.
 *
 * @param {String} path Full path of the file.
 * @param {String} application Full path of the macOS application.
 *
 * @returns {Promise} Returns a Promise.
 *
 * @example
 * systemOpenWith(fileData.filePath, "/Applications/TextEdit.app")
 *    .then(
 *        function() {
 *            console.log("success");
 *        },
 *        function(reason) {
 *            let error = reason; // String or Null
 *            console.error("fail: ", error);
 *        },
 *    );
 **/
function systemOpenWith(path, application)

/**
 * Open the specified application.
 *
 * @param {String} path Full path of the macOS application.
 *
 * @returns {Promise} Returns a Promise.
 *
 * @example
 * systemOpenApp("/Applications/TextEdit.app")
 *    .then(
 *        function() {
 *            console.log("success");
 *        },
 *        function(reason) {
 *            let error = reason; // String or Null
 *            console.error("fail: ", error);
 *        },
 *    );
 **/
function systemOpenApp(path)

/**
 * Execute an external `command` passing the arguments as an array of strings.
 *
 * @param {String} command Full path of the command to be executed.
 * @param {String[]} arguments List of arguments for the command.
 *
 * @returns {Promise} Returns a Promise.
 *
 * @example
 * systemExec("command", ["arg1", "arg2"])
 *    .then(
 *        function (reason) {
 *            let output = reason; // String
 *            console.log("success: ", output);
 *        },
 *        function (reason) {
 *            let exit_code = reason[0]; // Int
 *            let output = reason[1]; // String
 *            console.error("fail: ", exit_code, output);
 *        },
 *    );
 *
 **/
function systemExec(command, arguments)

/**
 * Copy a text into the clipboard.
 *
 * @param {String} text 
 *
 * @returns {Bool} True on success.
 *
 * @example
 * systemCopyToClipboard("Hello world");
 *
 **/
function systemCopyToClipboard(text)

These function are only available inside an action trigger or when executing a custom action from an item generated by a global script.

Common properties

Settings

propertytypedescriptionexample
settings.folders[String]Array of monitored folder path.
settingd.bytesFormatint2: system format, 0: decimal, 1: binary
settingd.bitsFormatint0: decimal, 2: binary
settings.handleExternalDiskbool
settings.iconsHiddenbool
settings.infoOnMainItembool
settings.infoOnSubMenubool
settings.skipEmptybool
settings.tracksGroupedbool
settings.useFirstItemAsMainbool
settings.versiondoubleVersion settings.2.0
settings.tracksGroupedbool
settings.engines[Int]Media engine priority. An array of integer. 0: Core Graphics engine; 1: FFMpeg engine, 2: Metadata engine.
settings.isRatioPrecisebool
settings.menuActionint0: do nothing; 1: open with the default app
settings.archiveSettingsObjectSettings for the compressed archives.
settings.archiveSettings.enabledbool
settings.archiveSettings.maxFilesint
settings.archiveSettings.templatesArrayArray of menu items templates.
settings.archiveSettings.triggersObject
settings.audioSettingsObjectSettings for the audio files.
settings.audioSettings.enabledbool
settings.audioSettings.templatesArrayArray of menu items template.
settings.audioSettings.triggersObject
settings.audioTrackSettingsObjectSettings for the audio tracks
settings.audioTrackSettings.enabledbool
settings.audioTrackSettings.templatesArrayArray of menu item templates.
settings.customFormats[Object]Settings for other formats.
settings.customFormats[0].enabledbool
settings.customFormats[0].utiStringUTI of the supported files.
settings.customFormats[0].templatesArrayArray of menu items templates.
settings.customFormats[0].triggersObject
settings.folderSettingsObjectSettings for the folders.
settings.folderSettings.enabledbool
settings.folderSettings.actionint0: standard action, 1: open, 2: reveal.
settings.folderSettings.bundlebool
settings.folderSettings.genericIconbool
settings.folderSettings.maxDepthint
settings.folderSettings.maxFilesint
settings.folderSettings.maxFilesInDepthint
settings.folderSettings.sizeMethodint0: none, 1: fast, 2: full.
settings.folderSettings.skipHiddenbool
settings.folderSettings.templatesArrayArray of menu items templates.
settings.folderSettings.triggersObject
settings.imageSettingsObjectSettings for the images.
settings.imageSettings.enabledbool
settings.imageSettings.metadatabool
settings.imageSettings.templatesArrayArray of menu items templates.
settings.imageSettings.triggersObject
settings.officeSettingsObjectSettings for the office files.
settings.officeSettings.enabledbool
settings.officeSettings.deepScanbool
settings.officeSettings.templatesArrayArray of menu items templates.
settings.officeSettings.triggersObject
settings.otherFormatsObjectSettings for other formats not specified.
settings.otherFormats.enabledbool
settings.otherFormats.templatesArrayArray of menu items templates.
settings.otherFormats.triggersObject
settings.pdfSettingsObjectSettings for the PDF files.
settings.pdfSettings.enabledbool
settings.pdfSettings.templatesArrayArray of menu items templates.
settings.pdfSettings.triggersObject
settings.videoSettingsObjectSettings for the video files.
settings.videoSettings.enabledbool
settings.videoSettings.groupTracksbool
settings.videoSettings.templatesArrayArray of menu items templates.
settings.videoSettings.triggersObject
settings.videoTrackSettingsObjectSettings for the video tracks.
settings.videoTrackSettings.enabledbool
settings.videoTrackSettings.templatesArrayArray of menu items templates.

fileData

propertytypedescriptionexample
fileData.fileUrlStringThe url of the processed file."file:///Users/Default/Documents/file.jpg"
fileData.fileSizeintFile size (in bytes) of file.31470
fileData.fileNameStringFile base name."file.jpg"
fileData.fileExtensionstringFile extension."jpg"
fileData.filePathStringFull path."/Users/Default/Documents/file.jpg"
fileData.fileCreationDateIntCreation date (Unix timestamp).
fileData.fileModificationDateIntModification date (Unix timestamp).
fileData.fileAccessDateIntLast access date (Unix timestamp).
fileData.fileModeIntUnix file modes.
fileData.fileFormattedModeStringUnix file modes."- rw- r-- r--"
fileData.spotlight[String: Any]List of the spotlight metadata. For the key see https://developer.apple.com/documentation/coreservices/file_metadata/mditem .
fileData.acl[Object]Access Control List.
fileData.acl[0].nameStringUser/Group name.sbarex
fileData.acl[0].idIntUser/Group id.501
fileData.acl[0].uidStringUnique User/Group id.2F609312-13E2-4765-BC22-07C3F42A109B
fileData.acl[0].isUserBool
fileData.acl[0].allowBool
fileData.acl[0].attributes[String]["read","write","readattr","readsecurity"]
fileData.utiStringUniform Type Identifier."public.jpeg"
fileData.utiConforms[String]Uniform Type Identifier conformance.["public.image", "public.item", "public.data", "public.content"]
fileData.extAttrs[String: String]Extended attributes.
fileData.extra[String: Any]Extra info.

Properties for images

propertytypedescriptionexample
fileData.depthint8
fileData.dpiint300
fileData.hasAlphaboolfalse
fileData.isAnimatedboolfalse
fileData.isFloatingboolfalse
fileData.isIndexedboolfalse
fileData.colorModestring"RGB"
fileData.profileNamestring"Color LCD"
fileData.metadataObjectAll extracted metadata.
fileData.metadata.ExifArrayExif metadata.
fileData.metadata.ExifAuxArrayAuxiliary Exif metadata.
fileData.metadata.TIFFArrayTIFF metadata.
fileData.metadata.JFIFArrayJFIF metadata.
fileData.metadata.GIFArrayGIF metadata.
fileData.metadata.HEICSArrayHEICS metadata.
fileData.metadata.PNGArrayPNG metadata.
fileData.metadata.IPTCArrayIPTC metadata.
fileData.metadata.GPSArrayGPS metadata.
fileData.metadata.RAWArrayRAW metadata.
fileData.metadata.CanonArrayCanon metadata.
fileData.metadata.NiconArrayNicon metadata.
fileData.metadata.MinoltaArrayMinolta metadata.
fileData.metadata.FujiArrayFuji metadata.
fileData.metadata.OlympusArrayOlympus metadata.
fileData.metadata.PentaxArrayPentax metadata.
fileData.metadata.8BIMArray8BIM metadata.
fileData.metadata.DNGArrayDNG metadata.
fileData.metadata.OpenEXRArrayOpenEXR metadata.
fileData.metadata.AppleArrayApple metadata.
fileData.metadata.FileArrayFile metadata.
fileData.metadata.WebPArrayWebP metadata.
fileData.metadata.TGAArrayTGA metadata.
fileData.metadataRawObjectAn object with the same properties of fileData.metadata with a JSON representation of the original metadata array. Only dictionaries that can be converted to JSON are exported.

If a script require the metadata, add at the begin of the code the comment /* require-metadata */. Depending on the image type, not all metadata properties will be populated.

Every metadata group is an array of objects. Each object has three string properties: code, value and label. For a list of metadata codes see ImageIO - CGImageProperties.h on the Apple documentation.

Properties for video files

propertytypedescriptionexample
fileData.audioTracksArray
fileData.bitRateint1048576
fileData.chaptersArray
fileData.codecLongNamestring|null"H265 / HEVC"
fileData.codecShortNamestring"hevc"
fileData.colorSpaceint|null7
fileData.colorSpaceLabelstring|null"smpte240m"
fileData.durationintNumber of seconds.3600
fileData.encoderstring|null
fileData.engineintEngine used to decode the file.1
fileData.engineNameStringEngine used to decode the file."Core Media engine"
fileData.fieldOrderint|null0: topFirst. 1: bottomFirst. 2: topFirstSwapped. 3: bottomFirstSwapped. 4: unknown. 5: progressive.0
fileData.fieldOrderLabelstring|null"top first"
fileData.fpsint24
fileData.framesint
fileData.isLosslessbool|null
fileData.langstring|nullEN
fileData.langFlagstring|null":it:"
fileData.pixelFormatint|null32
fileData.pixelFormatLabelint|null32
fileData.profilestring|null"Main"
fileData.startTimeint-1
fileData.subtitlesArray
fileData.titlestring|null"Movie title"
fileData.videoTrackArrayMain video track.
fileData.videoTracksArray

Every item in the fileData.audioTracks is an object with these properties:

propertytypedescriptionexample
codecLongNamestring|null"MP3 (MPEG audio layer 3)"
codecShortNamestring"mp3"
bitRateint524800
channelsint2
durationintNumber of seconds.3600
encoderstring|null
isLosslessbool|nullfalse
langstring|nullEN
langFlagstring|null":it:"
startTimeint0
titlestring

Every item in the fileData.chapters is an object with these properties:

propertytypedescriptionexample
titlestring|null
startint201
endint600

Every item in the fileData.subtitles is an object with these properties:

propertytypedescriptionexample
titlestring|null
langstring|null"EN"
langFlagstring|null":it:"

Properties for audio files

propertytypedescriptionexample
fileData.audioTrackArrayMain audio track.
fileData.bitRateint156027
fileData.channelsint2
fileData.chaptersArraySee the chapters of the video files.
fileData.codecLongNamestring|null
fileData.codecShortNamestring"mp3"
fileData.durationdouble2.35
fileData.encoderstring|null
fileData.engineint1
fileData.engineNameStringEngine used to decode the file."Core Media engine"
fileData.isLosslessbool|nullfalse
fileData.langstring|null"EN"
fileData.langFlagstring|null":it:"
fileData.startTimeint-1
fileData.titlestring|null

Properties for PDF files

propertytypedescriptionexample
fileData.allowsCopyingbooltrue
fileData.allowsPrintingbooltrue
fileData.artBoxRect ArrayAn array of two array. The first contains the x and y coordinate of the origin, ant the second the width and height.[[0, 0], [612, 792]
fileData.authorstring"sbarex"
fileData.bleedBoxRect ArraySee fileData.artBox.
fileData.creationDateDate|null
fileData.creationDateTimestampdouble|nullTime interval since 1970.642924149
fileData.creator|nullstring"Acrobat Pro DC 21.1.20155"
fileData.cropBoxRect ArraySee fileData.artBox.
fileData.isEncryptedboolfalse
fileData.isLockedfalse
fileData.keywordsArrayArray of string.["key1", "key2"]
fileData.mediaBoxRect ArraySee fileData.mediaBox.
fileData.modificationDateDate|null
fileData.modificationDateTimestampdouble|nullTime interval since 1970.642924257
fileData.pagesCountint1
fileData.producerstring|null"Acrobat Pro DC 21.1.20155"
fileData.subjectstring|null"PDF test file"
fileData.titlestring|null"Title of the PDF"
fileData.trimBoxRect ArraySee fileData.artBox.
fileData.versionstring"1.6"

Properties for Office files

propertytypedescriptionexample
fileData.applicationstring"Microsoft Word"
fileData.charactersCountint1765
fileData.charactersWithSpacesCountint2000
fileData.creationDateDate|null
fileData.creationDateTimestampdouble|null666192249.77143204
fileData.creatorstringsbarex
fileData.descriptionstring
fileData.heightdoubleInch.11.69291338582677
fileData.keywordsArrayArray of string.["key1", "key2"]
fileData.modificationDateDate|null
fileData.modificationDateTimestampdouble|null666195849.771433
fileData.modifiedstring"sbarex"
fileData.pagesCountint3
fileData.subjectstring
fileData.titlestring
fileData.widthdoubleInch.8.2677165354330704
fileData.wordsCountint123
fileData.sheetsArrayArray of the sheet names.["Worksheet 1", "Worksheet 2"]
fileData.slidesCountIntNumber of slides.15
fileData.presentationFormatString

Properties for compressed archives

propertytypedescriptionexample
fileData.filesArrayArray of files. The list is limited according to the user settings.
fileData.unlimitedFileCountintTotal files inside the archive.44
fileData.unlimitedFileSizeintUncompressed size of all files, in bytes.1153761

Every item in the fileData.files array has these properties:

propertytypedescriptionexample
urlStringURL of the uncompressed file.
pathStringFull path of the uncompressed file.
originalPathstringFull path as saved in the archive."folder/file.ext"
isAbsoluteboolCheck if the file has an absolute path.false
typeint5
typeLabelstring"directory"
filesArrayIf the item is a directory, this property has the file list.
formatstring"ZIP 1.0 (uncompressed)"
isEncryptedboolfalse
sizeintFile size, in bytes. Zero for directories.
isApplicationboolCheck if the file is a macOS Application bundle.false
isDirectoryboolCheck if the file is a directory.false
isPackageboolCheck if the file is a macOS generic bundle.false
isHiddenboolCheck if the file is hidden (file name start with a dot).false
isAliasboolfalse
isPartialbooltrue if the files and/or size attributes are incomplete.

Properties for folders

propertytypedescriptionexample
fileData.folderObject
fileData.folder.isAliasBool
fileData.folder.isApplicationBool
fileData.folder.isDirectoryBool
fileData.folder.isHiddenBool
fileData.folder.isPackageBool
fileData.folder.isPartialBooltrue if the file list of subfiles is incomplete.
fileData.folder.localizedNameString?
fileData.folder.pathString"/Users/sbarex/Documents/test.jpg"
fileData.folder.sizeInt?
fileData.folder.urlString"file:///Users/sbarex/Documents/test.jpg"
fileData.folder.filesArrayArray of files with the same properties.
fileData.totalPartialBooltrue if the number of files or the total file size are incomplete.
fileData.unlimitedFileCountintTotal number of subfiles and folders.
fileData.unlimitedFileSizeintTotal folder size.
fileData.unlimitedFullFileSizeintTotal allocated folder size.
fileData.unlimitedFileCountintTotal number of subfiles and folders.
fileData.unlimitedFileCountintTotal number of subfiles and folders.

Known bugs and limitations

  • A managed folder placed in the Finder sidebar uses a wrong icon. This only happens for directly managed folders, not for subfolders. This is a common issue for many Finder Extension due to a macOS API limitation. A temporary workaround is to manage the parent folder of the one located in the sidebar.

  • Menu item separators are not rendered as usual. This is a limitation of the Apple API.

  • The Apple API allow to set only few option for each menu items: title, tag, image (automatically resized to 16x16 px), indentationLevel, enabled, state, action (the target is always the FIFinderSync instance). When the menu image is passed from the code to the System it will be reprocessed ad lose the template attribute. This prevent the B/W image to change the color from black to white when the menu item is selected.

  • When multiple Finder Extensions are enabled, there is no way to set in witch order the menu of every extension is positioned.

  • All menu items generated by Finder extensions are available only when all extensions complete their processing stage.

  • Files/Folder inside CloudStorage (GoogleDrive, Dropbox, …) cannot be handled.

Build from source

Clone the repository (do not download the source code because break the required git submodule):

git clone https://github.com/sbarex/MediaInfo.git 

Then open the Xcode project, change the signing team and build. First time the build process can be slow due to the compilation of the dependencies libraries.

The required libraries are linked inside the extension and compiled within Xcode, so no others external dependencies are required.

Dependencies

This app uses these libraries:

Application processes

The application uses two XPC processes:

  • MediaInfo Settings XPC: used by the main application to store the settings. This bypass the AppGroup functionality that require a signed app to works.
  • MediaInfo Helper XPC: used by the Finder Extension to read the settings an analyze the selected file. The XPC process can access to files within mounted disks (external or network disks) that would not be accessible by the MediaInfo Finder Extension.

Credits

Developed by sbarex with :heart:.