A small C library with that portably invokes native file open, folder select and file save dialogs.

Native File Dialog Extended

GitHub Actions

A small C library with that portably invokes native file open, folder select and file save dialogs. Write dialog code once and have it pop up native dialogs on all supported platforms. Avoid linking large dependencies like wxWidgets and Qt.

This library is based on Michael Labbe's Native File Dialog (mlabbe/nativefiledialog).

Features:

  • Lean C API, static library -- no C++/ObjC runtime needed
  • Supports Windows (MSVC, MinGW), MacOS (Clang), and Linux (GCC, Clang)
  • Zlib licensed
  • Friendly names for filters (e.g. C/C++ Source files (*.c;*.cpp) instead of (*.c;*.cpp)) on platforms that support it
  • Automatically append file extension on platforms where users expect it
  • Support for setting a default folder path
  • Support for setting a default file name (e.g. Untitled.c)
  • Consistent UTF-8 support on all platforms
  • Native character set (UTF-16 wchar_t) support on Windows
  • Initialization and de-initialization of platform library (e.g. COM (Windows) / GTK (Linux)) decoupled from dialog functions, so applications can choose when to initialize/de-initialize
  • Multiple file selection support (for file open dialog)
  • Support for Vista's modern IFileDialog on Windows
  • No third party dependencies
  • Modern CMake build system
  • Works alongside SDL2 on all platforms
  • Optional C++ wrapper with unique_ptr auto-freeing semantics and optional parameters, for those using this library from C++

Comparison with original Native File Dialog:

The friendly names feature is the primary reason for breaking API compatibility with Michael Labbe's library (and hence this library probably will never be merged with it). There are also a number of tweaks that cause observable differences in this library.

Features added in Native File Dialog Extended:

  • Friendly names for filters
  • Automatically appending file extensions
  • Support for setting a default file name
  • Native character set (UTF-16 wchar_t) support on Windows
  • Initialization and de-initialization of platform library decoupled from file dialog functions
  • Modern CMake build system
  • Optional C++ wrapper with unique_ptr auto-freeing semantics and optional parameters

There is also significant code refractoring, especially for the Windows implementation.

Basic Usage

#include <nfd.h>
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    
    NFD_Init();

    nfdchar_t *outPath;
    nfdfilteritem_t filterItem[2] = { { "Source code", "c,cpp,cc" }, { "Headers", "h,hpp" } };
    nfdresult_t result = NFD_OpenDialog(&outPath, filterItem, 2, NULL);
    if (result == NFD_OKAY)
    {
        puts("Success!");
        puts(outPath);
        NFD_FreePath(outPath);
    }
    else if (result == NFD_CANCEL)
    {
        puts("User pressed cancel.");
    }
    else 
    {
        printf("Error: %s\n", NFD_GetError());
    }

    NFD_Quit();
    return 0;
}

See NFD.h for more options.

If you are using a platform abstraction framework such as SDL or GLFW, also see the "Usage" section below.

Screenshots

Windows 10 MacOS 10.13 GTK3 on Ubuntu 20.04

Building

CMake Projects

If your project uses CMake, simply add the following lines to your CMakeLists.txt:

add_subdirectory(path/to/nativefiledialog-extended)
target_link_libraries(MyProgram PRIVATE nfd)

Make sure that you also have the needed dependencies.

Standalone Library

If you want to build the standalone static library, execute the following commands (starting from the project root directory):

mkdir build
cd build
cmake -DCMAKE_BUILD_TYPE=Release ..
cmake --build .

The above commands will make a build directory, and build the project (in release mode) there. If you are developing NFDe, you may want to do -DCMAKE_BUILD_TYPE=Debug to build a debug version of the library instead.

If you want to build the sample programs, add -DNFD_BUILD_TESTS=ON (sample programs are not built by default).

Visual Studio on Windows

Recent versions of Visual Studio have CMake support built into the IDE. You should be able to "Open Folder" in the project root directory, and Visual Studio will recognize and configure the project appropriately. From there, you will be able to set configurations for Debug vs Release, and for x86 vs x64. For more information, see the Microsoft Docs page. This has been tested to work on Visual Studio 2019, and it probably works on Visual Studio 2017 too.

Compiling Your Programs

  1. Add src/include to your include search path.
  2. Add nfd.lib or nfd_d.lib to the list of static libraries to link against (for release or debug, respectively).
  3. Add build/ / to the library search path.

Dependencies

Linux

apt-get libgtk-3-dev installs the GTK+3 dependency on debian based systems.

MacOS

On MacOS, add AppKit to the list of frameworks.

Windows

On Windows, ensure you are building against comctl32.lib and uuid.lib.

