File: foundry-text-manager.c

package info (click to toggle)
foundry 1.1~beta-2
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 15,552 kB
  • sloc: ansic: 167,487; xml: 417; makefile: 21; sh: 19; javascript: 10
file content (483 lines) | stat: -rw-r--r-- 15,975 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
/* foundry-text-manager.c
 *
 * Copyright 2024 Christian Hergert <chergert@redhat.com>
 *
 * This library is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of the
 * License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * SPDX-License-Identifier: LGPL-2.1-or-later
 */

#include "config.h"

#include <libpeas.h>

#include "foundry-extension.h"
#include "foundry-inhibitor.h"
#include "foundry-operation.h"
#include "foundry-simple-text-buffer-provider.h"
#include "foundry-text-buffer.h"
#include "foundry-text-buffer-provider.h"
#include "foundry-text-document-private.h"
#include "foundry-text-edit.h"
#include "foundry-text-manager-private.h"
#include "foundry-service-private.h"
#include "foundry-util-private.h"

/**
 * FoundryTextManager:
 *
 * Manages text documents and provides text editing services.
 *
 * FoundryTextManager coordinates text buffer creation, document management, and
 * provides a unified interface for text editing operations. It handles document
 * loading, saving, and maintains relationships between files and their text representations.
 */

struct _FoundryTextManager
{
  FoundryService             parent_instance;
  FoundryTextBufferProvider *text_buffer_provider;
  GHashTable                *documents_by_file;
  GHashTable                *loading;
};

struct _FoundryTextManagerClass
{
  FoundryServiceClass parent_class;
};

G_DEFINE_FINAL_TYPE (FoundryTextManager, foundry_text_manager, FOUNDRY_TYPE_SERVICE)

enum {
  DOCUMENT_ADDED,
  DOCUMENT_REMOVED,
  DOCUMENT_SAVED,
  N_SIGNALS
};

static guint signals[N_SIGNALS];

static void
foundry_text_manager_document_saved_cb (FoundryTextManager  *self,
                                        GFile               *file,
                                        FoundryTextDocument *document)
{
  g_assert (FOUNDRY_IS_TEXT_MANAGER (self));
  g_assert (G_IS_FILE (file));
  g_assert (FOUNDRY_IS_TEXT_DOCUMENT (document));

  g_signal_emit (self, signals[DOCUMENT_SAVED], 0, document);
}

static DexFuture *
foundry_text_manager_start (FoundryService *service)
{
  FoundryTextManager *self = (FoundryTextManager *)service;
  g_autoptr(FoundryContext) context = NULL;
  g_autoptr(FoundryExtension) text_buffer_provider = NULL;

  g_assert (FOUNDRY_IS_TEXT_MANAGER (self));

  context = foundry_contextual_dup_context (FOUNDRY_CONTEXTUAL (self));

  text_buffer_provider = foundry_extension_new (context,
                                                peas_engine_get_default (),
                                                FOUNDRY_TYPE_TEXT_BUFFER_PROVIDER,
                                                "Text-Buffer-Provider", "*");

  /* You can only setup the buffer provider once at startup since that is what
   * will get used for all buffers that get displayed in UI/etc. They need to
   * be paired with their display counterpart (so GtkTextBuffer/GtkTextView).
   */
  g_set_object (&self->text_buffer_provider,
                foundry_extension_get_extension (text_buffer_provider));

  if (self->text_buffer_provider == NULL)
    self->text_buffer_provider = foundry_simple_text_buffer_provider_new (context);

  g_debug ("%s using %s as buffer provider",
           G_OBJECT_TYPE_NAME (self),
           G_OBJECT_TYPE_NAME (self->text_buffer_provider));

  return dex_future_new_true ();
}

static DexFuture *
foundry_text_manager_stop (FoundryService *service)
{
  FoundryTextManager *self = (FoundryTextManager *)service;

  g_assert (FOUNDRY_IS_TEXT_MANAGER (self));

  g_hash_table_remove_all (self->documents_by_file);
  g_hash_table_remove_all (self->loading);

  return dex_future_new_true ();
}

