| 1 | |
| 2 | #define _POSIX_C_SOURCE 200809L |
| 3 | #include <gtk/gtk.h> |
| 4 | #include <webkit2/webkit2.h> |
| 5 | #include <json-glib/json-glib.h> |
| 6 | #include <glib/gstdio.h> |
| 7 | #include <unistd.h> |
| 8 | #include <string.h> |
| 9 | #include <stdlib.h> |
| 10 | #include <sys/stat.h> |
| 11 | #include <math.h> |
| 12 | #include "native-input.h" |
| 13 | |
| 14 | #ifndef CAGE_VERSION |
| 15 | #define CAGE_VERSION "development" |
| 16 | #endif |
| 17 | #ifndef CAGE_CLIENT_ONLY |
| 18 | #define CAGE_CLIENT_ONLY 0 |
| 19 | #endif |
| 20 | #define MAX_THEME (256 * 1024) |
| 21 | #define MAX_MESSAGE (2 * 1024 * 1024) |
| 22 | |
| 23 | typedef struct { |
| 24 | GtkApplication *application; |
| 25 | GtkWidget *window, *stack, *status, *retry, *existing, *complete; |
| 26 | WebKitWebView *web; |
| 27 | WebKitUserContentManager *content; |
| 28 | char *backend, *profile, *token, *smoke_output, *web_data, *web_cache; |
| 29 | const char *storage_phase, *storage_marker; |
| 30 | int port, result; |
| 31 | gboolean bootstrapping, needs_update, ready, picker_open, smoke_started, navigation_failed; |
| 32 | gboolean initial_dark; |
| 33 | } Cage; |
| 34 | static Cage app; |
| 35 | typedef struct { GPtrArray *paths; gint64 expires; } FileSelection; |
| 36 | static GHashTable *file_selections; |
| 37 | static guint64 clipboard_revision = 1; |
| 38 | static guint64 clipboard_generation = 0; |
| 39 | static gboolean clipboard_watching = FALSE; |
| 40 | typedef struct { GPtrArray *paths; gboolean pending, releasing; } ClipboardCopy; |
| 41 | static GHashTable *clipboard_copies; |
| 42 | static GPtrArray *clipboard_readers; |
| 43 | static gboolean clipboard_cache_loaded = FALSE, clipboard_cache_collecting = FALSE; |
| 44 | static void clipboard_cache_watch(void); |
| 45 | static void clipboard_cache_ignored(JsonObject *object, const GError *error, gpointer data); |
| 46 | static void clipboard_changed(GtkClipboard *clipboard, GdkEventOwnerChange *event, gpointer data) { |
| 47 | (void)clipboard; (void)event; (void)data; clipboard_revision++; |
| 48 | } |
| 49 | static guint64 clipboard_current_revision(void) { |
| 50 | clipboard_cache_watch(); |
| 51 | if (!clipboard_watching) { |
| 52 | g_signal_connect(gtk_clipboard_get(GDK_SELECTION_CLIPBOARD), "owner-change", G_CALLBACK(clipboard_changed), NULL); |
| 53 | clipboard_watching = TRUE; |
| 54 | } |
| 55 | return clipboard_revision; |
| 56 | } |
| 57 | static void bootstrap(const char *option); |
| 58 | static void show_error(const char *message); |
| 59 | |
| 60 | typedef void (*BackendCallback)(JsonObject *, const GError *, gpointer); |
| 61 | typedef struct { |
| 62 | GSubprocess *process; |
| 63 | GCancellable *cancel; |
| 64 | guint deadline; |
| 65 | gsize output_limit; |
| 66 | BackendCallback callback; |
| 67 | gpointer data; |
| 68 | } Command; |
| 69 | |
| 70 | static const char *text_member(JsonObject *object, const char *name) { |
| 71 | JsonNode *node = object ? json_object_get_member(object, name) : NULL; |
| 72 | return node && JSON_NODE_HOLDS_VALUE(node) && json_node_get_value_type(node) == G_TYPE_STRING |
| 73 | ? json_node_get_string(node) : ""; |
| 74 | } |
| 75 | static char *json_text(JsonNode *node) { |
| 76 | JsonGenerator *generator = json_generator_new(); |
| 77 | json_generator_set_root(generator, node); |
| 78 | char *text = json_generator_to_data(generator, NULL); |
| 79 | g_object_unref(generator); |
| 80 | return text; |
| 81 | } |
| 82 | static char *quote(const char *value) { |
| 83 | JsonNode *node = json_node_new(JSON_NODE_VALUE); |
| 84 | json_node_set_string(node, value); |
| 85 | char *result = json_text(node); |
| 86 | json_node_free(node); |
| 87 | return result; |
| 88 | } |
| 89 | static void diagnostic_sent(GObject *source, GAsyncResult *result, gpointer data) { |
| 90 | (void)data; |
| 91 | g_subprocess_communicate_utf8_finish(G_SUBPROCESS(source), result, NULL, NULL, NULL); |
| 92 | } |
| 93 | static void diagnostic_event(const char *message) { |
| 94 | if (!app.backend || !app.profile) return; |
| 95 | GSubprocessLauncher *launcher = g_subprocess_launcher_new(G_SUBPROCESS_FLAGS_STDIN_PIPE | G_SUBPROCESS_FLAGS_STDOUT_SILENCE | G_SUBPROCESS_FLAGS_STDERR_SILENCE); |
| 96 | g_subprocess_launcher_setenv(launcher, "CLAUDE_CAGE_CONFIG", app.profile, TRUE); |
| 97 | GSubprocess *process = g_subprocess_launcher_spawn(launcher, NULL, app.backend, "diagnostic-event", NULL); |
| 98 | g_object_unref(launcher); |
| 99 | if (!process) return; |
| 100 | char *limited = g_utf8_substring(message, 0, MIN(g_utf8_strlen(message, -1), 4096)); |
| 101 | char *quoted = quote(limited); |
| 102 | char *body = g_strdup_printf("{\"source\":\"native\",\"message\":%s}", quoted); |
| 103 | g_subprocess_communicate_utf8_async(process, body, NULL, diagnostic_sent, NULL); |
| 104 | g_object_unref(process); g_free(body); g_free(quoted); g_free(limited); |
| 105 | } |
| 106 | static void diagnostic_glib(const gchar *domain, GLogLevelFlags level, const gchar *message, gpointer data) { |
| 107 | (void)data; |
| 108 | if (level & (G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_WARNING)) diagnostic_event(message); |
| 109 | g_log_default_handler(domain, level, message, NULL); |
| 110 | } |
| 111 | static gboolean valid_workbench(const char *raw, int expected_port, gboolean entry) { |
| 112 | if (!raw) return FALSE; |
| 113 | GUri *uri = g_uri_parse(raw, G_URI_FLAGS_NONE, NULL); |
| 114 | if (!uri) return FALSE; |
| 115 | int port = g_uri_get_port(uri); |
| 116 | const char *fragment = g_uri_get_fragment(uri); |
| 117 | gboolean valid = g_strcmp0(g_uri_get_scheme(uri), "http") == 0 && |
| 118 | g_strcmp0(g_uri_get_host(uri), "localhost") == 0 && |
| 119 | !g_uri_get_userinfo(uri) && port >= 1024 && port <= 65535 && |
| 120 | (!expected_port || expected_port == port) && |
| 121 | (!entry || (fragment && strlen(fragment) >= 2)); |
| 122 | g_uri_unref(uri); |
| 123 | return valid; |
| 124 | } |
| 125 | static gboolean private_directory(const char *path) { |
| 126 | if (g_mkdir_with_parents(path, 0700) != 0) return FALSE; |
| 127 | GFile *file = g_file_new_for_path(path); |
| 128 | GFileInfo *info = g_file_query_info(file, G_FILE_ATTRIBUTE_STANDARD_TYPE "," G_FILE_ATTRIBUTE_UNIX_UID, |
| 129 | G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS, NULL, NULL); |
| 130 | gboolean valid = info && g_file_info_get_file_type(info) == G_FILE_TYPE_DIRECTORY && |
| 131 | g_file_info_get_attribute_uint32(info, G_FILE_ATTRIBUTE_UNIX_UID) == geteuid() && g_chmod(path, 0700) == 0; |
| 132 | g_clear_object(&info); g_object_unref(file); |
| 133 | return valid; |
| 134 | } |
| 135 | static gboolean prepare_web_storage(void) { |
| 136 | char *profile_directory = g_path_get_dirname(app.profile); |
| 137 | char *root = g_build_filename(profile_directory, "webkit", NULL); |
| 138 | app.web_data = g_build_filename(root, "data", NULL); |
| 139 | app.web_cache = g_build_filename(root, "cache", NULL); |
| 140 | gboolean valid = private_directory(profile_directory) && private_directory(root) && |
| 141 | private_directory(app.web_data) && private_directory(app.web_cache); |
| 142 | g_free(root); g_free(profile_directory); |
| 143 | return valid; |
| 144 | } |
| 145 | static gboolean command_timeout(gpointer data) { |
| 146 | Command *command = data; |
| 147 | command->deadline = 0; |
| 148 | g_cancellable_cancel(command->cancel); |
| 149 | g_subprocess_force_exit(command->process); |
| 150 | return G_SOURCE_REMOVE; |
| 151 | } |
| 152 | static void command_finished(GObject *source, GAsyncResult *result, gpointer data) { |
| 153 | Command *command = data; |
| 154 | GError *error = NULL; |
| 155 | char *output = NULL; |
| 156 | JsonParser *parser = json_parser_new(); |
| 157 | JsonObject *object = NULL; |
| 158 | if (command->deadline) g_source_remove(command->deadline); |
| 159 | if (g_subprocess_communicate_utf8_finish(G_SUBPROCESS(source), result, &output, NULL, &error)) { |
| 160 | if (!output || strlen(output) > command->output_limit || !json_parser_load_from_data(parser, output, -1, NULL) || |
| 161 | !JSON_NODE_HOLDS_OBJECT(json_parser_get_root(parser))) { |
| 162 | g_set_error_literal(&error, G_IO_ERROR, G_IO_ERROR_INVALID_DATA, "Cage 后台未返回有效状态,请查看私有配置中的 logs/。"); |
| 163 | } else { |
| 164 | object = json_node_get_object(json_parser_get_root(parser)); |
| 165 | if (!g_subprocess_get_successful(command->process)) { |
| 166 | const char *message = text_member(object, "message"); |
| 167 | g_set_error_literal(&error, G_IO_ERROR, G_IO_ERROR_FAILED, |
| 168 | *message ? message : "Cage 后台操作失败,请查看 logs/。"); |
| 169 | } |
| 170 | } |
| 171 | } |
| 172 | command->callback(object, error, command->data); |
| 173 | g_clear_error(&error); |
| 174 | g_free(output); |
| 175 | g_object_unref(parser); |
| 176 | g_object_unref(command->process); |
| 177 | g_object_unref(command->cancel); |
| 178 | g_free(command); |
| 179 | } |
| 180 | static void backend_arguments_limited(const char *const *args, guint seconds, gsize output_limit, BackendCallback callback, gpointer data) { |
| 181 | GError *error = NULL; |
| 182 | GSubprocessLauncher *launcher = g_subprocess_launcher_new(G_SUBPROCESS_FLAGS_STDOUT_PIPE | G_SUBPROCESS_FLAGS_STDERR_SILENCE); |
| 183 | g_subprocess_launcher_setenv(launcher, "CLAUDE_CAGE_CONFIG", app.profile, TRUE); |
| 184 | if (g_strcmp0(args[1], "desktop") == 0) { |
| 185 | char owner[32]; |
| 186 | g_snprintf(owner, sizeof(owner), "%ld", (long)getpid()); |
| 187 | g_subprocess_launcher_setenv(launcher, "CAGE_DESKTOP_OWNER_PID", owner, TRUE); |
| 188 | } |
| 189 | GSubprocess *process = g_subprocess_launcher_spawnv(launcher, args, &error); |
| 190 | g_object_unref(launcher); |
| 191 | if (!process) { |
| 192 | callback(NULL, error, data); |
| 193 | g_clear_error(&error); |
| 194 | return; |
| 195 | } |
| 196 | Command *command = g_new0(Command, 1); |
| 197 | command->process = process; |
| 198 | command->cancel = g_cancellable_new(); |
| 199 | command->callback = callback; |
| 200 | command->data = data; |
| 201 | command->output_limit = output_limit; |
| 202 | command->deadline = g_timeout_add_seconds(seconds, command_timeout, command); |
| 203 | g_subprocess_communicate_utf8_async(process, NULL, command->cancel, command_finished, command); |
| 204 | } |
| 205 | static void backend_arguments(const char *const *args, guint seconds, BackendCallback callback, gpointer data) { |
| 206 | backend_arguments_limited(args, seconds, 65536, callback, data); |
| 207 | } |
| 208 | static void backend(const char *action, const char *option, BackendCallback callback, gpointer data) { |
| 209 | const char *args[] = {app.backend, action, "--json", option, NULL}; |
| 210 | backend_arguments(args, 180, callback, data); |
| 211 | } |
| 212 | static void script(const char *code) { |
| 213 | if (app.web && app.port && valid_workbench(webkit_web_view_get_uri(app.web), app.port, FALSE)) |
| 214 | webkit_web_view_evaluate_javascript(app.web, code, -1, NULL, NULL, NULL, NULL, NULL); |
| 215 | } |
| 216 | static void action(const char *name) { |
| 217 | char *quoted = quote(name); |
| 218 | char *code = g_strdup_printf("window.cageNativeAction?.(%s)", quoted); |
| 219 | script(code); |
| 220 | g_free(code); |
| 221 | g_free(quoted); |
| 222 | } |
| 223 | static void publish_visibility(void) { |
| 224 | GdkWindow *window = gtk_widget_get_window(app.window); |
| 225 | gboolean visible = gtk_widget_get_visible(app.window) && window && |
| 226 | !(gdk_window_get_state(window) & GDK_WINDOW_STATE_ICONIFIED); |
| 227 | script(visible ? |
| 228 | "window.cageWindowVisible=true;window.dispatchEvent(new Event('cage-window-visibility'));" : |
| 229 | "window.cageWindowVisible=false;window.dispatchEvent(new Event('cage-window-visibility'));" ); |
| 230 | } |
| 231 | static gboolean visibility_changed(GtkWidget *widget, GdkEvent *event, gpointer data) { |
| 232 | (void)widget; (void)event; (void)data; |
| 233 | publish_visibility(); |
| 234 | return FALSE; |
| 235 | } |
| 236 | static gboolean close_window(GtkWidget *widget, GdkEvent *event, gpointer data) { |
| 237 | (void)event; (void)data; |
| 238 | gtk_widget_hide(widget); |
| 239 | publish_visibility(); |
| 240 | return TRUE; |
| 241 | } |
| 242 | static gboolean quit_idle(gpointer data) { |
| 243 | (void)data; |
| 244 | g_application_quit(G_APPLICATION(app.application)); |
| 245 | return G_SOURCE_REMOVE; |
| 246 | } |
| 247 | static void show_error(const char *message) { |
| 248 | diagnostic_event(message); |
| 249 | gtk_label_set_text(GTK_LABEL(app.status), message); |
| 250 | gtk_stack_set_visible_child_name(GTK_STACK(app.stack), "status"); |
| 251 | gtk_widget_show(app.retry); |
| 252 | } |
| 253 | static void reply_json(WebKitScriptMessageReply *reply, JSCContext *context, const char *json) { |
| 254 | JSCValue *value = jsc_value_new_from_json(context, json); |
| 255 | webkit_script_message_reply_return_value(reply, value); |
| 256 | g_object_unref(value); |
| 257 | } |
| 258 | static void reply_string(WebKitScriptMessageReply *reply, JSCContext *context, const char *text) { |
| 259 | JSCValue *value = jsc_value_new_string(context, text); |
| 260 | webkit_script_message_reply_return_value(reply, value); |
| 261 | g_object_unref(value); |
| 262 | } |
| 263 | static void reply_error(WebKitScriptMessageReply *reply, const char *message) { |
| 264 | webkit_script_message_reply_return_error_message(reply, message); |
| 265 | } |
| 266 | static char *choose_file(GtkFileChooserAction kind, const char *title, const char *filename) { |
| 267 | if (app.picker_open) return NULL; |
| 268 | app.picker_open = TRUE; |
| 269 | GtkWidget *dialog = gtk_file_chooser_dialog_new(title, GTK_WINDOW(app.window), kind, |
| 270 | "取消", GTK_RESPONSE_CANCEL, kind == GTK_FILE_CHOOSER_ACTION_SAVE ? "保存" : "选择", GTK_RESPONSE_ACCEPT, NULL); |
| 271 | gtk_file_chooser_set_local_only(GTK_FILE_CHOOSER(dialog), TRUE); |
| 272 | if (kind == GTK_FILE_CHOOSER_ACTION_SAVE) { |
| 273 | char *base = g_path_get_basename(filename && *filename ? filename : "Cage.cage-theme.json"); |
| 274 | gtk_file_chooser_set_current_name(GTK_FILE_CHOOSER(dialog), base); |
| 275 | gtk_file_chooser_set_do_overwrite_confirmation(GTK_FILE_CHOOSER(dialog), TRUE); |
| 276 | g_free(base); |
| 277 | } |
| 278 | if (kind != GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER) { |
| 279 | GtkFileFilter *filter = gtk_file_filter_new(); |
| 280 | gboolean diagnostic = filename && g_str_has_suffix(filename, ".zip"); |
| 281 | gtk_file_filter_set_name(filter, diagnostic ? "诊断包 (*.zip)" : "Cage 主题 (*.json)"); |
| 282 | gtk_file_filter_add_pattern(filter, diagnostic ? "*.zip" : "*.json"); |
| 283 | gtk_file_chooser_add_filter(GTK_FILE_CHOOSER(dialog), filter); |
| 284 | } |
| 285 | char *path = gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_ACCEPT |
| 286 | ? gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(dialog)) : NULL; |
| 287 | gtk_widget_destroy(dialog); |
| 288 | app.picker_open = FALSE; |
| 289 | return path; |
| 290 | } |
| 291 | typedef struct { WebKitScriptMessageReply *reply; JSCContext *context; gboolean sync; guint64 revision, generation; char *connection; GPtrArray *clipboard_paths; } PendingReply; |
| 292 | static PendingReply *pending_reply(WebKitScriptMessageReply *reply, JSCContext *context) { |
| 293 | PendingReply *pending = g_new0(PendingReply, 1); |
| 294 | pending->reply = webkit_script_message_reply_ref(reply); |
| 295 | pending->context = g_object_ref(context); |
| 296 | return pending; |
| 297 | } |
| 298 | static void pending_free(PendingReply *pending) { |
| 299 | if (pending->clipboard_paths) { |
| 300 | g_ptr_array_remove(clipboard_readers, pending->clipboard_paths); |
| 301 | g_ptr_array_unref(pending->clipboard_paths); |
| 302 | } |
| 303 | webkit_script_message_reply_unref(pending->reply); |
| 304 | g_object_unref(pending->context); |
| 305 | g_free(pending->connection); |
| 306 | g_free(pending); |
| 307 | } |
| 308 | static void browser_file_finished(JsonObject *object, const GError *error, gpointer data) { |
| 309 | PendingReply *pending = data; |
| 310 | if (error) reply_error(pending->reply, error->message); |
| 311 | else { |
| 312 | if (pending->sync) { |
| 313 | json_object_set_int_member(object, "revision", pending->revision); |
| 314 | const char *id = text_member(object, "files"); |
| 315 | if (*id && (pending->generation != clipboard_generation || pending->revision != clipboard_current_revision())) { |
| 316 | const char *args[] = {app.backend, "clipboard-files", "--json", "--connection", pending->connection, "release", id, NULL}; |
| 317 | backend_arguments(args, 10, clipboard_cache_ignored, NULL); |
| 318 | } |
| 319 | } |
| 320 | JsonNode *node = json_node_new(JSON_NODE_OBJECT); |
| 321 | json_node_set_object(node, object); |
| 322 | char *json = json_to_string(node, FALSE); |
| 323 | reply_json(pending->reply, pending->context, json); |
| 324 | g_free(json); json_node_free(node); |
| 325 | } |
| 326 | pending_free(pending); |
| 327 | } |
| 328 | static void clipboard_received(GtkClipboard *clipboard, const gchar *text, gpointer data) { |
| 329 | (void)clipboard; |
| 330 | PendingReply *pending = data; |
| 331 | if (text && strlen(text) > MAX_MESSAGE) reply_error(pending->reply, "剪贴板内容超过 2 MB。"); |
| 332 | else reply_string(pending->reply, pending->context, text ? text : ""); |
| 333 | pending_free(pending); |
| 334 | } |
| 335 | static void clipboard_content_text(GtkClipboard *clipboard, const gchar *text, gpointer data) { |
| 336 | (void)clipboard; |
| 337 | PendingReply *pending = data; |
| 338 | if (text && strlen(text) > MAX_MESSAGE) reply_error(pending->reply, "剪贴板内容超过 2 MB。"); |
| 339 | else { |
| 340 | char *quoted = quote(text ? text : ""); |
| 341 | char *json = pending->sync ? g_strdup_printf("{\"text\":%s,\"revision\":%lu}", quoted, (unsigned long)pending->revision) : g_strdup_printf("{\"text\":%s}", quoted); |
| 342 | reply_json(pending->reply, pending->context, json); |
| 343 | g_free(json); g_free(quoted); |
| 344 | } |
| 345 | pending_free(pending); |
| 346 | } |
| 347 | static void clipboard_content_image(GtkClipboard *clipboard, GdkPixbuf *image, gpointer data) { |
| 348 | PendingReply *pending = data; |
| 349 | if (!image) { |
| 350 | gtk_clipboard_request_text(clipboard, clipboard_content_text, pending); |
| 351 | return; |
| 352 | } |
| 353 | gchar *buffer = NULL; |
| 354 | gsize length = 0; |
| 355 | if ((gint64)gdk_pixbuf_get_width(image) * gdk_pixbuf_get_height(image) > 40000000 || |
| 356 | !gdk_pixbuf_save_to_buffer(image, &buffer, &length, "png", NULL, NULL) || length > 20 * 1024 * 1024) { |
| 357 | reply_error(pending->reply, "图片不能超过 20 MB 或 4000 万像素。"); |
| 358 | } else { |
| 359 | char *encoded = g_base64_encode((const guchar *)buffer, length); |
| 360 | char *json = pending->sync ? g_strdup_printf("{\"png\":\"%s\",\"revision\":%lu}", encoded, (unsigned long)pending->revision) : g_strdup_printf("{\"png\":\"%s\"}", encoded); |
| 361 | reply_json(pending->reply, pending->context, json); |
| 362 | g_free(json); g_free(encoded); |
| 363 | } |
| 364 | g_free(buffer); |
| 365 | pending_free(pending); |
| 366 | } |
| 367 | static void file_selection_free(gpointer data) { |
| 368 | FileSelection *selection = data; |
| 369 | g_ptr_array_unref(selection->paths); |
| 370 | g_free(selection); |
| 371 | } |
| 372 | static char *remember_files(GPtrArray *paths, GError **error) { |
| 373 | if (!paths->len || paths->len > 100) { |
| 374 | g_set_error_literal(error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT, "请选择 1 至 100 个文件。"); |
| 375 | return NULL; |
| 376 | } |
| 377 | for (guint i = 0; i < paths->len; i++) { |
| 378 | const char *path = g_ptr_array_index(paths, i); |
| 379 | GStatBuf info; |
| 380 | if (!g_path_is_absolute(path) || g_lstat(path, &info) != 0 || !S_ISREG(info.st_mode)) { |
| 381 | g_set_error_literal(error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT, "请选择本机普通文件,暂不支持文件夹或链接。"); |
| 382 | return NULL; |
| 383 | } |
| 384 | if (info.st_size > 2LL * 1024 * 1024 * 1024) { |
| 385 | g_set_error_literal(error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT, "每个文件不能超过 2 GB。"); |
| 386 | return NULL; |
| 387 | } |
| 388 | } |
| 389 | if (!file_selections) file_selections = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, file_selection_free); |
| 390 | gint64 now = g_get_monotonic_time(); |
| 391 | GHashTableIter iter; gpointer key, value; |
| 392 | g_hash_table_iter_init(&iter, file_selections); |
| 393 | while (g_hash_table_iter_next(&iter, &key, &value)) |
| 394 | if (((FileSelection *)value)->expires <= now) g_hash_table_iter_remove(&iter); |
| 395 | if (g_hash_table_size(file_selections) >= 16) { |
| 396 | gpointer oldest_key = NULL; gint64 oldest_time = G_MAXINT64; |
| 397 | g_hash_table_iter_init(&iter, file_selections); |
| 398 | while (g_hash_table_iter_next(&iter, &key, &value)) { |
| 399 | if (((FileSelection *)value)->expires < oldest_time) { oldest_key = key; oldest_time = ((FileSelection *)value)->expires; } |
| 400 | } |
| 401 | g_hash_table_remove(file_selections, oldest_key); |
| 402 | } |
| 403 | FileSelection *selection = g_new0(FileSelection, 1); |
| 404 | selection->paths = g_ptr_array_ref(paths); selection->expires = now + 600 * G_USEC_PER_SEC; |
| 405 | char *id = g_uuid_string_random(); |
| 406 | g_hash_table_insert(file_selections, id, selection); |
| 407 | return g_strdup_printf("{\"fileSelection\":\"%s\",\"count\":%u}", id, paths->len); |
| 408 | } |
| 409 | static void reply_selected_uris(char **uris, PendingReply *pending) { |
| 410 | GPtrArray *paths = g_ptr_array_new_with_free_func(g_free); |
| 411 | GError *error = NULL; |
| 412 | for (guint i = 0; uris[i]; i++) { |
| 413 | char *hostname = NULL; |
| 414 | char *path = g_filename_from_uri(uris[i], &hostname, NULL); |
| 415 | if (!path || (hostname && *hostname && strcmp(hostname, "localhost"))) { |
| 416 | g_free(path); g_free(hostname); |
| 417 | g_set_error_literal(&error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT, "请选择本机文件。"); |
| 418 | break; |
| 419 | } |
| 420 | g_free(hostname); g_ptr_array_add(paths, path); |
| 421 | } |
| 422 | if (!error && pending->sync) { |
| 423 | if (!clipboard_readers) clipboard_readers = g_ptr_array_new(); |
| 424 | pending->clipboard_paths = g_ptr_array_ref(paths); |
| 425 | g_ptr_array_add(clipboard_readers, pending->clipboard_paths); |
| 426 | const char **args = g_new0(const char *, paths->len + 7); |
| 427 | args[0] = app.backend; args[1] = "clipboard-files"; args[2] = "--json"; args[3] = "--connection"; args[4] = pending->connection; args[5] = "send"; |
| 428 | for (guint i = 0; i < paths->len; i++) args[i + 6] = g_ptr_array_index(paths, i); |
| 429 | backend_arguments(args, 1800, browser_file_finished, pending); |
| 430 | g_free(args); g_ptr_array_unref(paths); return; |
| 431 | } |
| 432 | char *json = error ? NULL : remember_files(paths, &error); |
| 433 | if (error) reply_error(pending->reply, error->message); |
| 434 | else reply_json(pending->reply, pending->context, json); |
| 435 | g_free(json); g_clear_error(&error); g_ptr_array_unref(paths); pending_free(pending); |
| 436 | } |
| 437 | static void clipboard_gnome_files(GtkClipboard *clipboard, GtkSelectionData *selection, gpointer data) { |
| 438 | gint length = gtk_selection_data_get_length(selection); |
| 439 | if (length <= 0) { gtk_clipboard_request_image(clipboard, clipboard_content_image, data); return; } |
| 440 | if (length > MAX_MESSAGE) { |
| 441 | PendingReply *pending = data; reply_error(pending->reply, "剪贴板文件列表过大。"); pending_free(pending); return; |
| 442 | } |
| 443 | char *text = g_strndup((const char *)gtk_selection_data_get_data(selection), length); |
| 444 | char *start = strchr(text, '\n'); |
| 445 | char **uris = start ? g_uri_list_extract_uris(start + 1) : NULL; |
| 446 | if (uris && uris[0]) reply_selected_uris(uris, data); |
| 447 | else { PendingReply *pending = data; reply_error(pending->reply, "剪贴板文件列表无效,请重新复制文件。"); pending_free(pending); } |
| 448 | g_strfreev(uris); g_free(text); |
| 449 | } |
| 450 | static void clipboard_file_uris(GtkClipboard *clipboard, gchar **uris, gpointer data) { |
| 451 | if (uris && uris[0]) reply_selected_uris(uris, data); |
| 452 | else gtk_clipboard_request_contents(clipboard, gdk_atom_intern_static_string("x-special/gnome-copied-files"), clipboard_gnome_files, data); |
| 453 | } |
| 454 | static void clipboard_sync_reply(PendingReply *pending, gboolean superseded) { |
| 455 | gdk_display_sync(gdk_display_get_default()); |
| 456 | while (g_main_context_iteration(NULL, FALSE)) { } |
| 457 | char *json = g_strdup_printf("{\"revision\":%lu,\"superseded\":%s}", (unsigned long)clipboard_current_revision(), superseded ? "true" : "false"); |
| 458 | reply_json(pending->reply, pending->context, json); g_free(json); pending_free(pending); |
| 459 | } |
| 460 | static void clipboard_cache_command(const char *action, const char *id, BackendCallback callback, gpointer data) { |
| 461 | char *quoted = quote(id ? id : ""); |
| 462 | char *request = g_strdup_printf("{\"action\":\"%s\",\"cache_id\":%s}", action, quoted); |
| 463 | const char *args[] = {app.backend, "clipboard-files", "--json", "cache", request, NULL}; |
| 464 | backend_arguments_limited(args, 10, 30 << 20, callback, data); |
| 465 | g_free(request); g_free(quoted); |
| 466 | } |
| 467 | static void clipboard_cache_ignored(JsonObject *object, const GError *error, gpointer data) { (void)object; (void)error; (void)data; } |
| 468 | static void clipboard_copy_free(gpointer data) { ClipboardCopy *copy = data; g_ptr_array_unref(copy->paths); g_free(copy); } |
| 469 | static void clipboard_cache_remember(JsonObject *object, gboolean pending) { |
| 470 | const char *id = text_member(object, "cache_id"); |
| 471 | JsonArray *paths = json_object_has_member(object, "paths") ? json_object_get_array_member(object, "paths") : NULL; |
| 472 | if (!*id || !paths || !json_array_get_length(paths) || g_hash_table_contains(clipboard_copies, id)) return; |
| 473 | ClipboardCopy *copy = g_new0(ClipboardCopy, 1); |
| 474 | copy->pending = pending; |
| 475 | copy->paths = g_ptr_array_new_with_free_func(g_free); |
| 476 | for (guint i = 0; i < json_array_get_length(paths); i++) g_ptr_array_add(copy->paths, g_strdup(json_array_get_string_element(paths, i))); |
| 477 | g_hash_table_insert(clipboard_copies, g_strdup(id), copy); |
| 478 | } |
| 479 | typedef struct { char *id; PendingReply *discarded; } ClipboardDisposal; |
| 480 | static void clipboard_cache_released(JsonObject *object, const GError *error, gpointer data) { |
| 481 | (void)object; |
| 482 | ClipboardDisposal *disposal = data; |
| 483 | ClipboardCopy *copy = g_hash_table_lookup(clipboard_copies, disposal->id); |
| 484 | if (copy) { copy->releasing = FALSE; if (!error) g_hash_table_remove(clipboard_copies, disposal->id); } |
| 485 | if (disposal->discarded) clipboard_sync_reply(disposal->discarded, TRUE); |
| 486 | g_free(disposal->id); g_free(disposal); |
| 487 | } |
| 488 | static void clipboard_cache_release(const char *id, PendingReply *discarded) { |
| 489 | if (!id || !*id) { if (discarded) clipboard_sync_reply(discarded, TRUE); return; } |
| 490 | ClipboardCopy *copy = g_hash_table_lookup(clipboard_copies, id); |
| 491 | if (copy) { copy->releasing = TRUE; copy->pending = FALSE; } |
| 492 | ClipboardDisposal *disposal = g_new0(ClipboardDisposal, 1); |
| 493 | disposal->id = g_strdup(id); disposal->discarded = discarded; |
| 494 | clipboard_cache_command("release", id, clipboard_cache_released, disposal); |
| 495 | } |
| 496 | static gboolean clipboard_cache_referenced(GPtrArray *selected, GPtrArray *owned) { |
| 497 | if (!selected) return FALSE; |
| 498 | char *root = g_path_get_dirname(g_ptr_array_index(owned, 0)); |
| 499 | char *prefix = g_strconcat(root, G_DIR_SEPARATOR_S, NULL); |
| 500 | gboolean found = FALSE; |
| 501 | for (guint i = 0; i < selected->len && !found; i++) { |
| 502 | const char *path = g_ptr_array_index(selected, i); |
| 503 | char *parent = g_strconcat(path, G_DIR_SEPARATOR_S, NULL); |
| 504 | found = !strcmp(path, root) || g_str_has_prefix(path, prefix) || g_str_has_prefix(root, parent); |
| 505 | g_free(parent); |
| 506 | } |
| 507 | g_free(root); g_free(prefix); return found; |
| 508 | } |
| 509 | static void clipboard_cache_collect_uris(char **uris, guint64 revision) { |
| 510 | clipboard_cache_collecting = FALSE; |
| 511 | if (revision != clipboard_revision) return; |
| 512 | GPtrArray *selected = g_ptr_array_new_with_free_func(g_free); |
| 513 | for (guint i = 0; uris && uris[i]; i++) { |
| 514 | char *path = g_filename_from_uri(uris[i], NULL, NULL); |
| 515 | if (!path) { g_ptr_array_unref(selected); return; } |
| 516 | g_ptr_array_add(selected, path); |
| 517 | } |
| 518 | GHashTableIter iterator; gpointer key, value; |
| 519 | g_hash_table_iter_init(&iterator, clipboard_copies); |
| 520 | while (g_hash_table_iter_next(&iterator, &key, &value)) { |
| 521 | ClipboardCopy *copy = value; |
| 522 | gboolean referenced = copy->pending || copy->releasing || clipboard_cache_referenced(selected, copy->paths); |
| 523 | for (guint i = 0; clipboard_readers && i < clipboard_readers->len && !referenced; i++) |
| 524 | referenced = clipboard_cache_referenced(g_ptr_array_index(clipboard_readers, i), copy->paths); |
| 525 | if (!referenced) clipboard_cache_release(key, NULL); |
| 526 | } |
| 527 | g_ptr_array_unref(selected); |
| 528 | } |
| 529 | static void clipboard_cache_gnome(GtkClipboard *clipboard, GtkSelectionData *selection, gpointer data) { |
| 530 | (void)clipboard; |
| 531 | guint64 revision = *(guint64 *)data; |
| 532 | gint length = gtk_selection_data_get_length(selection); |
| 533 | if (length > MAX_MESSAGE) { clipboard_cache_collecting = FALSE; g_free(data); return; } |
| 534 | char *text = length > 0 ? g_strndup((const char *)gtk_selection_data_get_data(selection), length) : NULL; |
| 535 | char *start = text ? strchr(text, '\n') : NULL; |
| 536 | char **uris = start ? g_uri_list_extract_uris(start + 1) : NULL; |
| 537 | clipboard_cache_collect_uris(uris, revision); |
| 538 | g_strfreev(uris); g_free(text); g_free(data); |
| 539 | } |
| 540 | static void clipboard_cache_uris(GtkClipboard *clipboard, gchar **uris, gpointer data) { |
| 541 | if (!uris) { gtk_clipboard_request_contents(clipboard, gdk_atom_intern_static_string("x-special/gnome-copied-files"), clipboard_cache_gnome, data); return; } |
| 542 | clipboard_cache_collect_uris(uris, *(guint64 *)data); g_free(data); |
| 543 | } |
| 544 | static gboolean clipboard_cache_tick(gpointer data) { |
| 545 | (void)data; |
| 546 | if (!clipboard_cache_loaded || clipboard_cache_collecting || !g_hash_table_size(clipboard_copies)) return G_SOURCE_CONTINUE; |
| 547 | clipboard_cache_collecting = TRUE; |
| 548 | guint64 *revision = g_new(guint64, 1); *revision = clipboard_revision; |
| 549 | gtk_clipboard_request_uris(gtk_clipboard_get(GDK_SELECTION_CLIPBOARD), clipboard_cache_uris, revision); |
| 550 | return G_SOURCE_CONTINUE; |
| 551 | } |
| 552 | static void clipboard_cache_loaded_reply(JsonObject *object, const GError *error, gpointer data) { |
| 553 | (void)data; |
| 554 | clipboard_cache_loaded = TRUE; |
| 555 | if (error || !object || !json_object_has_member(object, "selections")) return; |
| 556 | JsonArray *items = json_object_get_array_member(object, "selections"); |
| 557 | for (guint i = 0; items && i < json_array_get_length(items); i++) clipboard_cache_remember(json_array_get_object_element(items, i), FALSE); |
| 558 | clipboard_cache_tick(NULL); |
| 559 | } |
| 560 | static void clipboard_cache_watch(void) { |
| 561 | if (clipboard_copies) return; |
| 562 | clipboard_copies = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, clipboard_copy_free); |
| 563 | g_timeout_add_seconds(1, clipboard_cache_tick, NULL); |
| 564 | clipboard_cache_command("list", "", clipboard_cache_loaded_reply, NULL); |
| 565 | } |
| 566 | static void clipboard_sync_provide(GtkClipboard *clipboard, GtkSelectionData *selection, guint info, gpointer data) { |
| 567 | (void)clipboard; char **payload = data; |
| 568 | gtk_selection_data_set(selection, gdk_atom_intern_static_string(info ? "x-special/gnome-copied-files" : "text/uri-list"),8,(const guchar *)payload[info],strlen(payload[info])); |
| 569 | } |
| 570 | static void clipboard_sync_clear(GtkClipboard *clipboard, gpointer data) { (void)clipboard; g_strfreev(data); } |
| 571 | static void clipboard_files_received(JsonObject *object, const GError *error, gpointer data) { |
| 572 | PendingReply *pending = data; |
| 573 | if (error) { clipboard_cache_command("list", "", clipboard_cache_loaded_reply, NULL); reply_error(pending->reply, error->message); pending_free(pending); return; } |
| 574 | clipboard_cache_watch(); clipboard_cache_remember(object, TRUE); |
| 575 | const char *cache = text_member(object, "cache_id"); |
| 576 | if (pending->generation != clipboard_generation || pending->revision != clipboard_current_revision()) { clipboard_cache_release(cache, pending); return; } |
| 577 | JsonArray *paths = json_object_get_array_member(object, "paths"); |
| 578 | if (!paths || !json_array_get_length(paths)) { clipboard_cache_release(cache, NULL); reply_error(pending->reply,"剪贴板文件读取失败。"); pending_free(pending); return; } |
| 579 | GString *text = g_string_new("copy\n"), *uris = g_string_new(""); |
| 580 | for (guint i = 0; i < json_array_get_length(paths); i++) { |
| 581 | char *uri = g_filename_to_uri(json_array_get_string_element(paths, i), NULL, NULL); |
| 582 | if (!uri) { clipboard_cache_release(cache, NULL); g_string_free(text,TRUE); g_string_free(uris,TRUE); reply_error(pending->reply,"剪贴板文件位置无效。"); pending_free(pending); return; } |
| 583 | g_string_append_printf(text,"%s\n",uri); g_string_append_printf(uris,"%s\r\n",uri); g_free(uri); |
| 584 | } |
| 585 | |
| 586 | |
| 587 | GtkTargetEntry targets[] = {{"text/uri-list",0,0},{"x-special/gnome-copied-files",0,1}}; |
| 588 | char **payload = g_new0(char *,3); payload[0] = g_string_free(uris,FALSE); payload[1] = g_string_free(text,FALSE); |
| 589 | if (!gtk_clipboard_set_with_data(gtk_clipboard_get(GDK_SELECTION_CLIPBOARD), targets,2, clipboard_sync_provide,clipboard_sync_clear,payload)) { |
| 590 | clipboard_cache_release(cache, NULL); g_strfreev(payload); reply_error(pending->reply,"剪贴板文件写入失败。"); pending_free(pending); |
| 591 | } else { |
| 592 | clipboard_revision++; |
| 593 | ClipboardCopy *copy = g_hash_table_lookup(clipboard_copies, cache); if (copy) copy->pending = FALSE; |
| 594 | if (*cache) clipboard_cache_command("publish", cache, clipboard_cache_ignored, NULL); |
| 595 | clipboard_sync_reply(pending,FALSE); |
| 596 | } |
| 597 | } |
| 598 | static void session_refreshed(JsonObject *object, const GError *error, gpointer data) { |
| 599 | PendingReply *pending = data; |
| 600 | const char *url = text_member(object, "url"); |
| 601 | if (error || !valid_workbench(url, 0, TRUE)) |
| 602 | reply_error(pending->reply, error ? error->message : "工作台会话恢复失败,请重新连接。"); |
| 603 | else { |
| 604 | char *quoted = quote(url); |
| 605 | char *json = g_strdup_printf("{\"url\":%s}", quoted); |
| 606 | reply_json(pending->reply, pending->context, json); |
| 607 | g_free(json); g_free(quoted); |
| 608 | } |
| 609 | pending_free(pending); |
| 610 | } |
| 611 | static void smoke_report(char *evidence) { |
| 612 | GError *error = NULL; |
| 613 | if (g_file_set_contents(app.smoke_output, evidence, -1, &error)) app.result = 0; |
| 614 | else { |
| 615 | g_printerr("Linux smoke: cannot save report: %s\n", error->message); |
| 616 | g_clear_error(&error); |
| 617 | } |
| 618 | g_free(evidence); |
| 619 | g_application_quit(G_APPLICATION(app.application)); |
| 620 | } |
| 621 | static void smoke_stopped(JsonObject *object, const GError *error, gpointer data) { |
| 622 | if (error || g_strcmp0(text_member(object, "status"), "prepared") != 0) { |
| 623 | g_printerr("Linux smoke: controller cleanup failed.\n"); |
| 624 | g_free(data); |
| 625 | g_application_quit(G_APPLICATION(app.application)); |
| 626 | } else smoke_report(data); |
| 627 | } |
| 628 | static void smoke_snapshot(GObject *source, GAsyncResult *result, gpointer data) { |
| 629 | char *report = data; |
| 630 | GError *error = NULL; |
| 631 | cairo_surface_t *surface = webkit_web_view_get_snapshot_finish(WEBKIT_WEB_VIEW(source), result, &error); |
| 632 | char *path = g_strconcat(app.smoke_output, ".png", NULL); |
| 633 | gboolean saved = surface && cairo_surface_write_to_png(surface, path) == CAIRO_STATUS_SUCCESS; |
| 634 | if (surface) cairo_surface_destroy(surface); |
| 635 | g_free(path); g_clear_error(&error); |
| 636 | if (saved && g_strcmp0(app.storage_phase, "seed") == 0) smoke_report(report); |
| 637 | else if (saved) backend("prepare-update", NULL, smoke_stopped, report); |
| 638 | else { |
| 639 | g_printerr("Linux smoke: could not capture rendered workbench.\n"); |
| 640 | g_free(report); |
| 641 | g_application_quit(G_APPLICATION(app.application)); |
| 642 | } |
| 643 | } |
| 644 | static void smoke_evaluated(GObject *source, GAsyncResult *result, gpointer data) { |
| 645 | (void)data; |
| 646 | GError *error = NULL; |
| 647 | JSCValue *value = webkit_web_view_call_async_javascript_function_finish(WEBKIT_WEB_VIEW(source), result, &error); |
| 648 | if (!value || error || !jsc_value_is_object(value)) { |
| 649 | g_printerr("Linux smoke: authenticated workbench verification failed (error domain=%s, code=%d, object=%d).\n", |
| 650 | error ? g_quark_to_string(error->domain) : "none", error ? error->code : 0, |
| 651 | value ? jsc_value_is_object(value) : FALSE); |
| 652 | g_clear_error(&error); g_clear_object(&value); |
| 653 | g_application_quit(G_APPLICATION(app.application)); |
| 654 | return; |
| 655 | } |
| 656 | char *json = jsc_value_to_json(value, 0); |
| 657 | JsonParser *parser = json_parser_new(); |
| 658 | gboolean ok = json && json_parser_load_from_data(parser, json, -1, NULL) && |
| 659 | JSON_NODE_HOLDS_OBJECT(json_parser_get_root(parser)); |
| 660 | JsonObject *object = ok ? json_node_get_object(json_parser_get_root(parser)) : NULL; |
| 661 | ok = object && json_object_has_member(object, "success") && json_object_get_boolean_member(object, "success"); |
| 662 | if (ok) { |
| 663 | json_object_set_string_member(object, "version", CAGE_VERSION); |
| 664 | json_object_set_int_member(object, "webkitMajor", webkit_get_major_version()); |
| 665 | json_object_set_int_member(object, "webkitMinor", webkit_get_minor_version()); |
| 666 | json_object_set_int_member(object, "webkitMicro", webkit_get_micro_version()); |
| 667 | char *report = json_text(json_parser_get_root(parser)); |
| 668 | webkit_web_view_get_snapshot(app.web, WEBKIT_SNAPSHOT_REGION_VISIBLE, WEBKIT_SNAPSHOT_OPTIONS_NONE, |
| 669 | NULL, smoke_snapshot, report); |
| 670 | } else { |
| 671 | g_printerr("Linux smoke: workbench evidence was incomplete: %s\n", json ? json : "null"); |
| 672 | g_application_quit(G_APPLICATION(app.application)); |
| 673 | } |
| 674 | g_free(json); g_object_unref(parser); g_object_unref(value); |
| 675 | } |
| 676 | static gboolean start_smoke(gpointer data) { |
| 677 | (void)data; |
| 678 | char *phase = quote(app.storage_phase ? app.storage_phase : ""); |
| 679 | char *marker = quote(app.storage_marker ? app.storage_marker : ""); |
| 680 | char *body = g_strdup_printf( |
| 681 | "let stage='storage';try{" |
| 682 | "const phase=%s,marker=%s;const storageKey='cage-linux-smoke-persistence';" |
| 683 | "if(phase==='seed')localStorage.setItem(storageKey,marker);" |
| 684 | "const storageMarkerMatched=!phase||localStorage.getItem(storageKey)===marker;" |
| 685 | "if(phase==='verify'&&storageMarkerMatched)localStorage.removeItem(storageKey);" |
| 686 | "stage='bridge';const bridge=window.cageNativeBridge;" |
| 687 | "let unauthenticatedBridgeDenied=false;try{await window.webkit.messageHandlers.cageTransport.postMessage({token:'invalid',request:{action:'clipboardRead'}});}catch{unauthenticatedBridgeDenied=true;}" |
| 688 | "stage='account-device';const native=await bridge.postMessage({action:'accountDevice',operation:'status'});" |
| 689 | "stage='app-update';const update=await bridge.postMessage({action:'appUpdate',operation:'status'});" |
| 690 | "stage='context';const context=await (await fetch('/api/client/context')).json();" |
| 691 | "if(context.desktop_gateway&&context.mode!=='local')throw new Error('local workbench not selected');" |
| 692 | "const scoped={headers:{'X-Cage-Connection':context.connection_id}};" |
| 693 | "stage='account';const accountResponse=await fetch('/api/account',scoped);const account=await accountResponse.json();" |
| 694 | "stage='status';const stateResponse=await fetch('/api/status',scoped);const state=await stateResponse.json();" |
| 695 | "stage='settings';const settingsResponse=await fetch('/api/settings',scoped);await settingsResponse.json();" |
| 696 | "const root=document.getElementById('root');" |
| 697 | "const rendered=!!root&&root.innerText.trim().length>40&&root.querySelectorAll('button').length>3;" |
| 698 | "const success=rendered&&accountResponse.ok&&account.unlocked===true&&stateResponse.ok&&settingsResponse.ok&&native.supported===false&&update.phase==='manual'&&unauthenticatedBridgeDenied&&storageMarkerMatched;" |
| 699 | "return {success,nativeBridgeReady:true,authenticated:accountResponse.ok,accountUnlocked:account.unlocked===true," |
| 700 | "workbenchRendered:rendered,workbenchReadyAcknowledged:true,statusReceived:stateResponse.ok,settingsReceived:settingsResponse.ok,unauthenticatedBridgeDenied," |
| 701 | "storageMarkerMatched,localStoragePersisted:phase==='verify'&&storageMarkerMatched};" |
| 702 | "}catch(error){return {success:false,stage,errorName:error.name};}", phase, marker); |
| 703 | webkit_web_view_call_async_javascript_function(app.web, body, -1, NULL, NULL, NULL, NULL, smoke_evaluated, NULL); |
| 704 | g_free(body); g_free(phase); g_free(marker); |
| 705 | return G_SOURCE_REMOVE; |
| 706 | } |
| 707 | static gboolean bridge_received(WebKitUserContentManager *manager, JSCValue *value, WebKitScriptMessageReply *reply, gpointer data) { |
| 708 | (void)manager; (void)data; |
| 709 | char *json = jsc_value_to_json(value, 0); |
| 710 | JsonParser *parser = json_parser_new(); |
| 711 | if (!json || strlen(json) > 30 * 1024 * 1024 || !json_parser_load_from_data(parser, json, -1, NULL) || |
| 712 | !JSON_NODE_HOLDS_OBJECT(json_parser_get_root(parser))) { |
| 713 | reply_error(reply, "原生请求格式无效。"); |
| 714 | goto done; |
| 715 | } |
| 716 | JsonObject *envelope = json_node_get_object(json_parser_get_root(parser)); |
| 717 | if (!app.token || g_strcmp0(text_member(envelope, "token"), app.token) != 0 || |
| 718 | !valid_workbench(webkit_web_view_get_uri(app.web), app.port, FALSE)) { |
| 719 | reply_error(reply, "请求来源无效。"); |
| 720 | goto done; |
| 721 | } |
| 722 | JsonNode *request_node = json_object_get_member(envelope, "request"); |
| 723 | if (!request_node || !JSON_NODE_HOLDS_OBJECT(request_node)) { |
| 724 | reply_error(reply, "原生请求格式无效。"); |
| 725 | goto done; |
| 726 | } |
| 727 | JsonObject *request = json_node_get_object(request_node); |
| 728 | const char *name = text_member(request, "action"); |
| 729 | JSCContext *context = jsc_value_get_context(value); |
| 730 | if (!strcmp(name, "remoteInput")) { |
| 731 | reply_json(reply, context, input_handle(request) ? "true" : "false"); |
| 732 | } else if (!strcmp(name, "exportDiagnostics")) { |
| 733 | if (app.picker_open) reply_error(reply, "请先完成当前文件窗口。"); |
| 734 | else { |
| 735 | char *path = choose_file(GTK_FILE_CHOOSER_ACTION_SAVE, "导出诊断包", "cage-diagnostics.zip"); |
| 736 | if (!path) reply_json(reply, context, "{\"canceled\":true}"); |
| 737 | else { |
| 738 | const char *connection = text_member(request, "connection_id"); |
| 739 | const char *args[] = {app.backend, "diagnostics", "--json", "--connection", *connection ? connection : "local", path, NULL}; |
| 740 | backend_arguments(args, 60, browser_file_finished, pending_reply(reply, context)); |
| 741 | g_free(path); |
| 742 | } |
| 743 | } |
| 744 | } else if (!strcmp(name, "workbenchReady")) { |
| 745 | if (app.needs_update) reply_error(reply, "后台版本尚未同步,更新未完成。"); |
| 746 | else { |
| 747 | app.ready = TRUE; |
| 748 | reply_json(reply, context, "true"); |
| 749 | if (app.smoke_output && !app.smoke_started) { |
| 750 | app.smoke_started = TRUE; |
| 751 | g_idle_add(start_smoke, NULL); |
| 752 | } |
| 753 | } |
| 754 | } else if (!strcmp(name, "accountDevice")) { |
| 755 | if (!strcmp(text_member(request, "operation"), "status")) reply_json(reply, context, "{\"supported\":false}"); |
| 756 | else reply_error(reply, "Linux 版本使用 Cage 账户密码解锁。"); |
| 757 | } else if (!strcmp(name, "appUpdate")) { |
| 758 | const char *operation = text_member(request, "operation"); |
| 759 | if (strcmp(operation, "status") && strcmp(operation, "check") && strcmp(operation, "install") && strcmp(operation, "cancel")) |
| 760 | reply_error(reply, "更新操作无效。"); |
| 761 | else { |
| 762 | char *version = quote(CAGE_VERSION); |
| 763 | const char *update_message = CAGE_CLIENT_ONLY |
| 764 | ? "轻量客户端使用独立安装包更新。退出客户端后更换程序;连接配置会保留,云端任务继续运行。" |
| 765 | : "Linux 版本使用系统安装包更新。请保存工作、停止环境并退出 Cage,再安装新版 .deb;用户数据会保留。"; |
| 766 | char *message = quote(update_message); |
| 767 | char *state = g_strdup_printf("{\"phase\":\"manual\",\"currentVersion\":%s,\"message\":%s}", version, message); |
| 768 | reply_json(reply, context, state); |
| 769 | g_free(state); g_free(version); g_free(message); |
| 770 | } |
| 771 | } else if (!strcmp(name, "desktopFileAction")) { |
| 772 | const char *id = text_member(request, "id"), *connection = text_member(request, "connection_id"); |
| 773 | if (!g_uuid_string_is_valid(id)) reply_error(reply, "文件打开标识无效。"); |
| 774 | else { |
| 775 | const char *args[] = {app.backend,"desktop-file","--json","--connection",*connection ? connection : "local",id,NULL}; |
| 776 | backend_arguments(args,1800,browser_file_finished,pending_reply(reply,context)); |
| 777 | } |
| 778 | } else if (!strcmp(name, "saveBrowserDownload") || !strcmp(name, "browserDownloadAction")) { |
| 779 | const char *id = text_member(request, "id"); |
| 780 | const char *operation = !strcmp(name, "saveBrowserDownload") ? "save" : text_member(request, "operation"); |
| 781 | if (!g_uuid_string_is_valid(id) || (strcmp(operation,"save") && strcmp(operation,"open") && strcmp(operation,"reveal"))) { |
| 782 | reply_error(reply, "下载操作无效。"); |
| 783 | } else if (app.picker_open) { |
| 784 | reply_error(reply, "请先完成当前文件窗口。"); |
| 785 | } else { |
| 786 | char *path = NULL; |
| 787 | if (!strcmp(operation,"save")) { |
| 788 | app.picker_open = TRUE; |
| 789 | GtkWidget *dialog = gtk_file_chooser_dialog_new("将下载另存为到本机", GTK_WINDOW(app.window), GTK_FILE_CHOOSER_ACTION_SAVE, |
| 790 | "取消", GTK_RESPONSE_CANCEL, "保存", GTK_RESPONSE_ACCEPT, NULL); |
| 791 | char *base = g_path_get_basename(text_member(request,"name")); |
| 792 | gtk_file_chooser_set_current_name(GTK_FILE_CHOOSER(dialog), *base ? base : "download"); |
| 793 | gtk_file_chooser_set_do_overwrite_confirmation(GTK_FILE_CHOOSER(dialog), TRUE); |
| 794 | if (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_ACCEPT) path = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(dialog)); |
| 795 | gtk_widget_destroy(dialog); g_free(base); app.picker_open = FALSE; |
| 796 | } |
| 797 | if (!strcmp(operation,"save") && !path) reply_json(reply,context,"{\"canceled\":true}"); |
| 798 | else { |
| 799 | const char *connection = text_member(request, "connection_id"); |
| 800 | const char *args[] = {app.backend,"browser-file","--json","--connection",*connection ? connection : "local",operation,id,path,NULL}; |
| 801 | backend_arguments(args,1800,browser_file_finished,pending_reply(reply,context)); |
| 802 | } |
| 803 | g_free(path); |
| 804 | } |
| 805 | } else if (!strcmp(name, "shareLocalProject")) { |
| 806 | const char *connection = text_member(request, "connection_id"), *mode = text_member(request, "mode"); |
| 807 | if (app.picker_open || !*connection || (strcmp(mode,"read") && strcmp(mode,"write"))) { |
| 808 | reply_error(reply, "请在云端工作台重新选择项目。"); |
| 809 | } else { |
| 810 | const char *prompt = !strcmp(mode,"write") ? "云端 Cage 可以读取、修改和删除所选项目中的文件。" : "云端 Cage 可以读取所选项目中的文件。"; |
| 811 | char *path = choose_file(GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER, prompt, NULL); |
| 812 | if (path) { |
| 813 | const char *args[] = {app.backend,"share-project","--json","--connection",connection,mode,path,NULL}; |
| 814 | backend_arguments(args,90,browser_file_finished,pending_reply(reply,context)); |
| 815 | } else reply_json(reply,context,"{\"canceled\":true}"); |
| 816 | g_free(path); |
| 817 | } |
| 818 | } else if (!strcmp(name, "chooseFolder")) { |
| 819 | if (app.picker_open) reply_error(reply, "请先完成当前文件选择。"); |
| 820 | else { |
| 821 | const char *prompt = !strcmp(text_member(request, "purpose"), "environmentStorage") |
| 822 | ? "请选择用于保存镜像和虚拟磁盘的空文件夹。" : "仅此文件夹会与 Cage 共享。请选择具体项目。"; |
| 823 | char *path = choose_file(GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER, prompt, NULL); |
| 824 | reply_string(reply, context, path ? path : ""); |
| 825 | g_free(path); |
| 826 | } |
| 827 | } else if (!strcmp(name, "clipboardRead")) { |
| 828 | gtk_clipboard_request_text(gtk_clipboard_get(GDK_SELECTION_CLIPBOARD), clipboard_received, pending_reply(reply, context)); |
| 829 | } else if (!strcmp(name, "clipboardRevision")) { |
| 830 | char revision[32]; g_snprintf(revision,sizeof(revision),"%lu",(unsigned long)clipboard_current_revision()); reply_json(reply,context,revision); |
| 831 | } else if (!strcmp(name, "clipboardSyncCancel")) { |
| 832 | clipboard_generation++; reply_json(reply,context,"true"); |
| 833 | } else if (!strcmp(name, "clipboardSyncRelease")) { |
| 834 | const char *id = text_member(request, "files"); |
| 835 | if (!g_uuid_string_is_valid(id)) reply_error(reply, "剪贴板文件标识无效。"); |
| 836 | else { |
| 837 | const char *args[] = {app.backend, "clipboard-files", "--json", "--connection", text_member(request, "connection_id"), "release", id, NULL}; |
| 838 | backend_arguments(args, 10, browser_file_finished, pending_reply(reply, context)); |
| 839 | } |
| 840 | } else if (!strcmp(name, "clipboardSyncRead")) { |
| 841 | PendingReply *pending = pending_reply(reply,context); pending->sync = TRUE; pending->generation = clipboard_generation; pending->revision = clipboard_current_revision(); pending->connection = g_strdup(text_member(request,"connection_id")); |
| 842 | gtk_clipboard_request_uris(gtk_clipboard_get(GDK_SELECTION_CLIPBOARD),clipboard_file_uris,pending); |
| 843 | } else if (!strcmp(name, "clipboardSyncWrite")) { |
| 844 | PendingReply *pending = pending_reply(reply,context); pending->generation = clipboard_generation; pending->revision = json_object_has_member(request,"revision") ? (guint64)json_object_get_int_member(request,"revision") : clipboard_current_revision(); |
| 845 | if (pending->revision != clipboard_current_revision()) clipboard_sync_reply(pending,TRUE); |
| 846 | else if (*text_member(request,"files")) { |
| 847 | const char *id = text_member(request,"files"); |
| 848 | if (!g_uuid_string_is_valid(id)) { reply_error(reply,"剪贴板文件标识无效。"); pending_free(pending); } |
| 849 | else { const char *args[] = {app.backend,"clipboard-files","--json","--connection",text_member(request,"connection_id"),"receive",id,NULL}; backend_arguments(args,1800,clipboard_files_received,pending); } |
| 850 | } else if (*text_member(request,"png")) { |
| 851 | gsize length = 0; guchar *bytes = g_base64_decode(text_member(request,"png"),&length); |
| 852 | GdkPixbufLoader *loader = gdk_pixbuf_loader_new_with_type("png",NULL); |
| 853 | gboolean valid = loader && length <= 20 * 1024 * 1024 && gdk_pixbuf_loader_write(loader,bytes,length,NULL) && gdk_pixbuf_loader_close(loader,NULL); |
| 854 | GdkPixbuf *image = valid ? gdk_pixbuf_loader_get_pixbuf(loader) : NULL; |
| 855 | if (!image || (gint64)gdk_pixbuf_get_width(image) * gdk_pixbuf_get_height(image) > 40000000) { reply_error(reply,"剪贴板图片格式或大小无效。"); pending_free(pending); } |
| 856 | else { gtk_clipboard_set_image(gtk_clipboard_get(GDK_SELECTION_CLIPBOARD),image); clipboard_revision++; clipboard_sync_reply(pending,FALSE); } |
| 857 | if (loader) g_object_unref(loader); |
| 858 | g_free(bytes); |
| 859 | } else if (json_object_has_member(request,"text") && strlen(text_member(request,"text")) <= MAX_MESSAGE) { |
| 860 | gtk_clipboard_set_text(gtk_clipboard_get(GDK_SELECTION_CLIPBOARD),text_member(request,"text"),-1); clipboard_revision++; clipboard_sync_reply(pending,FALSE); |
| 861 | } else { reply_error(reply,"剪贴板内容格式或大小无效。"); pending_free(pending); } |
| 862 | } else if (!strcmp(name, "clipboardReadContent")) { |
| 863 | gtk_clipboard_request_uris(gtk_clipboard_get(GDK_SELECTION_CLIPBOARD), clipboard_file_uris, pending_reply(reply, context)); |
| 864 | } else if (!strcmp(name, "chooseUploadFiles")) { |
| 865 | if (app.picker_open) reply_error(reply, "请先完成当前文件窗口。"); |
| 866 | else { |
| 867 | app.picker_open = TRUE; |
| 868 | GtkWidget *dialog = gtk_file_chooser_dialog_new("选择本机文件", GTK_WINDOW(app.window), GTK_FILE_CHOOSER_ACTION_OPEN, |
| 869 | "取消", GTK_RESPONSE_CANCEL, "选择", GTK_RESPONSE_ACCEPT, NULL); |
| 870 | JsonNode *multiple = json_object_get_member(request, "multiple"); |
| 871 | gtk_file_chooser_set_select_multiple(GTK_FILE_CHOOSER(dialog), multiple && JSON_NODE_HOLDS_VALUE(multiple) && json_node_get_value_type(multiple) == G_TYPE_BOOLEAN && json_node_get_boolean(multiple)); |
| 872 | gtk_file_chooser_set_local_only(GTK_FILE_CHOOSER(dialog), TRUE); |
| 873 | if (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_ACCEPT) { |
| 874 | GSList *list = gtk_file_chooser_get_filenames(GTK_FILE_CHOOSER(dialog)); |
| 875 | GPtrArray *paths = g_ptr_array_new_with_free_func(g_free); |
| 876 | for (GSList *item = list; item; item = item->next) g_ptr_array_add(paths, item->data); |
| 877 | g_slist_free(list); |
| 878 | GError *error = NULL; char *json = remember_files(paths, &error); |
| 879 | if (error) reply_error(reply, error->message); else reply_json(reply, context, json); |
| 880 | g_free(json); g_clear_error(&error); g_ptr_array_unref(paths); |
| 881 | } else reply_json(reply, context, "{\"canceled\":true}"); |
| 882 | gtk_widget_destroy(dialog); app.picker_open = FALSE; |
| 883 | } |
| 884 | } else if (!strcmp(name, "uploadHostFiles")) { |
| 885 | const char *target = text_member(request, "target"), *id = text_member(request, "id"), *token = text_member(request, "selection"); |
| 886 | FileSelection *selected = file_selections ? g_hash_table_lookup(file_selections, token) : NULL; |
| 887 | if (!(strcmp(target, "terminal") == 0 ? g_regex_match_simple("^[a-f0-9]{16}$", id, 0, 0) : g_uuid_string_is_valid(id)) || (strcmp(target, "browser") && strcmp(target, "desktop") && strcmp(target, "terminal"))) reply_error(reply, "文件上传目标无效。"); |
| 888 | else if (!selected || selected->expires <= g_get_monotonic_time()) { |
| 889 | if (file_selections) g_hash_table_remove(file_selections, token); |
| 890 | reply_error(reply, "文件选择已过期,请重新复制或选择文件。"); |
| 891 | } else { |
| 892 | GPtrArray *paths = g_ptr_array_ref(selected->paths); |
| 893 | g_hash_table_remove(file_selections, token); |
| 894 | const char *connection = text_member(request, "connection_id"); |
| 895 | const char **args = g_new0(const char *, paths->len + 8); |
| 896 | args[0] = app.backend; args[1] = "upload-files"; args[2] = "--json"; args[3] = "--connection"; args[4] = *connection ? connection : "local"; args[5] = target; args[6] = id; |
| 897 | for (guint i = 0; i < paths->len; i++) args[i + 7] = g_ptr_array_index(paths, i); |
| 898 | backend_arguments(args, 1800, browser_file_finished, pending_reply(reply, context)); |
| 899 | g_free(args); g_ptr_array_unref(paths); |
| 900 | } |
| 901 | } else if (!strcmp(name, "clipboardWrite")) { |
| 902 | const char *text = text_member(request, "text"); |
| 903 | GtkClipboard *clipboard = gtk_clipboard_get(GDK_SELECTION_CLIPBOARD); |
| 904 | gtk_clipboard_set_text(clipboard, text, -1); |
| 905 | gtk_clipboard_store(clipboard); |
| 906 | reply_json(reply, context, "true"); |
| 907 | } else if (!strcmp(name, "appearance")) { |
| 908 | const char *mode = text_member(request, "mode"); |
| 909 | const char *background = text_member(request, "background"); |
| 910 | GdkRGBA color; |
| 911 | gboolean valid = (!strcmp(mode, "light") || !strcmp(mode, "dark") || !strcmp(mode, "system")) && |
| 912 | strlen(background) == 7 && background[0] == '#' && strspn(background + 1, "0123456789abcdefABCDEF") == 6 && |
| 913 | gdk_rgba_parse(&color, background); |
| 914 | if (!valid) reply_error(reply, "外观参数无效。"); |
| 915 | else { |
| 916 | g_object_set(gtk_settings_get_default(), "gtk-application-prefer-dark-theme", |
| 917 | !strcmp(mode, "system") ? app.initial_dark : !strcmp(mode, "dark"), NULL); |
| 918 | webkit_web_view_set_background_color(app.web, &color); |
| 919 | reply_json(reply, context, "true"); |
| 920 | } |
| 921 | } else if (!strcmp(name, "importTheme")) { |
| 922 | if (app.picker_open) reply_error(reply, "请先完成当前文件选择。"); |
| 923 | else { |
| 924 | char *path = choose_file(GTK_FILE_CHOOSER_ACTION_OPEN, "导入主题", NULL); |
| 925 | if (!path) reply_string(reply, context, ""); |
| 926 | else { |
| 927 | |
| 928 | GFile *file = g_file_new_for_path(path); |
| 929 | GFileInfo *info = g_file_query_info(file, G_FILE_ATTRIBUTE_STANDARD_TYPE "," G_FILE_ATTRIBUTE_STANDARD_SIZE, |
| 930 | G_FILE_QUERY_INFO_NONE, NULL, NULL); |
| 931 | gboolean regular = info && g_file_info_get_file_type(info) == G_FILE_TYPE_REGULAR && g_file_info_get_size(info) <= MAX_THEME; |
| 932 | GFileInputStream *stream = regular ? g_file_read(file, NULL, NULL) : NULL; |
| 933 | char *contents = g_malloc(MAX_THEME + 2); |
| 934 | gsize length = 0; |
| 935 | gboolean ok = stream && g_input_stream_read_all(G_INPUT_STREAM(stream), contents, MAX_THEME + 1, &length, NULL, NULL); |
| 936 | if (ok && length <= MAX_THEME && g_utf8_validate(contents, length, NULL) && !memchr(contents, 0, length)) { |
| 937 | contents[length] = 0; |
| 938 | reply_string(reply, context, contents); |
| 939 | } else reply_error(reply, "请选择不超过 256 KB 的 UTF-8 JSON 主题文件。"); |
| 940 | g_clear_object(&stream); g_clear_object(&info); g_object_unref(file); g_free(contents); |
| 941 | } |
| 942 | g_free(path); |
| 943 | } |
| 944 | } else if (!strcmp(name, "exportTheme")) { |
| 945 | const char *contents = text_member(request, "text"); |
| 946 | JsonParser *theme_parser = json_parser_new(); |
| 947 | gboolean valid = strlen(contents) <= MAX_THEME && json_parser_load_from_data(theme_parser, contents, -1, NULL) && |
| 948 | JSON_NODE_HOLDS_OBJECT(json_parser_get_root(theme_parser)); |
| 949 | JsonObject *theme = valid ? json_node_get_object(json_parser_get_root(theme_parser)) : NULL; |
| 950 | JsonNode *version = theme ? json_object_get_member(theme, "version") : NULL; |
| 951 | valid = theme && !strcmp(text_member(theme, "format"), "cage-theme") && version && |
| 952 | JSON_NODE_HOLDS_VALUE(version) && json_node_get_value_type(version) == G_TYPE_INT64 && json_node_get_int(version) == 1; |
| 953 | if (!valid) reply_error(reply, "主题文件格式无效。"); |
| 954 | else if (app.picker_open) reply_error(reply, "请先完成当前文件选择。"); |
| 955 | else { |
| 956 | char *path = choose_file(GTK_FILE_CHOOSER_ACTION_SAVE, "导出主题", text_member(request, "filename")); |
| 957 | if (!path) reply_json(reply, context, "false"); |
| 958 | else if (g_file_set_contents(path, contents, -1, NULL)) reply_json(reply, context, "true"); |
| 959 | else reply_error(reply, "主题未能导出,请检查保存位置的权限。"); |
| 960 | g_free(path); |
| 961 | } |
| 962 | g_object_unref(theme_parser); |
| 963 | } else if (!strcmp(name, "refreshSession")) { |
| 964 | backend("desktop", app.needs_update ? "--existing" : NULL, session_refreshed, pending_reply(reply, context)); |
| 965 | } else if (!strcmp(name, "reconnect")) { |
| 966 | reply_json(reply, context, "true"); bootstrap(NULL); |
| 967 | } else if (!strcmp(name, "quitNow")) { |
| 968 | reply_json(reply, context, "true"); g_idle_add(quit_idle, NULL); |
| 969 | } else reply_error(reply, "未知原生操作。"); |
| 970 | done: |
| 971 | g_free(json); g_object_unref(parser); |
| 972 | return TRUE; |
| 973 | } |
| 974 | static void install_bridge(void) { |
| 975 | |
| 976 | |
| 977 | |
| 978 | |
| 979 | g_free(app.token); |
| 980 | app.token = g_uuid_string_random(); |
| 981 | char *token = quote(app.token); |
| 982 | char *code = g_strdup_printf( |
| 983 | "(()=>{'use strict';window.cageLinuxBridgeInit='injected';if(window!==window.top||location.protocol!=='http:'||location.hostname!=='localhost'||location.port!=='%d')return;" |
| 984 | "window.cageLinuxBridgeInit='origin-valid';window.cageNativeIMEAvailable=true;try{" |
| 985 | "const transport=window.webkit.messageHandlers.cageTransport;const token=%s;" |
| 986 | "const cage=Object.freeze({postMessage(request){return transport.postMessage({token,request});}});" |
| 987 | "Object.defineProperty(window,'cageNativeBridge',{value:cage,writable:false,configurable:false});" |
| 988 | "window.cageLinuxBridgeInit='ready';}catch(error){window.cageLinuxBridgeInit=error.name;}" |
| 989 | "})();", app.port, token); |
| 990 | |
| 991 | |
| 992 | char *origin = g_strdup("http://localhost/*"); |
| 993 | const char *allowed[] = {origin, NULL}; |
| 994 | WebKitUserScript *user_script = webkit_user_script_new(code, WEBKIT_USER_CONTENT_INJECT_TOP_FRAME, |
| 995 | WEBKIT_USER_SCRIPT_INJECT_AT_DOCUMENT_START, allowed, NULL); |
| 996 | webkit_user_content_manager_remove_all_scripts(app.content); |
| 997 | webkit_user_content_manager_add_script(app.content, user_script); |
| 998 | webkit_user_script_unref(user_script); |
| 999 | g_free(code); g_free(origin); g_free(token); |
| 1000 | } |
| 1001 | static void bootstrapped(JsonObject *object, const GError *error, gpointer data) { |
| 1002 | (void)data; |
| 1003 | app.bootstrapping = FALSE; |
| 1004 | gtk_widget_set_sensitive(app.retry, TRUE); |
| 1005 | if (error) { |
| 1006 | diagnostic_event(error->message); |
| 1007 | gboolean chinese = FALSE; |
| 1008 | for (const char *p = error->message; *p; p = g_utf8_next_char(p)) { |
| 1009 | gunichar value = g_utf8_get_char(p); |
| 1010 | if (value >= 0x4E00 && value <= 0x9FFF) { chinese = TRUE; break; } |
| 1011 | } |
| 1012 | if (chinese) show_error(error->message); |
| 1013 | else { |
| 1014 | char *message = g_strdup_printf("启动工作台失败:本机后台未返回可识别的原因(错误码 %d)。请点击“重试连接”;仍失败时请保留此提示并反馈给维护者。", error->code); |
| 1015 | show_error(message); g_free(message); |
| 1016 | } |
| 1017 | return; |
| 1018 | } |
| 1019 | const char *status = text_member(object, "status"); |
| 1020 | app.needs_update = strcmp(status, "ready") != 0; |
| 1021 | if (!strcmp(status, "upgrade_pending")) { |
| 1022 | gtk_label_set_text(GTK_LABEL(app.status), text_member(object, "message")); |
| 1023 | gtk_widget_show(app.existing); gtk_widget_show(app.complete); |
| 1024 | return; |
| 1025 | } |
| 1026 | const char *url = text_member(object, "url"); |
| 1027 | if ((strcmp(status, "ready") && strcmp(status, "existing")) || !valid_workbench(url, 0, TRUE)) { |
| 1028 | show_error("后台返回了无效的工作台入口。"); return; |
| 1029 | } |
| 1030 | GUri *uri = g_uri_parse(url, G_URI_FLAGS_NONE, NULL); |
| 1031 | app.port = g_uri_get_port(uri); |
| 1032 | g_uri_unref(uri); |
| 1033 | app.ready = FALSE; |
| 1034 | install_bridge(); |
| 1035 | gtk_window_set_title(GTK_WINDOW(app.window), app.needs_update ? "Cage(更新待完成)" : "Cage"); |
| 1036 | webkit_web_view_load_uri(app.web, url); |
| 1037 | } |
| 1038 | static void bootstrap(const char *option) { |
| 1039 | if (app.bootstrapping) return; |
| 1040 | app.bootstrapping = TRUE; |
| 1041 | gtk_label_set_text(GTK_LABEL(app.status), "正在连接 Cage 工作台…"); |
| 1042 | gtk_stack_set_visible_child_name(GTK_STACK(app.stack), "status"); |
| 1043 | gtk_widget_hide(app.retry); gtk_widget_hide(app.existing); gtk_widget_hide(app.complete); |
| 1044 | backend("desktop", option, bootstrapped, NULL); |
| 1045 | } |
| 1046 | static void retry_clicked(GtkButton *button, gpointer data) { (void)button; (void)data; bootstrap(NULL); } |
| 1047 | static void existing_clicked(GtkButton *button, gpointer data) { (void)button; (void)data; bootstrap("--existing"); } |
| 1048 | static void complete_clicked(GtkButton *button, gpointer data) { |
| 1049 | (void)button; (void)data; |
| 1050 | GtkWidget *dialog = gtk_message_dialog_new(GTK_WINDOW(app.window), GTK_DIALOG_MODAL, GTK_MESSAGE_QUESTION, GTK_BUTTONS_OK_CANCEL, |
| 1051 | "请先保存文件。继续后将停止 Cage 环境并完成后台更新,终端任务会结束,项目和登录状态会保留。"); |
| 1052 | gboolean accepted = gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_OK; |
| 1053 | gtk_widget_destroy(dialog); |
| 1054 | if (accepted) bootstrap("--complete-update"); |
| 1055 | } |
| 1056 | static gboolean decide_policy(WebKitWebView *web, WebKitPolicyDecision *decision, WebKitPolicyDecisionType type, gpointer data) { |
| 1057 | (void)web; (void)data; |
| 1058 | if (type == WEBKIT_POLICY_DECISION_TYPE_NEW_WINDOW_ACTION) { webkit_policy_decision_ignore(decision); return TRUE; } |
| 1059 | if (type == WEBKIT_POLICY_DECISION_TYPE_NAVIGATION_ACTION) { |
| 1060 | WebKitNavigationAction *navigation = webkit_navigation_policy_decision_get_navigation_action(WEBKIT_NAVIGATION_POLICY_DECISION(decision)); |
| 1061 | const char *uri = webkit_uri_request_get_uri(webkit_navigation_action_get_request(navigation)); |
| 1062 | if (!valid_workbench(uri, app.port, FALSE)) { webkit_policy_decision_ignore(decision); return TRUE; } |
| 1063 | } |
| 1064 | return FALSE; |
| 1065 | } |
| 1066 | static gboolean deny_permission(WebKitWebView *web, WebKitPermissionRequest *request, gpointer data) { |
| 1067 | (void)web; (void)data; webkit_permission_request_deny(request); return TRUE; |
| 1068 | } |
| 1069 | static gboolean workbench_file_chooser(WebKitWebView *web, WebKitFileChooserRequest *request, gpointer data) { |
| 1070 | (void)data; |
| 1071 | |
| 1072 | if (valid_workbench(webkit_web_view_get_uri(web), app.port, FALSE)) return FALSE; |
| 1073 | webkit_file_chooser_request_cancel(request); |
| 1074 | return TRUE; |
| 1075 | } |
| 1076 | static void deny_download(WebKitWebContext *context, WebKitDownload *download, gpointer data) { |
| 1077 | (void)context; (void)data; webkit_download_cancel(download); |
| 1078 | } |
| 1079 | static gboolean deny_context_menu(WebKitWebView *web, WebKitContextMenu *menu, GdkEvent *event, WebKitHitTestResult *hit, gpointer data) { |
| 1080 | (void)web; (void)menu; (void)event; (void)hit; (void)data; return TRUE; |
| 1081 | } |
| 1082 | static void load_changed(WebKitWebView *web, WebKitLoadEvent event, gpointer data) { |
| 1083 | (void)data; |
| 1084 | if (event == WEBKIT_LOAD_STARTED) app.navigation_failed = FALSE; |
| 1085 | if (event == WEBKIT_LOAD_FINISHED && !app.navigation_failed && valid_workbench(webkit_web_view_get_uri(web), app.port, FALSE)) { |
| 1086 | gtk_stack_set_visible_child_name(GTK_STACK(app.stack), "web"); |
| 1087 | gtk_widget_grab_focus(GTK_WIDGET(web)); |
| 1088 | publish_visibility(); |
| 1089 | } |
| 1090 | } |
| 1091 | static gboolean load_failed(WebKitWebView *web, WebKitLoadEvent event, const char *uri, GError *error, gpointer data) { |
| 1092 | (void)web; (void)event; (void)uri; (void)data; |
| 1093 | app.navigation_failed = TRUE; |
| 1094 | if (error) diagnostic_event(error->message); |
| 1095 | char *message = g_strdup_printf("打开工作台失败:内置网页组件未能加载本机后台(错误码 %d)。请点击“重试连接”;仍失败时请保留此错误提示并反馈给维护者。后台任务不会因此自动结束。", error ? error->code : 0); |
| 1096 | show_error(message); |
| 1097 | g_free(message); |
| 1098 | return TRUE; |
| 1099 | } |
| 1100 | static void process_terminated(WebKitWebView *web, WebKitWebProcessTerminationReason reason, gpointer data) { |
| 1101 | (void)web; (void)reason; (void)data; |
| 1102 | show_error("工作台显示进程已退出。后台任务保留,可重试连接。"); |
| 1103 | } |
| 1104 | static void menu_action(GSimpleAction *simple, GVariant *parameter, gpointer data) { |
| 1105 | (void)parameter; (void)data; |
| 1106 | const char *name = g_action_get_name(G_ACTION(simple)); |
| 1107 | if (!strcmp(name, "closeWindow")) { gtk_widget_hide(app.window); publish_visibility(); } |
| 1108 | else if (!strcmp(name, "quit")) { |
| 1109 | if (gtk_stack_get_visible_child(GTK_STACK(app.stack)) == GTK_WIDGET(app.web)) action("quit"); |
| 1110 | else g_application_quit(G_APPLICATION(app.application)); |
| 1111 | } else if (!strcmp(name, "updates")) { |
| 1112 | GtkWidget *dialog = gtk_message_dialog_new(GTK_WINDOW(app.window), GTK_DIALOG_MODAL, GTK_MESSAGE_INFO, GTK_BUTTONS_CLOSE, |
| 1113 | "Linux 版本通过安装包更新。请保存文件、停止环境并退出 Cage,再安装已核对摘要的官方新版本。"); |
| 1114 | gtk_dialog_run(GTK_DIALOG(dialog)); gtk_widget_destroy(dialog); |
| 1115 | } else if (!strcmp(name, "about")) { |
| 1116 | gtk_show_about_dialog(GTK_WINDOW(app.window), "program-name", "Cage", "version", CAGE_VERSION, |
| 1117 | "comments", "本机隔离编码工作区", "license-type", GTK_LICENSE_MIT_X11, NULL); |
| 1118 | } else action(name); |
| 1119 | } |
| 1120 | static void add_menu_action(GMenu *menu, const char *name, const char *label, const char *accelerator) { |
| 1121 | GSimpleAction *simple = g_simple_action_new(name, NULL); |
| 1122 | g_signal_connect(simple, "activate", G_CALLBACK(menu_action), NULL); |
| 1123 | g_action_map_add_action(G_ACTION_MAP(app.application), G_ACTION(simple)); |
| 1124 | g_object_unref(simple); |
| 1125 | char *full = g_strconcat("app.", name, NULL); |
| 1126 | g_menu_append(menu, label, full); |
| 1127 | if (accelerator) { |
| 1128 | const char *accelerators[] = {accelerator, NULL}; |
| 1129 | gtk_application_set_accels_for_action(app.application, full, accelerators); |
| 1130 | } |
| 1131 | g_free(full); |
| 1132 | } |
| 1133 | static void create_window(void) { |
| 1134 | app.window = gtk_application_window_new(app.application); |
| 1135 | gtk_window_set_title(GTK_WINDOW(app.window), "Cage"); |
| 1136 | gtk_window_set_default_size(GTK_WINDOW(app.window), 1280, 850); |
| 1137 | gtk_widget_set_size_request(app.window, 820, 580); |
| 1138 | gtk_window_set_icon_name(GTK_WINDOW(app.window), "io.github.lee_xeo.Cage"); |
| 1139 | g_signal_connect(app.window, "delete-event", G_CALLBACK(close_window), NULL); |
| 1140 | g_signal_connect(app.window, "window-state-event", G_CALLBACK(visibility_changed), NULL); |
| 1141 | g_signal_connect(app.window, "map-event", G_CALLBACK(visibility_changed), NULL); |
| 1142 | g_signal_connect(app.window, "unmap-event", G_CALLBACK(visibility_changed), NULL); |
| 1143 | g_object_get(gtk_settings_get_default(), "gtk-application-prefer-dark-theme", &app.initial_dark, NULL); |
| 1144 | GtkWidget *layout = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0); |
| 1145 | gtk_container_add(GTK_CONTAINER(app.window), layout); |
| 1146 | GMenu *menu = g_menu_new(), *file = g_menu_new(), *settings = g_menu_new(), *help = g_menu_new(); |
| 1147 | |
| 1148 | add_menu_action(file, "openProject", "打开项目…", NULL); |
| 1149 | add_menu_action(file, "newTab", "新建网页", NULL); |
| 1150 | add_menu_action(file, "newTerminal", "新建终端", NULL); |
| 1151 | add_menu_action(file, "closeTab", "关闭当前标签", NULL); |
| 1152 | add_menu_action(file, "closeWindow", "关闭窗口(保留环境)", NULL); |
| 1153 | add_menu_action(file, "quit", "退出 Cage…", "<Primary>q"); |
| 1154 | add_menu_action(settings, "settings", "打开设置", NULL); |
| 1155 | add_menu_action(settings, "updates", "应用更新…", NULL); |
| 1156 | add_menu_action(help, "about", "关于 Cage", NULL); |
| 1157 | g_menu_append_submenu(menu, "文件", G_MENU_MODEL(file)); |
| 1158 | g_menu_append_submenu(menu, "设置", G_MENU_MODEL(settings)); |
| 1159 | g_menu_append_submenu(menu, "帮助", G_MENU_MODEL(help)); |
| 1160 | gtk_box_pack_start(GTK_BOX(layout), gtk_menu_bar_new_from_model(G_MENU_MODEL(menu)), FALSE, FALSE, 0); |
| 1161 | g_object_unref(menu); g_object_unref(file); g_object_unref(settings); g_object_unref(help); |
| 1162 | app.stack = gtk_stack_new(); |
| 1163 | gtk_box_pack_start(GTK_BOX(layout), app.stack, TRUE, TRUE, 0); |
| 1164 | GtkWidget *status_box = gtk_box_new(GTK_ORIENTATION_VERTICAL, 16); |
| 1165 | gtk_widget_set_margin_start(status_box, 48); gtk_widget_set_margin_end(status_box, 48); |
| 1166 | gtk_widget_set_margin_top(status_box, 48); gtk_widget_set_valign(status_box, GTK_ALIGN_START); |
| 1167 | app.status = gtk_label_new("正在启动 Cage 工作台…"); |
| 1168 | gtk_label_set_line_wrap(GTK_LABEL(app.status), TRUE); |
| 1169 | gtk_label_set_xalign(GTK_LABEL(app.status), 0); |
| 1170 | gtk_box_pack_start(GTK_BOX(status_box), app.status, FALSE, FALSE, 0); |
| 1171 | app.retry = gtk_button_new_with_label("重试连接"); |
| 1172 | app.existing = gtk_button_new_with_label("打开现有环境保存文件"); |
| 1173 | app.complete = gtk_button_new_with_label("保存后停止环境并完成更新"); |
| 1174 | GtkWidget *buttons[] = {app.retry, app.existing, app.complete}; |
| 1175 | for (guint i = 0; i < G_N_ELEMENTS(buttons); i++) { |
| 1176 | gtk_widget_set_halign(buttons[i], GTK_ALIGN_START); |
| 1177 | gtk_box_pack_start(GTK_BOX(status_box), buttons[i], FALSE, FALSE, 0); |
| 1178 | } |
| 1179 | g_signal_connect(app.retry, "clicked", G_CALLBACK(retry_clicked), NULL); |
| 1180 | g_signal_connect(app.existing, "clicked", G_CALLBACK(existing_clicked), NULL); |
| 1181 | g_signal_connect(app.complete, "clicked", G_CALLBACK(complete_clicked), NULL); |
| 1182 | gtk_stack_add_named(GTK_STACK(app.stack), status_box, "status"); |
| 1183 | |
| 1184 | |
| 1185 | WebKitWebsiteDataManager *storage = webkit_website_data_manager_new( |
| 1186 | "base-data-directory", app.web_data, "base-cache-directory", app.web_cache, NULL); |
| 1187 | WebKitWebContext *context = webkit_web_context_new_with_website_data_manager(storage); |
| 1188 | g_object_unref(storage); |
| 1189 | webkit_web_context_set_sandbox_enabled(context, TRUE); |
| 1190 | webkit_website_data_manager_set_network_proxy_settings(webkit_web_context_get_website_data_manager(context), WEBKIT_NETWORK_PROXY_MODE_NO_PROXY, NULL); |
| 1191 | g_signal_connect(context, "download-started", G_CALLBACK(deny_download), NULL); |
| 1192 | app.content = webkit_user_content_manager_new(); |
| 1193 | g_signal_connect(app.content, "script-message-with-reply-received::cageTransport", G_CALLBACK(bridge_received), NULL); |
| 1194 | webkit_user_content_manager_register_script_message_handler_with_reply(app.content, "cageTransport", NULL); |
| 1195 | app.web = WEBKIT_WEB_VIEW(g_object_new(WEBKIT_TYPE_WEB_VIEW, "web-context", context, "user-content-manager", app.content, NULL)); |
| 1196 | input_initialize(app.web); |
| 1197 | g_object_unref(context); |
| 1198 | WebKitSettings *web_settings = webkit_web_view_get_settings(app.web); |
| 1199 | webkit_settings_set_enable_developer_extras(web_settings, FALSE); |
| 1200 | webkit_settings_set_javascript_can_open_windows_automatically(web_settings, FALSE); |
| 1201 | webkit_settings_set_enable_write_console_messages_to_stdout(web_settings, FALSE); |
| 1202 | g_signal_connect(app.web, "decide-policy", G_CALLBACK(decide_policy), NULL); |
| 1203 | g_signal_connect(app.web, "permission-request", G_CALLBACK(deny_permission), NULL); |
| 1204 | g_signal_connect(app.web, "run-file-chooser", G_CALLBACK(workbench_file_chooser), NULL); |
| 1205 | g_signal_connect(app.web, "context-menu", G_CALLBACK(deny_context_menu), NULL); |
| 1206 | g_signal_connect(app.web, "load-changed", G_CALLBACK(load_changed), NULL); |
| 1207 | g_signal_connect(app.web, "load-failed", G_CALLBACK(load_failed), NULL); |
| 1208 | g_signal_connect(app.web, "web-process-terminated", G_CALLBACK(process_terminated), NULL); |
| 1209 | gtk_stack_add_named(GTK_STACK(app.stack), GTK_WIDGET(app.web), "web"); |
| 1210 | gtk_widget_show_all(app.window); |
| 1211 | bootstrap(NULL); |
| 1212 | } |
| 1213 | static void activate(GtkApplication *application, gpointer data) { |
| 1214 | (void)application; (void)data; |
| 1215 | if (!app.window) create_window(); |
| 1216 | else { gtk_widget_show(app.window); gtk_window_deiconify(GTK_WINDOW(app.window)); gtk_window_present(GTK_WINDOW(app.window)); publish_visibility(); } |
| 1217 | } |
| 1218 | static gboolean smoke_deadline(gpointer data) { |
| 1219 | (void)data; |
| 1220 | g_printerr("Linux smoke: timed out before a ready, authenticated workbench.\n"); |
| 1221 | g_application_quit(G_APPLICATION(app.application)); |
| 1222 | return G_SOURCE_REMOVE; |
| 1223 | } |
| 1224 | static void smoke_diagnostics_ready(GObject *source, GAsyncResult *result, gpointer data) { |
| 1225 | (void)data; |
| 1226 | GError *error = NULL; |
| 1227 | JSCValue *value = webkit_web_view_call_async_javascript_function_finish(WEBKIT_WEB_VIEW(source), result, &error); |
| 1228 | if (value) { |
| 1229 | char *json = jsc_value_to_json(value, 0); |
| 1230 | g_printerr("Linux smoke startup diagnostics: %s\n", json ? json : "unavailable"); |
| 1231 | g_free(json); g_object_unref(value); |
| 1232 | } else g_printerr("Linux smoke: JavaScript diagnostics unavailable.\n"); |
| 1233 | g_clear_error(&error); |
| 1234 | } |
| 1235 | static gboolean smoke_diagnostics(gpointer data) { |
| 1236 | (void)data; |
| 1237 | if (app.ready || !app.web) return G_SOURCE_REMOVE; |
| 1238 | const char *body = |
| 1239 | "const account=await fetch('/api/account');const state=await fetch('/api/status');const settings=await fetch('/api/settings');" |
| 1240 | "let unlocked=false;try{unlocked=(await account.json()).unlocked===true;}catch{}" |
| 1241 | "const descriptor=Object.getOwnPropertyDescriptor(window,'webkit');" |
| 1242 | "return {bridgeAvailable:!!window.cageNativeBridge,bridgeInit:window.cageLinuxBridgeInit||'not-injected',webkitConfigurable:descriptor?.configurable,transportPresent:!!window.webkit?.messageHandlers?.cageTransport,readyState:document.readyState," |
| 1243 | "renderedButtons:document.querySelectorAll('button').length,accountStatus:account.status,accountUnlocked:unlocked,statusStatus:state.status,settingsStatus:settings.status};"; |
| 1244 | webkit_web_view_call_async_javascript_function(app.web, body, -1, NULL, NULL, "cage-smoke-diagnostics", NULL, smoke_diagnostics_ready, NULL); |
| 1245 | return G_SOURCE_REMOVE; |
| 1246 | } |
| 1247 | static int self_test(void) { |
| 1248 | g_assert_true(valid_workbench("http://localhost:23456/#secret", 23456, TRUE)); |
| 1249 | g_assert_true(valid_workbench("http://localhost:23456/", 23456, FALSE)); |
| 1250 | g_assert_false(valid_workbench("http://localhost:23456/", 23456, TRUE)); |
| 1251 | g_assert_false(valid_workbench("http://localhost:23457/#secret", 23456, TRUE)); |
| 1252 | g_assert_false(valid_workbench("http://127.0.0.1:23456/#secret", 23456, TRUE)); |
| 1253 | g_assert_false(valid_workbench("http://localhost.evil.test:23456/#secret", 23456, TRUE)); |
| 1254 | g_assert_false(valid_workbench("http://user@localhost:23456/#secret", 23456, TRUE)); |
| 1255 | g_assert_false(valid_workbench("https://localhost:23456/#secret", 23456, TRUE)); |
| 1256 | g_assert_false(valid_workbench("file:///tmp/workbench.html", 0, FALSE)); |
| 1257 | g_assert_false(valid_workbench("javascript:alert(1)", 0, FALSE)); |
| 1258 | g_assert_false(valid_workbench("http://localhost:80/#secret", 0, TRUE)); |
| 1259 | g_print("Linux desktop origin policy: 11 checks passed.\n"); |
| 1260 | return 0; |
| 1261 | } |
| 1262 | int main(int argc, char **argv) { |
| 1263 | if (argc == 2 && !strcmp(argv[1], "--self-test")) return self_test(); |
| 1264 | if (argc == 2 && !strcmp(argv[1], "--version")) { g_print("Cage %s\n", CAGE_VERSION); return 0; } |
| 1265 | if (argc == 3 && !strcmp(argv[1], "--smoke-test") && g_path_is_absolute(argv[2]) && g_getenv("CLAUDE_CAGE_CONFIG")) { |
| 1266 | app.smoke_output = g_strdup(argv[2]); app.result = 1; |
| 1267 | app.storage_phase = g_getenv("CAGE_SMOKE_STORAGE_PHASE"); |
| 1268 | app.storage_marker = g_getenv("CAGE_SMOKE_STORAGE_MARKER"); |
| 1269 | if (app.storage_phase && (g_strcmp0(app.storage_phase, "seed") && g_strcmp0(app.storage_phase, "verify"))) return 2; |
| 1270 | if (app.storage_phase && (!app.storage_marker || !*app.storage_marker || strlen(app.storage_marker) > 128)) return 2; |
| 1271 | } else if (argc != 1) { |
| 1272 | g_printerr("Usage: cage-desktop [--version | --self-test | --smoke-test /absolute/report.json]\nSmoke tests require an isolated CLAUDE_CAGE_CONFIG with an unlocked test account.\n"); |
| 1273 | return 2; |
| 1274 | } |
| 1275 | if (geteuid() == 0) { g_printerr("Cage 桌面需要以普通用户运行,请勿使用 sudo 启动。\n"); return 1; } |
| 1276 | char *executable = g_file_read_link("/proc/self/exe", NULL); |
| 1277 | if (!executable) { g_printerr("无法定位 Cage 安装目录。\n"); return 1; } |
| 1278 | char *directory = g_path_get_dirname(executable); |
| 1279 | app.backend = g_build_filename(directory, "cage", NULL); |
| 1280 | g_free(directory); g_free(executable); |
| 1281 | if (!g_file_test(app.backend, G_FILE_TEST_IS_EXECUTABLE)) { g_printerr("安装目录缺少 Cage 后台,请重新安装。\n"); return 1; } |
| 1282 | const char *configured = g_getenv("CLAUDE_CAGE_CONFIG"); |
| 1283 | app.profile = configured && *configured ? g_canonicalize_filename(configured, NULL) |
| 1284 | : CAGE_CLIENT_ONLY ? g_build_filename(g_get_home_dir(), ".claude-cage", "client", "config.json", NULL) |
| 1285 | : g_build_filename(g_get_home_dir(), ".claude-cage", "config.json", NULL); |
| 1286 | g_setenv("CLAUDE_CAGE_CONFIG", app.profile, TRUE); |
| 1287 | g_log_set_default_handler(diagnostic_glib, NULL); |
| 1288 | if (!prepare_web_storage()) { |
| 1289 | g_printerr("无法创建 Cage 私有界面数据目录,请检查配置目录的所有者、权限或符号链接。\n"); |
| 1290 | return 1; |
| 1291 | } |
| 1292 | char *hash = g_compute_checksum_for_string(G_CHECKSUM_SHA256, app.profile, -1); |
| 1293 | char *id = g_strdup_printf("app.cage.desktop.p%.24s", hash); |
| 1294 | app.application = gtk_application_new(id, G_APPLICATION_FLAGS_NONE); |
| 1295 | g_free(hash); g_free(id); |
| 1296 | g_signal_connect(app.application, "activate", G_CALLBACK(activate), NULL); |
| 1297 | if (app.smoke_output) { |
| 1298 | g_timeout_add_seconds(120, smoke_deadline, NULL); |
| 1299 | g_timeout_add_seconds(15, smoke_diagnostics, NULL); |
| 1300 | } |
| 1301 | int status = g_application_run(G_APPLICATION(app.application), 1, argv); |
| 1302 | if (app.window) gtk_widget_destroy(app.window); |
| 1303 | g_object_unref(app.application); |
| 1304 | g_free(app.backend); g_free(app.profile); g_free(app.token); g_free(app.smoke_output); |
| 1305 | g_free(app.web_data); g_free(app.web_cache); |
| 1306 | g_clear_object(&app.content); |
| 1307 | return status ? status : app.result; |
| 1308 | } |