Usage

See NFD.h for API calls. See the test directory for example code (both C and C++).

If you turned on the option to build the test directory (-DNFD_BUILD_TESTS=ON), then build/bin will contain the compiled test programs.

File Filter Syntax

Files can be filtered by file extension groups:

nfdfilteritem_t filterItem[2] = { { "Source code", "c,cpp,cc" }, { "Headers", "h,hpp" } };

A file filter is a pair of strings comprising the friendly name and the specification (multiple file extensions are comma-separated).

A list of file filters can be passed as an argument when invoking the library.

A wildcard filter is always added to every dialog.

Note: On MacOS, the file dialogs do not have friendly names and there is no way to switch between filters, so the filter specifications are combined (e.g. "c,cpp,cc,h,hpp"). The filter specification is also never explicitly shown to the user. This is usual MacOS behaviour and users expect it.

Note 2: You must ensure that the specification string is non-empty and that every file extension has at least one character. Otherwise, bad things might ensue (i.e. undefined behaviour).

Note 3: On Linux, the file extension is appended (if missing) when the user presses down the "Save" button. The appended file extension will remain visible to the user, even if an overwrite prompt is shown and the user then presses "Cancel".

Note 4: On Windows, the default folder parameter is only used if there is no recently used folder available. Otherwise, the default folder will be the folder that was last used. Internally, the Windows implementation calls IFileDialog::SetDefaultFolder(IShellItem). This is usual Windows behaviour and users expect it.

Iterating Over PathSets

A file open dialog that supports multiple selection produces a PathSet, which is a thin abstraction over the platform-specific collection. There are two ways to iterate over a PathSet:

Accessing by index

This method does array-like access on the PathSet, and is the easiest to use. However, on certain platforms (Linux, and possibly Windows), it takes O(N2) time in total to iterate the entire PathSet, because the underlying platform-specific implementation uses a linked list.

See test_opendialogmultiple.c.

Using an enumerator (experimental)

This method uses an enumerator object to iterate the paths in the PathSet. It is guaranteed to take O(N) time in total to iterate the entire PathSet.

See test_opendialogmultiple_enum.c.

This API is experimental, and subject to change.

Customization Macros

You can define the following macros before including nfd.h/nfd.hpp:

  • NFD_NATIVE: Define this before including nfd.h to make non-suffixed function names and typedefs (e.g. NFD_OpenDialog) aliases for the native functions (e.g. NFD_OpenDialogN) instead of aliases for the UTF-8 functions (e.g. NFD_OpenDialogU8). This macro does not affect the C++ wrapper nfd.hpp.
  • NFD_THROWS_EXCEPTIONS: (C++ only) Define this before including nfd.hpp to make NFD::Guard construction throw std::runtime_error if NFD_Init fails. Otherwise, there is no way to detect failure in NFD::Guard construction.

Macros that might be defined by nfd.h:

  • NFD_DIFFERENT_NATIVE_FUNCTIONS: Defined if the native and UTF-8 versions of functions are different (i.e. compiling for Windows); not defined otherwise. If NFD_DIFFERENT_NATIVE_FUNCTIONS is not defined, then the UTF-8 versions of functions are aliases for the native versions. This might be useful if you are writing a function that wants to provide overloads depending on whether the native functions and UTF-8 functions are the same. (Native is UTF-16 (wchar_t) for Windows and UTF-8 (char) for Mac/Linux.)

Usage with a Platform Abstraction Framework

NFDe is known to work with SDL2 and GLFW, and should also work with other platform abstraction framworks. However, you should initialize NFDe after initializing the framework, and probably should deinitialize NFDe before deinitializing the framework. This is because some frameworks expect to be initialized on a "clean slate", and they may configure the system in a different way from NFDe. NFD_Init is generally very careful not to disrupt the existing configuration unless necessary, and NFD_Quit restores the configuration back exactly to what it was before initialization.

An example with SDL2:

// Initialize SDL2 first
if (SDL_Init(SDL_INIT_VIDEO|SDL_INIT_AUDIO) != 0) {
    // display some error here
}

// Then initialize NFDe
if (NFD_Init() != NFD_OKAY) {
    // display some error here
}

/*
Your main program goes here
*/

NFD_Quit(); // deinitialize NFDe first

SDL_Quit(); // Then deinitialize SDL2

