fileoperation: make undo and redo more careful

An undo that stops halfway keeps the rest, only one runs at a time, and
restoring from the trash never overwrites a file that's there now. On
Windows only the file that was trashed comes back. A question whose
window was closed now cancels instead of waiting forever.
This commit is contained in:
Daemonratte 2026-10-18 17:59:34 +02:00
commit 6d333d5a32

View file

@ -122,6 +122,7 @@ typedef struct
GFile *source;
GFile *target;
gchar *link;
gint64 time; /* STEP_TRASHED: just before, by g_get_real_time() */
} Step;
typedef enum
@ -195,10 +196,16 @@ struct _GtkFileOperation
gint own_depth; /* in a folder this copy made: not noted */
gboolean restorable; /* all trashed files can be put back */
/* Undo and Redo: the entry, taken off its stack meanwhile */
/* Undo and Redo: the entry, taken off its stack meanwhile, and how
* many of its steps were gone through */
UndoEntry *replay;
guint replayed;
};
/* operations that run; Undo and Redo wait for them, as they may depend
* on what is being done; only touched in the main loop */
static guint operations_running = 0;
static void
step_free (Step *step)
{
@ -351,7 +358,7 @@ _gtk_file_operation_undo_label (gboolean redo,
: (undo_stack ? undo_stack->data : NULL);
if (possible)
*possible = entry != NULL && entry->possible;
*possible = entry != NULL && entry->possible && operations_running == 0;
if (entry == NULL)
return redo ? _("_Redo") : _("_Undo");
@ -637,6 +644,7 @@ typedef struct
GtkFileOperation *op;
GtkWidget *all_check;
GtkWidget *entry;
gboolean answered;
} AskData;
static void
@ -702,8 +710,19 @@ ask_response (GtkDialog *dialog,
op->conflict_for_all = ANSWER_RENAME;
g_mutex_unlock (&op->mutex);
}
ask->answered = TRUE;
gtk_widget_destroy (GTK_WIDGET (dialog));
}
/* The dialog went: with its window, too, without an answer, which then
* is Cancel, as the thread waits for one */
static void
ask_destroyed (GtkWidget *dialog,
AskData *ask)
{
if (!ask->answered)
answer (ask->op, ANSWER_CANCEL, NULL, FALSE);
g_slice_free (AskData, ask);
}
@ -848,6 +867,7 @@ ask_in_main_loop (gpointer data)
gtk_window_set_title (GTK_WINDOW (dialog), "");
gtk_window_set_modal (GTK_WINDOW (dialog), TRUE);
g_signal_connect (dialog, "response", G_CALLBACK (ask_response), ask);
g_signal_connect (dialog, "destroy", G_CALLBACK (ask_destroyed), ask);
gtk_widget_show (dialog);
out:
@ -983,6 +1003,8 @@ win32_trash_file (GFile *file,
return TRUE;
}
#define GTK_CMIC_MASK_NOASYNC 0x00000100 /* CMIC_MASK_NOASYNC of Vista */
/* the interfaces, here so that no uuid library is needed */
static const GUID gtk_IID_IShellFolder2 =
{ 0x93f2f68c, 0x1d1b, 0x11d3, { 0xa3, 0x0e, 0x00, 0xc0, 0x4f, 0x79, 0xab, 0xd1 } };
@ -992,6 +1014,29 @@ static const GUID gtk_IID_IContextMenu =
static const SHCOLUMNID gtk_SCID_DateDeleted =
{ { 0x9b174b33, 0x40ff, 0x11d2, { 0xa2, 0x7e, 0x00, 0xc0, 0x4f, 0xc3, 0x08, 0x71 } }, 3 };
/* A STRRET as UTF-8, freed: StrRetToStrW() without shlwapi */
static gchar *
win32_strret (STRRET *str,
LPITEMIDLIST item)
{
gchar *result = NULL;
switch (str->uType)
{
case STRRET_WSTR:
result = g_utf16_to_utf8 ((gunichar2 *) str->pOleStr, -1, NULL, NULL, NULL);
CoTaskMemFree (str->pOleStr);
break;
case STRRET_CSTR:
result = g_locale_to_utf8 (str->cStr, -1, NULL, NULL, NULL);
break;
case STRRET_OFFSET:
result = g_locale_to_utf8 ((const gchar *) item + str->uOffset, -1, NULL, NULL, NULL);
break;
}
return result;
}
/* A detail of an item in the Recycle Bin as UTF-8: 0 the name, 1 the
* folder it came from */
static gchar *
@ -1000,25 +1045,53 @@ win32_bin_detail (IShellFolder2 *bin,
UINT column)
{
SHELLDETAILS details = { 0 };
gchar *result = NULL;
if (FAILED (IShellFolder2_GetDetailsOf (bin, item, column, &details)))
return NULL;
return win32_strret (&details.str, item);
}
/* StrRetToStrW() without shlwapi */
switch (details.str.uType)
{
case STRRET_WSTR:
result = g_utf16_to_utf8 ((gunichar2 *) details.str.pOleStr, -1, NULL, NULL, NULL);
CoTaskMemFree (details.str.pOleStr);
break;
case STRRET_CSTR:
result = g_locale_to_utf8 (details.str.cStr, -1, NULL, NULL, NULL);
break;
case STRRET_OFFSET:
result = g_locale_to_utf8 ((const gchar *) item + details.str.uOffset, -1, NULL, NULL, NULL);
break;
}
/* The extension of the name the Recycle Bin keeps @item under (Dc1.txt
* on XP, $R1A2B3C.txt later: that of the file), or NULL */
static gchar *
win32_bin_extension (IShellFolder2 *bin,
LPITEMIDLIST item)
{
STRRET name;
gchar *parsing, *dot, *result = NULL;
if (FAILED (IShellFolder2_GetDisplayNameOf (bin, item, SHGDN_INFOLDER | SHGDN_FORPARSING, &name)))
return NULL;
parsing = win32_strret (&name, item);
if (parsing && (dot = strrchr (parsing, '.')) != NULL &&
strchr (dot, '\\') == NULL && strchr (dot, '/') == NULL)
result = g_utf8_casefold (dot, -1);
g_free (parsing);
return result;
}
/* @usec of g_get_real_time() as a date of the shell: days since 30
* December 1899, of the local time */
static gdouble
win32_ole_date (gint64 usec)
{
GDateTime *local = g_date_time_new_from_unix_local (usec / G_USEC_PER_SEC);
GDate *day, *base;
gdouble result;
if (local == NULL)
return 0;
day = g_date_new_dmy (g_date_time_get_day_of_month (local),
g_date_time_get_month (local),
g_date_time_get_year (local));
base = g_date_new_dmy (30, G_DATE_DECEMBER, 1899);
result = g_date_days_between (base, day) +
(g_date_time_get_hour (local) * 3600 +
g_date_time_get_minute (local) * 60 +
g_date_time_get_second (local)) / 86400.0;
g_date_free (day);
g_date_free (base);
g_date_time_unref (local);
return result;
}
@ -1111,7 +1184,8 @@ win32_bin_restore (IShellFolder2 *bin,
CMINVOKECOMMANDINFO invoke = { 0 };
invoke.cbSize = sizeof (invoke);
invoke.fMask = CMIC_MASK_FLAG_NO_UI;
/* done when it returns (Vista and later; XP does it so) */
invoke.fMask = CMIC_MASK_FLAG_NO_UI | GTK_CMIC_MASK_NOASYNC;
invoke.lpVerb = MAKEINTRESOURCEA (id - 1);
invoke.nShow = SW_SHOWNORMAL;
result = SUCCEEDED (IContextMenu_InvokeCommand (menu, &invoke));
@ -1125,23 +1199,51 @@ win32_bin_restore (IShellFolder2 *bin,
}
/* Puts @file back from the Recycle Bin, as Restore there does: the item
* that came from its place, the one trashed last */
* that came from its place, trashed at @since or later, the last one;
* never over a file that is there now */
static gboolean
win32_restore_file (GFile *file,
gint64 since,
GError **error)
{
gchar *path = g_file_get_path (file);
HRESULT init = CoInitialize (NULL);
wchar_t *wpath = path ? g_utf8_to_utf16 (path, -1, NULL, NULL, NULL) : NULL;
gchar *extension = NULL;
HRESULT init;
IShellFolder *desktop = NULL;
IShellFolder2 *bin = NULL;
IEnumIDList *items = NULL;
LPITEMIDLIST bin_pidl = NULL, item, best = NULL;
gint best_match = 0;
gdouble best_date = 0;
gboolean done = FALSE;
gint best_match = 0, i;
gdouble best_date = 0, since_date;
gboolean done = FALSE, found = FALSE;
if (path &&
SUCCEEDED (SHGetDesktopFolder (&desktop)) &&
if (wpath == NULL)
{
g_free (path);
g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_INVALID_FILENAME, _("Invalid file name"));
return FALSE;
}
if (GetFileAttributesW (wpath) != INVALID_FILE_ATTRIBUTES)
{
g_free (wpath);
g_free (path);
g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_EXISTS, g_strerror (EEXIST));
return FALSE;
}
{
gchar *base = g_path_get_basename (path), *dot = strrchr (base, '.');
if (dot && dot != base)
extension = g_utf8_casefold (dot, -1);
g_free (base);
}
/* a little earlier, as the clocks round */
since_date = since > 0 ? win32_ole_date (since) - 2.0 / 86400 : 0;
init = CoInitialize (NULL);
if (SUCCEEDED (SHGetDesktopFolder (&desktop)) &&
SUCCEEDED (SHGetSpecialFolderLocation (NULL, CSIDL_BITBUCKET, &bin_pidl)) &&
SUCCEEDED (IShellFolder_BindToObject (desktop, bin_pidl, NULL, &gtk_IID_IShellFolder2, (void **) &bin)) &&
IShellFolder2_EnumObjects (bin, NULL, SHCONTF_FOLDERS | SHCONTF_NONFOLDERS | SHCONTF_INCLUDEHIDDEN, &items) == S_OK)
@ -1154,12 +1256,29 @@ win32_restore_file (GFile *file,
VARIANT date;
gdouble when = 0;
/* without its extension in the name: the one the Recycle Bin
* keeps it under tells, so that photo.jpg is not photo.png */
if (match == 1)
{
gchar *kept = win32_bin_extension (bin, item);
if (kept == NULL || extension == NULL || strcmp (kept, extension) != 0)
match = 0;
g_free (kept);
}
/* without oleaut32: PropVariantClear() of ole32 clears it */
memset (&date, 0, sizeof (date));
if (match > 0 &&
SUCCEEDED (IShellFolder2_GetDetailsEx (bin, item, &gtk_SCID_DateDeleted, &date)) &&
V_VT (&date) == VT_DATE)
when = V_DATE (&date);
{
when = V_DATE (&date);
/* trashed before: another file of that name, the one
* trashed was deleted for good after all */
if (since_date > 0 && when < since_date)
match = 0;
}
PropVariantClear ((PROPVARIANT *) &date);
/* the better name, then the later one (the order of the shell
@ -1181,12 +1300,15 @@ win32_restore_file (GFile *file,
if (best)
{
wchar_t *wpath = g_utf8_to_utf16 (path, -1, NULL, NULL, NULL);
if (win32_bin_restore (bin, best) && wpath &&
GetFileAttributesW (wpath) != INVALID_FILE_ATTRIBUTES)
done = TRUE;
g_free (wpath);
found = TRUE;
if (win32_bin_restore (bin, best))
/* the shell may be slow to say so */
for (i = 0; i < 20 && !done; i++)
{
done = GetFileAttributesW (wpath) != INVALID_FILE_ATTRIBUTES;
if (!done)
Sleep (100);
}
CoTaskMemFree (best);
}
@ -1200,12 +1322,14 @@ win32_restore_file (GFile *file,
IShellFolder_Release (desktop);
if (SUCCEEDED (init))
CoUninitialize ();
g_free (extension);
g_free (wpath);
g_free (path);
if (!done)
g_set_error_literal (error, G_IO_ERROR, best ? G_IO_ERROR_FAILED : G_IO_ERROR_NOT_FOUND,
best ? _("The shell could not put the file back from the Recycle Bin")
: _("It is no longer in the Trash."));
g_set_error_literal (error, G_IO_ERROR, found ? G_IO_ERROR_FAILED : G_IO_ERROR_NOT_FOUND,
found ? _("The shell could not put the file back from the Recycle Bin")
: _("It is no longer in the Trash."));
return done;
}
#endif
@ -1220,6 +1344,7 @@ typedef struct
GFile *trashed;
GError *error;
gboolean restore; /* Windows: put @file back */
gint64 since; /* trashed after that */
gboolean result;
gboolean handled;
gboolean finished;
@ -1234,7 +1359,7 @@ trash_in_main_loop (gpointer data)
if (call->restore)
{
call->handled = TRUE;
call->result = win32_restore_file (call->file, &call->error);
call->result = win32_restore_file (call->file, call->since, &call->error);
}
else
call->result = win32_trash_file (call->file, &call->handled, &call->error);
@ -1436,7 +1561,12 @@ restore_local (const gchar *path,
g_free (info_dir);
}
if (best_file)
if (best_file && g_file_test (path, G_FILE_TEST_EXISTS | G_FILE_TEST_IS_SYMLINK))
{
/* rename() would replace it */
g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_EXISTS, g_strerror (EEXIST));
}
else if (best_file)
{
if (g_rename (best_file, path) == 0)
{
@ -1468,7 +1598,8 @@ restore_local (const gchar *path,
static gboolean
restore_gvfs (GtkFileOperation *op,
GFile *original,
gboolean *found)
gboolean *found,
GError **error)
{
const gchar * const *schemes = g_vfs_get_supported_uri_schemes (g_vfs_get_default ());
gchar *path = g_file_get_path (original);
@ -1518,8 +1649,9 @@ restore_gvfs (GtkFileOperation *op,
if (best)
{
*found = TRUE;
/* not over what is there now */
done = g_file_move (best, original, G_FILE_COPY_NOFOLLOW_SYMLINKS,
op->cancellable, NULL, NULL, NULL);
op->cancellable, NULL, NULL, error);
g_object_unref (best);
}
@ -1536,6 +1668,7 @@ static gboolean
restore_from_trash (GtkFileOperation *op,
GFile *original,
GFile *trashed,
gint64 since,
GError **error)
{
if (trashed)
@ -1547,8 +1680,10 @@ restore_from_trash (GtkFileOperation *op,
gboolean found;
gchar *path;
if (restore_gvfs (op, original, &found))
return TRUE;
/* what GVfs found it says itself, without a second try that might
* overwrite what is there now */
if (restore_gvfs (op, original, &found, error) || found)
return found && (error == NULL || *error == NULL);
path = g_file_get_path (original);
if (path)
@ -1567,6 +1702,7 @@ restore_from_trash (GtkFileOperation *op,
call.op = op;
call.file = original;
call.restore = TRUE;
call.since = since;
gdk_threads_add_idle (trash_in_main_loop, &call);
g_mutex_lock (&op->mutex);
while (!call.finished)
@ -2355,14 +2491,18 @@ trash_all (GtkFileOperation *op)
GFile *trashed;
GError *error = NULL;
gboolean restorable;
gint64 before;
if (g_cancellable_is_cancelled (op->cancellable))
break;
set_current (op, l->data);
before = g_get_real_time ();
if (trash_file (op, l->data, &trashed, &restorable, &error))
{
note (op, STEP_TRASHED, l->data, trashed, NULL);
if (op->steps)
((Step *) op->steps->data)->time = before;
op->restorable = op->restorable && restorable;
}
else
@ -2444,7 +2584,7 @@ undo_step (GtkFileOperation *op,
case STEP_TRASHED:
set_current (op, step->source);
make_parent (op, step->source);
return restore_from_trash (op, step->source, step->target, error);
return restore_from_trash (op, step->source, step->target, step->time, error);
default:
g_assert_not_reached ();
@ -2459,8 +2599,9 @@ redo_step (GtkFileOperation *op,
GError **error)
{
GFileInfo *info;
GFile *trashed;
GFile *trashed = NULL;
gboolean restorable;
gint64 before;
switch (step->kind)
{
@ -2506,11 +2647,19 @@ redo_step (GtkFileOperation *op,
case STEP_TRASHED:
set_current (op, step->source);
before = g_get_real_time ();
if (!trash_file (op, step->source, &trashed, &restorable, error))
return FALSE;
{
if (trashed)
g_object_unref (trashed);
return FALSE;
}
if (step->target)
g_object_unref (step->target);
step->target = trashed;
step->time = before;
/* where it went must be known again for another Undo */
op->restorable = op->restorable && restorable;
return TRUE;
default:
@ -2530,6 +2679,7 @@ replay (GtkFileOperation *op)
steps = g_list_reverse (steps);
set_totals (op, 0, g_list_length (steps));
op->restorable = TRUE;
for (l = steps; l; l = l->next)
{
Step *step = l->data;
@ -2553,6 +2703,8 @@ replay (GtkFileOperation *op)
if (!go_on)
break;
}
/* gone through, also when skipped or cancelled in it */
op->replayed++;
add_done (op, 0, 1);
}
@ -2620,11 +2772,51 @@ keep_for_undo (GtkFileOperation *op)
switch (op->kind)
{
case GTK_FILE_OPERATION_UNDO:
undo_push (&redo_stack, op->replay);
return;
case GTK_FILE_OPERATION_REDO:
undo_push (&undo_stack, op->replay);
return;
{
gboolean undo = op->kind == GTK_FILE_OPERATION_UNDO;
GList **own = undo ? &undo_stack : &redo_stack;
GList **other = undo ? &redo_stack : &undo_stack;
UndoEntry *rest = op->replay, *done;
guint n = g_list_length (rest->steps);
GList *cut;
op->replay = NULL;
if (op->replayed == 0)
{
/* nothing done: as it was */
undo_push (own, rest);
return;
}
if (op->replayed >= n)
{
done = rest;
rest = NULL;
}
else
{
/* stopped halfway: what was gone through can be done the
* other way, the rest stays (Undo goes from the last step
* backwards, Redo from the first) */
done = undo_entry_new (rest->kind);
cut = g_list_nth (rest->steps, undo ? n - op->replayed : op->replayed);
cut->prev->next = NULL;
cut->prev = NULL;
if (undo)
done->steps = cut;
else
{
done->steps = rest->steps;
rest->steps = cut;
}
}
/* a Redo of the trash must know where things went again */
done->possible = undo ? TRUE : op->restorable;
if (rest)
undo_push (own, rest);
undo_push (other, done);
return;
}
default:
break;
}
@ -2665,6 +2857,7 @@ finish_in_main_loop (gpointer data)
/* a cancelled copy can be undone as well: what was copied goes */
keep_for_undo (op);
operations_running--;
if (op->done)
op->done (op, cancelled, op->all_moved && !cancelled, op->user_data);
@ -2712,6 +2905,7 @@ operation_start (GtkFileOperationKind kind,
op->show_id = gdk_threads_add_timeout (500, show_timeout, op);
op->update_id = gdk_threads_add_timeout (100, update_timeout, op);
operations_running++;
thread = g_thread_new ("gtk-file-operation", operation_thread, op);
g_thread_unref (thread);
@ -2750,7 +2944,8 @@ _gtk_file_operation_undo (gboolean redo,
g_return_val_if_fail (GTK_IS_BOX (box), NULL);
if (*stack == NULL || !((UndoEntry *) (*stack)->data)->possible)
/* one at a time, after what is being done */
if (*stack == NULL || !((UndoEntry *) (*stack)->data)->possible || operations_running > 0)
return NULL;
entry = (*stack)->data;