static void
foundry_text_manager_finalize (GObject *object)
{
  FoundryTextManager *self = (FoundryTextManager *)object;

  g_clear_pointer (&self->documents_by_file, g_hash_table_unref);
  g_clear_pointer (&self->loading, g_hash_table_unref);

  G_OBJECT_CLASS (foundry_text_manager_parent_class)->finalize (object);
}

static void
foundry_text_manager_class_init (FoundryTextManagerClass *klass)
{
  GObjectClass *object_class = G_OBJECT_CLASS (klass);
  FoundryServiceClass *service_class = FOUNDRY_SERVICE_CLASS (klass);

  object_class->finalize = foundry_text_manager_finalize;

  service_class->start = foundry_text_manager_start;
  service_class->stop = foundry_text_manager_stop;

  signals[DOCUMENT_ADDED] =
    g_signal_new ("document-added",
                  G_TYPE_FROM_CLASS (klass),
                  G_SIGNAL_RUN_LAST,
                  0,
                  NULL, NULL,
                  NULL,
                  G_TYPE_NONE, 2, G_TYPE_FILE, FOUNDRY_TYPE_TEXT_DOCUMENT);

  signals[DOCUMENT_REMOVED] =
    g_signal_new ("document-removed",
                  G_TYPE_FROM_CLASS (klass),
                  G_SIGNAL_RUN_LAST,
                  0,
                  NULL, NULL,
                  NULL,
                  G_TYPE_NONE, 1, G_TYPE_FILE);

  /**
   * FoundryTextManager::document-saved:
   * @self: a [class@Foundry.TextManager]
   * @document: a [class@Foundry.TextDocument]
   *
   * This signal is emitted whenever a [class@Foundry.TextDocument] managed
   * by the manager emits "saved".
   *
   * Since: 1.1
   */
  signals[DOCUMENT_SAVED] =
    g_signal_new ("document-saved",
                  G_TYPE_FROM_CLASS (klass),
                  G_SIGNAL_RUN_LAST,
                  0,
                  NULL, NULL,
                  NULL,
                  G_TYPE_NONE, 1, FOUNDRY_TYPE_TEXT_DOCUMENT);
}

static void
foundry_text_manager_init (FoundryTextManager *self)
{
  self->documents_by_file = g_hash_table_new_full ((GHashFunc) g_file_hash,
                                                   (GEqualFunc) g_file_equal,
                                                   g_object_unref,
                                                   NULL);
  self->loading = g_hash_table_new_full ((GHashFunc) g_file_hash,
                                         (GEqualFunc) g_file_equal,
                                         g_object_unref,
                                         dex_unref);
}

static DexFuture *
foundry_text_manager_load_fiber (FoundryTextManager *self,
                                 GFile              *file,
                                 FoundryOperation   *operation,
                                 const char         *encoding)
{
  g_autoptr(FoundryTextDocument) document = NULL;
  g_autoptr(FoundryTextBuffer) buffer = NULL;
  g_autoptr(FoundryContext) context = NULL;
  g_autoptr(DexPromise) promise = NULL;
  g_autoptr(DexFuture) future = NULL;
  g_autoptr(GError) error = NULL;
  g_autofree char *draft_id = NULL;
  FoundryTextDocument *existing;
  g_autofree char *uri = NULL;

  g_assert (FOUNDRY_IS_TEXT_MANAGER (self));
  g_assert (G_IS_FILE (file));
  g_assert (FOUNDRY_IS_OPERATION (operation));

  /* If loaded already, share the existing document */
  if ((existing = g_hash_table_lookup (self->documents_by_file, file)))
    return dex_future_new_take_object (g_object_ref (existing));

  /* If actively loading, await the same future */
  if ((future = g_hash_table_lookup (self->loading, file)))
    return dex_ref (future);

  promise = dex_promise_new ();
  g_hash_table_replace (self->loading, g_file_dup (file), dex_ref (promise));

  uri = g_file_get_uri (file);

  /* TODO: Stable draft-id */
  draft_id = NULL;

  context = foundry_contextual_dup_context (FOUNDRY_CONTEXTUAL (self));
  buffer = foundry_text_buffer_provider_create_buffer (self->text_buffer_provider);

  if (!(document = dex_await_object (_foundry_text_document_new (context, self, file, draft_id, buffer), &error)))
    return dex_future_new_for_error (g_steal_pointer (&error));

  dex_await (_foundry_text_document_pre_load (document), NULL);

  if (!dex_await (foundry_text_buffer_provider_load (self->text_buffer_provider,
                                                     buffer, file, operation,
                                                     encoding, NULL), &error))
    {
      g_hash_table_remove (self->loading, file);
      dex_promise_reject (promise, g_error_copy (error));
      return dex_future_new_for_error (g_steal_pointer (&error));
    }

  dex_await (_foundry_text_document_post_load (document), NULL);

  g_hash_table_remove (self->loading, file);

  /* Use borrowed reference, we'll get a callback to remove when
   * the document is disposed.
   */
  g_hash_table_replace (self->documents_by_file,
                        g_file_dup (file),
                        document);

  g_signal_connect_object (document,
                           "saved",
                           G_CALLBACK (foundry_text_manager_document_saved_cb),
                           self,
                           G_CONNECT_SWAPPED);

  g_signal_emit (self, signals[DOCUMENT_ADDED], 0, file, document);

  dex_promise_resolve_object (promise, g_object_ref (document));

  return dex_future_new_take_object (g_steal_pointer (&document));
}

