@crossbind/extension-dialog 0.0.0-stage → 2.0.0-beta.69

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Buğra Sarı and crossbind contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,27 @@
1
- # Temporary Holding Version
1
+ # @crossbind/extension-dialog
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Open and save dialogs on the desktop, message dialogs everywhere.
4
+
5
+ An app has it by having `@crossbind/core-app-host`, which lists it as a dependency: there is nothing to install or list.
6
+
7
+ ## Use
8
+
9
+ ```js
10
+ import { dialog } from 'crossbind/app';
11
+
12
+ const files = await dialog.open({ multiple: true, filters: [{ name: 'Text', extensions: ['txt'] }] });
13
+ const button = await dialog.message({ message: 'Saved.', buttons: ['OK', 'Show'] });
14
+ ```
15
+
16
+ `dialog.open` and `dialog.save` resolve with what the user picked, or `null` when they cancel; `dialog.message` with the
17
+ index of the button clicked. A file a dialog picked is one the page's `shell` functions may reach during this run.
18
+
19
+ ## Platforms
20
+
21
+ `dialog.open` and `dialog.save` on macOS, Linux and Windows; `dialog.message` there and on iOS and Android.
22
+
23
+ ## Replace or leave out
24
+
25
+ It holds the role `dialog`. An extension that gives `replaces: 'dialog'` takes it; `app: { without: ['dialog'] }` in `crossbind.config.js` leaves it out. [The guide](https://crossbind.dev/guide/extensions/#replace) shows how, and [extensions.md](https://github.com/crossbind/crossbind/blob/main/docs/api/extensions.md#the-hosts-own-extensions) what a replacement answers.
26
+
27
+ [app.md](https://github.com/crossbind/crossbind/blob/main/docs/api/app.md#the-apps-functions) has every option.
@@ -0,0 +1,15 @@
1
+ export default function dialog() {
2
+ return {
3
+ name: 'dialog',
4
+ contract: 1,
5
+ root: import.meta.dirname,
6
+ app: {
7
+ sources: ['native/dialog.cpp'],
8
+ macos: { sources: ['native/darwin.mm'], frameworks: ['UniformTypeIdentifiers'] },
9
+ ios: { sources: ['native/ios.mm'] },
10
+ linux: { sources: ['native/linux.cpp'] },
11
+ windows: { sources: ['native/windows.cpp'], libraries: ['comctl32'] },
12
+ android: { sources: ['native/android.cpp'], java: 'native/android', class: 'dev.crossbind.extension.dialog.DialogExtension' },
13
+ },
14
+ };
15
+ }
@@ -0,0 +1,60 @@
1
+ package dev.crossbind.extension.dialog;
2
+
3
+ import android.app.Activity;
4
+ import android.app.AlertDialog;
5
+ import android.view.WindowManager;
6
+
7
+ import dev.crossbind.app.Extension;
8
+ import dev.crossbind.app.ExtensionHost;
9
+
10
+ import org.json.JSONArray;
11
+ import org.json.JSONObject;
12
+
13
+ // The message dialog the native code shows, in the activity in front, answered with the index of the button clicked,
14
+ // or -1 when it went without one.
15
+ public final class DialogExtension implements Extension {
16
+ private AlertDialog messageDialog;
17
+
18
+ @Override
19
+ public void call(ExtensionHost host, String function, JSONObject options, Call call) {
20
+ if (!function.equals("message")) {
21
+ call.reject("crossbind: the dialog extension's Java has no function " + function);
22
+ return;
23
+ }
24
+ JSONArray buttons = options.optJSONArray("buttons");
25
+ String[] labels = new String[buttons == null ? 0 : buttons.length()];
26
+ for (int i = 0; i < labels.length; i += 1) labels[i] = buttons.optString(i);
27
+ showMessageDialog(host.activity(), options.optString("message"), options.optString("detail"), labels, call);
28
+ }
29
+
30
+ // A message dialog that goes with its activity answers as one closed.
31
+ @Override
32
+ public void onDestroy(ExtensionHost host) {
33
+ if (messageDialog != null) messageDialog.dismiss();
34
+ }
35
+
36
+ // Android has a positive, a neutral and a negative button: the first label is the positive one, and the last of
37
+ // several the negative, which Android places where its apps put Cancel. Back and a tap outside close the dialog. The
38
+ // message goes in the dialog's text with the detail, as a title stops after two lines.
39
+ private void showMessageDialog(Activity activity, String message, String detail, String[] labels, Call call) {
40
+ if (activity.isFinishing() || activity.isDestroyed()) {
41
+ call.resolve(-1);
42
+ return;
43
+ }
44
+ String[] names = labels.length == 0 ? new String[] {activity.getString(android.R.string.ok)} : labels;
45
+ int[] clicked = {-1};
46
+ AlertDialog.Builder builder = new AlertDialog.Builder(activity).setMessage(detail.isEmpty() ? message : message + "\n\n" + detail)
47
+ .setPositiveButton(names[0], (dialog, which) -> clicked[0] = 0)
48
+ .setOnDismissListener((dialog) -> {
49
+ messageDialog = null;
50
+ call.resolve(clicked[0]);
51
+ });
52
+ if (names.length == 3) builder.setNeutralButton(names[1], (dialog, which) -> clicked[0] = 1);
53
+ if (names.length > 1) builder.setNegativeButton(names[names.length - 1], (dialog, which) -> clicked[0] = names.length - 1);
54
+ try {
55
+ messageDialog = builder.show();
56
+ } catch (WindowManager.BadTokenException gone) {
57
+ call.resolve(-1);
58
+ }
59
+ }
60
+ }
@@ -0,0 +1,24 @@
1
+ #include "dialog.h"
2
+
3
+ #include <cstdio>
4
+ #include <stdexcept>
5
+
6
+ namespace crossbind::dialog {
7
+
8
+ void showOpenDialog(uint64_t, OpenOptions, std::function<void(Picked)>) { throw std::runtime_error("crossbind: an Android app has no file dialogs yet"); }
9
+
10
+ void showSaveDialog(uint64_t, SaveOptions, std::function<void(std::optional<std::string>)>) {
11
+ throw std::runtime_error("crossbind: an Android app has no file dialogs yet");
12
+ }
13
+
14
+ // The extension's Java shows it in the activity in front; a dialog nothing could show, as when the activity is gone,
15
+ // went without a button.
16
+ void showMessageDialog(uint64_t, MessageOptions options, std::function<void(int)> done) {
17
+ android::callJava("dialog", "message", {{"message", options.message}, {"detail", options.detail}, {"buttons", options.buttons}},
18
+ [done = std::move(done)](std::optional<std::string> failure, Value result) {
19
+ if (failure) std::fprintf(stderr, "%s\n", failure->c_str());
20
+ done(failure ? NO_BUTTON : static_cast<int>(result.asNumber()));
21
+ });
22
+ }
23
+
24
+ } // namespace crossbind::dialog
@@ -0,0 +1,83 @@
1
+ #import <Cocoa/Cocoa.h>
2
+ #import <UniformTypeIdentifiers/UniformTypeIdentifiers.h>
3
+
4
+ #include "dialog.h"
5
+
6
+ namespace crossbind::dialog {
7
+ namespace {
8
+
9
+ NSString *ns(const std::string &text) { return [NSString stringWithUTF8String:text.c_str()] ?: @""; }
10
+
11
+ void onMain(void (^block)(void)) { dispatch_async(dispatch_get_main_queue(), block); }
12
+
13
+ // The panel shows every filter's files at once; none at all, or "*", lets it show any file.
14
+ NSArray<UTType *> *typesOf(const std::vector<FileFilter> &filters) {
15
+ NSMutableArray<UTType *> *types = [NSMutableArray new];
16
+ for (const auto &filter : filters) {
17
+ for (const auto &extension : filter.extensions) {
18
+ if (extension == "*") return @[];
19
+ if (UTType *type = [UTType typeWithFilenameExtension:ns(extension)]) [types addObject:type];
20
+ }
21
+ }
22
+ return types;
23
+ }
24
+
25
+ } // namespace
26
+
27
+ // The panels are app-modal: nothing else in the app, quitting among it, happens while one asks.
28
+ void showOpenDialog(uint64_t, OpenOptions options, std::function<void(Picked)> done) {
29
+ onMain(^{
30
+ NSOpenPanel *panel = [NSOpenPanel openPanel];
31
+ panel.canChooseFiles = !options.directory;
32
+ panel.canChooseDirectories = options.directory;
33
+ panel.allowsMultipleSelection = options.multiple;
34
+ if (!options.title.empty()) panel.message = ns(options.title);
35
+ if (!options.defaultPath.empty()) panel.directoryURL = [NSURL fileURLWithPath:ns(options.defaultPath)];
36
+ panel.allowedContentTypes = typesOf(options.filters);
37
+ if ([panel runModal] != NSModalResponseOK) {
38
+ done(std::nullopt);
39
+ return;
40
+ }
41
+ std::vector<std::string> paths;
42
+ for (NSURL *url in panel.URLs) paths.push_back(url.path.UTF8String);
43
+ done(paths);
44
+ });
45
+ }
46
+
47
+ void showSaveDialog(uint64_t, SaveOptions options, std::function<void(std::optional<std::string>)> done) {
48
+ onMain(^{
49
+ NSSavePanel *panel = [NSSavePanel savePanel];
50
+ if (!options.title.empty()) panel.message = ns(options.title);
51
+ if (!options.defaultPath.empty()) panel.directoryURL = [NSURL fileURLWithPath:ns(options.defaultPath)];
52
+ if (!options.defaultName.empty()) panel.nameFieldStringValue = ns(options.defaultName);
53
+ panel.allowedContentTypes = typesOf(options.filters);
54
+ if ([panel runModal] != NSModalResponseOK) {
55
+ done(std::nullopt);
56
+ return;
57
+ }
58
+ done(std::string(panel.URL.path.UTF8String));
59
+ });
60
+ }
61
+
62
+ // App-modal, as the panels are. Return clicks the first button and Escape the last of several, as closing the dialog
63
+ // does elsewhere; NSAlert would give Escape to one named Cancel instead, wherever it is.
64
+ void showMessageDialog(uint64_t, MessageOptions options, std::function<void(int)> done) {
65
+ onMain(^{
66
+ NSAlert *alert = [NSAlert new];
67
+ alert.messageText = ns(options.message);
68
+ alert.informativeText = ns(options.detail);
69
+ alert.alertStyle = options.kind == MessageKind::error ? NSAlertStyleCritical
70
+ : options.kind == MessageKind::warning ? NSAlertStyleWarning
71
+ : NSAlertStyleInformational;
72
+ for (const auto &label : options.buttons) [alert addButtonWithTitle:ns(label)];
73
+ NSString *escape = @"\x1b";
74
+ for (NSButton *button in alert.buttons) {
75
+ if ([button.keyEquivalent isEqualToString:escape]) button.keyEquivalent = @"";
76
+ }
77
+ alert.buttons.firstObject.keyEquivalent = @"\r";
78
+ if (alert.buttons.count > 1) alert.buttons.lastObject.keyEquivalent = escape;
79
+ done(static_cast<int>([alert runModal] - NSAlertFirstButtonReturn));
80
+ });
81
+ }
82
+
83
+ } // namespace crossbind::dialog
@@ -0,0 +1,119 @@
1
+ // The file and message dialogs the page calls through crossbind/app and the app's own code by their names, one at a time,
2
+ // which each platform shows; the page may reach what a file dialog's user picked.
3
+ #include "dialog.h"
4
+
5
+ #include <algorithm>
6
+ #include <atomic>
7
+ #include <stdexcept>
8
+ #include <type_traits>
9
+ #include <utility>
10
+
11
+ namespace crossbind::dialog {
12
+ namespace {
13
+
14
+ // One dialog at a time: another would open inside the first one's modal loop.
15
+ std::atomic<bool> dialogOpen{false};
16
+ // Android's dialogs take three buttons at most.
17
+ constexpr size_t MAX_BUTTONS = 3;
18
+
19
+ std::vector<std::string> texts(const Value &list) {
20
+ std::vector<std::string> out;
21
+ if (list.isNull()) return out;
22
+ for (const Value &item : list.asArray()) out.push_back(item.asString());
23
+ return out;
24
+ }
25
+
26
+ std::vector<FileFilter> filters(const Value &options) {
27
+ std::vector<FileFilter> out;
28
+ if (options["filters"].isNull()) return out;
29
+ for (const Value &filter : options["filters"].asArray()) out.push_back({filter["name"].asString(""), texts(filter["extensions"])});
30
+ return out;
31
+ }
32
+
33
+ MessageKind kindOf(const std::string &kind) {
34
+ if (kind.empty() || kind == "info") return MessageKind::info;
35
+ if (kind == "warning") return MessageKind::warning;
36
+ if (kind == "error") return MessageKind::error;
37
+ throw std::invalid_argument("crossbind: no message dialog has the kind " + kind);
38
+ }
39
+
40
+ // An extension goes without its dot, whoever gave it.
41
+ template <typename Options>
42
+ Options withoutDots(Options options) {
43
+ for (auto &filter : options.filters) {
44
+ for (auto &extension : filter.extensions) {
45
+ if (!extension.empty() && extension[0] == '.') extension.erase(0, 1);
46
+ if (extension.empty()) throw std::invalid_argument("crossbind: the filter " + filter.name + " has an empty extension");
47
+ }
48
+ }
49
+ return options;
50
+ }
51
+
52
+ // Shows a dialog unless one is open.
53
+ template <typename Options, typename T>
54
+ void showDialog(void (*show)(uint64_t, Options, std::function<void(T)>), uint64_t window, std::type_identity_t<Options> options,
55
+ std::type_identity_t<std::function<void(T)>> done) {
56
+ if (dialogOpen.exchange(true)) throw std::runtime_error("crossbind: another dialog is open");
57
+ try {
58
+ show(window, std::move(options), [done = std::move(done)](T result) {
59
+ dialogOpen = false;
60
+ done(std::move(result));
61
+ });
62
+ } catch (...) {
63
+ dialogOpen = false;
64
+ throw;
65
+ }
66
+ }
67
+
68
+ void allow(const std::string &path) { allowPath(path); }
69
+
70
+ void allow(const std::vector<std::string> &paths) {
71
+ for (const auto &path : paths) allowPath(path);
72
+ }
73
+
74
+ // A file dialog, whose user's picks the page may reach then.
75
+ template <typename Options, typename T>
76
+ void showFileDialog(void (*show)(uint64_t, Options, std::function<void(T)>), uint64_t window, std::type_identity_t<Options> options,
77
+ std::type_identity_t<std::function<void(T)>> done) {
78
+ showDialog(show, window, withoutDots(std::move(options)), [done = std::move(done)](T result) {
79
+ if (result) allow(*result);
80
+ done(std::move(result));
81
+ });
82
+ }
83
+
84
+ // A message dialog, which a page that went around crossbind/app is held to as well; closing it clicks its last button.
85
+ void showMessage(uint64_t window, MessageOptions options, std::function<void(int)> done) {
86
+ if (options.message.empty()) throw std::invalid_argument("crossbind: a message dialog takes a message");
87
+ const bool hasEmptyLabel = std::any_of(options.buttons.begin(), options.buttons.end(), [](const std::string &label) { return label.empty(); });
88
+ if (options.buttons.size() > MAX_BUTTONS || hasEmptyLabel) {
89
+ throw std::invalid_argument("crossbind: a message dialog takes three buttons at most, each with a label");
90
+ }
91
+ const int last = std::max(static_cast<int>(options.buttons.size()) - 1, 0);
92
+ showDialog(showMessageDialog, window, std::move(options), [last, done = std::move(done)](int button) { done(button < 0 ? last : button); });
93
+ }
94
+
95
+ } // namespace
96
+ } // namespace crossbind::dialog
97
+
98
+ void crossbind_extension_dialog(crossbind::Registry &registry) {
99
+ using namespace crossbind::dialog;
100
+ using crossbind::Call;
101
+ using crossbind::Value;
102
+ registry.function("dialog.open", [](Call call) {
103
+ const Value &options = call.options();
104
+ crossbind::dialog::OpenOptions open{options["title"].asString(""), options["defaultPath"].asString(""), filters(options),
105
+ options["directory"].asBool(false), options["multiple"].asBool(false)};
106
+ showFileDialog(showOpenDialog, call.page().windowId(), std::move(open), [call](Picked picked) { call.resolve(picked ? Value(*picked) : Value()); });
107
+ });
108
+ registry.function("dialog.save", [](Call call) {
109
+ const Value &options = call.options();
110
+ crossbind::dialog::SaveOptions save{options["title"].asString(""), options["defaultPath"].asString(""), options["defaultName"].asString(""),
111
+ filters(options)};
112
+ showFileDialog(showSaveDialog, call.page().windowId(), std::move(save), [call](std::optional<std::string> file) { call.resolve(file ? Value(*file) : Value()); });
113
+ });
114
+ registry.function("dialog.message", [](Call call) {
115
+ const Value &options = call.options();
116
+ showMessage(call.page().windowId(), {options["message"].asString(""), options["detail"].asString(""), kindOf(options["kind"].asString("")), texts(options["buttons"])},
117
+ [call](int button) { call.resolve(button); });
118
+ });
119
+ }
@@ -0,0 +1,59 @@
1
+ #pragma once
2
+
3
+ // The dialogs each platform shows. Each is called on the module's thread, shows its dialog on the main thread, over the
4
+ // window of this id, the calling page's, or the app's oldest for 0, but on macOS, whose panels are the app's, and calls
5
+ // done there: a file dialog with what its user picked, or nothing when they cancelled; a message dialog with the index
6
+ // of the button clicked, or NO_BUTTON when its user closed it without one. A platform that has no such dialog throws.
7
+ #include "crossbind/extension.h"
8
+
9
+ #include <functional>
10
+ #include <optional>
11
+ #include <string>
12
+ #include <vector>
13
+
14
+ namespace crossbind::dialog {
15
+
16
+ // A kind of file a dialog offers: its name, and the extensions, with or without the dot, that make it; "*" is any file.
17
+ struct FileFilter {
18
+ std::string name;
19
+ std::vector<std::string> extensions;
20
+ };
21
+
22
+ struct OpenOptions {
23
+ std::string title;
24
+ // The folder the dialog shows first.
25
+ std::string defaultPath;
26
+ std::vector<FileFilter> filters;
27
+ // Folders instead of files.
28
+ bool directory = false;
29
+ bool multiple = false;
30
+ };
31
+
32
+ struct SaveOptions {
33
+ std::string title;
34
+ // The folder the dialog shows first.
35
+ std::string defaultPath;
36
+ std::string defaultName;
37
+ std::vector<FileFilter> filters;
38
+ };
39
+
40
+ enum class MessageKind { info, warning, error };
41
+
42
+ struct MessageOptions {
43
+ std::string message;
44
+ // Smaller text under the message.
45
+ std::string detail;
46
+ // Windows shows its icon for each, and macOS a caution sign for error; Linux, iOS and Android show none.
47
+ MessageKind kind = MessageKind::info;
48
+ // One to three labels, the first the default; none is OK.
49
+ std::vector<std::string> buttons;
50
+ };
51
+
52
+ using Picked = std::optional<std::vector<std::string>>;
53
+ constexpr int NO_BUTTON = -1;
54
+
55
+ void showOpenDialog(uint64_t window, OpenOptions options, std::function<void(Picked)> done);
56
+ void showSaveDialog(uint64_t window, SaveOptions options, std::function<void(std::optional<std::string>)> done);
57
+ void showMessageDialog(uint64_t window, MessageOptions options, std::function<void(int)> done);
58
+
59
+ } // namespace crossbind::dialog
package/native/ios.mm ADDED
@@ -0,0 +1,68 @@
1
+ #import <UIKit/UIKit.h>
2
+
3
+ #include "dialog.h"
4
+
5
+ #include <memory>
6
+ #include <stdexcept>
7
+
8
+ namespace crossbind::dialog {
9
+ namespace {
10
+
11
+ NSString *ns(const std::string &text) { return [NSString stringWithUTF8String:text.c_str()] ?: @""; }
12
+
13
+ void onMain(void (^block)(void)) { dispatch_async(dispatch_get_main_queue(), block); }
14
+
15
+ // A message dialog's answer, given once. UIKit can let an alert go without a click, as when its scene goes, and then
16
+ // the last of its actions to go answers it as closed.
17
+ struct MessageAnswer {
18
+ std::function<void(int)> done;
19
+ bool isGiven = false;
20
+
21
+ void give(int button) {
22
+ if (isGiven) return;
23
+ isGiven = true;
24
+ done(button);
25
+ }
26
+ ~MessageAnswer() { give(NO_BUTTON); }
27
+ };
28
+
29
+ // Over whatever the window of this id, or the app's oldest, shows on top; false when it has nothing to show it over.
30
+ bool presentOnTop(UIViewController *controller, uint64_t window) {
31
+ const std::optional<Window> open = windowOf(window);
32
+ UIViewController *top = ((__bridge UIWindow *)(open ? open->native() : appWindow())).rootViewController;
33
+ while (top.presentedViewController) top = top.presentedViewController;
34
+ if (!top || top.isBeingDismissed) return false;
35
+ [top presentViewController:controller animated:YES completion:nil];
36
+ return true;
37
+ }
38
+
39
+ } // namespace
40
+
41
+ void showOpenDialog(uint64_t, OpenOptions, std::function<void(Picked)>) { throw std::runtime_error("crossbind: an iOS app has no file dialogs yet"); }
42
+
43
+ void showSaveDialog(uint64_t, SaveOptions, std::function<void(std::optional<std::string>)>) {
44
+ throw std::runtime_error("crossbind: an iOS app has no file dialogs yet");
45
+ }
46
+
47
+ // The last of several buttons is the one a keyboard's Escape clicks, which iOS places where its apps put Cancel.
48
+ void showMessageDialog(uint64_t window, MessageOptions options, std::function<void(int)> done) {
49
+ onMain(^{
50
+ auto answer = std::make_shared<MessageAnswer>();
51
+ answer->done = done;
52
+ UIAlertController *alert = [UIAlertController alertControllerWithTitle:ns(options.message)
53
+ message:options.detail.empty() ? nil : ns(options.detail)
54
+ preferredStyle:UIAlertControllerStyleAlert];
55
+ const std::vector<std::string> labels = options.buttons.empty() ? std::vector<std::string>{"OK"} : options.buttons;
56
+ for (size_t i = 0; i < labels.size(); i += 1) {
57
+ const bool isCancel = labels.size() > 1 && i == labels.size() - 1;
58
+ UIAlertAction *action = [UIAlertAction actionWithTitle:ns(labels[i])
59
+ style:isCancel ? UIAlertActionStyleCancel : UIAlertActionStyleDefault
60
+ handler:^(UIAlertAction *) { answer->give(static_cast<int>(i)); }];
61
+ [alert addAction:action];
62
+ if (i == 0) alert.preferredAction = action;
63
+ }
64
+ if (!presentOnTop(alert, window)) answer->give(NO_BUTTON);
65
+ });
66
+ }
67
+
68
+ } // namespace crossbind::dialog
@@ -0,0 +1,104 @@
1
+ #include "dialog.h"
2
+
3
+ #include <gtk/gtk.h>
4
+
5
+ namespace crossbind::dialog {
6
+ namespace {
7
+
8
+ // The window a dialog is modal to: the calling page's, or the app's oldest.
9
+ GtkWindow *parentOf(uint64_t window) {
10
+ const std::optional<Window> open = windowOf(window);
11
+ return static_cast<GtkWindow *>(open ? open->native() : appWindow());
12
+ }
13
+
14
+ // GTK matches a pattern in one case alone, where macOS and Windows match an extension in any; "*" is any file.
15
+ std::string patternOf(const std::string &extension) {
16
+ if (extension == "*") return "*";
17
+ std::string pattern = "*.";
18
+ for (const char c : extension) {
19
+ const char lower = g_ascii_tolower(c);
20
+ const char upper = g_ascii_toupper(c);
21
+ pattern += lower == upper ? std::string(1, c) : std::string{'[', lower, upper, ']'};
22
+ }
23
+ return pattern;
24
+ }
25
+
26
+ void addFilters(GtkFileChooser *chooser, const std::vector<FileFilter> &filters) {
27
+ for (const auto &filter : filters) {
28
+ GtkFileFilter *kind = gtk_file_filter_new();
29
+ gtk_file_filter_set_name(kind, filter.name.c_str());
30
+ for (const auto &extension : filter.extensions) gtk_file_filter_add_pattern(kind, patternOf(extension).c_str());
31
+ gtk_file_chooser_add_filter(chooser, kind);
32
+ }
33
+ }
34
+
35
+ } // namespace
36
+
37
+ // The portal's chooser where there is one, as in a Flatpak, else GTK's own; modal to the app's window.
38
+ void showOpenDialog(uint64_t window, OpenOptions options, std::function<void(Picked)> done) {
39
+ onMainThread([window, options = std::move(options), done = std::move(done)] {
40
+ GtkFileChooserNative *dialog = gtk_file_chooser_native_new(options.title.empty() ? nullptr : options.title.c_str(), parentOf(window),
41
+ options.directory ? GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER : GTK_FILE_CHOOSER_ACTION_OPEN, nullptr, nullptr);
42
+ GtkFileChooser *chooser = GTK_FILE_CHOOSER(dialog);
43
+ gtk_file_chooser_set_select_multiple(chooser, options.multiple);
44
+ if (!options.defaultPath.empty()) gtk_file_chooser_set_current_folder(chooser, options.defaultPath.c_str());
45
+ addFilters(chooser, options.filters);
46
+ Picked picked;
47
+ if (gtk_native_dialog_run(GTK_NATIVE_DIALOG(dialog)) == GTK_RESPONSE_ACCEPT) {
48
+ picked.emplace();
49
+ GSList *files = gtk_file_chooser_get_filenames(chooser);
50
+ for (GSList *file = files; file; file = file->next) {
51
+ picked->push_back(static_cast<char *>(file->data));
52
+ g_free(file->data);
53
+ }
54
+ g_slist_free(files);
55
+ }
56
+ g_object_unref(dialog);
57
+ done(std::move(picked));
58
+ });
59
+ }
60
+
61
+ void showSaveDialog(uint64_t window, SaveOptions options, std::function<void(std::optional<std::string>)> done) {
62
+ onMainThread([window, options = std::move(options), done = std::move(done)] {
63
+ GtkFileChooserNative *dialog = gtk_file_chooser_native_new(options.title.empty() ? nullptr : options.title.c_str(), parentOf(window),
64
+ GTK_FILE_CHOOSER_ACTION_SAVE, nullptr, nullptr);
65
+ GtkFileChooser *chooser = GTK_FILE_CHOOSER(dialog);
66
+ gtk_file_chooser_set_do_overwrite_confirmation(chooser, TRUE);
67
+ if (!options.defaultPath.empty()) gtk_file_chooser_set_current_folder(chooser, options.defaultPath.c_str());
68
+ if (!options.defaultName.empty()) gtk_file_chooser_set_current_name(chooser, options.defaultName.c_str());
69
+ addFilters(chooser, options.filters);
70
+ std::optional<std::string> file;
71
+ if (gtk_native_dialog_run(GTK_NATIVE_DIALOG(dialog)) == GTK_RESPONSE_ACCEPT) {
72
+ if (char *name = gtk_file_chooser_get_filename(chooser)) {
73
+ file = name;
74
+ g_free(name);
75
+ }
76
+ }
77
+ g_object_unref(dialog);
78
+ done(std::move(file));
79
+ });
80
+ }
81
+
82
+ // Modal to the app's window, its buttons in GNOME's order: the first, the default, on the right.
83
+ void showMessageDialog(uint64_t window, MessageOptions options, std::function<void(int)> done) {
84
+ onMainThread([window, options = std::move(options), done = std::move(done)] {
85
+ const GtkMessageType type = options.kind == MessageKind::error ? GTK_MESSAGE_ERROR
86
+ : options.kind == MessageKind::warning ? GTK_MESSAGE_WARNING
87
+ : GTK_MESSAGE_INFO;
88
+ GtkWidget *dialog = gtk_message_dialog_new(parentOf(window), GTK_DIALOG_MODAL, type, options.buttons.empty() ? GTK_BUTTONS_OK : GTK_BUTTONS_NONE,
89
+ "%s", options.message.c_str());
90
+ if (!options.detail.empty()) gtk_message_dialog_format_secondary_text(GTK_MESSAGE_DIALOG(dialog), "%s", options.detail.c_str());
91
+ gtk_window_set_title(GTK_WINDOW(dialog), appName().c_str());
92
+ for (int i = static_cast<int>(options.buttons.size()) - 1; i >= 0; i -= 1) {
93
+ // A label's underscores stay as they are.
94
+ gtk_button_set_use_underline(GTK_BUTTON(gtk_dialog_add_button(GTK_DIALOG(dialog), options.buttons[i].c_str(), i)), FALSE);
95
+ }
96
+ gtk_dialog_set_default_response(GTK_DIALOG(dialog), options.buttons.empty() ? GTK_RESPONSE_OK : 0);
97
+ const int response = gtk_dialog_run(GTK_DIALOG(dialog));
98
+ gtk_widget_destroy(dialog);
99
+ // Escape and closing the dialog answer GTK_RESPONSE_DELETE_EVENT.
100
+ done(response >= 0 ? response : response == GTK_RESPONSE_OK ? 0 : NO_BUTTON);
101
+ });
102
+ }
103
+
104
+ } // namespace crossbind::dialog
@@ -0,0 +1,187 @@
1
+ #include "dialog.h"
2
+
3
+ #include <windows.h>
4
+
5
+ #include <commctrl.h>
6
+ #include <shobjidl.h>
7
+
8
+ #include <cstdio>
9
+
10
+ namespace crossbind::dialog {
11
+ namespace {
12
+
13
+ // The window a dialog is modal to: the calling page's, or the app's oldest.
14
+ HWND parentOf(uint64_t window) {
15
+ const std::optional<Window> open = windowOf(window);
16
+ return static_cast<HWND>(open ? open->native() : appWindow());
17
+ }
18
+
19
+ // A message dialog's own buttons are numbered past the common ones, IDOK to IDCONTINUE.
20
+ constexpr int FIRST_BUTTON = 100;
21
+
22
+ std::wstring wide(const std::string &text) {
23
+ if (text.empty()) return {};
24
+ const int size = MultiByteToWideChar(CP_UTF8, 0, text.data(), static_cast<int>(text.size()), nullptr, 0);
25
+ std::wstring result(static_cast<size_t>(size), L'\0');
26
+ MultiByteToWideChar(CP_UTF8, 0, text.data(), static_cast<int>(text.size()), result.data(), size);
27
+ return result;
28
+ }
29
+
30
+ std::string utf8(const wchar_t *text) {
31
+ if (!text || !*text) return {};
32
+ const int size = WideCharToMultiByte(CP_UTF8, 0, text, -1, nullptr, 0, nullptr, nullptr);
33
+ std::string result(static_cast<size_t>(size - 1), '\0');
34
+ WideCharToMultiByte(CP_UTF8, 0, text, -1, result.data(), size, nullptr, nullptr);
35
+ return result;
36
+ }
37
+
38
+ // A dialog's file types, as COMDLG_FILTERSPECs pointing into the strings beside them.
39
+ struct FileTypes {
40
+ std::vector<std::wstring> names;
41
+ std::vector<std::wstring> patterns;
42
+ std::vector<COMDLG_FILTERSPEC> specs;
43
+ };
44
+
45
+ FileTypes fileTypesOf(const std::vector<FileFilter> &filters) {
46
+ FileTypes types;
47
+ for (const auto &filter : filters) {
48
+ std::wstring pattern;
49
+ for (const auto &extension : filter.extensions) pattern += (pattern.empty() ? L"*." : L";*.") + wide(extension);
50
+ types.names.push_back(wide(filter.name));
51
+ types.patterns.push_back(pattern);
52
+ }
53
+ for (size_t i = 0; i < filters.size(); i += 1) types.specs.push_back({types.names[i].c_str(), types.patterns[i].c_str()});
54
+ return types;
55
+ }
56
+
57
+ void setUp(IFileDialog *dialog, const std::string &title, const std::string &folder, const FileTypes &types) {
58
+ if (!title.empty()) dialog->SetTitle(wide(title).c_str());
59
+ IShellItem *start = nullptr;
60
+ if (!folder.empty() && SUCCEEDED(SHCreateItemFromParsingName(wide(folder).c_str(), nullptr, IID_PPV_ARGS(&start)))) {
61
+ dialog->SetFolder(start);
62
+ start->Release();
63
+ }
64
+ if (!types.specs.empty()) dialog->SetFileTypes(static_cast<UINT>(types.specs.size()), types.specs.data());
65
+ }
66
+
67
+ std::string pathOf(IShellItem *item) {
68
+ PWSTR path = nullptr;
69
+ if (FAILED(item->GetDisplayName(SIGDN_FILESYSPATH, &path))) return {};
70
+ std::string out = utf8(path);
71
+ CoTaskMemFree(path);
72
+ return out;
73
+ }
74
+
75
+ // The caller of a dialog that could not show hears no more than of one cancelled, so the reason goes to the output.
76
+ void report(const char *dialog, HRESULT result) {
77
+ if (FAILED(result) && result != HRESULT_FROM_WIN32(ERROR_CANCELLED)) {
78
+ std::fprintf(stderr, "crossbind: the %s dialog failed: 0x%08lx\n", dialog, static_cast<unsigned long>(result));
79
+ }
80
+ }
81
+
82
+ } // namespace
83
+
84
+ // Modal to the app's window, as the system's file dialogs are.
85
+ void showOpenDialog(uint64_t window, OpenOptions options, std::function<void(Picked)> done) {
86
+ onMainThread([window, options = std::move(options), done = std::move(done)] {
87
+ IFileOpenDialog *dialog = nullptr;
88
+ if (const HRESULT made = CoCreateInstance(CLSID_FileOpenDialog, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&dialog)); FAILED(made)) {
89
+ report("open", made);
90
+ done(std::nullopt);
91
+ return;
92
+ }
93
+ FILEOPENDIALOGOPTIONS flags = 0;
94
+ dialog->GetOptions(&flags);
95
+ dialog->SetOptions(flags | FOS_FORCEFILESYSTEM | (options.directory ? FOS_PICKFOLDERS : 0) | (options.multiple ? FOS_ALLOWMULTISELECT : 0));
96
+ const FileTypes types = fileTypesOf(options.filters);
97
+ setUp(dialog, options.title, options.defaultPath, types);
98
+ Picked picked;
99
+ IShellItemArray *items = nullptr;
100
+ const HRESULT shown = dialog->Show(parentOf(window));
101
+ report("open", shown);
102
+ if (SUCCEEDED(shown) && SUCCEEDED(dialog->GetResults(&items))) {
103
+ picked.emplace();
104
+ DWORD count = 0;
105
+ items->GetCount(&count);
106
+ for (DWORD i = 0; i < count; i += 1) {
107
+ IShellItem *item = nullptr;
108
+ if (FAILED(items->GetItemAt(i, &item))) continue;
109
+ picked->push_back(pathOf(item));
110
+ item->Release();
111
+ }
112
+ items->Release();
113
+ }
114
+ dialog->Release();
115
+ done(std::move(picked));
116
+ });
117
+ }
118
+
119
+ void showSaveDialog(uint64_t window, SaveOptions options, std::function<void(std::optional<std::string>)> done) {
120
+ onMainThread([window, options = std::move(options), done = std::move(done)] {
121
+ IFileSaveDialog *dialog = nullptr;
122
+ if (const HRESULT made = CoCreateInstance(CLSID_FileSaveDialog, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&dialog)); FAILED(made)) {
123
+ report("save", made);
124
+ done(std::nullopt);
125
+ return;
126
+ }
127
+ FILEOPENDIALOGOPTIONS flags = 0;
128
+ dialog->GetOptions(&flags);
129
+ dialog->SetOptions(flags | FOS_FORCEFILESYSTEM | FOS_OVERWRITEPROMPT);
130
+ const FileTypes types = fileTypesOf(options.filters);
131
+ setUp(dialog, options.title, options.defaultPath, types);
132
+ if (!options.defaultName.empty()) dialog->SetFileName(wide(options.defaultName).c_str());
133
+ // A name typed without an extension takes the first file type's.
134
+ if (!options.filters.empty() && !options.filters[0].extensions.empty()) {
135
+ dialog->SetDefaultExtension(wide(options.filters[0].extensions[0]).c_str());
136
+ }
137
+ std::optional<std::string> file;
138
+ IShellItem *item = nullptr;
139
+ const HRESULT shown = dialog->Show(parentOf(window));
140
+ report("save", shown);
141
+ if (SUCCEEDED(shown) && SUCCEEDED(dialog->GetResult(&item))) {
142
+ file = pathOf(item);
143
+ item->Release();
144
+ }
145
+ dialog->Release();
146
+ done(std::move(file));
147
+ });
148
+ }
149
+
150
+ // Modal to the app's window, as a message box is.
151
+ void showMessageDialog(uint64_t window, MessageOptions options, std::function<void(int)> done) {
152
+ onMainThread([window, options = std::move(options), done = std::move(done)] {
153
+ const std::wstring title = wide(appName());
154
+ const std::wstring message = wide(options.message);
155
+ const std::wstring detail = wide(options.detail);
156
+ std::vector<std::wstring> labels;
157
+ for (const auto &label : options.buttons) {
158
+ // A label's ampersands stay as they are, as no access key takes them.
159
+ std::wstring text;
160
+ for (const wchar_t c : wide(label)) text += c == L'&' ? L"&&" : std::wstring(1, c);
161
+ labels.push_back(text);
162
+ }
163
+ std::vector<TASKDIALOG_BUTTON> buttons;
164
+ for (size_t i = 0; i < labels.size(); i += 1) buttons.push_back({FIRST_BUTTON + static_cast<int>(i), labels[i].c_str()});
165
+ TASKDIALOGCONFIG config{};
166
+ config.cbSize = sizeof config;
167
+ config.hwndParent = parentOf(window);
168
+ // Escape and closing the dialog answer IDCANCEL.
169
+ config.dwFlags = TDF_ALLOW_DIALOG_CANCELLATION | TDF_POSITION_RELATIVE_TO_WINDOW;
170
+ config.dwCommonButtons = buttons.empty() ? TDCBF_OK_BUTTON : 0;
171
+ config.pszWindowTitle = title.c_str();
172
+ config.pszMainIcon = options.kind == MessageKind::error ? TD_ERROR_ICON
173
+ : options.kind == MessageKind::warning ? TD_WARNING_ICON
174
+ : TD_INFORMATION_ICON;
175
+ config.pszMainInstruction = message.c_str();
176
+ if (!detail.empty()) config.pszContent = detail.c_str();
177
+ config.cButtons = static_cast<UINT>(buttons.size());
178
+ config.pButtons = buttons.data();
179
+ config.nDefaultButton = buttons.empty() ? IDOK : FIRST_BUTTON;
180
+ int clicked = IDCANCEL;
181
+ const HRESULT shown = TaskDialogIndirect(&config, &clicked, nullptr, nullptr);
182
+ report("message", shown);
183
+ done(FAILED(shown) || clicked == IDCANCEL ? NO_BUTTON : clicked == IDOK ? 0 : clicked - FIRST_BUTTON);
184
+ });
185
+ }
186
+
187
+ } // namespace crossbind::dialog
package/package.json CHANGED
@@ -1,6 +1,41 @@
1
1
  {
2
2
  "name": "@crossbind/extension-dialog",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "2.0.0-beta.69",
4
+ "description": "crossbind app extension: open and save dialogs on the desktop, message dialogs everywhere.",
5
+ "homepage": "https://github.com/crossbind/crossbind/tree/main/extensions/dialog#readme",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "https://github.com/crossbind/crossbind.git"
9
+ },
10
+ "license": "MIT",
11
+ "type": "module",
12
+ "exports": {
13
+ "./page": {
14
+ "types": "./page.d.ts",
15
+ "default": "./page.js"
16
+ },
17
+ "./crossbind.extension.js": "./crossbind.extension.js"
18
+ },
19
+ "files": [
20
+ "crossbind.extension.js",
21
+ "native",
22
+ "page.d.ts",
23
+ "page.js"
24
+ ],
25
+ "crossbind": {
26
+ "extension": "./crossbind.extension.js"
27
+ },
28
+ "peerDependencies": {
29
+ "crossbind": "^2.0.0-beta.69"
30
+ },
31
+ "devDependencies": {
32
+ "crossbind": "^2.0.0-beta.69"
33
+ },
34
+ "keywords": [
35
+ "crossbind-extension",
36
+ "crossbind",
37
+ "system",
38
+ "dialog",
39
+ "app"
40
+ ]
6
41
  }