Known Limitations

  • No support for Windows XP's legacy dialogs such as GetOpenFileName. (There are no plans to support this; you shouldn't be still using Windows XP anyway.)
  • No Emscripten (WebAssembly) bindings. (This might get implemented if I decide to port Circuit Sandbox for the web, but I don't think there is any way to implement a web-based folder picker.)
  • GTK dialogs don't set the existing window as parent, so if users click the existing window while the dialog is open then the dialog will go behind it. GTK writes a warning to stdout or stderr about this.
  • This library is not compatible with the original Native File Dialog library. Things might break if you use both in the same project. (There are no plans to support this; you have to use one or the other.)

Reporting Bugs

Please use the GitHub issue tracker to report bugs or to contribute to this repository. Feel free to submit bug reports of any kind.

Credit

Bernard Teo (me) and other contributors for everything that wasn't from Michael Labbe's Native File Dialog.

Michael Labbe for his awesome Native File Dialog library, and the other contributors to that library.

Much of this README has also been copied from the README of original Native File Dialog repository.

License

Everything in this repository is distributed under the ZLib license, as is the original Native File Dialog library.

Support

I don't provide any paid support. Michael Labbe appears to provide paid support for his library at the time of writing.

Comments
  • Generate shared library

    Generate shared library

    Is it possible to generate a shared library instead of just a static one? Using static libs in major Linux distros is generally frowned upon.

    https://docs.fedoraproject.org/en-US/packaging-guidelines/#_packaging_static_libraries

  • MacOS: Add CMake flag to avoid using and linking the UniformTypeIdentifiers framework

    MacOS: Add CMake flag to avoid using and linking the UniformTypeIdentifiers framework

    Hi Currently as soon as you're compiling an application that uses nfd-extended on macOS 11 or higher, the UniformTypeIdentifiers Framework gets automatically linked in. This prevents the application from running on any macOS version that's lower than version 11.0.

    This PR adds a cmake option to explicitly enable/disable linking of this framework, even on newer macOS releases. By default this is set to ON so there shouldn't be any behaviour changes for existing applications.

  • README: Fix Windows link dependencies

    README: Fix Windows link dependencies

    To build under MSYS2 + MinGW64 with -lcomctl32 -luuid fails with undefined reference to__imp_CoInitializeEx` and similar linking errors.

    C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/11.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\msys64\tmp\cc4PrAbe.ltrans0.ltrans.o:C:/msys64/home/Bayonetta2.0/new-horizon/lbs/nativefiledialog-extended/src/nfd_win.cpp:309: undefined reference to `__imp_CoInitializeEx'
    C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/11.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\msys64\tmp\cc4PrAbe.ltrans0.ltrans.o:C:/msys64/home/Bayonetta2.0/new-horizon/lbs/nativefiledialog-extended/src/nfd_win.cpp:340: undefined reference to `__imp_CoCreateInstance'
    C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/11.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\msys64\tmp\cc4PrAbe.ltrans0.ltrans.o:C:/msys64/home/Bayonetta2.0/new-horizon/lbs/nativefiledialog-extended/src/nfd_win.cpp:330: undefined reference to `__imp_CoTaskMemFree'
    collect2.exe: error: ld returned 1 exit status
    

    Instead building with -lole32 -luuid solves everything. By my logic, the build info for Windows should be changed as well, but I didn't test that and I don't now enough about the Windows SDK to understand why ole32 is needed but not comctl32. Otherwise, works great <3

  • Formatting with .clang-format

    Formatting with .clang-format

    It would be nice to use clang-format to format the code base.

    One issue brought up would be the raised barrier of entry to contribute. I found an action that automatically checks(but doesn't format): https://github.com/marketplace/actions/clang-format-lint. Could be useful for people without clang-format mayhaps?

    Also, I vouch for trying 80 columns. It's the most common width to use, and it's always possible to relax this limit in the future as it's all automatically formatted. Imo it makes it easier to read from top to bottom :)

  • Call the macos file dialog from Main thread only

    Call the macos file dialog from Main thread only

    The latest macos versions will crash if you try to call its UI components from a non-main thread. Therefore it would be nice if we dispatch all of the calls to the main thread.

  • Implement basic cmake build system

    Implement basic cmake build system

    Hello there,

    Are you interested in this? I want to put it up on conan next, so CMake is the obvious choice. I realize this is quite a radical change, especially since I just threw the premake and scons stuff out, so it's quite understandable if you don't like it.

    If you do want it, I'd be very happy to collaborate on this further and linking the conan recipe to your repo.

    It's currently tested and running on windows, I will setup linux and mac next.

  • [OSX] Dialog does not capture focus

    [OSX] Dialog does not capture focus

    • OS: OSX 19.6.0

    I have opened a similar issue in the original nfd repo, but I had no luck finding help there, but this fork looks a lot more maintained so I decided to ask here, so...

    My file dialogs on MacOs do not catch the focus no matter how hard I try, which also means that the keyboard does not work and only some mouse inputs reach the dialog.

    The described problem is present in nativefiledialog, nativefiledialog-extended, and in osdialog, but it does not occur when using osascript

    GIF:

    Top one is nfd dialog, bottom one is osascript dialog for comparasion GIF

    Workaround that I found that can potentially help to narrow down the problem:

    • Open some sort of window/prompt/dialog (I used NSAlert)
    • After the NSAlert is closed open NSOpenPanel (closing is not necessary)
    • Done, now file dialog will work as expected

    Another Workaround that I found

    • I have to click on the very edge of dialog, and then it catches focus and works as expected: GIF
  • Option to generate shared library & use GNUInstallDirs on linux

    Option to generate shared library & use GNUInstallDirs on linux

    I think this will take care of #75. Please test on windows/apple if you can - i tested the new option on linux and it works well.

    Windows/apple change slightly just due to adding GNUInstallDirs and compatible variables for win/apple.

    You'll probably want to change the way versioning is handled in CMakeLists.txt line 2 long term.

    This causes the shared lib to be versioned based on the major version number (ie 1 here) so if the ABI changes you'll probably want to increment major versions.

  • Clarify build instructions

    Clarify build instructions

    This addresses #19. I took the liberty of breaking off some lines before the 80 column mark, makes it easier to read the source. Also removed the comment about Zenity, as I didn't think it fit there and was mostly distracting.

    I left the instruction on how to build it separately, as I don't know if nfde aims to support non-cmake projects. If it doesn't, it should be possible to make the instructions even more straightforward.

    Also, is the pkg-config comment under Linux still relevant? Don't know what that part does but wouldn't surprise me if it was make specific.

  • Add NFD_INSTALL option + disable install target for subproject usage

    Add NFD_INSTALL option + disable install target for subproject usage

    This checks whether the project is being included as a subproject, and sets NFD_INSTALL and NFD_BUILD_TESTS accordingly.

    Note: this does change the default for NFD_BUILD_TESTS to ON when being built as the root project, this can be reverted if not desired.

  • Add versioning/tags

    Add versioning/tags

    Can you add versioning/tags so this can be included in OS repositories? I'm planning to package it for Fedora/EPEL as a dependency of something else.

  • Add GTK4 support

    Add GTK4 support

    This PR is for (experimental) GTK4 support. Resolves #24.

    As this backend is experimental, GTK3 remains as the default backend. Use -DNFD_GTK_VERSION=4 to activate this new backend.

    Blocking issues:

    • The "Save" button in the dialog is sometimes disabled if the user does not click on an item in the file/directory list. This doesn't make sense in the context of a file save dialog though - it shouldn't be necessary to select something in the list, if the user types something into the text box. This is important but I'm not sure how to fix it - help wanted.
    • SaveDialog has "pressed"/"button-press-event" signals that need to be replaced with gestures. In progress, but doesn't work yet.

    Other unresolved issues (non-blocking):

    • X11 pop-under issue not yet applied to GTK4.
    • Downloading a non-local file might take a while, but it is impossible to cancel. On Windows, the file is downloaded while the dialog is still open (this is automatically done by the file dialog), so the user can cancel it.
    • There is a warning about the lack of transient parent for all dialogs, and the dialog is not modal; this is probably unresolvable.
  • More C++y API

    More C++y API

    The C++ wrapper atm is still (understandabley) pretty C-y. Some things that could be improved would be to use std::basic_string instead of unique_ptr, and to use std::filesystem::path to represent paths.

    I understand that this could possibly mean API breaks, so I'm wondering how backwards compatible this project tries to be? We could also use [[deprecated(reason)]] to faze out old functions if that would help.

    One issue could possibly be the need to maintain two separate APIs for C and C++, as they'd diverge more.

    I'm thinking about forking this and just do away with all the C, but I'd rather contribute to an already existing repo if it's possible :^)

P1031 low level file i/o and filesystem library for the C++ standard

This is the post-peer-review LLFIO v2 rewrite. You can view its documentation at https://ned14.github.io/llfio/ master branch develop branch CMake das

Sep 20, 2022
Cross-platform C++11 header-only library for memory mapped file IO

mio An easy to use header-only cross-platform C++11 memory mapping library with an MIT license. mio has been created with the goal to be easily includ

Sep 22, 2022
Lightweight, portable and easy to integrate C directory and file reader

TinyDir Lightweight, portable and easy to integrate C directory and file reader. TinyDir wraps dirent for POSIX and FindFirstFile for Windows. Windows

Sep 27, 2022
Lightweight, portable and easy to integrate C directory and file reader

TinyDir Lightweight, portable and easy to integrate C directory and file reader. TinyDir wraps dirent for POSIX and FindFirstFile for Windows. Windows

Sep 21, 2022
localfuse - File system implemented on Linux using C and libfuse

localfuse - File system implemented on Linux using C and libfuse Use pure C to have a simple file system of your own on the linux system Install and b

Sep 23, 2021
The MHS Filesystem- A very simple linked-list based file system designed for recoverability and low data redundancy. Public domain filesystem (Version 1)

MHS Filesystem The MHS filesystem. Features: can be modified to work with any size of disk or sector, even non powers of two! Allocation bitmap stored

Sep 17, 2022
FSearch is a fast file search utility for Unix-like systems based on GTK+3
FSearch is a fast file search utility for Unix-like systems based on GTK+3

FSearch is a fast file search utility, inspired by Everything Search Engine. It's written in C and based on GTK3.

Oct 2, 2022
WineFS is a file system for Persistent Memory (PM) which is aimed at maximizing the performance of memory-mapped applications.

WineFS WineFS is a file system for Persistent Memory (PM) which is aimed at maximizing the performance of memory-mapped applications. WineFS uses a no

Oct 2, 2022
LoomIO is an object-level coordination system for distributed file systems.

LoomIO is an object-level coordination system for distributed file systems. It adopts wait-free design to enable interfering object requests self-organizing and obtain an optimized scheduling decision. Currently, LoomIO is implemented and integrated in Ceph.

Jun 19, 2022
C++ implementation of a platform independent endian safe binary file stream

EndianSafeBinaryStream A C++ implementation of a platform independent endian safe binary file stream that can save primitive types and is easily exten

Mar 22, 2022
An implementation of C++17 std::filesystem for C++11 /C++14/C++17/C++20 on Windows, macOS, Linux and FreeBSD.

Filesystem Motivation Why the namespace GHC? Platforms Tests Usage Downloads Using it as Single-File-Header Using it as Forwarding-/Implementation-Hea

Sep 27, 2022
Plays native alert sound and shows native dialogs/alerts in your Flutter app.
Plays native alert sound and shows native dialogs/alerts in your Flutter app.

flutter_platform_alert 2021 © Weizhong Yang a.k.a zonble. A simple plugin to present native alerts, including playing alert sounds and showing alert d

Sep 21, 2022
Open source Splatoon 2 save editor for the Nintendo Switch (NX) built on top of the effective-spoon project
Open source Splatoon 2 save editor for the Nintendo Switch (NX) built on top of the effective-spoon project

Open source Splatoon 2 save editor for the Nintendo Switch (NX) built on top of the effective-spoon project

Sep 16, 2022
A program to backup all of your game savefiles on your system, neatly, and into a single folder.

Savefile Saver I created this project as a solution to a simple, but annoying problem: Backing up my game savefiles. I wanted to be able to copy all o

Jun 8, 2022
Protect files under a specific folder from deleting or moving by explorer.exe.
Protect files under a specific folder from deleting or moving by explorer.exe.

Explorer-Delete-Protection Protect files under a specific folder from deleting or moving by explorer.exe. Requierments: Microsoft Detours Library - ht

Jan 2, 2022
ldd as a tree with an option to bundle dependencies into a single folder
ldd as a tree with an option to bundle dependencies into a single folder

libtree A tool that: ?? turns ldd into a tree ☝️ explains why shared libraries are found and why not ?? optionally deploys executables and dependencie

Sep 26, 2022
A simple CLI to extract & save artwork of a 🎵 music/audio file.
A simple CLI to extract & save artwork of a 🎵 music/audio file.

artwork-extractor A simple CLI to extract & save artwork of a ?? music/audio file. Usage Dependencies MediaInfoLib On Debian based distros, one may in

Aug 4, 2021
🌳 A compressed rank/select dictionary exploiting approximate linearity and repetitiveness.

The block-ε tree is a compressed rank/select dictionary that achieves new space-time trade-offs by exploiting the approximate linearity and the repeti

Jun 5, 2022
Guess a random number between your selected range within the chances you select to win the game!

Number-Guessing-Game Guess a random number between your selected range within the chances you select to win the game! This project was developed by Sa

May 13, 2022
Love 6's Regular Expression Engine. Support Concat/Select/Closure Basic function. Hope u can enjoy this tiny engine :)
Love 6's Regular Expression Engine. Support Concat/Select/Closure Basic function. Hope u can enjoy this tiny engine :)

Regex_Engine Love 6's Blog Website: https://love6.blog.csdn.net/ Love 6's Regular Expression Engine Hope u can love my tiny regex engine :) maybe a fe

May 24, 2022