@crossbind/extension-dialog 2.0.0-beta.69 → 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/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @crossbind/extension-dialog
2
2
 
3
- Open and save dialogs on the desktop, message dialogs everywhere.
3
+ Open and message dialogs everywhere, save dialogs on the desktop.
4
4
 
5
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
6
 
@@ -18,7 +18,13 @@ index of the button clicked. A file a dialog picked is one the page's `shell` fu
18
18
 
19
19
  ## Platforms
20
20
 
21
- `dialog.open` and `dialog.save` on macOS, Linux and Windows; `dialog.message` there and on iOS and Android.
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.
22
28
 
23
29
  ## Replace or leave out
24
30
 
@@ -6,7 +6,7 @@ export default function dialog() {
6
6
  app: {
7
7
  sources: ['native/dialog.cpp'],
8
8
  macos: { sources: ['native/darwin.mm'], frameworks: ['UniformTypeIdentifiers'] },
9
- ios: { sources: ['native/ios.mm'] },
9
+ ios: { sources: ['native/ios.mm'], frameworks: ['UniformTypeIdentifiers'] },
10
10
  linux: { sources: ['native/linux.cpp'] },
11
11
  windows: { sources: ['native/windows.cpp'], libraries: ['comctl32'] },
12
12
  android: { sources: ['native/android.cpp'], java: 'native/android', class: 'dev.crossbind.extension.dialog.DialogExtension' },
@@ -2,29 +2,67 @@ package dev.crossbind.extension.dialog;
2
2
 
3
3
  import android.app.Activity;
4
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;
5
12
  import android.view.WindowManager;
13
+ import android.webkit.MimeTypeMap;
6
14
 
7
15
  import dev.crossbind.app.Extension;
8
16
  import dev.crossbind.app.ExtensionHost;
9
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
+
10
32
  import org.json.JSONArray;
11
33
  import org.json.JSONObject;
12
34
 
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.
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.
15
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
+
16
45
  private AlertDialog messageDialog;
17
46
 
18
47
  @Override
19
48
  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;
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);
23
58
  }
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);
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));
28
66
  }
29
67
 
30
68
  // A message dialog that goes with its activity answers as one closed.
@@ -33,6 +71,109 @@ public final class DialogExtension implements Extension {
33
71
  if (messageDialog != null) messageDialog.dismiss();
34
72
  }
35
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
+
36
177
  // Android has a positive, a neutral and a negative button: the first label is the positive one, and the last of
37
178
  // several the negative, which Android places where its apps put Cancel. Back and a tap outside close the dialog. The
38
179
  // message goes in the dialog's text with the detail, as a title stops after two lines.
@@ -5,10 +5,28 @@
5
5
 
6
6
  namespace crossbind::dialog {
7
7
 
8
- void showOpenDialog(uint64_t, OpenOptions, std::function<void(Picked)>) { throw std::runtime_error("crossbind: an Android app has no file dialogs yet"); }
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
+ }
9
26
 
27
+ // A file the page makes reaches its user's folders as a download, which shows the system's save picker.
10
28
  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");
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");
12
30
  }
13
31
 
14
32
  // The extension's Java shows it in the activity in front; a dialog nothing could show, as when the activity is gone,
package/native/ios.mm CHANGED
@@ -1,17 +1,80 @@
1
1
  #import <UIKit/UIKit.h>
2
+ #import <UniformTypeIdentifiers/UniformTypeIdentifiers.h>
3
+ #import <objc/runtime.h>
2
4
 
3
5
  #include "dialog.h"
4
6
 
5
7
  #include <memory>
6
8
  #include <stdexcept>
7
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
+
8
57
  namespace crossbind::dialog {
9
58
  namespace {
10
59
 
60
+ char ANSWER_KEY;
61
+
11
62
  NSString *ns(const std::string &text) { return [NSString stringWithUTF8String:text.c_str()] ?: @""; }
12
63
 
13
64
  void onMain(void (^block)(void)) { dispatch_async(dispatch_get_main_queue(), block); }
14
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
+
15
78
  // A message dialog's answer, given once. UIKit can let an alert go without a click, as when its scene goes, and then
16
79
  // the last of its actions to go answers it as closed.
17
80
  struct MessageAnswer {
@@ -38,10 +101,25 @@ bool presentOnTop(UIViewController *controller, uint64_t window) {
38
101
 
39
102
  } // namespace
40
103
 
41
- void showOpenDialog(uint64_t, OpenOptions, std::function<void(Picked)>) { throw std::runtime_error("crossbind: an iOS app has no file dialogs yet"); }
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
+ }
42
119
 
120
+ // A file the page makes reaches its user's folders as a download, which shows the system's export sheet.
43
121
  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");
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");
45
123
  }
46
124
 
47
125
  // The last of several buttons is the one a keyboard's Escape clicks, which iOS places where its apps put Cancel.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@crossbind/extension-dialog",
3
- "version": "2.0.0-beta.69",
4
- "description": "crossbind app extension: open and save dialogs on the desktop, message dialogs everywhere.",
3
+ "version": "2.0.0-beta.72",
4
+ "description": "crossbind app extension: open and message dialogs everywhere, save dialogs on the desktop.",
5
5
  "homepage": "https://github.com/crossbind/crossbind/tree/main/extensions/dialog#readme",
6
6
  "repository": {
7
7
  "type": "git",
@@ -26,10 +26,10 @@
26
26
  "extension": "./crossbind.extension.js"
27
27
  },
28
28
  "peerDependencies": {
29
- "crossbind": "^2.0.0-beta.69"
29
+ "crossbind": "^2.0.0-beta.72"
30
30
  },
31
31
  "devDependencies": {
32
- "crossbind": "^2.0.0-beta.69"
32
+ "crossbind": "^2.0.0-beta.72"
33
33
  },
34
34
  "keywords": [
35
35
  "crossbind-extension",
package/page.d.ts CHANGED
@@ -5,6 +5,7 @@ export interface FileFilter {
5
5
  }
6
6
 
7
7
  export interface OpenOptions {
8
+ /** Not on a phone, whose picker has none. */
8
9
  title?: string;
9
10
  /** The folder the dialog shows first. */
10
11
  defaultPath?: string;
@@ -33,9 +34,12 @@ export interface MessageOptions {
33
34
  }
34
35
 
35
36
  export declare const dialog: {
36
- /** The paths of the files or folders the user picked, or null when they cancelled. */
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
+ */
37
41
  open(options?: OpenOptions): Promise<string[] | null>;
38
- /** The path the user chose to save to, or null when they cancelled. */
42
+ /** The path the user chose to save to, or null when they cancelled. On the desktop: a phone saves the page's downloads. */
39
43
  save(options?: SaveOptions): Promise<string | null>;
40
44
  /** The index of the button the user clicked: Return gives the first, and Escape or closing the dialog the last. */
41
45
  message(options: MessageOptions): Promise<number>;