package/page.d.ts ADDED
@@ -0,0 +1,42 @@
1
+ /** A kind of file a dialog offers: its name, and the extensions, with or without the dot, that make it; "*" is any file. */
2
+ export interface FileFilter {
3
+ name: string;
4
+ extensions: string[];
5
+ }
6
+
7
+ export interface OpenOptions {
8
+ title?: string;
9
+ /** The folder the dialog shows first. */
10
+ defaultPath?: string;
11
+ filters?: FileFilter[];
12
+ /** Folders instead of files. */
13
+ directory?: boolean;
14
+ multiple?: boolean;
15
+ }
16
+
17
+ export interface SaveOptions {
18
+ title?: string;
19
+ /** The folder the dialog shows first. */
20
+ defaultPath?: string;
21
+ defaultName?: string;
22
+ filters?: FileFilter[];
23
+ }
24
+
25
+ export interface MessageOptions {
26
+ message: string;
27
+ /** Smaller text under the message. */
28
+ detail?: string;
29
+ /** info by default. Windows shows its icon for each, and macOS a caution sign for error; Linux, iOS and Android show none. */
30
+ kind?: 'info' | 'warning' | 'error';
31
+ /** One to three labels, the first the default; without them OK. */
32
+ buttons?: string[];
33
+ }
34
+
35
+ export declare const dialog: {
36
+ /** The paths of the files or folders the user picked, or null when they cancelled. */
37
+ open(options?: OpenOptions): Promise<string[] | null>;
38
+ /** The path the user chose to save to, or null when they cancelled. */
39
+ save(options?: SaveOptions): Promise<string | null>;
40
+ /** The index of the button the user clicked: Return gives the first, and Escape or closing the dialog the last. */
41
+ message(options: MessageOptions): Promise<number>;
42
+ };
package/page.js ADDED
@@ -0,0 +1,37 @@
1
+ import { checkedOptions, invoke } from 'crossbind/app/core';
2
+
3
+ // The system's dialogs that pick files or show a message, as a page calls them.
4
+ const isFilters = (value) => Array.isArray(value) && value.every((filter) => typeof filter?.name === 'string'
5
+ && Array.isArray(filter.extensions) && filter.extensions.every((extension) => typeof extension === 'string'));
6
+
7
+ // Spread reads a hole as undefined, which every() skips.
8
+ const isButtons = (value) => Array.isArray(value) && value.length >= 1 && value.length <= MAX_BUTTONS
9
+ && [...value].every((label) => typeof label === 'string' && label !== '');
10
+
11
+ const FILTERS = { isFitting: isFilters, name: 'list of { name, extensions }' };
12
+ const BUTTONS = { isFitting: isButtons, name: 'list of one to three labels' };
13
+ const OPEN = { title: 'string', defaultPath: 'string', filters: FILTERS, directory: 'boolean', multiple: 'boolean' };
14
+ const SAVE = { title: 'string', defaultPath: 'string', defaultName: 'string', filters: FILTERS };
15
+ const MESSAGE = { message: 'string', detail: 'string', kind: 'string', buttons: BUTTONS };
16
+ const MESSAGE_KINDS = ['info', 'warning', 'error'];
17
+ // Android's dialogs take three buttons at most.
18
+ const MAX_BUTTONS = 3;
19
+
20
+ function checkedMessage(options) {
21
+ checkedOptions('dialog.message', options, MESSAGE);
22
+ if (!options.message) throw new TypeError('crossbind: dialog.message takes a message.');
23
+ if (options.kind !== undefined && !MESSAGE_KINDS.includes(options.kind)) {
24
+ throw new TypeError(`crossbind: dialog.message's kind is info, warning or error, not ${JSON.stringify(options.kind)}.`);
25
+ }
26
+ return options;
27
+ }
28
+
29
+ export const dialog = {
30
+ // The paths of the files or folders the user picked, or null when they cancelled.
31
+ open: async (options = {}) => invoke('dialog.open', checkedOptions('dialog.open', options, OPEN)),
32
+ // The path the user chose to save to, or null when they cancelled.
33
+ save: async (options = {}) => invoke('dialog.save', checkedOptions('dialog.save', options, SAVE)),
34
+ // The index of the button the user clicked: Return gives the first, and Escape or closing the dialog the last.
35
+ message: async (options) => invoke('dialog.message', checkedMessage(options)),
36
+ };
37
+