From 9d313a8816f6341a9da1a84975c30c95dec5340e Mon Sep 17 00:00:00 2001 From: Charles Kerr Date: Sun, 8 Nov 2020 21:31:02 -0600 Subject: [PATCH] sonarcloud warnings 9 (#1511) * refactor: const correctness * refactor: fix some implicit conversions * refactor: make local pointers const if their objects are not modified * refactor: do not cast away const in torrent-cell-renderer * refactor: remove call to deprecated gtk_icon_size_lookup_for_settings * refactor: member functions that do not mutate their objects should be declared const * chore: do not end comments with a semicolon --- gtk/filter.c | 19 +- gtk/icons.c | 11 +- gtk/main.c | 47 +- gtk/makemeta-ui.c | 2 +- gtk/notify.c | 13 +- gtk/torrent-cell-renderer.c | 22 +- gtk/tr-core.c | 15 +- gtk/tr-window.c | 7 +- gtk/util.c | 6 +- libtransmission/announcer.c | 13 +- libtransmission/blocklist.c | 3 +- libtransmission/cache.c | 2 +- libtransmission/file-posix.c | 2 +- libtransmission/handshake.c | 2 +- libtransmission/net.c | 6 +- libtransmission/peer-io.c | 2 +- libtransmission/peer-mgr.c | 20 +- libtransmission/peer-msgs.c | 11 +- libtransmission/platform-quota.c | 4 +- libtransmission/platform.c | 8 +- libtransmission/ptrarray.c | 2 +- libtransmission/quark.c | 7 +- libtransmission/resume.c | 4 +- libtransmission/session.c | 2 +- libtransmission/torrent.c | 2 +- libtransmission/tr-utp.c | 2 +- libtransmission/variant-json.c | 8 +- libtransmission/variant.c | 2 +- libtransmission/watchdir-inotify.c | 2 +- libtransmission/web.c | 4 +- libtransmission/webseed.c | 6 +- qt/ComInteropHelper.cc | 2 +- qt/ComInteropHelper.h | 2 +- qt/DBusInteropHelper.cc | 2 +- qt/DBusInteropHelper.h | 2 +- qt/DetailsDialog.cc | 63 +- qt/DetailsDialog.cc.orig | 1569 ++++++++++++++++++++++++++++ qt/DetailsDialog.h | 4 +- qt/FaviconCache.cc | 2 +- qt/FileTreeItem.cc | 4 +- qt/FileTreeItem.h | 2 +- qt/FileTreeView.cc | 43 +- qt/FilterBar.cc | 8 +- qt/Formatter.cc | 17 +- qt/Formatter.h | 1 + qt/InteropHelper.cc | 2 +- qt/InteropHelper.h | 2 +- qt/InteropObject.cc | 4 +- qt/InteropObject.h | 4 +- qt/MainWindow.cc | 40 +- qt/MainWindow.h | 12 +- qt/MakeDialog.cc | 7 +- qt/PathButton.cc | 2 +- qt/PathButton.h | 2 +- qt/Prefs.cc | 2 +- qt/Prefs.h | 2 +- qt/PrefsDialog.cc | 2 +- qt/PrefsDialog.h | 2 +- qt/RelocateDialog.cc | 2 +- qt/RelocateDialog.h | 2 +- qt/RpcClient.cc | 4 +- qt/RpcClient.h | 4 +- qt/RpcQueue.h | 12 +- qt/Session.cc | 4 +- qt/Session.h | 4 +- qt/SessionDialog.cc | 2 +- qt/SessionDialog.h | 2 +- qt/Torrent.h | 2 +- qt/TorrentDelegate.cc | 20 +- qt/TrackerDelegate.cc | 4 +- utils/edit.c | 13 +- utils/remote.c | 2 +- 72 files changed, 1838 insertions(+), 299 deletions(-) create mode 100644 qt/DetailsDialog.cc.orig diff --git a/gtk/filter.c b/gtk/filter.c index 7bc632e2d..e1d5ff48f 100644 --- a/gtk/filter.c +++ b/gtk/filter.c @@ -645,7 +645,7 @@ static void activity_model_update_idle(gpointer activity_model) } } -static void activity_torrent_model_row_changed(GtkTreeModel* tmodel, GtkTreePath* path, GtkTreeIter* iter, +static void activity_torrent_model_row_changed(GtkTreeModel const* tmodel, GtkTreePath const* path, GtkTreeIter const* iter, gpointer activity_model) { TR_UNUSED(tmodel); @@ -655,7 +655,7 @@ static void activity_torrent_model_row_changed(GtkTreeModel* tmodel, GtkTreePath activity_model_update_idle(activity_model); } -static void activity_torrent_model_row_deleted_cb(GtkTreeModel* tmodel, GtkTreePath* path, gpointer activity_model) +static void activity_torrent_model_row_deleted_cb(GtkTreeModel const* tmodel, GtkTreePath const* path, gpointer activity_model) { TR_UNUSED(tmodel); TR_UNUSED(path); @@ -726,16 +726,14 @@ static gboolean testText(tr_torrent const* tor, char const* key) tr_info const* inf = tr_torrentInfo(tor); /* test the torrent name... */ - { - char* pch = g_utf8_casefold(tr_torrentName(tor), -1); - ret = key == NULL || strstr(pch, key) != NULL; - g_free(pch); - } + char* pch = g_utf8_casefold(tr_torrentName(tor), -1); + ret = key == NULL || strstr(pch, key) != NULL; + g_free(pch); /* test the files... */ for (tr_file_index_t i = 0; i < inf->fileCount && !ret; ++i) { - char* pch = g_utf8_casefold(inf->files[i].name, -1); + pch = g_utf8_casefold(inf->files[i].name, -1); ret = key == NULL || strstr(pch, key) != NULL; g_free(pch); } @@ -916,7 +914,8 @@ static void update_count_label_idle(struct filter_data* data) } } -static void on_filter_model_row_inserted(GtkTreeModel* tree_model, GtkTreePath* path, GtkTreeIter* iter, gpointer data) +static void on_filter_model_row_inserted(GtkTreeModel const* tree_model, GtkTreePath const* path, GtkTreeIter const* iter, + gpointer data) { TR_UNUSED(tree_model); TR_UNUSED(path); @@ -925,7 +924,7 @@ static void on_filter_model_row_inserted(GtkTreeModel* tree_model, GtkTreePath* update_count_label_idle(data); } -static void on_filter_model_row_deleted(GtkTreeModel* tree_model, GtkTreePath* path, gpointer data) +static void on_filter_model_row_deleted(GtkTreeModel const* tree_model, GtkTreePath const* path, gpointer data) { TR_UNUSED(tree_model); TR_UNUSED(path); diff --git a/gtk/icons.c b/gtk/icons.c index 6ea93afa2..20654ef56 100644 --- a/gtk/icons.c +++ b/gtk/icons.c @@ -49,12 +49,11 @@ static GdkPixbuf* create_void_pixbuf(int width, int height) return p; } -static int get_size_in_pixels(GtkWidget* widget, GtkIconSize icon_size) +static int get_size_in_pixels(GtkIconSize icon_size) { - int width; - int height; - - gtk_icon_size_lookup_for_settings(gtk_widget_get_settings(widget), icon_size, &width, &height); + int width = 0; + int height = 0; + gtk_icon_size_lookup(icon_size, &width, &height); return MAX(width, height); } @@ -64,7 +63,7 @@ static IconCache* icon_cache_new(GtkWidget* for_widget, int icon_size) IconCache* icons = g_new0(IconCache, 1); icons->icon_theme = gtk_icon_theme_get_for_screen(gtk_widget_get_screen(for_widget)); - icons->icon_size = get_size_in_pixels(for_widget, icon_size); + icons->icon_size = get_size_in_pixels(icon_size); icons->cache = g_hash_table_new_full(g_str_hash, g_str_equal, NULL, g_object_unref); g_hash_table_insert(icons->cache, (void*)VOID_PIXBUF_KEY, create_void_pixbuf(icons->icon_size, diff --git a/gtk/main.c b/gtk/main.c index c2280af8e..44bf86a90 100644 --- a/gtk/main.c +++ b/gtk/main.c @@ -286,7 +286,7 @@ static void refresh_actions_soon(gpointer gdata) } } -static void on_selection_changed(GtkTreeSelection* s, gpointer gdata) +static void on_selection_changed(GtkTreeSelection const* s, gpointer gdata) { TR_UNUSED(s); @@ -332,7 +332,7 @@ static void ensure_magnet_handler_exists(void) } } -static void on_main_window_size_allocated(GtkWidget* gtk_window, GtkAllocation* alloc, gpointer gdata) +static void on_main_window_size_allocated(GtkWidget* gtk_window, GtkAllocation const* alloc, gpointer gdata) { TR_UNUSED(alloc); TR_UNUSED(gdata); @@ -409,7 +409,7 @@ static gboolean on_rpc_changed_idle(gpointer gdata) for (int i = 0; tr_variantDictChild(&tmp, i, &key, &newval); ++i) { bool changed; - tr_variant* oldval = tr_variantDictFind(oldvals, key); + tr_variant const* oldval = tr_variantDictFind(oldvals, key); if (oldval == NULL) { @@ -591,7 +591,7 @@ static void open_files(GSList* files, gpointer gdata) gtr_core_add_files(cbdata->core, files, do_start, do_prompt, do_notify); } -static void on_open(GApplication* application, GFile** f, gint file_count, gchar* hint, gpointer gdata) +static void on_open(GApplication const* application, GFile** f, gint file_count, gchar const* hint, gpointer gdata) { TR_UNUSED(application); TR_UNUSED(hint); @@ -699,16 +699,16 @@ int main(int argc, char** argv) return ret; } -static void on_core_busy(TrCore* core, gboolean busy, struct cbdata* c) +static void on_core_busy(TrCore const* core, gboolean busy, struct cbdata* c) { TR_UNUSED(core); gtr_window_set_busy(c->wind, busy); } -static void on_core_error(TrCore*, guint, char const*, struct cbdata*); +static void on_core_error(TrCore const*, guint, char const*, struct cbdata*); static void on_add_torrent(TrCore*, tr_ctor*, gpointer); -static void on_prefs_changed(TrCore* core, tr_quark const key, gpointer); +static void on_prefs_changed(TrCore const* core, tr_quark const key, gpointer); static void main_window_setup(struct cbdata* cbdata, GtkWindow* wind); static gboolean update_model_loop(gpointer gdata); static gboolean update_model_once(gpointer gdata); @@ -777,6 +777,14 @@ static void app_setup(GtkWindow* wind, struct cbdata* cbdata) } } +static void placeWindowFromPrefs(GtkWindow* window) +{ + gtk_window_resize(window, (int)gtr_pref_int_get(TR_KEY_main_window_width), + (int)gtr_pref_int_get(TR_KEY_main_window_height)); + gtk_window_move(window, (int)gtr_pref_int_get(TR_KEY_main_window_x), + (int)gtr_pref_int_get(TR_KEY_main_window_y)); +} + static void presentMainWindow(struct cbdata* cbdata) { GtkWindow* window = cbdata->wind; @@ -790,8 +798,7 @@ static void presentMainWindow(struct cbdata* cbdata) if (!gtk_widget_get_visible(GTK_WIDGET(window))) { - gtk_window_resize(window, gtr_pref_int_get(TR_KEY_main_window_width), gtr_pref_int_get(TR_KEY_main_window_height)); - gtk_window_move(window, gtr_pref_int_get(TR_KEY_main_window_x), gtr_pref_int_get(TR_KEY_main_window_y)); + placeWindowFromPrefs(window); gtr_widget_set_visible(GTK_WIDGET(window), TRUE); } @@ -821,7 +828,7 @@ static void toggleMainWindow(struct cbdata* cbdata) static void on_app_exit(gpointer vdata); -static gboolean winclose(GtkWidget* w, GdkEvent* event, gpointer gdata) +static gboolean winclose(GtkWidget const* w, GdkEvent const* event, gpointer gdata) { TR_UNUSED(w); TR_UNUSED(event); @@ -840,7 +847,7 @@ static gboolean winclose(GtkWidget* w, GdkEvent* event, gpointer gdata) return TRUE; /* don't propagate event further */ } -static void rowChangedCB(GtkTreeModel* model, GtkTreePath* path, GtkTreeIter* iter, gpointer gdata) +static void rowChangedCB(GtkTreeModel const* model, GtkTreePath* path, GtkTreeIter const* iter, gpointer gdata) { TR_UNUSED(model); TR_UNUSED(iter); @@ -853,8 +860,8 @@ static void rowChangedCB(GtkTreeModel* model, GtkTreePath* path, GtkTreeIter* it } } -static void on_drag_data_received(GtkWidget* widget, GdkDragContext* drag_context, gint x, gint y, - GtkSelectionData* selection_data, guint info, guint time_, gpointer gdata) +static void on_drag_data_received(GtkWidget const* widget, GdkDragContext* drag_context, gint x, gint y, + GtkSelectionData const* selection_data, guint info, guint time_, gpointer gdata) { TR_UNUSED(widget); TR_UNUSED(x); @@ -956,11 +963,8 @@ static gpointer session_close_threadfunc(gpointer gdata) return NULL; } -static void exit_now_cb(GtkWidget* w, gpointer data) +static void exit_now_cb() { - TR_UNUSED(w); - TR_UNUSED(data); - exit(0); } @@ -1027,8 +1031,7 @@ static void on_app_exit(gpointer vdata) /* ensure the window is in its previous position & size. * this seems to be necessary because changing the main window's * child seems to unset the size */ - gtk_window_resize(cbdata->wind, gtr_pref_int_get(TR_KEY_main_window_width), gtr_pref_int_get(TR_KEY_main_window_height)); - gtk_window_move(cbdata->wind, gtr_pref_int_get(TR_KEY_main_window_x), gtr_pref_int_get(TR_KEY_main_window_y)); + placeWindowFromPrefs(cbdata->wind); /* shut down libT */ session_close_data = g_new(struct session_close_struct, 1); @@ -1074,7 +1077,7 @@ static void flush_torrent_errors(struct cbdata* cbdata) } } -static void on_core_error(TrCore* core, guint code, char const* msg, struct cbdata* c) +static void on_core_error(TrCore const* core, guint code, char const* msg, struct cbdata* c) { TR_UNUSED(core); @@ -1098,7 +1101,7 @@ static void on_core_error(TrCore* core, guint code, char const* msg, struct cbda } } -static gboolean on_main_window_focus_in(GtkWidget* widget, GdkEventFocus* event, gpointer gdata) +static gboolean on_main_window_focus_in(GtkWidget const* widget, GdkEventFocus const* event, gpointer gdata) { TR_UNUSED(widget); TR_UNUSED(event); @@ -1128,7 +1131,7 @@ static void on_add_torrent(TrCore* core, tr_ctor* ctor, gpointer gdata) gtk_widget_show(w); } -static void on_prefs_changed(TrCore* core, tr_quark const key, gpointer data) +static void on_prefs_changed(TrCore const* core, tr_quark const key, gpointer data) { TR_UNUSED(core); diff --git a/gtk/makemeta-ui.c b/gtk/makemeta-ui.c index 628bde6ef..5273752cc 100644 --- a/gtk/makemeta-ui.c +++ b/gtk/makemeta-ui.c @@ -130,7 +130,7 @@ static void onProgressDialogDestroyed(gpointer data, GObject* dead) { TR_UNUSED(dead); - MakeMetaUI* ui = data; + MakeMetaUI const* ui = data; g_source_remove(ui->progress_tag); } diff --git a/gtk/notify.c b/gtk/notify.c index 3383b1714..594a9f867 100644 --- a/gtk/notify.c +++ b/gtk/notify.c @@ -102,16 +102,13 @@ static void g_signal_callback(GDBusProxy const* dbus_proxy, char const* sender_n } else if (g_strcmp0(signal_name, "ActionInvoked") == 0 && g_variant_is_of_type(params, G_VARIANT_TYPE("(us)"))) { - char* action; - tr_torrent* tor; - - tor = gtr_core_find_torrent(n->core, n->torrent_id); - + tr_torrent const* tor = gtr_core_find_torrent(n->core, n->torrent_id); if (tor == NULL) { return; } + char* action = NULL; g_variant_get(params, "(u&s)", NULL, &action); if (g_strcmp0(action, "folder") == 0) @@ -180,8 +177,6 @@ static void notify_callback(GObject* source, GAsyncResult* res, gpointer user_da void gtr_notify_torrent_completed(TrCore* core, int torrent_id) { - TrNotification* n; - tr_torrent* tor; char const* cmd = gtr_pref_string_get(TR_KEY_torrent_complete_sound_command); if (gtr_pref_flag_get(TR_KEY_torrent_complete_sound_enabled)) @@ -196,9 +191,9 @@ void gtr_notify_torrent_completed(TrCore* core, int torrent_id) g_return_if_fail(G_IS_DBUS_PROXY(proxy)); - tor = gtr_core_find_torrent(core, torrent_id); + tr_torrent const* const tor = gtr_core_find_torrent(core, torrent_id); - n = g_new0(TrNotification, 1); + TrNotification* const n = g_new0(TrNotification, 1); g_object_ref(G_OBJECT(core)); n->core = core; n->torrent_id = torrent_id; diff --git a/gtk/torrent-cell-renderer.c b/gtk/torrent-cell-renderer.c index 4d38f0fbf..75a7c499c 100644 --- a/gtk/torrent-cell-renderer.c +++ b/gtk/torrent-cell-renderer.c @@ -383,8 +383,8 @@ static void get_size_compact(TorrentCellRenderer* cell, GtkWidget* widget, gint* GdkPixbuf* icon; struct TorrentCellRendererPrivate* p = cell->priv; - tr_torrent const* tor = p->tor; - tr_stat const* st = tr_torrentStatCached((tr_torrent*)tor); + tr_torrent* tor = p->tor; + tr_stat const* st = tr_torrentStatCached(tor); GString* gstr_stat = p->gstr1; icon = get_icon(tor, COMPACT_ICON_SIZE, widget); @@ -433,8 +433,8 @@ static void get_size_full(TorrentCellRenderer* cell, GtkWidget* widget, gint* wi GdkPixbuf* icon; struct TorrentCellRendererPrivate* p = cell->priv; - tr_torrent const* tor = p->tor; - tr_stat const* st = tr_torrentStatCached((tr_torrent*)tor); + tr_torrent* tor = p->tor; + tr_stat const* st = tr_torrentStatCached(tor); tr_info const* inf = tr_torrentInfo(tor); GString* gstr_prog = p->gstr1; GString* gstr_stat = p->gstr2; @@ -480,13 +480,13 @@ static void get_size_full(TorrentCellRenderer* cell, GtkWidget* widget, gint* wi static void torrent_cell_renderer_get_size(GtkCellRenderer* cell, GtkWidget* widget, GdkRectangle const* cell_area, gint* x_offset, gint* y_offset, gint* width, gint* height) { - TorrentCellRenderer* self = TORRENT_CELL_RENDERER(cell); + TorrentCellRenderer const* const self = TORRENT_CELL_RENDERER(cell); if (self != NULL && self->priv->tor != NULL) { int w; int h; - struct TorrentCellRendererPrivate* p = self->priv; + struct TorrentCellRendererPrivate const* const p = self->priv; if (p->compact) { @@ -588,8 +588,8 @@ static void render_compact(TorrentCellRenderer* cell, GtrDrawable* window, GtkWi bool seed; struct TorrentCellRendererPrivate* p = cell->priv; - tr_torrent const* tor = p->tor; - tr_stat const* st = tr_torrentStatCached((tr_torrent*)tor); + tr_torrent* tor = p->tor; + tr_stat const* st = tr_torrentStatCached(tor); gboolean const active = st->activity != TR_STATUS_STOPPED && st->activity != TR_STATUS_DOWNLOAD_WAIT && st->activity != TR_STATUS_SEED_WAIT; double const percentDone = get_percent_done(tor, st, &seed); @@ -666,8 +666,8 @@ static void render_full(TorrentCellRenderer* cell, GtrDrawable* window, GtkWidge bool seed; struct TorrentCellRendererPrivate* p = cell->priv; - tr_torrent const* tor = p->tor; - tr_stat const* st = tr_torrentStatCached((tr_torrent*)tor); + tr_torrent* tor = p->tor; + tr_stat const* st = tr_torrentStatCached(tor); tr_info const* inf = tr_torrentInfo(tor); gboolean const active = st->activity != TR_STATUS_STOPPED && st->activity != TR_STATUS_DOWNLOAD_WAIT && st->activity != TR_STATUS_SEED_WAIT; @@ -772,7 +772,7 @@ static void torrent_cell_renderer_render(GtkCellRenderer* cell, GtrDrawable* win if (self != NULL && self->priv->tor != NULL) { - struct TorrentCellRendererPrivate* p = self->priv; + struct TorrentCellRendererPrivate const* const p = self->priv; if (p->compact) { diff --git a/gtk/tr-core.c b/gtk/tr-core.c index f209b25aa..4438b61e7 100644 --- a/gtk/tr-core.c +++ b/gtk/tr-core.c @@ -1023,15 +1023,15 @@ static gboolean find_row_from_torrent_id(GtkTreeModel* model, int id, GtkTreeIte static gboolean on_torrent_metadata_changed_idle(gpointer gdata) { - struct notify_callback_data* data = gdata; - tr_session* session = gtr_core_session(data->core); - tr_torrent* tor = tr_torrentFindFromId(session, data->torrent_id); + struct notify_callback_data* const data = gdata; + tr_session* const session = gtr_core_session(data->core); + tr_torrent const* const tor = tr_torrentFindFromId(session, data->torrent_id); /* update the torrent's collated name */ if (tor != NULL) { GtkTreeIter iter; - GtkTreeModel* model = core_raw_model(data->core); + GtkTreeModel* const model = core_raw_model(data->core); if (find_row_from_torrent_id(model, data->torrent_id, &iter)) { @@ -1124,15 +1124,14 @@ void gtr_core_add_torrent(TrCore* core, tr_torrent* tor, gboolean do_notify) static tr_torrent* core_create_new_torrent(TrCore* core, tr_ctor* ctor) { - tr_torrent* tor; bool do_trash = false; - tr_session* session = gtr_core_session(core); + tr_session const* const session = gtr_core_session(core); /* let the gtk client handle the removal, since libT * doesn't have any concept of the glib trash API */ tr_ctorGetDeleteSource(ctor, &do_trash); tr_ctorSetDeleteSource(ctor, FALSE); - tor = tr_torrentNew(ctor, NULL, NULL); + tr_torrent* const tor = tr_torrentNew(ctor, NULL, NULL); if (tor != NULL && do_trash) { @@ -1266,7 +1265,7 @@ static void add_file_async_callback(GObject* file, GAsyncResult* result, gpointe static bool add_file(TrCore* core, GFile* file, gboolean do_start, gboolean do_prompt, gboolean do_notify) { bool handled = false; - tr_session* session = gtr_core_session(core); + tr_session const* const session = gtr_core_session(core); if (session != NULL) { diff --git a/gtk/tr-window.c b/gtk/tr-window.c index eb0417143..5cea452d1 100644 --- a/gtk/tr-window.c +++ b/gtk/tr-window.c @@ -766,16 +766,15 @@ GtkWidget* gtr_window_new(GtkApplication* app, GtkUIManager* ui_mgr, TrCore* cor static void updateStats(PrivateData* p) { - char const* pch; char up[32]; char down[32]; char ratio[32]; char buf[512]; struct tr_session_stats stats; - tr_session* session = gtr_core_session(p->core); + tr_session const* const session = gtr_core_session(p->core); /* update the stats */ - pch = gtr_pref_string_get(TR_KEY_statusbar_stats); + char const* pch = gtr_pref_string_get(TR_KEY_statusbar_stats); if (g_strcmp0(pch, "session-ratio") == 0) { @@ -815,7 +814,7 @@ static void updateStats(PrivateData* p) static void updateSpeeds(PrivateData* p) { - tr_session* session = gtr_core_session(p->core); + tr_session const* const session = gtr_core_session(p->core); if (session != NULL) { diff --git a/gtk/util.c b/gtk/util.c index aed918dda..bc320f892 100644 --- a/gtk/util.c +++ b/gtk/util.c @@ -369,7 +369,7 @@ bool gtr_file_trash_or_remove(char const* filename, tr_error** error) char const* gtr_get_help_uri(void) { - static char* uri = NULL; + static char const* uri = NULL; if (uri == NULL) { @@ -534,7 +534,7 @@ void gtr_widget_set_visible(GtkWidget* w, gboolean b) if (GTK_IS_WINDOW(w)) { GList* windows = gtk_window_list_toplevels(); - GtkWindow* window = GTK_WINDOW(w); + GtkWindow const* const window = GTK_WINDOW(w); for (GList* l = windows; l != NULL; l = l->next) { @@ -621,7 +621,7 @@ void gtr_paste_clipboard_url_into_entry(GtkWidget* e) for (size_t i = 0; i < G_N_ELEMENTS(text); ++i) { - char* s = text[i]; + char const* const s = text[i]; if (s != NULL && (gtr_is_supported_url(s) || gtr_is_magnet_link(s) || gtr_is_hex_hashcode(s))) { diff --git a/libtransmission/announcer.c b/libtransmission/announcer.c index 43cce46ad..91a0543c2 100644 --- a/libtransmission/announcer.c +++ b/libtransmission/announcer.c @@ -779,7 +779,7 @@ bool tr_announcerCanManualAnnounce(tr_torrent const* tor) TR_ASSERT(tr_isTorrent(tor)); TR_ASSERT(tor->tiers != NULL); - struct tr_torrent_tiers* tt = NULL; + struct tr_torrent_tiers const* tt = NULL; if (tor->isRunning) { @@ -801,7 +801,7 @@ bool tr_announcerCanManualAnnounce(tr_torrent const* tor) time_t tr_announcerNextManualAnnounce(tr_torrent const* tor) { time_t ret = ~(time_t)0; - struct tr_torrent_tiers* tt = tor->tiers; + struct tr_torrent_tiers const* tt = tor->tiers; /* find the earliest manual announce time from all peers */ for (int i = 0; tt != NULL && i < tt->tier_count; ++i) @@ -989,13 +989,13 @@ static void announce_request_free(tr_announce_request* req); void tr_announcerRemoveTorrent(tr_announcer* announcer, tr_torrent* tor) { - struct tr_torrent_tiers* tt = tor->tiers; + struct tr_torrent_tiers const* tt = tor->tiers; if (tt != NULL) { for (int i = 0; i < tt->tier_count; ++i) { - tr_tier* tier = &tt->tiers[i]; + tr_tier const* tier = &tt->tiers[i]; if (tier->isRunning) { @@ -1767,12 +1767,11 @@ tr_tracker_stat* tr_announcerStats(tr_torrent const* torrent, int* setmeTrackerC time_t const now = tr_time(); int out = 0; - tr_tracker_stat* ret; - struct tr_torrent_tiers* tt = torrent->tiers; + struct tr_torrent_tiers const* const tt = torrent->tiers; /* alloc the stats */ *setmeTrackerCount = tt->tracker_count; - ret = tr_new0(tr_tracker_stat, tt->tracker_count); + tr_tracker_stat* const ret = tr_new0(tr_tracker_stat, tt->tracker_count); /* populate the stats */ for (int i = 0; i < tt->tier_count; ++i) diff --git a/libtransmission/blocklist.c b/libtransmission/blocklist.c index e9d054c3b..b6942fc43 100644 --- a/libtransmission/blocklist.c +++ b/libtransmission/blocklist.c @@ -221,13 +221,12 @@ bool tr_blocklistFileHasAddress(tr_blocklistFile* b, tr_address const* addr) */ static bool parseLine1(char const* line, struct tr_ipv4_range* range) { - char* walk; int b[4]; int e[4]; char str[64]; tr_address addr; - walk = strrchr(line, ':'); + char const* walk = strrchr(line, ':'); if (walk == NULL) { diff --git a/libtransmission/cache.c b/libtransmission/cache.c index 384ec4ccf..db2fa9261 100644 --- a/libtransmission/cache.c +++ b/libtransmission/cache.c @@ -365,7 +365,7 @@ int tr_cacheReadBlock(tr_cache* cache, tr_torrent* torrent, tr_piece_index_t pie int tr_cachePrefetchBlock(tr_cache* cache, tr_torrent* torrent, tr_piece_index_t piece, uint32_t offset, uint32_t len) { int err = 0; - struct cache_block* cb = findBlock(cache, torrent, piece, offset); + struct cache_block const* const cb = findBlock(cache, torrent, piece, offset); if (cb == NULL) { diff --git a/libtransmission/file-posix.c b/libtransmission/file-posix.c index 59856e93a..08c9277cc 100644 --- a/libtransmission/file-posix.c +++ b/libtransmission/file-posix.c @@ -1190,7 +1190,7 @@ char const* tr_sys_dir_read_name(tr_sys_dir_t handle, tr_error** error) char const* ret = NULL; errno = 0; - struct dirent* entry = readdir((DIR*)handle); + struct dirent const* const entry = readdir((DIR*)handle); if (entry != NULL) { diff --git a/libtransmission/handshake.c b/libtransmission/handshake.c index bc88f5bcd..7b5471c33 100644 --- a/libtransmission/handshake.c +++ b/libtransmission/handshake.c @@ -798,7 +798,6 @@ static ReadState readCryptoProvide(tr_handshake* handshake, struct evbuffer* inb uint8_t obfuscatedTorrentHash[SHA_DIGEST_LENGTH]; uint16_t padc_len = 0; uint32_t crypto_provide = 0; - tr_torrent* tor; size_t const needlen = SHA_DIGEST_LENGTH + /* HASH('req1', s) */ SHA_DIGEST_LENGTH + /* HASH('req2', SKEY) xor HASH('req3', S) */ VC_LENGTH + sizeof(crypto_provide) + sizeof(padc_len); @@ -823,6 +822,7 @@ static ReadState readCryptoProvide(tr_handshake* handshake, struct evbuffer* inb obfuscatedTorrentHash[i] = req2[i] ^ req3[i]; } + tr_torrent const* tor; if ((tor = tr_torrentFindFromObfuscatedHash(handshake->session, obfuscatedTorrentHash)) != NULL) { bool const clientIsSeed = tr_torrentIsSeed(tor); diff --git a/libtransmission/net.c b/libtransmission/net.c index 2be92a48a..2f65e27e2 100644 --- a/libtransmission/net.c +++ b/libtransmission/net.c @@ -636,7 +636,7 @@ static int tr_globalAddress(int af, void* addr, int* addr_len) socklen_t sslen = sizeof(ss); struct sockaddr_in sin; struct sockaddr_in6 sin6; - struct sockaddr* sa; + struct sockaddr const* sa; socklen_t salen; int rc; @@ -647,7 +647,7 @@ static int tr_globalAddress(int af, void* addr, int* addr_len) sin.sin_family = AF_INET; evutil_inet_pton(AF_INET, "91.121.74.28", &sin.sin_addr); sin.sin_port = htons(6969); - sa = (struct sockaddr*)&sin; + sa = (struct sockaddr const*)&sin; salen = sizeof(sin); break; @@ -658,7 +658,7 @@ static int tr_globalAddress(int af, void* addr, int* addr_len) a native IPv6 address, not Teredo or 6to4. */ evutil_inet_pton(AF_INET6, "2001:1890:1112:1::20", &sin6.sin6_addr); sin6.sin6_port = htons(6969); - sa = (struct sockaddr*)&sin6; + sa = (struct sockaddr const*)&sin6; salen = sizeof(sin6); break; diff --git a/libtransmission/peer-io.c b/libtransmission/peer-io.c index b9e987864..15cef7a88 100644 --- a/libtransmission/peer-io.c +++ b/libtransmission/peer-io.c @@ -489,7 +489,7 @@ static void utp_on_write(void* closure, unsigned char* buf, size_t buflen) static size_t utp_get_rb_size(void* closure) { - tr_peerIo* io = closure; + tr_peerIo const* const io = closure; TR_ASSERT(tr_isPeerIo(io)); diff --git a/libtransmission/peer-mgr.c b/libtransmission/peer-mgr.c index 78eceb41c..99de75453 100644 --- a/libtransmission/peer-mgr.c +++ b/libtransmission/peer-mgr.c @@ -444,7 +444,7 @@ static void replicationNew(tr_swarm* s) for (int peer_i = 0; peer_i < n; ++peer_i) { - tr_peer* peer = tr_ptrArrayNth(&s->peers, peer_i); + tr_peer const* const peer = tr_ptrArrayNth(&s->peers, peer_i); if (tr_bitfieldHas(&peer->have, piece_i)) { @@ -1113,10 +1113,10 @@ static void pieceListRebuild(tr_swarm* s) * the new list so we don't lose its requestCounts */ if (s->pieces != NULL) { - struct weighted_piece* o = s->pieces; - struct weighted_piece* oend = o + s->pieceCount; + struct weighted_piece const* o = s->pieces; + struct weighted_piece const* const oend = o + s->pieceCount; struct weighted_piece* n = pieces; - struct weighted_piece* nend = n + pieceCount; + struct weighted_piece const* const nend = n + pieceCount; pieceListSort(s, PIECES_SORTED_BY_INDEX); @@ -1151,7 +1151,7 @@ static void pieceListRebuild(tr_swarm* s) static void pieceListRemovePiece(tr_swarm* s, tr_piece_index_t piece) { - struct weighted_piece* p; + struct weighted_piece const* p; if ((p = pieceListLookup(s, piece)) != NULL) { @@ -1541,7 +1541,7 @@ static void refillUpkeep(evutil_socket_t fd, short what, void* vmgr) for (int i = 0; i < n; ++i) { struct block_request const* const request = &s->requests[i]; - tr_peerMsgs* msgs = PEER_MSGS(request->peer); + tr_peerMsgs const* const msgs = PEER_MSGS(request->peer); if (msgs != NULL && request->sentAt <= too_old && !tr_peerMsgsIsReadingBlock(msgs, request->block)) { @@ -2094,7 +2094,7 @@ static bool myHandshakeDoneCB(tr_handshake* handshake, tr_peerIo* io, bool readA } else { - tr_peer* peer = atom->peer; + tr_peer const* const peer = atom->peer; if (peer != NULL) { @@ -2789,7 +2789,7 @@ struct tr_peer_stat* tr_peerMgrPeerStats(tr_torrent const* tor, int* setmeCount) { char* pch; tr_peer* peer = peers[i]; - tr_peerMsgs* msgs = PEER_MSGS(peer); + tr_peerMsgs const* const msgs = PEER_MSGS(peer); struct peer_atom const* atom = peer->atom; tr_peer_stat* stat = ret + i; @@ -3675,8 +3675,8 @@ static void enforceTorrentPeerLimit(tr_swarm* s, uint64_t now) if (n > max) { - void* base = tr_ptrArrayBase(&s->peers); - tr_peer** peers = tr_memdup(base, n * sizeof(tr_peer*)); + void const* const base = tr_ptrArrayBase(&s->peers); + tr_peer** const peers = tr_memdup(base, n * sizeof(tr_peer*)); sortPeersByLiveliness(peers, NULL, n, now); while (n > max) diff --git a/libtransmission/peer-msgs.c b/libtransmission/peer-msgs.c index 711c954e0..e0b8b11a5 100644 --- a/libtransmission/peer-msgs.c +++ b/libtransmission/peer-msgs.c @@ -1065,17 +1065,16 @@ static void parseLtepHandshake(tr_peerMsgs* msgs, uint32_t len, struct evbuffer* static void parseUtMetadata(tr_peerMsgs* msgs, uint32_t msglen, struct evbuffer* inbuf) { - tr_variant dict; - char* msg_end; - char const* benc_end; int64_t msg_type = -1; int64_t piece = -1; int64_t total_size = 0; - uint8_t* tmp = tr_new(uint8_t, msglen); + uint8_t* const tmp = tr_new(uint8_t, msglen); tr_peerIoReadBytes(msgs->io, inbuf, tmp, msglen); - msg_end = (char*)tmp + msglen; + char const* const msg_end = (char const*)tmp + msglen; + tr_variant dict; + char const* benc_end; if (tr_variantFromBencFull(&dict, tmp, msglen, NULL, &benc_end) == 0) { (void)tr_variantDictFindInt(&dict, TR_KEY_msg_type, &msg_type); @@ -1883,7 +1882,7 @@ bool tr_peerMsgsIsReadingBlock(tr_peerMsgs const* msgs, tr_block_index_t block) static void updateDesiredRequestCount(tr_peerMsgs* msgs) { - tr_torrent* const torrent = msgs->torrent; + tr_torrent const* const torrent = msgs->torrent; /* there are lots of reasons we might not want to request any blocks... */ if (tr_torrentIsSeed(torrent) || !tr_torrentHasMetadata(torrent) || msgs->client_is_choked || !msgs->client_is_interested) diff --git a/libtransmission/platform-quota.c b/libtransmission/platform-quota.c index dbc220234..1bc081220 100644 --- a/libtransmission/platform-quota.c +++ b/libtransmission/platform-quota.c @@ -105,7 +105,7 @@ static char const* getdev(char const* path) #else - struct mntent* mnt; + struct mntent const* mnt; fp = setmntent(_PATH_MOUNTED, "r"); @@ -181,7 +181,7 @@ static char const* getfstype(char const* device) #else - struct mntent* mnt; + struct mntent const* mnt; fp = setmntent(_PATH_MOUNTED, "r"); diff --git a/libtransmission/platform.c b/libtransmission/platform.c index 2b079c924..288ba21de 100644 --- a/libtransmission/platform.c +++ b/libtransmission/platform.c @@ -253,7 +253,7 @@ static char* win32_get_known_folder(REFKNOWNFOLDERID folder_id) static char const* getHomeDir(void) { - static char* home = NULL; + static char const* home = NULL; if (home == NULL) { @@ -328,7 +328,7 @@ char const* tr_getResumeDir(tr_session const* session) char const* tr_getDefaultConfigDir(char const* appname) { - static char* s = NULL; + static char const* s = NULL; if (tr_str_is_empty(appname)) { @@ -380,7 +380,7 @@ char const* tr_getDefaultConfigDir(char const* appname) char const* tr_getDefaultDownloadDir(void) { - static char* user_dir = NULL; + static char const* user_dir = NULL; if (user_dir == NULL) { @@ -477,7 +477,7 @@ static bool isWebClientDir(char const* path) char const* tr_getWebClientDir(tr_session const* session) { - static char* s = NULL; + static char const* s = NULL; if (s == NULL) { diff --git a/libtransmission/ptrarray.c b/libtransmission/ptrarray.c index 1d09aad98..9dad4c8c0 100644 --- a/libtransmission/ptrarray.c +++ b/libtransmission/ptrarray.c @@ -242,7 +242,7 @@ static void* tr_ptrArrayRemoveSortedValue(tr_ptrArray* t, void const* ptr, tr_vo void tr_ptrArrayRemoveSortedPointer(tr_ptrArray* t, void const* ptr, tr_voidptr_compare_func compare) { - void* removed = tr_ptrArrayRemoveSortedValue(t, ptr, compare); + void const* removed = tr_ptrArrayRemoveSortedValue(t, ptr, compare); #ifndef TR_ENABLE_ASSERTS diff --git a/libtransmission/quark.c b/libtransmission/quark.c index 27e131d70..b0b1bd8c2 100644 --- a/libtransmission/quark.c +++ b/libtransmission/quark.c @@ -436,19 +436,16 @@ static tr_ptrArray my_runtime = TR_PTR_ARRAY_INIT_STATIC; bool tr_quark_lookup(void const* str, size_t len, tr_quark* setme) { static size_t const n_static = TR_N_ELEMENTS(my_static); - TR_ASSERT(n_static == TR_N_KEYS); struct tr_key_struct tmp; - struct tr_key_struct* match; - bool success = false; - tmp.str = str; tmp.len = len; /* is it in our static array? */ - match = bsearch(&tmp, my_static, n_static, sizeof(struct tr_key_struct), compareKeys); + struct tr_key_struct const* const match = bsearch(&tmp, my_static, n_static, sizeof(struct tr_key_struct), compareKeys); + bool success = false; if (match != NULL) { *setme = match - my_static; diff --git a/libtransmission/resume.c b/libtransmission/resume.c index 7ce09ead7..bbc0fe698 100644 --- a/libtransmission/resume.c +++ b/libtransmission/resume.c @@ -666,8 +666,8 @@ static uint64_t loadProgress(tr_variant* dict, tr_torrent* tor) err = NULL; tr_bitfieldConstruct(&blocks, tor->blockCount); - tr_variant* b; - if ((b = tr_variantDictFind(prog, TR_KEY_blocks)) != NULL) + tr_variant const* const b = tr_variantDictFind(prog, TR_KEY_blocks); + if (b != NULL) { size_t buflen; uint8_t const* buf; diff --git a/libtransmission/session.c b/libtransmission/session.c index 8845ccc53..5ee1001c5 100644 --- a/libtransmission/session.c +++ b/libtransmission/session.c @@ -729,7 +729,7 @@ static void loadBlocklists(tr_session* session); static void tr_sessionInitImpl(void* vdata) { struct init_data* data = vdata; - tr_variant* clientSettings = data->clientSettings; + tr_variant const* const clientSettings = data->clientSettings; tr_session* session = data->session; TR_ASSERT(tr_amInEventThread(session)); diff --git a/libtransmission/torrent.c b/libtransmission/torrent.c index 1dd2bc16d..4252423f0 100644 --- a/libtransmission/torrent.c +++ b/libtransmission/torrent.c @@ -787,7 +787,7 @@ static void refreshCurrentDir(tr_torrent* tor); static void torrentInitFromInfo(tr_torrent* tor) { uint64_t t; - tr_info* info = &tor->info; + tr_info const* const info = &tor->info; tor->blockSize = tr_getBlockSize(info->pieceSize); diff --git a/libtransmission/tr-utp.c b/libtransmission/tr-utp.c index 7c30ac69f..9432e6142 100644 --- a/libtransmission/tr-utp.c +++ b/libtransmission/tr-utp.c @@ -133,7 +133,7 @@ static void incoming(void* closure, struct UTPSocket* s) void tr_utpSendTo(void* closure, unsigned char const* buf, size_t buflen, struct sockaddr const* to, socklen_t tolen) { - tr_session* ss = closure; + tr_session const* const ss = closure; if (to->sa_family == AF_INET && ss->udp_socket != TR_BAD_SOCKET) { diff --git a/libtransmission/variant-json.c b/libtransmission/variant-json.c index 8d191ab10..ddaca77b4 100644 --- a/libtransmission/variant-json.c +++ b/libtransmission/variant-json.c @@ -557,21 +557,19 @@ static void jsonStringFunc(tr_variant const* val, void* vdata) { char* out; char* outwalk; - char* outend; struct evbuffer_iovec vec[1]; - struct jsonWalk* data = vdata; + struct jsonWalk* const data = vdata; unsigned char const* it; - unsigned char const* end; char const* str = NULL; size_t len = 0; (void)tr_variantGetStr(val, &str, &len); it = (unsigned char const*)str; - end = it + len; + unsigned char const* const end = it + len; evbuffer_reserve_space(data->out, len * 4, vec, 1); out = vec[0].iov_base; - outend = out + vec[0].iov_len; + char const* const outend = out + vec[0].iov_len; outwalk = out; *outwalk++ = '"'; diff --git a/libtransmission/variant.c b/libtransmission/variant.c index 575c08db5..e7f84a9db 100644 --- a/libtransmission/variant.c +++ b/libtransmission/variant.c @@ -433,7 +433,7 @@ bool tr_variantDictFindReal(tr_variant* dict, tr_quark const key, double* setme) bool tr_variantDictFindStr(tr_variant* dict, tr_quark const key, char const** setme, size_t* len) { - tr_variant* child = tr_variantDictFind(dict, key); + tr_variant const* const child = tr_variantDictFind(dict, key); return tr_variantGetStr(child, setme, len); } diff --git a/libtransmission/watchdir-inotify.c b/libtransmission/watchdir-inotify.c index 329228fa7..579869510 100644 --- a/libtransmission/watchdir-inotify.c +++ b/libtransmission/watchdir-inotify.c @@ -71,7 +71,7 @@ static void tr_watchdir_inotify_on_event(struct bufferevent* event, void* contex tr_watchdir_t const handle = context; #ifdef TR_ENABLE_ASSERTS - tr_watchdir_inotify* const backend = BACKEND_UPCAST(tr_watchdir_get_backend(handle)); + tr_watchdir_inotify const* const backend = BACKEND_UPCAST(tr_watchdir_get_backend(handle)); #endif struct inotify_event ev; size_t nread; diff --git a/libtransmission/web.c b/libtransmission/web.c index 6d28ab082..6dbee276c 100644 --- a/libtransmission/web.c +++ b/libtransmission/web.c @@ -113,7 +113,7 @@ static size_t writeFunc(void* ptr, size_t size, size_t nmemb, void* vtask) /* webseed downloads should be speed limited */ if (task->torrentId != -1) { - tr_torrent* tor = tr_torrentFindFromId(task->session, task->torrentId); + tr_torrent const* const tor = tr_torrentFindFromId(task->session, task->torrentId); if (tor != NULL && tr_bandwidthClamp(&tor->bandwidth, TR_DOWN, nmemb) == 0) { @@ -133,7 +133,7 @@ static int sockoptfunction(void* vtask, curl_socket_t fd, curlsocktype purpose) { TR_UNUSED(purpose); - struct tr_web_task* task = vtask; + struct tr_web_task const* const task = vtask; bool const isScrape = strstr(task->url, "scrape") != NULL; bool const isAnnounce = strstr(task->url, "announce") != NULL; diff --git a/libtransmission/webseed.c b/libtransmission/webseed.c index 4c5b87671..779258472 100644 --- a/libtransmission/webseed.c +++ b/libtransmission/webseed.c @@ -201,7 +201,7 @@ static void connection_succeeded(void* vdata) if (data->real_url != NULL) { - tr_torrent* tor = tr_torrentFindFromId(w->session, w->torrent_id); + tr_torrent const* const tor = tr_torrentFindFromId(w->session, w->torrent_id); if (tor != NULL) { @@ -558,8 +558,8 @@ static void webseed_destruct(tr_peer* peer) /* if we have an array of file URLs, free it */ if (w->file_urls != NULL) { - tr_torrent* tor = tr_torrentFindFromId(w->session, w->torrent_id); - tr_info const* inf = tr_torrentInfo(tor); + tr_torrent const* const tor = tr_torrentFindFromId(w->session, w->torrent_id); + tr_info const* const inf = tr_torrentInfo(tor); for (tr_file_index_t i = 0; i < inf->fileCount; ++i) { diff --git a/qt/ComInteropHelper.cc b/qt/ComInteropHelper.cc index 395671e42..00550b792 100644 --- a/qt/ComInteropHelper.cc +++ b/qt/ComInteropHelper.cc @@ -37,7 +37,7 @@ bool ComInteropHelper::isConnected() const return !client_->isNull(); } -QVariant ComInteropHelper::addMetainfo(QString const& metainfo) +QVariant ComInteropHelper::addMetainfo(QString const& metainfo) const { return client_->dynamicCall("AddMetainfo(QString)", metainfo); } diff --git a/qt/ComInteropHelper.h b/qt/ComInteropHelper.h index 163f4df93..6e8986bd7 100644 --- a/qt/ComInteropHelper.h +++ b/qt/ComInteropHelper.h @@ -23,7 +23,7 @@ public: bool isConnected() const; - QVariant addMetainfo(QString const& metainfo); + QVariant addMetainfo(QString const& metainfo) const; static void initialize(); static void registerObject(QObject* parent); diff --git a/qt/DBusInteropHelper.cc b/qt/DBusInteropHelper.cc index 68bc75a07..57459039d 100644 --- a/qt/DBusInteropHelper.cc +++ b/qt/DBusInteropHelper.cc @@ -21,7 +21,7 @@ bool DBusInteropHelper::isConnected() const return QDBusConnection::sessionBus().isConnected(); } -QVariant DBusInteropHelper::addMetainfo(QString const& metainfo) +QVariant DBusInteropHelper::addMetainfo(QString const& metainfo) const { auto request = QDBusMessage::createMethodCall( QStringLiteral("com.transmissionbt.Transmission"), diff --git a/qt/DBusInteropHelper.h b/qt/DBusInteropHelper.h index c89af0ca2..9e5f16e28 100644 --- a/qt/DBusInteropHelper.h +++ b/qt/DBusInteropHelper.h @@ -19,7 +19,7 @@ public: bool isConnected() const; - QVariant addMetainfo(QString const& metainfo); + QVariant addMetainfo(QString const& metainfo) const; static void registerObject(QObject* parent); }; diff --git a/qt/DetailsDialog.cc b/qt/DetailsDialog.cc index b88d811d2..faa88e3a3 100644 --- a/qt/DetailsDialog.cc +++ b/qt/DetailsDialog.cc @@ -393,6 +393,7 @@ void DetailsDialog::refreshUI() QString const mixed = tr("Mixed"); QString const unknown = tr("Unknown"); auto const now = time(nullptr); + auto const& fmt = Formatter::get(); // build a list of torrents for (int const id : ids_) @@ -501,13 +502,14 @@ void DetailsDialog::refreshUI() double const d = size_when_done == 0 ? 100.0 : 100.0 * static_cast(size_when_done - left_until_done) / static_cast(size_when_done); - auto const pct = Formatter::get().percentToString(d); + auto const pct = fmt.percentToString(d); + auto const size_when_done_str = fmt.sizeToString(size_when_done); if (have_unverified == 0 && left_until_done == 0) { //: Text following the "Have:" label in torrent properties dialog; //: %1 is amount of downloaded and verified data - string = tr("%1 (100%)").arg(Formatter::get().sizeToString(have_verified)); + string = tr("%1 (100%)").arg(fmt.sizeToString(have_verified)); } else if (have_unverified == 0) { @@ -515,9 +517,10 @@ void DetailsDialog::refreshUI() //: %1 is amount of downloaded and verified data, //: %2 is overall size of torrent data, //: %3 is percentage (%1/%2*100) - string = tr("%1 of %2 (%3%)").arg(Formatter::get().sizeToString(have_verified)).arg(Formatter::get().sizeToString( - size_when_done)). - arg(pct); + string = tr("%1 of %2 (%3%)") + .arg(fmt.sizeToString(have_verified)) + .arg(size_when_done_str) + .arg(pct); } else { @@ -526,8 +529,11 @@ void DetailsDialog::refreshUI() //: %2 is overall size of torrent data, //: %3 is percentage (%1/%2*100), //: %4 is amount of downloaded but not yet verified data - string = tr("%1 of %2 (%3%), %4 Unverified").arg(Formatter::get().sizeToString(have_verified + have_unverified)). - arg(Formatter::get().sizeToString(size_when_done)).arg(pct).arg(Formatter::get().sizeToString(have_unverified)); + string = tr("%1 of %2 (%3%), %4 Unverified") + .arg(fmt.sizeToString(have_verified + have_unverified)) + .arg(size_when_done_str) + .arg(pct) + .arg(fmt.sizeToString(have_unverified)); } } @@ -541,7 +547,7 @@ void DetailsDialog::refreshUI() else { auto const percent = 100.0 * static_cast(available) / static_cast(size_when_done); - string = QStringLiteral("%1%").arg(Formatter::get().percentToString(percent)); + string = QStringLiteral("%1%").arg(fmt.percentToString(percent)); } ui_.availabilityValueLabel->setText(string); @@ -553,8 +559,8 @@ void DetailsDialog::refreshUI() } else { - uint64_t d = 0; - uint64_t f = 0; + auto d = uint64_t{}; + auto f = uint64_t{}; for (Torrent const* const t : torrents) { @@ -562,8 +568,8 @@ void DetailsDialog::refreshUI() f += t->failedEver(); } - QString const dstr = Formatter::get().sizeToString(d); - QString const fstr = Formatter::get().sizeToString(f); + QString const dstr = fmt.sizeToString(d); + QString const fstr = fmt.sizeToString(f); if (f != 0) { @@ -584,8 +590,8 @@ void DetailsDialog::refreshUI() } else { - uint64_t u = 0; - uint64_t d = 0; + auto u = uint64_t{}; + auto d = uint64_t{}; for (Torrent const* const t : torrents) { @@ -593,8 +599,9 @@ void DetailsDialog::refreshUI() d += t->downloadedEver(); } - string = tr("%1 (Ratio: %2)").arg(Formatter::get().sizeToString(u)).arg(Formatter::get().ratioToString(tr_getRatio(u, - d))); + string = tr("%1 (Ratio: %2)") + .arg(fmt.sizeToString(u)) + .arg(fmt.ratioToString(tr_getRatio(u, d))); } ui_.uploadedValueLabel->setText(string); @@ -633,7 +640,7 @@ void DetailsDialog::refreshUI() else { auto const seconds = int(std::difftime(now, baseline)); - string = Formatter::get().timeToString(seconds); + string = fmt.timeToString(seconds); } } @@ -667,7 +674,7 @@ void DetailsDialog::refreshUI() } else { - string = Formatter::get().timeToString(baseline); + string = fmt.timeToString(baseline); } } } @@ -705,7 +712,7 @@ void DetailsDialog::refreshUI() } else { - string = tr("%1 ago").arg(Formatter::get().timeToString(seconds)); + string = tr("%1 ago").arg(fmt.timeToString(seconds)); } } @@ -748,7 +755,7 @@ void DetailsDialog::refreshUI() else { int pieces = 0; - uint64_t size = 0; + auto size = uint64_t{}; uint32_t piece_size = torrents[0]->pieceSize(); for (Torrent const* const t : torrents) @@ -768,12 +775,14 @@ void DetailsDialog::refreshUI() } else if (piece_size > 0) { - string = tr("%1 (%Ln pieces @ %2)", "", pieces).arg(Formatter::get().sizeToString(size)). - arg(Formatter::get().memToString(piece_size)); + string = tr("%1 (%Ln pieces @ %2)", "", pieces) + .arg(fmt.sizeToString(size)) + .arg(fmt.memToString(piece_size)); } else { - string = tr("%1 (%Ln pieces)", "", pieces).arg(Formatter::get().sizeToString(size)); + string = tr("%1 (%Ln pieces)", "", pieces) + .arg(fmt.sizeToString(size)); } } @@ -1144,9 +1153,9 @@ void DetailsDialog::refreshUI() code_tip.resize(code_tip.size() - 1); // eat the trailing linefeed } - item->setText(COL_UP, peer.rate_to_peer.isZero() ? QString() : Formatter::get().speedToString(peer.rate_to_peer)); + item->setText(COL_UP, peer.rate_to_peer.isZero() ? QString() : fmt.speedToString(peer.rate_to_peer)); item->setText(COL_DOWN, - peer.rate_to_client.isZero() ? QString() : Formatter::get().speedToString(peer.rate_to_client)); + peer.rate_to_client.isZero() ? QString() : fmt.speedToString(peer.rate_to_client)); item->setText(COL_PERCENT, peer.progress > 0 ? QStringLiteral("%1%").arg(int(peer.progress * 100.0)) : QString()); item->setText(COL_STATUS, code); @@ -1484,7 +1493,7 @@ void DetailsDialog::initPeersTab() **** ***/ -void DetailsDialog::initFilesTab() +void DetailsDialog::initFilesTab() const { connect(ui_.filesView, &FileTreeView::openRequested, this, &DetailsDialog::onOpenRequested); connect(ui_.filesView, &FileTreeView::pathEdited, this, &DetailsDialog::onPathEdited); @@ -1525,7 +1534,7 @@ void DetailsDialog::onPathEdited(QString const& oldpath, QString const& newname) session_.torrentRenamePath(ids_, oldpath, newname); } -void DetailsDialog::onOpenRequested(QString const& path) +void DetailsDialog::onOpenRequested(QString const& path) const { if (!session_.isLocal()) { diff --git a/qt/DetailsDialog.cc.orig b/qt/DetailsDialog.cc.orig new file mode 100644 index 000000000..89769fea3 --- /dev/null +++ b/qt/DetailsDialog.cc.orig @@ -0,0 +1,1569 @@ +/* + * This file Copyright (C) 2009-2015 Mnemosyne LLC + * + * It may be used under the GNU GPL versions 2 or 3 + * or any future license endorsed by Mnemosyne LLC. + * + */ + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include // tr_getRatio() + +#include "ColumnResizer.h" +#include "DetailsDialog.h" +#include "Formatter.h" +#include "Prefs.h" +#include "Session.h" +#include "SqueezeLabel.h" +#include "Torrent.h" +#include "TorrentModel.h" +#include "TrackerDelegate.h" +#include "TrackerModel.h" +#include "TrackerModelFilter.h" +#include "Utils.h" + +class Prefs; +class Session; + +/**** +***** +****/ + +namespace +{ + +int constexpr DebounceIntervalMSec = 100; +int constexpr RefreshIntervalMSec = 4000; + +char const constexpr* const PrefKey = "pref_key"; + +enum // peer columns +{ + COL_LOCK, + COL_UP, + COL_DOWN, + COL_PERCENT, + COL_STATUS, + COL_ADDRESS, + COL_CLIENT, + N_COLUMNS +}; + +int measureViewItem(QTreeWidget const* view, int column, QString const& text) +{ + QTreeWidgetItem const* header_item = view->headerItem(); + + int const item_width = Utils::measureViewItem(view, text); + int const header_width = Utils::measureHeaderItem(view->header(), header_item->text(column)); + + return std::max(item_width, header_width); +} + +QString collateAddress(QString const& address) +{ + QString collated; + + QHostAddress ip_address; + if (ip_address.setAddress(address)) + { + if (ip_address.protocol() == QAbstractSocket::IPv4Protocol) + { + quint32 const ipv4_address = ip_address.toIPv4Address(); + collated = QStringLiteral("1-") + + QString::fromUtf8(QByteArray::number(ipv4_address, 16).rightJustified(8, '0')); + } + else if (ip_address.protocol() == QAbstractSocket::IPv6Protocol) + { + Q_IPV6ADDR const ipv6_address = ip_address.toIPv6Address(); + QByteArray tmp(16, '\0'); + + for (int i = 0; i < 16; ++i) + { + tmp[i] = ipv6_address[i]; + } + + collated = QStringLiteral("2-") + QString::fromUtf8(tmp.toHex()); + } + } + + if (collated.isEmpty()) + { + collated = QStringLiteral("3-") + address.toLower(); + } + + return collated; +} + +} // namespace + +/*** +**** +***/ + +class PeerItem : public QTreeWidgetItem +{ + Peer peer_; + QString mutable collated_address_; + QString status_; + +public: + explicit PeerItem(Peer p) : + peer_(std::move(p)) + { + } + + void refresh(Peer const& p) + { + if (p.address != peer_.address) + { + collated_address_.clear(); + } + + peer_ = p; + } + + void setStatus(QString const& s) + { + status_ = s; + } + + bool operator <(QTreeWidgetItem const& other) const override + { + auto const* i = dynamic_cast(&other); + auto const* tw = treeWidget(); + int const column = tw != nullptr ? tw->sortColumn() : 0; + + assert(i != nullptr); + + switch (column) + { + case COL_UP: + return peer_.rate_to_peer < i->peer_.rate_to_peer; + + case COL_DOWN: + return peer_.rate_to_client < i->peer_.rate_to_client; + + case COL_PERCENT: + return peer_.progress < i->peer_.progress; + + case COL_STATUS: + return status_ < i->status_; + + case COL_CLIENT: + return peer_.client_name < i->peer_.client_name; + + case COL_LOCK: + return peer_.is_encrypted && !i->peer_.is_encrypted; + + default: + return address() < i->address(); + } + } + +private: + QString const& address() const + { + if (collated_address_.isEmpty()) + { + collated_address_ = collateAddress(peer_.address); + } + + return collated_address_; + } +}; + +/*** +**** +***/ + +QIcon DetailsDialog::getStockIcon(QString const& freedesktop_name, int fallback) const +{ + QIcon icon = QIcon::fromTheme(freedesktop_name); + + if (icon.isNull()) + { + icon = style()->standardIcon(QStyle::StandardPixmap(fallback), nullptr, this); + } + + return icon; +} + +DetailsDialog::DetailsDialog(Session& session, Prefs& prefs, TorrentModel const& model, QWidget* parent) : + BaseDialog(parent), + session_(session), + prefs_(prefs), + model_(model) +{ + ui_.setupUi(this); + + initInfoTab(); + initPeersTab(); + initTrackerTab(); + initFilesTab(); + initOptionsTab(); + + adjustSize(); + ui_.commentBrowser->setMaximumHeight(QWIDGETSIZE_MAX); + + static std::array constexpr InitKeys = + { + Prefs::SHOW_TRACKER_SCRAPES, + Prefs::SHOW_BACKUP_TRACKERS + }; + + for (int const key : InitKeys) + { + refreshPref(key); + } + + connect(&model_, &TorrentModel::torrentsChanged, this, &DetailsDialog::onTorrentsChanged); + connect(&model_, &TorrentModel::torrentsEdited, this, &DetailsDialog::onTorrentsEdited); + connect(&prefs_, &Prefs::changed, this, &DetailsDialog::refreshPref); + + // call refreshModel periodically + connect(&model_timer_, &QTimer::timeout, this, &DetailsDialog::refreshModel); + model_timer_.setSingleShot(false); + model_timer_.start(RefreshIntervalMSec); + refreshModel(); + + // set up the debounce timer + connect(&ui_debounce_timer_, &QTimer::timeout, this, &DetailsDialog::refreshUI); + ui_debounce_timer_.setSingleShot(true); +} + +DetailsDialog::~DetailsDialog() +{ + tracker_delegate_->deleteLater(); + tracker_filter_->deleteLater(); + tracker_model_->deleteLater(); +} + +void DetailsDialog::setIds(torrent_ids_t const& ids) +{ + if (ids != ids_) + { + setEnabled(false); + ui_.filesView->clear(); + + ids_ = ids; + session_.refreshDetailInfo(ids_); + tracker_model_->refresh(model_, ids_); + + refreshModel(); + refreshUI(); + } +} + +void DetailsDialog::refreshPref(int key) +{ + QString str; + + switch (key) + { + case Prefs::SHOW_TRACKER_SCRAPES: + { + QItemSelectionModel* selection_model(ui_.trackersView->selectionModel()); + QItemSelection const selection(selection_model->selection()); + QModelIndex const current_index(selection_model->currentIndex()); + tracker_delegate_->setShowMore(prefs_.getBool(key)); + selection_model->clear(); + ui_.trackersView->reset(); + selection_model->select(selection, QItemSelectionModel::Select); + selection_model->setCurrentIndex(current_index, QItemSelectionModel::NoUpdate); + break; + } + + case Prefs::SHOW_BACKUP_TRACKERS: + tracker_filter_->setShowBackupTrackers(prefs_.getBool(key)); + break; + + default: + break; + } +} + +/*** +**** +***/ + +void DetailsDialog::refreshModel() +{ + if (!ids_.empty()) + { + session_.refreshExtraStats(ids_); + } +} + +void DetailsDialog::onTorrentsEdited(torrent_ids_t const& ids) +{ + // std::set_intersection requires sorted inputs + auto a = std::vector{ ids.begin(), ids.end() }; + std::sort(std::begin(a), std::end(a)); + auto b = std::vector{ ids_.begin(), ids_.end() }; + std::sort(std::begin(b), std::end(b)); + + // are any of the edited torrents on display here? + torrent_ids_t interesting_ids; + std::set_intersection(std::begin(a), std::end(a), + std::begin(b), std::end(b), + std::inserter(interesting_ids, std::begin(interesting_ids))); + + if (!interesting_ids.empty()) + { + session_.refreshDetailInfo(interesting_ids); + } +} + +void DetailsDialog::onTorrentsChanged(torrent_ids_t const& ids, Torrent::fields_t const& fields) +{ + Q_UNUSED(fields) + + if (ui_debounce_timer_.isActive()) + { + return; + } + + if (!std::any_of(ids.begin(), ids.end(), [this](auto const& id) { return ids_.count(id) != 0; })) + { + return; + } + + ui_debounce_timer_.start(DebounceIntervalMSec); +} + +void DetailsDialog::onSessionCalled(Session::Tag tag) +{ + if ((pending_changes_tags_.erase(tag) > 0) && canEdit()) + { + // no pending changes left, so stop listening + disconnect(pending_changes_connection_); + pending_changes_connection_ = {}; + + refreshModel(); + } +} + +namespace +{ + +void setIfIdle(QComboBox* box, int i) +{ + if (!box->hasFocus()) + { + box->blockSignals(true); + box->setCurrentIndex(i); + box->blockSignals(false); + } +} + +void setIfIdle(QDoubleSpinBox* spin, double value) +{ + if (!spin->hasFocus()) + { + spin->blockSignals(true); + spin->setValue(value); + spin->blockSignals(false); + } +} + +void setIfIdle(QSpinBox* spin, int value) +{ + if (!spin->hasFocus()) + { + spin->blockSignals(true); + spin->setValue(value); + spin->blockSignals(false); + } +} + +} // namespace + +void DetailsDialog::refreshUI() +{ + bool const single = ids_.size() == 1; + QString const blank; + QFontMetrics const fm(fontMetrics()); + QList torrents; + QString string; + QString const none = tr("None"); + QString const mixed = tr("Mixed"); + QString const unknown = tr("Unknown"); + auto const now = time(nullptr); + + // build a list of torrents + for (int const id : ids_) + { + Torrent const* tor = model_.getTorrentFromId(id); + + if (tor != nullptr) + { + torrents << tor; + } + } + + /// + /// activity tab + /// + + // myStateLabel + if (torrents.empty()) + { + string = none; + } + else + { + bool is_mixed = false; + bool all_paused = true; + bool all_finished = true; + tr_torrent_activity const baseline = torrents[0]->getActivity(); + + for (Torrent const* const t : torrents) + { + tr_torrent_activity const activity = t->getActivity(); + + if (activity != baseline) + { + is_mixed = true; + } + + if (activity != TR_STATUS_STOPPED) + { + all_paused = all_finished = false; + } + + if (!t->isFinished()) + { + all_finished = false; + } + } + + if (is_mixed) + { + string = mixed; + } + else if (all_finished) + { + string = tr("Finished"); + } + else if (all_paused) + { + string = tr("Paused"); + } + else + { + string = torrents[0]->activityString(); + } + } + + ui_.stateValueLabel->setText(string); + QString const state_string = string; + + // myHaveLabel + uint64_t size_when_done = 0; + uint64_t available = 0; + + if (torrents.empty()) + { + string = none; + } + else + { + uint64_t left_until_done = 0; + int64_t have_total = 0; + int64_t have_verified = 0; + int64_t have_unverified = 0; + int64_t verified_pieces = 0; + + for (Torrent const* const t : torrents) + { + if (t->hasMetadata()) + { + have_total += t->haveTotal(); + have_unverified += t->haveUnverified(); + uint64_t const v = t->haveVerified(); + have_verified += v; + + if (t->pieceSize()) + { + verified_pieces += v / t->pieceSize(); + } + + size_when_done += t->sizeWhenDone(); + left_until_done += t->leftUntilDone(); + available += t->sizeWhenDone() - t->leftUntilDone() + t->desiredAvailable(); + } + } + + double const d = size_when_done == 0 ? + 100.0 : + 100.0 * static_cast(size_when_done - left_until_done) / static_cast(size_when_done); + auto const pct = Formatter::get().percentToString(d); + + if (have_unverified == 0 && left_until_done == 0) + { + //: Text following the "Have:" label in torrent properties dialog; + //: %1 is amount of downloaded and verified data + string = tr("%1 (100%)").arg(Formatter::get().sizeToString(have_verified)); + } + else if (have_unverified == 0) + { + //: Text following the "Have:" label in torrent properties dialog; + //: %1 is amount of downloaded and verified data, + //: %2 is overall size of torrent data, + //: %3 is percentage (%1/%2*100) + string = tr("%1 of %2 (%3%)").arg(Formatter::get().sizeToString(have_verified)).arg(Formatter::get().sizeToString( + size_when_done)). + arg(pct); + } + else + { + //: Text following the "Have:" label in torrent properties dialog; + //: %1 is amount of downloaded data (both verified and unverified), + //: %2 is overall size of torrent data, + //: %3 is percentage (%1/%2*100), + //: %4 is amount of downloaded but not yet verified data + string = tr("%1 of %2 (%3%), %4 Unverified").arg(Formatter::get().sizeToString(have_verified + have_unverified)). + arg(Formatter::get().sizeToString(size_when_done)).arg(pct).arg(Formatter::get().sizeToString(have_unverified)); + } + } + + ui_.haveValueLabel->setText(string); + + // myAvailabilityLabel + if (torrents.empty() || size_when_done == 0) + { + string = none; + } + else + { + auto const percent = 100.0 * static_cast(available) / static_cast(size_when_done); + string = QStringLiteral("%1%").arg(Formatter::get().percentToString(percent)); + } + + ui_.availabilityValueLabel->setText(string); + + // myDownloadedLabel + if (torrents.empty()) + { + string = none; + } + else + { + uint64_t d = 0; + uint64_t f = 0; + + for (Torrent const* const t : torrents) + { + d += t->downloadedEver(); + f += t->failedEver(); + } + + QString const dstr = Formatter::get().sizeToString(d); + QString const fstr = Formatter::get().sizeToString(f); + + if (f != 0) + { + string = tr("%1 (%2 corrupt)").arg(dstr).arg(fstr); + } + else + { + string = dstr; + } + } + + ui_.downloadedValueLabel->setText(string); + + // myUploadedLabel + if (torrents.empty()) + { + string = none; + } + else + { + uint64_t u = 0; + uint64_t d = 0; + + for (Torrent const* const t : torrents) + { + u += t->uploadedEver(); + d += t->downloadedEver(); + } + + string = tr("%1 (Ratio: %2)").arg(Formatter::get().sizeToString(u)).arg(Formatter::get().ratioToString(tr_getRatio(u, + d))); + } + + ui_.uploadedValueLabel->setText(string); + + // myRunTimeLabel + if (torrents.empty()) + { + string = none; + } + else + { + bool all_paused = true; + auto baseline = torrents[0]->lastStarted(); + + for (Torrent const* const t : torrents) + { + if (baseline != t->lastStarted()) + { + baseline = 0; + } + + if (!t->isPaused()) + { + all_paused = false; + } + } + + if (all_paused) + { + string = state_string; // paused || finished + } + else if (baseline == 0) + { + string = mixed; + } + else + { + auto const seconds = int(std::difftime(now, baseline)); + string = Formatter::get().timeToString(seconds); + } + } + + ui_.runningTimeValueLabel->setText(string); + + // myETALabel + string.clear(); + + if (torrents.empty()) + { + string = none; + } + else + { + int baseline = torrents[0]->getETA(); + + for (Torrent const* const t : torrents) + { + if (baseline != t->getETA()) + { + string = mixed; + break; + } + } + + if (string.isEmpty()) + { + if (baseline < 0) + { + string = tr("Unknown"); + } + else + { + string = Formatter::get().timeToString(baseline); + } + } + } + + ui_.remainingTimeValueLabel->setText(string); + + // myLastActivityLabel + if (torrents.empty()) + { + string = none; + } + else + { + auto latest = torrents[0]->lastActivity(); + + for (Torrent const* const t : torrents) + { + auto const dt = t->lastActivity(); + + if (latest < dt) + { + latest = dt; + } + } + + auto const seconds = int(std::difftime(now, latest)); + + if (seconds < 0) + { + string = none; + } + else if (seconds < 5) + { + string = tr("Active now"); + } + else + { + string = tr("%1 ago").arg(Formatter::get().timeToString(seconds)); + } + } + + ui_.lastActivityValueLabel->setText(string); + + if (torrents.empty()) + { + string = none; + } + else + { + string = torrents[0]->getError(); + + for (Torrent const* const t : torrents) + { + if (string != t->getError()) + { + string = mixed; + break; + } + } + } + + if (string.isEmpty()) + { + string = none; + } + + ui_.errorValueLabel->setText(string); + + /// + /// information tab + /// + + // mySizeLabel + if (torrents.empty()) + { + string = none; + } + else + { + int pieces = 0; + uint64_t size = 0; + uint32_t piece_size = torrents[0]->pieceSize(); + + for (Torrent const* const t : torrents) + { + pieces += t->pieceCount(); + size += t->totalSize(); + + if (piece_size != t->pieceSize()) + { + piece_size = 0; + } + } + + if (size == 0) + { + string = none; + } + else if (piece_size > 0) + { + string = tr("%1 (%Ln pieces @ %2)", "", pieces).arg(Formatter::get().sizeToString(size)). + arg(Formatter::get().memToString(piece_size)); + } + else + { + string = tr("%1 (%Ln pieces)", "", pieces).arg(Formatter::get().sizeToString(size)); + } + } + + ui_.sizeValueLabel->setText(string); + + // myHashLabel + if (torrents.empty()) + { + string = none; + } + else if (torrents.size() > 1) + { + string = mixed; + } + else + { + string = torrents.front()->hash().toString(); + } + + ui_.hashValueLabel->setText(string); + + // myPrivacyLabel + string = none; + + if (!torrents.empty()) + { + bool b = torrents[0]->isPrivate(); + string = b ? tr("Private to this tracker -- DHT and PEX disabled") : tr("Public torrent"); + + for (Torrent const* const t : torrents) + { + if (b != t->isPrivate()) + { + string = mixed; + break; + } + } + } + + ui_.privacyValueLabel->setText(string); + + // myCommentBrowser + string = none; + bool is_comment_mixed = false; + + if (!torrents.empty()) + { + string = torrents[0]->comment(); + + for (Torrent const* const t : torrents) + { + if (string != t->comment()) + { + string = mixed; + is_comment_mixed = true; + break; + } + } + } + + if (ui_.commentBrowser->toPlainText() != string) + { + ui_.commentBrowser->setText(string); + } + + ui_.commentBrowser->setEnabled(!is_comment_mixed && !string.isEmpty()); + + // myOriginLabel + string = none; + + if (!torrents.empty()) + { + bool mixed_creator = false; + bool mixed_date = false; + QString const creator = torrents[0]->creator(); + auto const date = torrents[0]->dateCreated(); + + for (Torrent const* const t : torrents) + { + mixed_creator |= (creator != t->creator()); + mixed_date |= (date != t->dateCreated()); + } + + bool const empty_creator = creator.isEmpty(); + bool const empty_date = date <= 0; + + if (mixed_creator || mixed_date) + { + string = mixed; + } + else if (empty_creator && empty_date) + { + string = tr("N/A"); + } + else if (empty_date && !empty_creator) + { + string = tr("Created by %1").arg(creator); + } + else if (empty_creator && !empty_date) + { + auto const date_str = QDateTime::fromSecsSinceEpoch(date).toString(); + string = tr("Created on %1").arg(date_str); + } + else + { + auto const date_str = QDateTime::fromSecsSinceEpoch(date).toString(); + string = tr("Created by %1 on %2").arg(creator).arg(date_str); + } + } + + ui_.originValueLabel->setText(string); + + // myLocationLabel + string = none; + + if (!torrents.empty()) + { + string = torrents[0]->getPath(); + + for (Torrent const* const t : torrents) + { + if (string != t->getPath()) + { + string = mixed; + break; + } + } + } + + ui_.locationValueLabel->setText(string); + + /// + /// Options Tab + /// + + if (canEdit() && !torrents.empty()) + { + int i; + bool uniform; + bool baseline_flag; + int baseline_int; + Torrent const& baseline = *torrents.front(); + + // mySessionLimitCheck + uniform = true; + baseline_flag = baseline.honorsSessionLimits(); + + for (Torrent const* const tor : torrents) + { + if (baseline_flag != tor->honorsSessionLimits()) + { + uniform = false; + break; + } + } + + ui_.sessionLimitCheck->setChecked(uniform && baseline_flag); + + // mySingleDownCheck + uniform = true; + baseline_flag = baseline.downloadIsLimited(); + + for (Torrent const* const tor : torrents) + { + if (baseline_flag != tor->downloadIsLimited()) + { + uniform = false; + break; + } + } + + ui_.singleDownCheck->setChecked(uniform && baseline_flag); + + // mySingleUpCheck + uniform = true; + baseline_flag = baseline.uploadIsLimited(); + + for (Torrent const* const tor : torrents) + { + if (baseline_flag != tor->uploadIsLimited()) + { + uniform = false; + break; + } + } + + ui_.singleUpCheck->setChecked(uniform && baseline_flag); + + // myBandwidthPriorityCombo + uniform = true; + baseline_int = baseline.getBandwidthPriority(); + + for (Torrent const* const tor : torrents) + { + if (baseline_int != tor->getBandwidthPriority()) + { + uniform = false; + break; + } + } + + if (uniform) + { + i = ui_.bandwidthPriorityCombo->findData(baseline_int); + } + else + { + i = -1; + } + + setIfIdle(ui_.bandwidthPriorityCombo, i); + + setIfIdle(ui_.singleDownSpin, int(baseline.downloadLimit().getKBps())); + setIfIdle(ui_.singleUpSpin, int(baseline.uploadLimit().getKBps())); + setIfIdle(ui_.peerLimitSpin, baseline.peerLimit()); + } + + if (!torrents.empty()) + { + Torrent const& baseline = *torrents.front(); + + // ratio + bool uniform = true; + int baseline_int = baseline.seedRatioMode(); + + for (Torrent const* const tor : torrents) + { + if (baseline_int != tor->seedRatioMode()) + { + uniform = false; + break; + } + } + + setIfIdle(ui_.ratioCombo, uniform ? ui_.ratioCombo->findData(baseline_int) : -1); + ui_.ratioSpin->setVisible(uniform && baseline_int == TR_RATIOLIMIT_SINGLE); + + setIfIdle(ui_.ratioSpin, baseline.seedRatioLimit()); + + // idle + uniform = true; + baseline_int = baseline.seedIdleMode(); + + for (Torrent const* const tor : torrents) + { + if (baseline_int != tor->seedIdleMode()) + { + uniform = false; + break; + } + } + + setIfIdle(ui_.idleCombo, uniform ? ui_.idleCombo->findData(baseline_int) : -1); + ui_.idleSpin->setVisible(uniform && baseline_int == TR_RATIOLIMIT_SINGLE); + + setIfIdle(ui_.idleSpin, baseline.seedIdleLimit()); + onIdleLimitChanged(); + } + + /// + /// Tracker tab + /// + + tracker_model_->refresh(model_, ids_); + + /// + /// Peers tab + /// + + QMap peers2; + QList new_items; + + for (Torrent const* const t : torrents) + { + QString const id_str(QString::number(t->id())); + PeerList peers = t->peers(); + + for (Peer const& peer : peers) + { + QString const key = id_str + QLatin1Char(':') + peer.address; + PeerItem* item = static_cast(peers_.value(key, nullptr)); + + if (item == nullptr) // new peer has connected + { + item = new PeerItem(peer); + item->setTextAlignment(COL_UP, Qt::AlignRight | Qt::AlignVCenter); + item->setTextAlignment(COL_DOWN, Qt::AlignRight | Qt::AlignVCenter); + item->setTextAlignment(COL_PERCENT, Qt::AlignRight | Qt::AlignVCenter); + item->setIcon(COL_LOCK, peer.is_encrypted ? icon_encrypted_ : icon_unencrypted_); + item->setToolTip(COL_LOCK, peer.is_encrypted ? tr("Encrypted connection") : QString()); + item->setText(COL_ADDRESS, peer.address); + item->setText(COL_CLIENT, peer.client_name); + new_items << item; + } + + QString const code = peer.flags; + item->setStatus(code); + item->refresh(peer); + + QString code_tip; + + for (QChar const ch : code) + { + QString txt; + + switch (ch.unicode()) + { + case 'O': + txt = tr("Optimistic unchoke"); + break; + + case 'D': + txt = tr("Downloading from this peer"); + break; + + case 'd': + txt = tr("We would download from this peer if they would let us"); + break; + + case 'U': + txt = tr("Uploading to peer"); + break; + + case 'u': + txt = tr("We would upload to this peer if they asked"); + break; + + case 'K': + txt = tr("Peer has unchoked us, but we're not interested"); + break; + + case '?': + txt = tr("We unchoked this peer, but they're not interested"); + break; + + case 'E': + txt = tr("Encrypted connection"); + break; + + case 'H': + txt = tr("Peer was discovered through DHT"); + break; + + case 'X': + txt = tr("Peer was discovered through Peer Exchange (PEX)"); + break; + + case 'I': + txt = tr("Peer is an incoming connection"); + break; + + case 'T': + txt = tr("Peer is connected over uTP"); + break; + + default: + break; + } + + if (!txt.isEmpty()) + { + code_tip += QStringLiteral("%1: %2\n").arg(ch).arg(txt); + } + } + + if (!code_tip.isEmpty()) + { + code_tip.resize(code_tip.size() - 1); // eat the trailing linefeed + } + + item->setText(COL_UP, peer.rate_to_peer.isZero() ? QString() : Formatter::get().speedToString(peer.rate_to_peer)); + item->setText(COL_DOWN, + peer.rate_to_client.isZero() ? QString() : Formatter::get().speedToString(peer.rate_to_client)); + item->setText(COL_PERCENT, peer.progress > 0 ? QStringLiteral("%1%").arg(int(peer.progress * 100.0)) : + QString()); + item->setText(COL_STATUS, code); + item->setToolTip(COL_STATUS, code_tip); + + peers2.insert(key, item); + } + } + + ui_.peersView->addTopLevelItems(new_items); + + for (QString const& key : peers_.keys()) + { + if (!peers2.contains(key)) // old peer has disconnected + { + QTreeWidgetItem* item = peers_.value(key, nullptr); + ui_.peersView->takeTopLevelItem(ui_.peersView->indexOfTopLevelItem(item)); + delete item; + } + } + + peers_ = peers2; + + if (single) + { + ui_.filesView->update(torrents[0]->files(), canEdit()); + } + else + { + ui_.filesView->clear(); + } + + setEnabled(true); +} + +void DetailsDialog::setEnabled(bool enabled) +{ + ui_.tabs->setEnabled(enabled); +} + +/*** +**** +***/ + +void DetailsDialog::initInfoTab() +{ + int const h = QFontMetrics(ui_.commentBrowser->font()).lineSpacing() * 4; + ui_.commentBrowser->setFixedHeight(h); + + auto* cr = new ColumnResizer(this); + cr->addLayout(ui_.activitySectionLayout); + cr->addLayout(ui_.detailsSectionLayout); + cr->update(); +} + +/*** +**** +***/ + +void DetailsDialog::onShowTrackerScrapesToggled(bool val) +{ + prefs_.set(Prefs::SHOW_TRACKER_SCRAPES, val); +} + +void DetailsDialog::onShowBackupTrackersToggled(bool val) +{ + prefs_.set(Prefs::SHOW_BACKUP_TRACKERS, val); +} + +void DetailsDialog::onHonorsSessionLimitsToggled(bool val) +{ + torrentSet(TR_KEY_honorsSessionLimits, val); +} + +void DetailsDialog::onDownloadLimitedToggled(bool val) +{ + torrentSet(TR_KEY_downloadLimited, val); +} + +void DetailsDialog::onSpinBoxEditingFinished() +{ + QObject const* spin = sender(); + tr_quark const key = spin->property(PrefKey).toInt(); + auto const* d = qobject_cast(spin); + + if (d != nullptr) + { + torrentSet(key, d->value()); + } + else + { + torrentSet(key, qobject_cast(spin)->value()); + } +} + +void DetailsDialog::onUploadLimitedToggled(bool val) +{ + torrentSet(TR_KEY_uploadLimited, val); +} + +void DetailsDialog::onIdleModeChanged(int index) +{ + int const val = ui_.idleCombo->itemData(index).toInt(); + torrentSet(TR_KEY_seedIdleMode, val); +} + +void DetailsDialog::onIdleLimitChanged() +{ + //: Spin box suffix, "Stop seeding if idle for: [ 5 minutes ]" (includes leading space after the number, if needed) + QString const units_suffix = tr(" minute(s)", nullptr, ui_.idleSpin->value()); + + if (ui_.idleSpin->suffix() != units_suffix) + { + ui_.idleSpin->setSuffix(units_suffix); + } +} + +void DetailsDialog::onRatioModeChanged(int index) +{ + int const val = ui_.ratioCombo->itemData(index).toInt(); + torrentSet(TR_KEY_seedRatioMode, val); +} + +void DetailsDialog::onBandwidthPriorityChanged(int index) +{ + if (index != -1) + { + int const priority = ui_.bandwidthPriorityCombo->itemData(index).toInt(); + torrentSet(TR_KEY_bandwidthPriority, priority); + } +} + +void DetailsDialog::onTrackerSelectionChanged() +{ + int const selection_count = ui_.trackersView->selectionModel()->selectedRows().size(); + ui_.editTrackerButton->setEnabled(selection_count == 1); + ui_.removeTrackerButton->setEnabled(selection_count > 0); +} + +void DetailsDialog::onAddTrackerClicked() +{ + bool ok = false; + QString const url = QInputDialog::getText(this, tr("Add URL "), tr("Add tracker announce URL:"), QLineEdit::Normal, + QString(), &ok); + + if (!ok) + { + // user pressed "cancel" -- noop + } + else if (!QUrl(url).isValid()) + { + QMessageBox::warning(this, tr("Error"), tr("Invalid URL \"%1\"").arg(url)); + } + else + { + torrent_ids_t ids; + + for (int const id : ids_) + { + if (tracker_model_->find(id, url) == -1) + { + ids.insert(id); + } + } + + if (ids.empty()) // all the torrents already have this tracker + { + QMessageBox::warning(this, tr("Error"), tr("Tracker already exists.")); + } + else + { + auto const urls = QStringList{ url }; + torrentSet(ids, TR_KEY_trackerAdd, urls); + } + } +} + +void DetailsDialog::onEditTrackerClicked() +{ + QItemSelectionModel* selection_model = ui_.trackersView->selectionModel(); + QModelIndexList selected_rows = selection_model->selectedRows(); + assert(selected_rows.size() == 1); + QModelIndex i = selection_model->currentIndex(); + auto const tracker_info = ui_.trackersView->model()->data(i, TrackerModel::TrackerRole).value(); + + bool ok = false; + QString const newval = QInputDialog::getText(this, tr("Edit URL "), tr("Edit tracker announce URL:"), QLineEdit::Normal, + tracker_info.st.announce, &ok); + + if (!ok) + { + // user pressed "cancel" -- noop + } + else if (!QUrl(newval).isValid()) + { + QMessageBox::warning(this, tr("Error"), tr("Invalid URL \"%1\"").arg(newval)); + } + else + { + torrent_ids_t ids{ tracker_info.torrent_id }; + + QPair const id_url = qMakePair(tracker_info.st.id, newval); + + torrentSet(ids, TR_KEY_trackerReplace, id_url); + } +} + +void DetailsDialog::onRemoveTrackerClicked() +{ + // make a map of torrentIds to announce URLs to remove + QItemSelectionModel* selection_model = ui_.trackersView->selectionModel(); + QModelIndexList selected_rows = selection_model->selectedRows(); + QMap torrent_id_to_tracker_ids; + + for (QModelIndex const& i : selected_rows) + { + auto const inf = ui_.trackersView->model()->data(i, TrackerModel::TrackerRole).value(); + torrent_id_to_tracker_ids.insertMulti(inf.torrent_id, inf.st.id); + } + + // batch all of a tracker's torrents into one command + for (int const id : torrent_id_to_tracker_ids.uniqueKeys()) + { + torrent_ids_t const ids{ id }; + torrentSet(ids, TR_KEY_trackerRemove, torrent_id_to_tracker_ids.values(id)); + } + + selection_model->clearSelection(); +} + +void DetailsDialog::initOptionsTab() +{ + auto const speed_unit_str = Formatter::get().unitStr(Formatter::SPEED, Formatter::KB); + + ui_.singleDownSpin->setSuffix(QStringLiteral(" %1").arg(speed_unit_str)); + ui_.singleUpSpin->setSuffix(QStringLiteral(" %1").arg(speed_unit_str)); + + ui_.singleDownSpin->setProperty(PrefKey, TR_KEY_downloadLimit); + ui_.singleUpSpin->setProperty(PrefKey, TR_KEY_uploadLimit); + ui_.ratioSpin->setProperty(PrefKey, TR_KEY_seedRatioLimit); + ui_.idleSpin->setProperty(PrefKey, TR_KEY_seedIdleLimit); + ui_.peerLimitSpin->setProperty(PrefKey, TR_KEY_peer_limit); + + ui_.bandwidthPriorityCombo->addItem(tr("High"), TR_PRI_HIGH); + ui_.bandwidthPriorityCombo->addItem(tr("Normal"), TR_PRI_NORMAL); + ui_.bandwidthPriorityCombo->addItem(tr("Low"), TR_PRI_LOW); + + ui_.ratioCombo->addItem(tr("Use Global Settings"), TR_RATIOLIMIT_GLOBAL); + ui_.ratioCombo->addItem(tr("Seed regardless of ratio"), TR_RATIOLIMIT_UNLIMITED); + ui_.ratioCombo->addItem(tr("Stop seeding at ratio:"), TR_RATIOLIMIT_SINGLE); + + ui_.idleCombo->addItem(tr("Use Global Settings"), TR_IDLELIMIT_GLOBAL); + ui_.idleCombo->addItem(tr("Seed regardless of activity"), TR_IDLELIMIT_UNLIMITED); + ui_.idleCombo->addItem(tr("Stop seeding if idle for:"), TR_IDLELIMIT_SINGLE); + + auto* cr = new ColumnResizer(this); + cr->addLayout(ui_.speedSectionLayout); + cr->addLayout(ui_.seedingLimitsSectionRatioLayout); + cr->addLayout(ui_.seedingLimitsSectionIdleLayout); + cr->addLayout(ui_.peerConnectionsSectionLayout); + cr->update(); + + void (QComboBox::* combo_index_changed)(int) = &QComboBox::currentIndexChanged; + void (QSpinBox::* spin_value_changed)(int) = &QSpinBox::valueChanged; + connect(ui_.bandwidthPriorityCombo, combo_index_changed, this, &DetailsDialog::onBandwidthPriorityChanged); + connect(ui_.idleCombo, combo_index_changed, this, &DetailsDialog::onIdleModeChanged); + connect(ui_.idleSpin, &QSpinBox::editingFinished, this, &DetailsDialog::onSpinBoxEditingFinished); + connect(ui_.idleSpin, spin_value_changed, this, &DetailsDialog::onIdleLimitChanged); + connect(ui_.peerLimitSpin, &QSpinBox::editingFinished, this, &DetailsDialog::onSpinBoxEditingFinished); + connect(ui_.ratioCombo, combo_index_changed, this, &DetailsDialog::onRatioModeChanged); + connect(ui_.ratioSpin, &QSpinBox::editingFinished, this, &DetailsDialog::onSpinBoxEditingFinished); + connect(ui_.sessionLimitCheck, &QCheckBox::clicked, this, &DetailsDialog::onHonorsSessionLimitsToggled); + connect(ui_.singleDownCheck, &QCheckBox::clicked, this, &DetailsDialog::onDownloadLimitedToggled); + connect(ui_.singleDownSpin, &QSpinBox::editingFinished, this, &DetailsDialog::onSpinBoxEditingFinished); + connect(ui_.singleUpCheck, &QCheckBox::clicked, this, &DetailsDialog::onUploadLimitedToggled); + connect(ui_.singleUpSpin, &QSpinBox::editingFinished, this, &DetailsDialog::onSpinBoxEditingFinished); +} + +/*** +**** +***/ + +void DetailsDialog::initTrackerTab() +{ + tracker_model_ = new TrackerModel(); + tracker_filter_ = new TrackerModelFilter(); + tracker_filter_->setSourceModel(tracker_model_); + tracker_delegate_ = new TrackerDelegate(); + + ui_.trackersView->setModel(tracker_filter_); + ui_.trackersView->setItemDelegate(tracker_delegate_); + + ui_.addTrackerButton->setIcon(getStockIcon(QStringLiteral("list-add"), QStyle::SP_DialogOpenButton)); + ui_.editTrackerButton->setIcon(getStockIcon(QStringLiteral("document-properties"), QStyle::SP_DesktopIcon)); + ui_.removeTrackerButton->setIcon(getStockIcon(QStringLiteral("list-remove"), QStyle::SP_TrashIcon)); + + ui_.showTrackerScrapesCheck->setChecked(prefs_.getBool(Prefs::SHOW_TRACKER_SCRAPES)); + ui_.showBackupTrackersCheck->setChecked(prefs_.getBool(Prefs::SHOW_BACKUP_TRACKERS)); + + connect(ui_.addTrackerButton, &QAbstractButton::clicked, this, &DetailsDialog::onAddTrackerClicked); + connect(ui_.editTrackerButton, &QAbstractButton::clicked, this, &DetailsDialog::onEditTrackerClicked); + connect(ui_.removeTrackerButton, &QAbstractButton::clicked, this, &DetailsDialog::onRemoveTrackerClicked); + connect(ui_.showBackupTrackersCheck, &QAbstractButton::clicked, this, &DetailsDialog::onShowBackupTrackersToggled); + connect(ui_.showTrackerScrapesCheck, &QAbstractButton::clicked, this, &DetailsDialog::onShowTrackerScrapesToggled); + connect( + ui_.trackersView->selectionModel(), &QItemSelectionModel::selectionChanged, this, + &DetailsDialog::onTrackerSelectionChanged); + + onTrackerSelectionChanged(); +} + +/*** +**** +***/ + +void DetailsDialog::initPeersTab() +{ + ui_.peersView->setHeaderLabels({ QString(), tr("Up"), tr("Down"), tr("%"), tr("Status"), tr("Address"), tr("Client") }); + ui_.peersView->sortByColumn(COL_ADDRESS, Qt::AscendingOrder); + + ui_.peersView->setColumnWidth(COL_LOCK, 20); + ui_.peersView->setColumnWidth(COL_UP, measureViewItem(ui_.peersView, COL_UP, QStringLiteral("1024 MiB/s"))); + ui_.peersView->setColumnWidth(COL_DOWN, measureViewItem(ui_.peersView, COL_DOWN, QStringLiteral("1024 MiB/s"))); + ui_.peersView->setColumnWidth(COL_PERCENT, measureViewItem(ui_.peersView, COL_PERCENT, QStringLiteral("100%"))); + ui_.peersView->setColumnWidth(COL_STATUS, measureViewItem(ui_.peersView, COL_STATUS, QStringLiteral("ODUK?EXI"))); + ui_.peersView->setColumnWidth(COL_ADDRESS, measureViewItem(ui_.peersView, COL_ADDRESS, QStringLiteral("888.888.888.888"))); +} + +/*** +**** +***/ + +void DetailsDialog::initFilesTab() +{ + connect(ui_.filesView, &FileTreeView::openRequested, this, &DetailsDialog::onOpenRequested); + connect(ui_.filesView, &FileTreeView::pathEdited, this, &DetailsDialog::onPathEdited); + connect(ui_.filesView, &FileTreeView::priorityChanged, this, &DetailsDialog::onFilePriorityChanged); + connect(ui_.filesView, &FileTreeView::wantedChanged, this, &DetailsDialog::onFileWantedChanged); +} + +void DetailsDialog::onFilePriorityChanged(QSet const& indices, int priority) +{ + tr_quark key; + + switch (priority) + { + case TR_PRI_LOW: + key = TR_KEY_priority_low; + break; + + case TR_PRI_HIGH: + key = TR_KEY_priority_high; + break; + + default: + key = TR_KEY_priority_normal; + break; + } + + torrentSet(key, indices.values()); +} + +void DetailsDialog::onFileWantedChanged(QSet const& indices, bool wanted) +{ + tr_quark const key = wanted ? TR_KEY_files_wanted : TR_KEY_files_unwanted; + torrentSet(key, indices.values()); +} + +void DetailsDialog::onPathEdited(QString const& oldpath, QString const& newname) +{ + session_.torrentRenamePath(ids_, oldpath, newname); +} + +void DetailsDialog::onOpenRequested(QString const& path) +{ + if (!session_.isLocal()) + { + return; + } + + for (int const id : ids_) + { + Torrent const* const tor = model_.getTorrentFromId(id); + + if (tor == nullptr) + { + continue; + } + + QString const local_file_path = tor->getPath() + QLatin1Char('/') + path; + + if (!QFile::exists(local_file_path)) + { + continue; + } + + if (QDesktopServices::openUrl(QUrl::fromLocalFile(local_file_path))) + { + break; + } + } +} diff --git a/qt/DetailsDialog.h b/qt/DetailsDialog.h index e63a37777..d13b6219e 100644 --- a/qt/DetailsDialog.h +++ b/qt/DetailsDialog.h @@ -52,7 +52,7 @@ private: void initPeersTab(); void initTrackerTab(); void initInfoTab(); - void initFilesTab(); + void initFilesTab() const; void initOptionsTab(); QIcon getStockIcon(QString const& freedesktop_name, int fallback) const; @@ -79,7 +79,7 @@ private slots: void onFilePriorityChanged(QSet const& file_indices, int); void onFileWantedChanged(QSet const& file_indices, bool); void onPathEdited(QString const& old_path, QString const& new_name); - void onOpenRequested(QString const& path); + void onOpenRequested(QString const& path) const; // Options tab void onBandwidthPriorityChanged(int); diff --git a/qt/FaviconCache.cc b/qt/FaviconCache.cc index 2d2c8388a..d3d276eb3 100644 --- a/qt/FaviconCache.cc +++ b/qt/FaviconCache.cc @@ -33,7 +33,7 @@ FaviconCache::FaviconCache() : namespace { -QPixmap scale(QPixmap pixmap) +QPixmap scale(QPixmap const& pixmap) { return pixmap.scaled(FaviconCache::getIconSize(), Qt::KeepAspectRatio, Qt::SmoothTransformation); } diff --git a/qt/FileTreeItem.cc b/qt/FileTreeItem.cc index 666cd0c7e..18d1338ce 100644 --- a/qt/FileTreeItem.cc +++ b/qt/FileTreeItem.cc @@ -22,7 +22,7 @@ QHash const& FileTreeItem::getMyChildRows() { - size_t const n = childCount(); + int const n = childCount(); // ensure that all the rows are hashed while (first_unhashed_row_ < n) @@ -50,7 +50,7 @@ FileTreeItem::~FileTreeItem() void FileTreeItem::appendChild(FileTreeItem* child) { - size_t const n = childCount(); + int const n = childCount(); child->parent_ = this; children_.append(child); first_unhashed_row_ = n; diff --git a/qt/FileTreeItem.h b/qt/FileTreeItem.h index 6b72ed3f9..c52d01d7e 100644 --- a/qt/FileTreeItem.h +++ b/qt/FileTreeItem.h @@ -107,7 +107,7 @@ private: QString name_; uint64_t const total_size_ = {}; uint64_t have_size_ = {}; - size_t first_unhashed_row_ = {}; + int first_unhashed_row_ = {}; int const file_index_ = {}; int priority_ = {}; bool is_wanted_ = {}; diff --git a/qt/FileTreeView.cc b/qt/FileTreeView.cc index ec268349a..b0187313a 100644 --- a/qt/FileTreeView.cc +++ b/qt/FileTreeView.cc @@ -202,33 +202,7 @@ void FileTreeView::update(FileList const& files, bool update_fields) if (model_was_empty) { - // expand up until the item with more than one expandable child - for (QModelIndex index = proxy_->index(0, 0); index.isValid();) - { - QModelIndex const old_index = index; - - expand(old_index); - - index = QModelIndex(); - - for (int i = 0, count = proxy_->rowCount(old_index); i < count; ++i) - { - QModelIndex const new_index = proxy_->index(i, 0, old_index); - - if (proxy_->rowCount(new_index) == 0) - { - continue; - } - - if (index.isValid()) - { - index = QModelIndex(); - break; - } - - index = new_index; - } - } + expand(proxy_->index(0, 0)); } proxy_->sort(header()->sortIndicatorSection(), header()->sortIndicatorOrder()); @@ -325,16 +299,13 @@ void FileTreeView::onlyCheckSelectedItems() { unwanted_indices << child_index; } + else if (!wanted_indices_parents.contains(child_index)) + { + unwanted_indices << child_index; + } else { - if (!wanted_indices_parents.contains(child_index)) - { - unwanted_indices << child_index; - } - else - { - parents_queue.enqueue(child_index); - } + parents_queue.enqueue(child_index); } } } @@ -344,7 +315,7 @@ void FileTreeView::onlyCheckSelectedItems() void FileTreeView::setSelectedItemsPriority() { - auto* action = qobject_cast(sender()); + auto const* action = qobject_cast(sender()); assert(action != nullptr); model_->setPriority(selectedSourceRows(), action->property(PriorityKey).toInt()); } diff --git a/qt/FilterBar.cc b/qt/FilterBar.cc index 56991dbc2..9a9ab5387 100644 --- a/qt/FilterBar.cc +++ b/qt/FilterBar.cc @@ -92,7 +92,7 @@ FilterBarComboBox* FilterBar::createActivityCombo() namespace { -QString getCountString(int n) +QString getCountString(size_t n) { return QStringLiteral("%L1").arg(n); } @@ -136,7 +136,7 @@ void FilterBar::refreshTrackers() i->setData(display_name, Qt::DisplayRole); i->setData(display_name, TRACKER_ROLE); - i->setData(getCountString(count), FilterBarComboBox::CountStringRole); + i->setData(getCountString(static_cast(count)), FilterBarComboBox::CountStringRole); i->setData(icon, Qt::DecorationRole); i->setData(int(count), FilterBarComboBox::CountRole); @@ -192,7 +192,7 @@ FilterBarComboBox* FilterBar::createTrackerCombo(QStandardItemModel* model) row->setData(QString(), TRACKER_ROLE); int const count = torrents_.rowCount(); row->setData(count, FilterBarComboBox::CountRole); - row->setData(getCountString(count), FilterBarComboBox::CountStringRole); + row->setData(getCountString(static_cast(count)), FilterBarComboBox::CountStringRole); model->appendRow(row); model->appendRow(new QStandardItem); // separator @@ -380,7 +380,7 @@ void FilterBar::recount() auto const mode = index.data(ACTIVITY_ROLE).toInt(); auto const count = torrents_per_mode[mode]; model->setData(index, count, FilterBarComboBox::CountRole); - model->setData(index, getCountString(count), FilterBarComboBox::CountStringRole); + model->setData(index, getCountString(static_cast(count)), FilterBarComboBox::CountStringRole); } } diff --git a/qt/Formatter.cc b/qt/Formatter.cc index 9279af8e0..0e61316a4 100644 --- a/qt/Formatter.cc +++ b/qt/Formatter.cc @@ -73,13 +73,8 @@ QString Formatter::memToString(int64_t bytes) const return QString::fromUtf8(buf.data()); } -QString Formatter::sizeToString(int64_t bytes) const +QString Formatter::sizeToString(uint64_t bytes) const { - if (bytes < 0) - { - return tr("Unknown"); - } - if (bytes == 0) { return tr("None"); @@ -90,6 +85,16 @@ QString Formatter::sizeToString(int64_t bytes) const return QString::fromUtf8(buf.data()); } +QString Formatter::sizeToString(int64_t bytes) const +{ + if (bytes < 0) + { + return tr("Unknown"); + } + + return Formatter::sizeToString(static_cast(bytes)); +} + QString Formatter::speedToString(Speed const& speed) const { auto buf = std::array{}; diff --git a/qt/Formatter.h b/qt/Formatter.h index 6e3ab6764..44aaba761 100644 --- a/qt/Formatter.h +++ b/qt/Formatter.h @@ -49,6 +49,7 @@ public: QString memToString(int64_t bytes) const; QString sizeToString(int64_t bytes) const; + QString sizeToString(uint64_t bytes) const; QString speedToString(Speed const& speed) const; QString percentToString(double x) const; QString ratioToString(double ratio) const; diff --git a/qt/InteropHelper.cc b/qt/InteropHelper.cc index 8c6e9c7e3..36e815c7e 100644 --- a/qt/InteropHelper.cc +++ b/qt/InteropHelper.cc @@ -29,7 +29,7 @@ bool InteropHelper::isConnected() const return is_connected; } -bool InteropHelper::addMetainfo(QString const& metainfo) +bool InteropHelper::addMetainfo(QString const& metainfo) const { #ifdef ENABLE_DBUS_INTEROP diff --git a/qt/InteropHelper.h b/qt/InteropHelper.h index bd0675b32..e855bc0c7 100644 --- a/qt/InteropHelper.h +++ b/qt/InteropHelper.h @@ -22,7 +22,7 @@ class InteropHelper public: bool isConnected() const; - bool addMetainfo(QString const& metainfo); + bool addMetainfo(QString const& metainfo) const; static void initialize(); static void registerObject(QObject* parent); diff --git a/qt/InteropObject.cc b/qt/InteropObject.cc index 7f00443c0..c8d8f0802 100644 --- a/qt/InteropObject.cc +++ b/qt/InteropObject.cc @@ -16,14 +16,14 @@ InteropObject::InteropObject(QObject* parent) : } // NOLINTNEXTLINE(readability-identifier-naming) -bool InteropObject::PresentWindow() +bool InteropObject::PresentWindow() const { trApp->raise(); return true; } // NOLINTNEXTLINE(readability-identifier-naming) -bool InteropObject::AddMetainfo(QString const& metainfo) +bool InteropObject::AddMetainfo(QString const& metainfo) const { AddData addme(metainfo); diff --git a/qt/InteropObject.h b/qt/InteropObject.h index 8b2872fa9..750232f37 100644 --- a/qt/InteropObject.h +++ b/qt/InteropObject.h @@ -33,6 +33,6 @@ public: explicit InteropObject(QObject* parent = nullptr); public slots: - bool PresentWindow(); - bool AddMetainfo(QString const& metainfo); + bool PresentWindow() const; + bool AddMetainfo(QString const& metainfo) const; }; diff --git a/qt/MainWindow.cc b/qt/MainWindow.cc index 06cca722e..60b87a099 100644 --- a/qt/MainWindow.cc +++ b/qt/MainWindow.cc @@ -75,7 +75,7 @@ public: } }; -QIcon MainWindow::getStockIcon(QString const& name, int fallback) +QIcon MainWindow::getStockIcon(QString const& name, int fallback) const { QIcon icon = QIcon::fromTheme(name); @@ -87,7 +87,7 @@ QIcon MainWindow::getStockIcon(QString const& name, int fallback) return icon; } -QIcon MainWindow::addEmblem(QIcon base_icon, QStringList const& emblem_names) +QIcon MainWindow::addEmblem(QIcon base_icon, QStringList const& emblem_names) const { if (base_icon.isNull()) { @@ -121,11 +121,7 @@ QIcon MainWindow::addEmblem(QIcon base_icon, QStringList const& emblem_names) QPixmap pixmap = base_icon.pixmap(size); QPixmap emblem_pixmap = emblem_icon.pixmap(emblem_size); - - { - QPainter painter(&pixmap); - painter.drawPixmap(emblem_rect, emblem_pixmap, emblem_pixmap.rect()); - } + QPainter(&pixmap).drawPixmap(emblem_rect, emblem_pixmap, emblem_pixmap.rect()); icon.addPixmap(pixmap); } @@ -507,7 +503,7 @@ QMenu* MainWindow::createStatsModeMenu() ***** ****/ -void MainWindow::onSortModeChanged(QAction* action) +void MainWindow::onSortModeChanged(QAction const* action) { prefs_.set(Prefs::SORT_MODE, SortMode(action->property(SortModeKey).toInt())); } @@ -673,7 +669,7 @@ void MainWindow::openStats() Utils::openDialog(stats_dialog_, session_, this); } -void MainWindow::openDonate() +void MainWindow::openDonate() const { QDesktopServices::openUrl(QUrl(QStringLiteral("https://transmissionbt.com/donate/"))); } @@ -683,7 +679,7 @@ void MainWindow::openAbout() Utils::openDialog(about_dialog_, this); } -void MainWindow::openHelp() +void MainWindow::openHelp() const { QDesktopServices::openUrl(QUrl(QStringLiteral("https://transmissionbt.com/help/gtk/%1.%2x").arg(MAJOR_VERSION). arg(MINOR_VERSION / 10))); @@ -763,7 +759,7 @@ void MainWindow::refreshTitle() if (!url.isEmpty()) { - //: Second (optional) part of main window title "Transmission - host:port" (added when connected to remote session); + //: Second (optional) part of main window title "Transmission - host:port" (added when connected to remote session) //: notice that leading space (before the dash) is included here title += tr(" - %1:%2").arg(url.host()).arg(url.port()); } @@ -799,9 +795,10 @@ void MainWindow::refreshTrayIcon(TransferStats const& stats) void MainWindow::refreshStatusBar(TransferStats const& stats) { - ui_.uploadSpeedLabel->setText(Formatter::get().uploadSpeedToString(stats.speed_up)); + auto const& fmt = Formatter::get(); + ui_.uploadSpeedLabel->setText(fmt.uploadSpeedToString(stats.speed_up)); ui_.uploadSpeedLabel->setVisible(stats.peers_sending || stats.peers_receiving); - ui_.downloadSpeedLabel->setText(Formatter::get().downloadSpeedToString(stats.speed_down)); + ui_.downloadSpeedLabel->setText(fmt.downloadSpeedToString(stats.speed_down)); ui_.downloadSpeedLabel->setVisible(stats.peers_sending); ui_.networkLabel->setVisible(!session_.isServer()); @@ -812,27 +809,27 @@ void MainWindow::refreshStatusBar(TransferStats const& stats) if (mode == session_ratio_stats_mode_name_) { str = tr("Ratio: %1") - .arg(Formatter::get().ratioToString(session_.getStats().ratio)); + .arg(fmt.ratioToString(session_.getStats().ratio)); } else if (mode == session_transfer_stats_mode_name_) { auto const& st = session_.getStats(); str = tr("Down: %1, Up: %2") - .arg(Formatter::get().sizeToString(st.downloadedBytes)) - .arg(Formatter::get().sizeToString(st.uploadedBytes)); + .arg(fmt.sizeToString(st.downloadedBytes)) + .arg(fmt.sizeToString(st.uploadedBytes)); } else if (mode == total_transfer_stats_mode_name_) { auto const& st = session_.getCumulativeStats(); str = tr("Down: %1, Up: %2") - .arg(Formatter::get().sizeToString(st.downloadedBytes)) - .arg(Formatter::get().sizeToString(st.uploadedBytes)); + .arg(fmt.sizeToString(st.downloadedBytes)) + .arg(fmt.sizeToString(st.uploadedBytes)); } else // default is "total-ratio" { assert(mode == total_ratio_stats_mode_name_); str = tr("Ratio: %1") - .arg(Formatter::get().ratioToString(session_.getCumulativeStats().ratio)); + .arg(fmt.ratioToString(session_.getCumulativeStats().ratio)); } ui_.statsLabel->setText(str); @@ -1027,7 +1024,7 @@ void MainWindow::reannounceSelected() *** **/ -void MainWindow::onStatsModeChanged(QAction* action) +void MainWindow::onStatsModeChanged(QAction const* action) { prefs_.set(Prefs::STATUSBAR_STATS, action->property(StatsModeKey).toString()); } @@ -1085,7 +1082,6 @@ void MainWindow::toggleWindows(bool do_show) showNormal(); } - // activateWindow (); raise(); QApplication::setActiveWindow(this); } @@ -1111,7 +1107,7 @@ void MainWindow::refreshPref(int key) bool b; int i; QString str; - QActionGroup* action_group; + QActionGroup const* action_group; switch (key) { diff --git a/qt/MainWindow.h b/qt/MainWindow.h index c677282c1..72d568b64 100644 --- a/qt/MainWindow.h +++ b/qt/MainWindow.h @@ -102,12 +102,12 @@ private slots: void onSessionSourceChanged(); void onSetPrefs(); void onSetPrefs(bool); - void onSortModeChanged(QAction* action); - void onStatsModeChanged(QAction* action); + void onSortModeChanged(QAction const* action); + void onStatsModeChanged(QAction const* action); void openAbout(); - void openDonate(); + void openDonate() const; void openFolder(); - void openHelp(); + void openHelp() const; void openPreferences(); void openProperties(); void openStats(); @@ -123,8 +123,8 @@ private slots: void trayActivated(QSystemTrayIcon::ActivationReason); private: - QIcon getStockIcon(QString const&, int fallback = -1); - QIcon addEmblem(QIcon icon, QStringList const& emblem_names); + QIcon getStockIcon(QString const&, int fallback = -1) const; + QIcon addEmblem(QIcon icon, QStringList const& emblem_names) const; torrent_ids_t getSelectedTorrents(bool withMetadataOnly = false) const; void updateNetworkIcon(); diff --git a/qt/MakeDialog.cc b/qt/MakeDialog.cc index 054deb286..7a0728a64 100644 --- a/qt/MakeDialog.cc +++ b/qt/MakeDialog.cc @@ -221,8 +221,11 @@ void MakeDialog::onSourceChanged() { QString files = tr("%Ln File(s)", nullptr, builder_->fileCount); QString pieces = tr("%Ln Piece(s)", nullptr, builder_->pieceCount); - text = tr("%1 in %2; %3 @ %4").arg(Formatter::get().sizeToString(builder_->totalSize)).arg(files).arg(pieces). - arg(Formatter::get().sizeToString(builder_->pieceSize)); + text = tr("%1 in %2; %3 @ %4") + .arg(Formatter::get().sizeToString(builder_->totalSize)) + .arg(files) + .arg(pieces) + .arg(Formatter::get().sizeToString(static_cast(builder_->pieceSize))); } ui_.sourceSizeLabel->setText(text); diff --git a/qt/PathButton.cc b/qt/PathButton.cc index c1f5bba51..4a1c0666d 100644 --- a/qt/PathButton.cc +++ b/qt/PathButton.cc @@ -101,7 +101,7 @@ void PathButton::paintEvent(QPaintEvent* /*event*/) painter.drawComplexControl(QStyle::CC_ToolButton, option); } -void PathButton::onClicked() +void PathButton::onClicked() const { auto* dialog = new QFileDialog(window(), effectiveTitle()); dialog->setFileMode(isDirMode() ? QFileDialog::Directory : QFileDialog::ExistingFile); diff --git a/qt/PathButton.h b/qt/PathButton.h index 456e7085a..06e590bef 100644 --- a/qt/PathButton.h +++ b/qt/PathButton.h @@ -44,7 +44,7 @@ protected: void paintEvent(QPaintEvent* event) override; private slots: - void onClicked(); + void onClicked() const; void onFileSelected(QString const& path); private: diff --git a/qt/Prefs.cc b/qt/Prefs.cc index 0fffc859e..b364b19da 100644 --- a/qt/Prefs.cc +++ b/qt/Prefs.cc @@ -371,7 +371,7 @@ Prefs::~Prefs() * This is where we initialize the preferences file with the default values. * If you add a new preferences key, you /must/ add a default value here. */ -void Prefs::initDefaults(tr_variant* d) +void Prefs::initDefaults(tr_variant* d) const { auto constexpr FilterMode = std::string_view { "all" }; auto constexpr SessionHost = std::string_view { "localhost" }; diff --git a/qt/Prefs.h b/qt/Prefs.h index 230ec0f01..090d91f65 100644 --- a/qt/Prefs.h +++ b/qt/Prefs.h @@ -198,7 +198,7 @@ private: int type; }; - void initDefaults(tr_variant*); + void initDefaults(tr_variant*) const; void set(int key, char const* value) = delete; diff --git a/qt/PrefsDialog.cc b/qt/PrefsDialog.cc index a457cd746..1418264be 100644 --- a/qt/PrefsDialog.cc +++ b/qt/PrefsDialog.cc @@ -161,7 +161,7 @@ QString qtDayName(int day) } // namespace -bool PrefsDialog::updateWidgetValue(QWidget* widget, int pref_key) +bool PrefsDialog::updateWidgetValue(QWidget* widget, int pref_key) const { PreferenceWidget pref_widget(widget); diff --git a/qt/PrefsDialog.h b/qt/PrefsDialog.h index 15ba511c6..4116ef790 100644 --- a/qt/PrefsDialog.h +++ b/qt/PrefsDialog.h @@ -53,7 +53,7 @@ private slots: private: using key2widget_t = QMap; - bool updateWidgetValue(QWidget* widget, int pref_key); + bool updateWidgetValue(QWidget* widget, int pref_key) const; void linkWidgetToPref(QWidget* widget, int pref_key); void updateBlocklistLabel(); void updateDownloadingWidgetsLocality(); diff --git a/qt/RelocateDialog.cc b/qt/RelocateDialog.cc index 364d55a4b..a3a86a03f 100644 --- a/qt/RelocateDialog.cc +++ b/qt/RelocateDialog.cc @@ -22,7 +22,7 @@ void RelocateDialog::onSetLocation() close(); } -void RelocateDialog::onMoveToggled(bool b) +void RelocateDialog::onMoveToggled(bool b) const { move_flag = b; } diff --git a/qt/RelocateDialog.h b/qt/RelocateDialog.h index 6a853bc22..a7490893e 100644 --- a/qt/RelocateDialog.h +++ b/qt/RelocateDialog.h @@ -26,7 +26,7 @@ public: private slots: void onSetLocation(); - void onMoveToggled(bool); + void onMoveToggled(bool) const; private: QString newLocation() const; diff --git a/qt/RpcClient.cc b/qt/RpcClient.cc index 32bcc2852..6d0ac183c 100644 --- a/qt/RpcClient.cc +++ b/qt/RpcClient.cc @@ -297,13 +297,13 @@ void RpcClient::localRequestFinished(TrVariantPtr response) promise.reportFinished(&result); } -int64_t RpcClient::parseResponseTag(tr_variant& json) +int64_t RpcClient::parseResponseTag(tr_variant& json) const { auto const tag = dictFind(&json, TR_KEY_tag); return tag ? *tag : -1; } -RpcResponse RpcClient::parseResponseData(tr_variant& json) +RpcResponse RpcClient::parseResponseData(tr_variant& json) const { RpcResponse ret; diff --git a/qt/RpcClient.h b/qt/RpcClient.h index f6f51ef34..6c68701ed 100644 --- a/qt/RpcClient.h +++ b/qt/RpcClient.h @@ -87,8 +87,8 @@ private: void sendNetworkRequest(TrVariantPtr json, QFutureInterface const& promise); void sendLocalRequest(TrVariantPtr json, QFutureInterface const& promise, int64_t tag); - int64_t parseResponseTag(tr_variant& response); - RpcResponse parseResponseData(tr_variant& response); + int64_t parseResponseTag(tr_variant& response) const; + RpcResponse parseResponseData(tr_variant& response) const; static void localSessionCallback(tr_session* s, tr_variant* response, void* vself) noexcept; diff --git a/qt/RpcQueue.h b/qt/RpcQueue.h index b24f81cf2..b5e0b9b8c 100644 --- a/qt/RpcQueue.h +++ b/qt/RpcQueue.h @@ -69,7 +69,7 @@ private: template, RpcResponseFuture> >::type* = nullptr> - QueuedFunction normalizeFunc(Func const& func) + QueuedFunction normalizeFunc(Func const& func) const { return [func](RpcResponseFuture const& r) { @@ -81,7 +81,7 @@ private: template, RpcResponseFuture> >::type* = nullptr> - QueuedFunction normalizeFunc(Func const& func) + QueuedFunction normalizeFunc(Func const& func) const { return [func](RpcResponseFuture const&) { @@ -93,7 +93,7 @@ private: template, void> >::type* = nullptr> - QueuedFunction normalizeFunc(Func const& func) + QueuedFunction normalizeFunc(Func const& func) const { return [func](RpcResponseFuture const& r) { @@ -106,7 +106,7 @@ private: template, void> >::type* = nullptr> - QueuedFunction normalizeFunc(Func const& func) + QueuedFunction normalizeFunc(Func const& func) const { return [func](RpcResponseFuture const& r) { @@ -119,7 +119,7 @@ private: template, void> >::type* = nullptr> - ErrorHandlerFunction normalizeErrorHandler(Func const& func) + ErrorHandlerFunction normalizeErrorHandler(Func const& func) const { return [func](RpcResponseFuture const& r) { @@ -131,7 +131,7 @@ private: template, void> >::type* = nullptr> - ErrorHandlerFunction normalizeErrorHandler(Func const& func) + ErrorHandlerFunction normalizeErrorHandler(Func const& func) const { return [func](RpcResponseFuture const&) { diff --git a/qt/Session.cc b/qt/Session.cc index 9a438f013..4151b8aea 100644 --- a/qt/Session.cc +++ b/qt/Session.cc @@ -394,7 +394,7 @@ bool Session::isLocal() const **** ***/ -void Session::addOptionalIds(tr_variant* args, torrent_ids_t const& ids) +void Session::addOptionalIds(tr_variant* args, torrent_ids_t const& ids) const { auto constexpr RecentlyActiveKey = std::string_view { "recently-active" }; @@ -1234,7 +1234,7 @@ void Session::reannounceTorrents(torrent_ids_t const& ids) **** ***/ -void Session::launchWebInterface() +void Session::launchWebInterface() const { QUrl url; diff --git a/qt/Session.h b/qt/Session.h index 75ba977c4..28fc46928 100644 --- a/qt/Session.h +++ b/qt/Session.h @@ -120,7 +120,7 @@ public: public slots: void addTorrent(AddData const& addme); - void launchWebInterface(); + void launchWebInterface() const; void queueMoveBottom(torrent_ids_t const& torrentIds = {}); void queueMoveDown(torrent_ids_t const& torrentIds = {}); void queueMoveTop(torrent_ids_t const& torrentIds = {}); @@ -162,7 +162,7 @@ private: static void updateStats(tr_variant* d, tr_session_stats* stats); - void addOptionalIds(tr_variant* args, torrent_ids_t const& ids); + void addOptionalIds(tr_variant* args, torrent_ids_t const& ids) const; QString const config_dir_; Prefs& prefs_; diff --git a/qt/SessionDialog.cc b/qt/SessionDialog.cc index befb9447b..4b0931359 100644 --- a/qt/SessionDialog.cc +++ b/qt/SessionDialog.cc @@ -26,7 +26,7 @@ void SessionDialog::accept() BaseDialog::accept(); } -void SessionDialog::resensitize() +void SessionDialog::resensitize() const { bool const is_remote = ui_.remoteSessionRadio->isChecked(); bool const use_auth = ui_.authCheck->isChecked(); diff --git a/qt/SessionDialog.h b/qt/SessionDialog.h index 7a3aa1a75..4b22b0774 100644 --- a/qt/SessionDialog.h +++ b/qt/SessionDialog.h @@ -30,7 +30,7 @@ public slots: void accept() override; private slots: - void resensitize(); + void resensitize() const; private: Session& session_; diff --git a/qt/Torrent.h b/qt/Torrent.h index 9603db4a8..a9ea63570 100644 --- a/qt/Torrent.h +++ b/qt/Torrent.h @@ -285,7 +285,7 @@ public: { auto const l = leftUntilDone(); auto const s = sizeWhenDone(); - return s ? double(s - l) / s : 0.0; + return s ? static_cast(s - l) / static_cast(s) : 0.0; } double metadataPercentDone() const diff --git a/qt/TorrentDelegate.cc b/qt/TorrentDelegate.cc index 50dab8d42..e7a3339d1 100644 --- a/qt/TorrentDelegate.cc +++ b/qt/TorrentDelegate.cc @@ -149,14 +149,14 @@ QString TorrentDelegate::progressString(Torrent const& tor) if (is_magnet) // magnet link with no metadata { - //: First part of torrent progress string; + //: First part of torrent progress string, //: %1 is the percentage of torrent metadata downloaded str = tr("Magnetized transfer - retrieving metadata (%1%)"). arg(Formatter::get().percentToString(tor.metadataPercentDone() * 100.0)); } else if (!is_done) // downloading { - //: First part of torrent progress string; + //: First part of torrent progress string, //: %1 is how much we've got, //: %2 is how much we'll have when done, //: %3 is a percentage of the two @@ -169,7 +169,7 @@ QString TorrentDelegate::progressString(Torrent const& tor) { if (has_seed_ratio) { - //: First part of torrent progress string; + //: First part of torrent progress string, //: %1 is how much we've got, //: %2 is the torrent's total size, //: %3 is a percentage of the two, @@ -184,7 +184,7 @@ QString TorrentDelegate::progressString(Torrent const& tor) } else { - //: First part of torrent progress string; + //: First part of torrent progress string, //: %1 is how much we've got, //: %2 is the torrent's total size, //: %3 is a percentage of the two, @@ -200,7 +200,7 @@ QString TorrentDelegate::progressString(Torrent const& tor) { if (has_seed_ratio) { - //: First part of torrent progress string; + //: First part of torrent progress string, //: %1 is the torrent's total size, //: %2 is how much we've uploaded, //: %3 is our upload-to-download ratio, @@ -211,7 +211,7 @@ QString TorrentDelegate::progressString(Torrent const& tor) } else // seeding w/o a ratio { - //: First part of torrent progress string; + //: First part of torrent progress string, //: %1 is the torrent's total size, //: %2 is how much we've uploaded, //: %3 is our upload-to-download ratio @@ -225,14 +225,14 @@ QString TorrentDelegate::progressString(Torrent const& tor) { if (tor.hasETA()) { - //: Second (optional) part of torrent progress string; - //: %1 is duration; + //: Second (optional) part of torrent progress string, + //: %1 is duration, //: notice that leading space (before the dash) is included here str += tr(" - %1 left").arg(Formatter::get().timeToString(tor.getETA())); } else { - //: Second (optional) part of torrent progress string; + //: Second (optional) part of torrent progress string, //: notice that leading space (before the dash) is included here str += tr(" - Remaining time unknown"); } @@ -329,7 +329,7 @@ QString TorrentDelegate::statusString(Torrent const& tor) if (tor.webseedsWeAreDownloadingFrom()) { - //: Second (optional) part of phrase "Downloading from ... of ... connected peer(s) and ... web seed(s)"; + //: Second (optional) part of phrase "Downloading from ... of ... connected peer(s) and ... web seed(s)", //: notice that leading space (before "and") is included here str += tr(" and %Ln web seed(s)", nullptr, tor.webseedsWeAreDownloadingFrom()); } diff --git a/qt/TrackerDelegate.cc b/qt/TrackerDelegate.cc index 3dc068cb8..d9d2285c9 100644 --- a/qt/TrackerDelegate.cc +++ b/qt/TrackerDelegate.cc @@ -268,11 +268,11 @@ QString TrackerDelegate::getText(TrackerInfo const& inf) const } else if (inf.st.seeder_count >= 0 && inf.st.leecher_count >= 0) { - //: First part of phrase "Tracker had ... seeder(s) and ... leecher(s) ... ago"; + //: First part of phrase "Tracker had ... seeder(s) and ... leecher(s) ... ago", //: %1 and %2 are replaced with HTML markup str += tr("Tracker had%1 %Ln seeder(s)%2", nullptr, inf.st.seeder_count).arg(success_markup_begin). arg(success_markup_end); - //: Second part of phrase "Tracker had ... seeder(s) and ... leecher(s) ... ago"; + //: Second part of phrase "Tracker had ... seeder(s) and ... leecher(s) ... ago", //: %1 and %2 are replaced with HTML markup, %3 is duration; //: notice that leading space (before "and") is included here str += tr(" and%1 %Ln leecher(s)%2 %3 ago", nullptr, inf.st.leecher_count).arg(success_markup_begin). diff --git a/utils/edit.c b/utils/edit.c index 75994494c..cff2a30c1 100644 --- a/utils/edit.c +++ b/utils/edit.c @@ -107,9 +107,8 @@ static bool removeURL(tr_variant* metainfo, char const* url) while ((tier = tr_variantListChild(announce_list, tierIndex)) != NULL) { - tr_variant* node; int nodeIndex = 0; - + tr_variant const* node; while ((node = tr_variantListChild(tier, nodeIndex)) != NULL) { if (tr_variantGetStr(node, &str, NULL) && strcmp(str, url) == 0) @@ -163,8 +162,8 @@ static bool removeURL(tr_variant* metainfo, char const* url) static char* replaceSubstr(char const* str, char const* in, char const* out) { - char* walk; - struct evbuffer* buf = evbuffer_new(); + char const* walk; + struct evbuffer* const buf = evbuffer_new(); size_t const inlen = strlen(in); size_t const outlen = strlen(out); @@ -229,17 +228,17 @@ static bool replaceURL(tr_variant* metainfo, char const* in, char const* out) static bool announce_list_has_url(tr_variant* announce_list, char const* url) { - tr_variant* tier; int tierCount = 0; + tr_variant* tier; while ((tier = tr_variantListChild(announce_list, tierCount)) != NULL) { - tr_variant* node; - char const* str; int nodeCount = 0; + tr_variant const* node; while ((node = tr_variantListChild(tier, nodeCount)) != NULL) { + char const* str = NULL; if (tr_variantGetStr(node, &str, NULL) && strcmp(str, url) == 0) { return true; diff --git a/utils/remote.c b/utils/remote.c index bb58899e4..5ac48d297 100644 --- a/utils/remote.c +++ b/utils/remote.c @@ -976,7 +976,7 @@ static void printDetails(tr_variant* top) if (tr_variantDictFindList(t, TR_KEY_labels, &l)) { size_t child_pos = 0; - tr_variant* child; + tr_variant const* child; while ((child = tr_variantListChild(l, child_pos++))) { if (tr_variantGetStr(child, &str, NULL))