/**
 * foundry_text_manager_load:
 * @self: a #FoundryTextManager
 * @file: a #GFile
 * @operation: an operation for progress
 * @encoding: (nullable): an optional encoding charset
 *
 * Loads the file as a text document.
 *
 * Returns: (transfer full): a [class@Dex.Future] that resolves to a
 *   [class@Foundry.TextDocument].
 */
DexFuture *
foundry_text_manager_load (FoundryTextManager *self,
                           GFile              *file,
                           FoundryOperation   *operation,
                           const char         *encoding)
{
  dex_return_error_if_fail (FOUNDRY_IS_TEXT_MANAGER (self));
  dex_return_error_if_fail (G_IS_FILE (file));
  dex_return_error_if_fail (FOUNDRY_IS_OPERATION (operation));

  return foundry_scheduler_spawn (NULL, 0,
                                  G_CALLBACK (foundry_text_manager_load_fiber),
                                  4,
                                  FOUNDRY_TYPE_TEXT_MANAGER, self,
                                  G_TYPE_FILE, file,
                                  FOUNDRY_TYPE_OPERATION, operation,
                                  G_TYPE_STRING, encoding);
}

/**
 * foundry_text_manager_list_documents:
 * @self: a [class@Foundry.TextManager]
 *
 * Returns: (transfer full): a [iface@Gio.ListModel] of [class@Foundry.TextDocument]
 */
GListModel *
foundry_text_manager_list_documents (FoundryTextManager *self)
{
  FoundryTextDocument *document;
  GHashTableIter iter;
  GListStore *store;

  g_return_val_if_fail (FOUNDRY_IS_TEXT_MANAGER (self), NULL);

  store = g_list_store_new (FOUNDRY_TYPE_TEXT_DOCUMENT);

  g_hash_table_iter_init (&iter, self->documents_by_file);
  while (g_hash_table_iter_next (&iter, NULL, (gpointer *)&document))
    g_list_store_append (store, document);

  return G_LIST_MODEL (store);
}

FoundryTextBufferProvider *
_foundry_text_manager_dup_provider (FoundryTextManager *self)
{
  g_return_val_if_fail (FOUNDRY_IS_TEXT_MANAGER (self), NULL);

  return g_object_ref (self->text_buffer_provider);
}

typedef struct _ApplyEdits
{
  FoundryTextManager *self;
  FoundryOperation *operation;
  GHashTable *by_file;
} ApplyEdits;

static void
apply_edits_free (ApplyEdits *state)
{
  g_clear_object (&state->self);
  g_clear_object (&state->operation);
  g_clear_pointer (&state->by_file, g_hash_table_unref);
  g_free (state);
}

