@crossbind/extension-dialog 0.0.0-stage → 2.0.0-beta.72
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 +21 -0
- package/README.md +32 -2
- package/crossbind.extension.js +15 -0
- package/native/android/dev/crossbind/extension/dialog/DialogExtension.java +201 -0
- package/native/android.cpp +42 -0
- package/native/darwin.mm +83 -0
- package/native/dialog.cpp +119 -0
- package/native/dialog.h +59 -0
- package/native/ios.mm +146 -0
- package/native/linux.cpp +104 -0
- package/native/windows.cpp +187 -0
- package/package.json +38 -3
- package/page.d.ts +46 -0
- package/page.js +37 -0
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,33 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @crossbind/extension-dialog
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Open and message dialogs everywhere, save dialogs on the desktop.
|
|
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.message` on macOS, Linux, Windows, iOS and Android; `dialog.save` on macOS, Linux and Windows.
|
|
22
|
+
|
|
23
|
+
A phone's `dialog.open` shows the system's document picker, without a title, and gives copies of the files its user
|
|
24
|
+
picks, in a folder of their own in the app's temporary or cache folder, which the system may empty. With
|
|
25
|
+
`directory: true` an iOS app gets a folder where its user keeps it, which it reaches while it runs; Android picks files
|
|
26
|
+
alone. Android offers the files of the filters' types where it knows each extension's, and any file otherwise. A phone
|
|
27
|
+
saves the page's files as its downloads, which show the system's export sheet on iOS and its save picker on Android.
|
|
28
|
+
|
|
29
|
+
## Replace or leave out
|
|
30
|
+
|
|
31
|
+
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.
|
|
32
|
+
|
|
33
|
+
[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'], frameworks: ['UniformTypeIdentifiers'] },
|
|
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,201 @@
|
|
|
1
|
+
package dev.crossbind.extension.dialog;
|
|
2
|
+
|
|
3
|
+
import android.app.Activity;
|
|
4
|
+
import android.app.AlertDialog;
|
|
5
|
+
import android.content.ActivityNotFoundException;
|
|
6
|
+
import android.content.ClipData;
|
|
7
|
+
import android.content.Intent;
|
|
8
|
+
import android.database.Cursor;
|
|
9
|
+
import android.net.Uri;
|
|
10
|
+
import android.provider.OpenableColumns;
|
|
11
|
+
import android.util.Log;
|
|
12
|
+
import android.view.WindowManager;
|
|
13
|
+
import android.webkit.MimeTypeMap;
|
|
14
|
+
|
|
15
|
+
import dev.crossbind.app.Extension;
|
|
16
|
+
import dev.crossbind.app.ExtensionHost;
|
|
17
|
+
|
|
18
|
+
import java.io.File;
|
|
19
|
+
import java.io.IOException;
|
|
20
|
+
import java.io.InputStream;
|
|
21
|
+
import java.nio.charset.StandardCharsets;
|
|
22
|
+
import java.nio.file.Files;
|
|
23
|
+
import java.util.ArrayList;
|
|
24
|
+
import java.util.LinkedHashSet;
|
|
25
|
+
import java.util.List;
|
|
26
|
+
import java.util.Locale;
|
|
27
|
+
import java.util.Set;
|
|
28
|
+
import java.util.concurrent.ExecutorService;
|
|
29
|
+
import java.util.concurrent.Executors;
|
|
30
|
+
import java.util.concurrent.atomic.AtomicBoolean;
|
|
31
|
+
|
|
32
|
+
import org.json.JSONArray;
|
|
33
|
+
import org.json.JSONObject;
|
|
34
|
+
|
|
35
|
+
// The dialogs the native code shows in the activity in front: the system's picker, whose files it copies into the app's
|
|
36
|
+
// cache, answered with their paths, or null when its user cancelled; and a message dialog, answered with the index of
|
|
37
|
+
// the button clicked, or -1 when it went without one.
|
|
38
|
+
public final class DialogExtension implements Extension {
|
|
39
|
+
// Whether the process has had COPIES remove the picks of the process before, which no page of this one holds.
|
|
40
|
+
private static final AtomicBoolean ARE_PICKS_CLEARED = new AtomicBoolean();
|
|
41
|
+
private static final ExecutorService COPIES = Executors.newSingleThreadExecutor();
|
|
42
|
+
private static final int MAX_NAME_BYTES = 255;
|
|
43
|
+
private static final int MAX_ENDING = 16;
|
|
44
|
+
|
|
45
|
+
private AlertDialog messageDialog;
|
|
46
|
+
|
|
47
|
+
@Override
|
|
48
|
+
public void call(ExtensionHost host, String function, JSONObject options, Call call) {
|
|
49
|
+
switch (function) {
|
|
50
|
+
case "open" -> open(host, options.optBoolean("multiple"), options.optJSONArray("extensions"), call);
|
|
51
|
+
case "message" -> {
|
|
52
|
+
JSONArray buttons = options.optJSONArray("buttons");
|
|
53
|
+
String[] labels = new String[buttons == null ? 0 : buttons.length()];
|
|
54
|
+
for (int i = 0; i < labels.length; i += 1) labels[i] = buttons.optString(i);
|
|
55
|
+
showMessageDialog(host.activity(), options.optString("message"), options.optString("detail"), labels, call);
|
|
56
|
+
}
|
|
57
|
+
default -> call.reject("crossbind: the dialog extension's Java has no function " + function);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
@Override
|
|
62
|
+
public void onCreate(ExtensionHost host) {
|
|
63
|
+
if (ARE_PICKS_CLEARED.getAndSet(true)) return;
|
|
64
|
+
File picks = picksOf(host.activity());
|
|
65
|
+
COPIES.execute(() -> deleteTree(picks));
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// A message dialog that goes with its activity answers as one closed.
|
|
69
|
+
@Override
|
|
70
|
+
public void onDestroy(ExtensionHost host) {
|
|
71
|
+
if (messageDialog != null) messageDialog.dismiss();
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// The system's picker, for the types of the extensions where Android knows each, else for any file, as it filters
|
|
75
|
+
// by type alone. Its picks are copied into one folder of their own, as a file's sidecars are found beside it.
|
|
76
|
+
private void open(ExtensionHost host, boolean multiple, JSONArray extensions, Call call) {
|
|
77
|
+
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT).addCategory(Intent.CATEGORY_OPENABLE).setType("*/*");
|
|
78
|
+
String[] types = typesOf(extensions);
|
|
79
|
+
if (types.length > 0) intent.putExtra(Intent.EXTRA_MIME_TYPES, types);
|
|
80
|
+
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, multiple);
|
|
81
|
+
Activity activity = host.activity();
|
|
82
|
+
try {
|
|
83
|
+
host.startForResult(intent, (result, data) -> {
|
|
84
|
+
List<Uri> picked = picked(result, data);
|
|
85
|
+
if (picked.isEmpty()) call.resolve(null);
|
|
86
|
+
else COPIES.execute(() -> copy(activity, picked, call));
|
|
87
|
+
});
|
|
88
|
+
} catch (ActivityNotFoundException none) {
|
|
89
|
+
call.reject("crossbind: nothing on this device picks a file");
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
private static String[] typesOf(JSONArray extensions) {
|
|
94
|
+
Set<String> types = new LinkedHashSet<>();
|
|
95
|
+
for (int i = 0; extensions != null && i < extensions.length(); i += 1) {
|
|
96
|
+
String extension = extensions.optString(i);
|
|
97
|
+
String type = extension.equals("*") ? null : MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension.toLowerCase(Locale.ROOT));
|
|
98
|
+
if (type == null) return new String[0];
|
|
99
|
+
types.add(type);
|
|
100
|
+
}
|
|
101
|
+
return types.toArray(new String[0]);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// What the picker chose, several files as clip data; none when its user cancelled.
|
|
105
|
+
private static List<Uri> picked(int result, Intent data) {
|
|
106
|
+
List<Uri> picked = new ArrayList<>();
|
|
107
|
+
if (result != Activity.RESULT_OK || data == null) return picked;
|
|
108
|
+
ClipData clip = data.getClipData();
|
|
109
|
+
if (clip == null && data.getData() != null) picked.add(data.getData());
|
|
110
|
+
for (int i = 0; clip != null && i < clip.getItemCount(); i += 1) picked.add(clip.getItemAt(i).getUri());
|
|
111
|
+
return picked;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
private static void copy(Activity activity, List<Uri> picked, Call call) {
|
|
115
|
+
File folder = new File(picksOf(activity), Long.toString(System.nanoTime()));
|
|
116
|
+
JSONArray paths = new JSONArray();
|
|
117
|
+
try {
|
|
118
|
+
if (!folder.mkdirs()) throw new IOException("cannot make " + folder);
|
|
119
|
+
for (Uri uri : picked) {
|
|
120
|
+
File copy = freeFile(folder, nameOf(activity, uri));
|
|
121
|
+
try (InputStream in = activity.getContentResolver().openInputStream(uri)) {
|
|
122
|
+
if (in == null) throw new IOException("its provider gives no stream");
|
|
123
|
+
Files.copy(in, copy.toPath());
|
|
124
|
+
}
|
|
125
|
+
paths.put(copy.getPath());
|
|
126
|
+
}
|
|
127
|
+
} catch (IOException | RuntimeException error) {
|
|
128
|
+
// A copy cut short is no file its user picked.
|
|
129
|
+
deleteTree(folder);
|
|
130
|
+
call.reject("crossbind: the app cannot copy a file its user picked: " + error);
|
|
131
|
+
return;
|
|
132
|
+
}
|
|
133
|
+
call.resolve(paths);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
private static File picksOf(Activity activity) {
|
|
137
|
+
return new File(activity.getCacheDir(), "picked");
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
// A name the folder has no file of yet, as two picks may share one.
|
|
141
|
+
private static File freeFile(File folder, String name) {
|
|
142
|
+
File file = new File(folder, name);
|
|
143
|
+
int dot = name.lastIndexOf('.');
|
|
144
|
+
String stem = dot > 0 ? name.substring(0, dot) : name;
|
|
145
|
+
String ending = dot > 0 ? name.substring(dot) : "";
|
|
146
|
+
for (int i = 2; file.exists(); i += 1) file = new File(folder, stem + " " + i + ending);
|
|
147
|
+
return file;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// The name of a file, as its provider shows it, made one a folder takes: without a slash, neither . nor .., and cut
|
|
151
|
+
// to fit before its extension.
|
|
152
|
+
private static String nameOf(Activity activity, Uri uri) {
|
|
153
|
+
String name = null;
|
|
154
|
+
try (Cursor cursor = activity.getContentResolver().query(uri, new String[] {OpenableColumns.DISPLAY_NAME}, null, null, null)) {
|
|
155
|
+
if (cursor != null && cursor.moveToFirst()) name = cursor.getString(0);
|
|
156
|
+
} catch (RuntimeException error) {
|
|
157
|
+
Log.w("crossbind", "crossbind: the provider of " + uri + " gives no name", error);
|
|
158
|
+
}
|
|
159
|
+
if (name == null) name = uri.getLastPathSegment();
|
|
160
|
+
name = name == null ? "" : name.replace('/', '_').replace('\0', '_');
|
|
161
|
+
if (name.isEmpty() || name.equals(".") || name.equals("..")) return "file";
|
|
162
|
+
int dot = name.lastIndexOf('.');
|
|
163
|
+
String ending = dot > 0 && name.length() - dot <= MAX_ENDING ? name.substring(dot) : "";
|
|
164
|
+
String stem = name.substring(0, name.length() - ending.length());
|
|
165
|
+
while (!stem.isEmpty() && (stem + ending).getBytes(StandardCharsets.UTF_8).length > MAX_NAME_BYTES) {
|
|
166
|
+
stem = stem.substring(0, stem.offsetByCodePoints(stem.length(), -1));
|
|
167
|
+
}
|
|
168
|
+
return stem + ending;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
private static void deleteTree(File file) {
|
|
172
|
+
File[] children = file.listFiles();
|
|
173
|
+
if (children != null) for (File child : children) deleteTree(child);
|
|
174
|
+
file.delete();
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
// Android has a positive, a neutral and a negative button: the first label is the positive one, and the last of
|
|
178
|
+
// several the negative, which Android places where its apps put Cancel. Back and a tap outside close the dialog. The
|
|
179
|
+
// message goes in the dialog's text with the detail, as a title stops after two lines.
|
|
180
|
+
private void showMessageDialog(Activity activity, String message, String detail, String[] labels, Call call) {
|
|
181
|
+
if (activity.isFinishing() || activity.isDestroyed()) {
|
|
182
|
+
call.resolve(-1);
|
|
183
|
+
return;
|
|
184
|
+
}
|
|
185
|
+
String[] names = labels.length == 0 ? new String[] {activity.getString(android.R.string.ok)} : labels;
|
|
186
|
+
int[] clicked = {-1};
|
|
187
|
+
AlertDialog.Builder builder = new AlertDialog.Builder(activity).setMessage(detail.isEmpty() ? message : message + "\n\n" + detail)
|
|
188
|
+
.setPositiveButton(names[0], (dialog, which) -> clicked[0] = 0)
|
|
189
|
+
.setOnDismissListener((dialog) -> {
|
|
190
|
+
messageDialog = null;
|
|
191
|
+
call.resolve(clicked[0]);
|
|
192
|
+
});
|
|
193
|
+
if (names.length == 3) builder.setNeutralButton(names[1], (dialog, which) -> clicked[0] = 1);
|
|
194
|
+
if (names.length > 1) builder.setNegativeButton(names[names.length - 1], (dialog, which) -> clicked[0] = names.length - 1);
|
|
195
|
+
try {
|
|
196
|
+
messageDialog = builder.show();
|
|
197
|
+
} catch (WindowManager.BadTokenException gone) {
|
|
198
|
+
call.resolve(-1);
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
#include "dialog.h"
|
|
2
|
+
|
|
3
|
+
#include <cstdio>
|
|
4
|
+
#include <stdexcept>
|
|
5
|
+
|
|
6
|
+
namespace crossbind::dialog {
|
|
7
|
+
|
|
8
|
+
// The extension's Java shows the system's picker in the activity in front, then copies what its user picked into the
|
|
9
|
+
// app's cache, where native code opens it by a path. A pick it could not copy goes as a cancel, said in the log.
|
|
10
|
+
void showOpenDialog(uint64_t, OpenOptions options, std::function<void(Picked)> done) {
|
|
11
|
+
if (options.directory) throw std::runtime_error("crossbind: an Android app's open dialog picks files, not folders");
|
|
12
|
+
std::vector<std::string> extensions;
|
|
13
|
+
for (const auto &filter : options.filters) extensions.insert(extensions.end(), filter.extensions.begin(), filter.extensions.end());
|
|
14
|
+
android::callJava("dialog", "open", {{"multiple", options.multiple}, {"extensions", extensions}},
|
|
15
|
+
[done = std::move(done)](std::optional<std::string> failure, Value result) {
|
|
16
|
+
if (failure) std::fprintf(stderr, "%s\n", failure->c_str());
|
|
17
|
+
if (failure || result.isNull()) {
|
|
18
|
+
done(std::nullopt);
|
|
19
|
+
return;
|
|
20
|
+
}
|
|
21
|
+
std::vector<std::string> paths;
|
|
22
|
+
for (const Value &path : result.asArray()) paths.push_back(path.asString());
|
|
23
|
+
done(paths);
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
// A file the page makes reaches its user's folders as a download, which shows the system's save picker.
|
|
28
|
+
void showSaveDialog(uint64_t, SaveOptions, std::function<void(std::optional<std::string>)>) {
|
|
29
|
+
throw std::runtime_error("crossbind: an Android app saves a file as the page's download, which shows the system's save picker, not with dialog.save");
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// The extension's Java shows it in the activity in front; a dialog nothing could show, as when the activity is gone,
|
|
33
|
+
// went without a button.
|
|
34
|
+
void showMessageDialog(uint64_t, MessageOptions options, std::function<void(int)> done) {
|
|
35
|
+
android::callJava("dialog", "message", {{"message", options.message}, {"detail", options.detail}, {"buttons", options.buttons}},
|
|
36
|
+
[done = std::move(done)](std::optional<std::string> failure, Value result) {
|
|
37
|
+
if (failure) std::fprintf(stderr, "%s\n", failure->c_str());
|
|
38
|
+
done(failure ? NO_BUTTON : static_cast<int>(result.asNumber()));
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
} // namespace crossbind::dialog
|
package/native/darwin.mm
ADDED
|
@@ -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 ®istry) {
|
|
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
|
+
}
|
package/native/dialog.h
ADDED
|
@@ -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,146 @@
|
|
|
1
|
+
#import <UIKit/UIKit.h>
|
|
2
|
+
#import <UniformTypeIdentifiers/UniformTypeIdentifiers.h>
|
|
3
|
+
#import <objc/runtime.h>
|
|
4
|
+
|
|
5
|
+
#include "dialog.h"
|
|
6
|
+
|
|
7
|
+
#include <memory>
|
|
8
|
+
#include <stdexcept>
|
|
9
|
+
|
|
10
|
+
// A document picker's answer, given once. The picker holds it, so a picker that goes without its user's pick or cancel,
|
|
11
|
+
// as when its scene goes, answers as cancelled as it goes.
|
|
12
|
+
@interface CBPickAnswer : NSObject <UIDocumentPickerDelegate>
|
|
13
|
+
- (instancetype)initWithDone:(std::function<void(crossbind::dialog::Picked)>)done isFolder:(BOOL)isFolder;
|
|
14
|
+
- (void)give:(crossbind::dialog::Picked)picked;
|
|
15
|
+
@end
|
|
16
|
+
|
|
17
|
+
@implementation CBPickAnswer {
|
|
18
|
+
std::function<void(crossbind::dialog::Picked)> done;
|
|
19
|
+
BOOL isFolder;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
- (instancetype)initWithDone:(std::function<void(crossbind::dialog::Picked)>)answer isFolder:(BOOL)folder {
|
|
23
|
+
if ((self = [super init])) {
|
|
24
|
+
done = std::move(answer);
|
|
25
|
+
isFolder = folder;
|
|
26
|
+
}
|
|
27
|
+
return self;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
- (void)give:(crossbind::dialog::Picked)picked {
|
|
31
|
+
if (!done) return;
|
|
32
|
+
const auto answer = std::move(done);
|
|
33
|
+
done = nullptr;
|
|
34
|
+
answer(std::move(picked));
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
- (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentsAtURLs:(NSArray<NSURL *> *)urls {
|
|
38
|
+
std::vector<std::string> paths;
|
|
39
|
+
for (NSURL *url in urls) {
|
|
40
|
+
// A folder stays where its user keeps it, which the app reaches while it runs.
|
|
41
|
+
if (isFolder) [url startAccessingSecurityScopedResource];
|
|
42
|
+
paths.push_back(url.path.UTF8String);
|
|
43
|
+
}
|
|
44
|
+
[self give:paths];
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
- (void)documentPickerWasCancelled:(UIDocumentPickerViewController *)controller {
|
|
48
|
+
[self give:std::nullopt];
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
- (void)dealloc {
|
|
52
|
+
[self give:std::nullopt];
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
@end
|
|
56
|
+
|
|
57
|
+
namespace crossbind::dialog {
|
|
58
|
+
namespace {
|
|
59
|
+
|
|
60
|
+
char ANSWER_KEY;
|
|
61
|
+
|
|
62
|
+
NSString *ns(const std::string &text) { return [NSString stringWithUTF8String:text.c_str()] ?: @""; }
|
|
63
|
+
|
|
64
|
+
void onMain(void (^block)(void)) { dispatch_async(dispatch_get_main_queue(), block); }
|
|
65
|
+
|
|
66
|
+
// The picker offers every filter's files at once; none at all, or "*", lets it offer any file.
|
|
67
|
+
NSArray<UTType *> *typesOf(const std::vector<FileFilter> &filters) {
|
|
68
|
+
NSMutableArray<UTType *> *types = [NSMutableArray new];
|
|
69
|
+
for (const auto &filter : filters) {
|
|
70
|
+
for (const auto &extension : filter.extensions) {
|
|
71
|
+
if (extension == "*") return @[ UTTypeItem ];
|
|
72
|
+
if (UTType *type = [UTType typeWithFilenameExtension:ns(extension)]) [types addObject:type];
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
return types.count > 0 ? types : @[ UTTypeItem ];
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// A message dialog's answer, given once. UIKit can let an alert go without a click, as when its scene goes, and then
|
|
79
|
+
// the last of its actions to go answers it as closed.
|
|
80
|
+
struct MessageAnswer {
|
|
81
|
+
std::function<void(int)> done;
|
|
82
|
+
bool isGiven = false;
|
|
83
|
+
|
|
84
|
+
void give(int button) {
|
|
85
|
+
if (isGiven) return;
|
|
86
|
+
isGiven = true;
|
|
87
|
+
done(button);
|
|
88
|
+
}
|
|
89
|
+
~MessageAnswer() { give(NO_BUTTON); }
|
|
90
|
+
};
|
|
91
|
+
|
|
92
|
+
// Over whatever the window of this id, or the app's oldest, shows on top; false when it has nothing to show it over.
|
|
93
|
+
bool presentOnTop(UIViewController *controller, uint64_t window) {
|
|
94
|
+
const std::optional<Window> open = windowOf(window);
|
|
95
|
+
UIViewController *top = ((__bridge UIWindow *)(open ? open->native() : appWindow())).rootViewController;
|
|
96
|
+
while (top.presentedViewController) top = top.presentedViewController;
|
|
97
|
+
if (!top || top.isBeingDismissed) return false;
|
|
98
|
+
[top presentViewController:controller animated:YES completion:nil];
|
|
99
|
+
return true;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
} // namespace
|
|
103
|
+
|
|
104
|
+
// The system's document picker, which has no title. The files it gives are copies in the app's temporary folder, which
|
|
105
|
+
// the system empties in time; a folder is its user's own, reached where it is.
|
|
106
|
+
void showOpenDialog(uint64_t window, OpenOptions options, std::function<void(Picked)> done) {
|
|
107
|
+
onMain(^{
|
|
108
|
+
NSArray<UTType *> *types = options.directory ? @[ UTTypeFolder ] : typesOf(options.filters);
|
|
109
|
+
UIDocumentPickerViewController *picker = [[UIDocumentPickerViewController alloc] initForOpeningContentTypes:types
|
|
110
|
+
asCopy:!options.directory];
|
|
111
|
+
picker.allowsMultipleSelection = options.multiple;
|
|
112
|
+
if (!options.defaultPath.empty()) picker.directoryURL = [NSURL fileURLWithPath:ns(options.defaultPath)];
|
|
113
|
+
CBPickAnswer *answer = [[CBPickAnswer alloc] initWithDone:done isFolder:options.directory];
|
|
114
|
+
picker.delegate = answer;
|
|
115
|
+
objc_setAssociatedObject(picker, &ANSWER_KEY, answer, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
|
|
116
|
+
if (!presentOnTop(picker, window)) [answer give:std::nullopt];
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// A file the page makes reaches its user's folders as a download, which shows the system's export sheet.
|
|
121
|
+
void showSaveDialog(uint64_t, SaveOptions, std::function<void(std::optional<std::string>)>) {
|
|
122
|
+
throw std::runtime_error("crossbind: an iOS app saves a file as the page's download, which shows the system's export sheet, not with dialog.save");
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
// The last of several buttons is the one a keyboard's Escape clicks, which iOS places where its apps put Cancel.
|
|
126
|
+
void showMessageDialog(uint64_t window, MessageOptions options, std::function<void(int)> done) {
|
|
127
|
+
onMain(^{
|
|
128
|
+
auto answer = std::make_shared<MessageAnswer>();
|
|
129
|
+
answer->done = done;
|
|
130
|
+
UIAlertController *alert = [UIAlertController alertControllerWithTitle:ns(options.message)
|
|
131
|
+
message:options.detail.empty() ? nil : ns(options.detail)
|
|
132
|
+
preferredStyle:UIAlertControllerStyleAlert];
|
|
133
|
+
const std::vector<std::string> labels = options.buttons.empty() ? std::vector<std::string>{"OK"} : options.buttons;
|
|
134
|
+
for (size_t i = 0; i < labels.size(); i += 1) {
|
|
135
|
+
const bool isCancel = labels.size() > 1 && i == labels.size() - 1;
|
|
136
|
+
UIAlertAction *action = [UIAlertAction actionWithTitle:ns(labels[i])
|
|
137
|
+
style:isCancel ? UIAlertActionStyleCancel : UIAlertActionStyleDefault
|
|
138
|
+
handler:^(UIAlertAction *) { answer->give(static_cast<int>(i)); }];
|
|
139
|
+
[alert addAction:action];
|
|
140
|
+
if (i == 0) alert.preferredAction = action;
|
|
141
|
+
}
|
|
142
|
+
if (!presentOnTop(alert, window)) answer->give(NO_BUTTON);
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
} // namespace crossbind::dialog
|
package/native/linux.cpp
ADDED
|
@@ -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": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "2.0.0-beta.72",
|
|
4
|
+
"description": "crossbind app extension: open and message dialogs everywhere, save dialogs on the desktop.",
|
|
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.72"
|
|
30
|
+
},
|
|
31
|
+
"devDependencies": {
|
|
32
|
+
"crossbind": "^2.0.0-beta.72"
|
|
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,46 @@
|
|
|
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
|
+
/** Not on a phone, whose picker has none. */
|
|
9
|
+
title?: string;
|
|
10
|
+
/** The folder the dialog shows first. */
|
|
11
|
+
defaultPath?: string;
|
|
12
|
+
filters?: FileFilter[];
|
|
13
|
+
/** Folders instead of files. */
|
|
14
|
+
directory?: boolean;
|
|
15
|
+
multiple?: boolean;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export interface SaveOptions {
|
|
19
|
+
title?: string;
|
|
20
|
+
/** The folder the dialog shows first. */
|
|
21
|
+
defaultPath?: string;
|
|
22
|
+
defaultName?: string;
|
|
23
|
+
filters?: FileFilter[];
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export interface MessageOptions {
|
|
27
|
+
message: string;
|
|
28
|
+
/** Smaller text under the message. */
|
|
29
|
+
detail?: string;
|
|
30
|
+
/** info by default. Windows shows its icon for each, and macOS a caution sign for error; Linux, iOS and Android show none. */
|
|
31
|
+
kind?: 'info' | 'warning' | 'error';
|
|
32
|
+
/** One to three labels, the first the default; without them OK. */
|
|
33
|
+
buttons?: string[];
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export declare const dialog: {
|
|
37
|
+
/**
|
|
38
|
+
* The paths of the files or folders the user picked, or null when they cancelled. A phone gives copies of the files,
|
|
39
|
+
* in a folder of their own in the app's temporary or cache folder; an iOS app a folder where its user keeps it.
|
|
40
|
+
*/
|
|
41
|
+
open(options?: OpenOptions): Promise<string[] | null>;
|
|
42
|
+
/** The path the user chose to save to, or null when they cancelled. On the desktop: a phone saves the page's downloads. */
|
|
43
|
+
save(options?: SaveOptions): Promise<string | null>;
|
|
44
|
+
/** The index of the button the user clicked: Return gives the first, and Escape or closing the dialog the last. */
|
|
45
|
+
message(options: MessageOptions): Promise<number>;
|
|
46
|
+
};
|
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
|
+
|