static DexFuture *
foundry_text_manager_apply_edits_fiber (gpointer data)
{
  ApplyEdits *state = data;
  GHashTableIter hiter;
  gpointer key, value;

  g_assert (state != NULL);
  g_assert (FOUNDRY_IS_TEXT_MANAGER (state->self));
  g_assert (state->by_file != NULL);

  g_hash_table_iter_init (&hiter, state->by_file);

  while (g_hash_table_iter_next (&hiter, &key, &value))
    {
      g_autoptr(FoundryTextDocument) document = NULL;
      g_autoptr(GError) error = NULL;
      GPtrArray *edits = value;
      GFile *file = key;

      g_assert (G_IS_FILE (file));
      g_assert (edits != NULL);
      g_assert (edits->len > 0);

      if (!(document = dex_await_object (foundry_text_manager_load (state->self, file, state->operation, NULL), &error)))
        return dex_future_new_for_error (g_steal_pointer (&error));

      if (!foundry_text_document_apply_edits (document, (FoundryTextEdit **)edits->pdata, edits->len))
        return dex_future_new_reject (G_IO_ERROR,
                                      G_IO_ERROR_INVALID_DATA,
                                      "Failed to apply edits to document");

      if (!dex_await (foundry_text_document_save (document, state->operation), &error))
        return dex_future_new_for_error (g_steal_pointer (&error));
    }

  return dex_future_new_true ();
}

/**
 * foundry_text_manager_apply_edits:
 * @self: a [class@Foundry.TextManager]
 * @edits: a [iface@Gio.ListModel] of [class@Foundry.TextEdit]
 * @operation: (nullable): a [class@Foundry.Operation]
 *
 * Applies all of @edits to the respective files.
 *
 * Returns: (transfer full): a [class@Dex.Future] that resolves to
 *   any value or rejects with error.
 */
DexFuture *
foundry_text_manager_apply_edits (FoundryTextManager *self,
                                  GListModel         *edits,
                                  FoundryOperation   *operation)
{
  g_autoptr(GHashTable) by_file = NULL;
  ApplyEdits *state;
  guint n_items;

  dex_return_error_if_fail (FOUNDRY_IS_TEXT_MANAGER (self));
  dex_return_error_if_fail (G_IS_LIST_MODEL (edits));
  dex_return_error_if_fail (FOUNDRY_IS_OPERATION (operation));

  n_items = g_list_model_get_n_items (edits);
  by_file = g_hash_table_new_full ((GHashFunc) g_file_hash,
                                   (GEqualFunc) g_file_equal,
                                   g_object_unref,
                                   (GDestroyNotify) g_ptr_array_unref);

  for (guint i = 0; i < n_items; i++)
    {
      g_autoptr(FoundryTextEdit) edit = g_list_model_get_item (edits, i);
      g_autoptr(GFile) file = foundry_text_edit_dup_file (edit);
      GPtrArray *ar;

      g_assert (FOUNDRY_IS_TEXT_EDIT (edit));
      g_assert (G_IS_FILE (file));

      if (!(ar = g_hash_table_lookup (by_file, file)))
        {
          ar = g_ptr_array_new_with_free_func (g_object_unref);
          g_hash_table_replace (by_file, g_object_ref (file), ar);
        }

      g_ptr_array_add (ar, g_steal_pointer (&edit));
    }

  state = g_new0 (ApplyEdits, 1);
  state->self = g_object_ref (self);
  state->operation = operation ? g_object_ref (operation) : foundry_operation_new ();
  state->by_file = g_steal_pointer (&by_file);

  return dex_scheduler_spawn (NULL, 0,
                              foundry_text_manager_apply_edits_fiber,
                              state,
                              (GDestroyNotify) apply_edits_free);
}

void
_foundry_text_manager_release (FoundryTextManager  *self,
                               FoundryTextDocument *document)
{
  g_autoptr(GFile) file = NULL;
  GHashTableIter iter;
  gpointer value;

  g_return_if_fail (FOUNDRY_IS_MAIN_THREAD ());
  g_return_if_fail (FOUNDRY_IS_TEXT_MANAGER (self));
  g_return_if_fail (FOUNDRY_IS_TEXT_DOCUMENT (document));

  g_debug ("Releasing text document at %p", document);

  file = foundry_text_document_dup_file (document);

  g_hash_table_iter_init (&iter, self->documents_by_file);
  while (g_hash_table_iter_next (&iter, NULL, &value))
    {
      if (value == (gpointer)document)
        {
          g_hash_table_iter_remove (&iter);
          break;
        }
    }

  g_signal_emit (self, signals[DOCUMENT_REMOVED], 0, file);
}